Compare commits

...
1577 Commits
Author SHA1 Message Date
Gwendal Roué 5aa385094b Merge branch 'development' 2023-04-17 20:20:50 +02:00
Gwendal Roué 1cd20176c6 v6.11.0 2023-04-17 20:20:30 +02:00
Gwendal Roué 06891e99e1 Prepare for release 2023-04-17 20:20:30 +02:00
Gwendal Roué d5f38a6a24 Fix Swiftlint warning 2023-04-17 19:17:50 +02:00
Gwendal Roué 68d23a5f33 README layout 2023-04-17 08:36:32 +02:00
Gwendal Roué 75f92f6f14 Dark logo 2023-04-17 08:35:31 +02:00
Gwendal Roué 6c70ee6b77 Remove the Swift language versions 2023-04-16 16:51:33 +02:00
Gwendal Roué c8ae3cb61c Update usage sample code 2023-04-16 14:07:43 +02:00
Gwendal Roué dd4d3e35f3 Concurrency Guide layout 2023-04-16 13:27:11 +02:00
Gwendal Roué 7b2619e757 Refactor README introduction 2023-04-16 13:25:24 +02:00
Gwendal Roué a7b9a27c51 DocC home page layout 2023-04-16 13:09:31 +02:00
Gwendal Roué fcfd6e9028 ValueConcurrentObserver releases its initial WAL transaction earlier 2023-04-15 11:59:19 +02:00
Gwendal Roué 9011f71247 Fix tests for unavailable wal snapshots 2023-04-15 09:50:46 +02:00
Gwendal Roué 069bce217d Attempts at finding regression tests for #1362 2023-04-14 08:28:34 +02:00
Gwendal Roué 5a91340671 CHANGELOG 2023-04-13 08:02:41 +02:00
Gwendal Roué ba2e3cb468 Merge pull request #1361 from groue/dev/issue-1360
DatabaseMigrator.eraseDatabaseOnSchemaChange ignores internal schema objects
2023-04-13 08:00:05 +02:00
Gwendal Roué f633be4ba1 Fix test for #1360 2023-04-12 08:02:38 +02:00
Gwendal Roué 4074fcfcc7 Failing test for #1360 2023-04-12 08:00:19 +02:00
Gwendal Roué 18cdf4956e Fix typos 2023-04-10 16:52:03 +02:00
Gwendal Roué 18e06a78a3 Merge branch 'development' 2023-04-10 15:06:33 +02:00
Gwendal Roué 065ca71876 v6.10.2 2023-04-10 14:16:41 +02:00
Gwendal Roué 859a1d6184 Enhance Recommended Practices for Designing Record Types 2023-04-10 14:11:39 +02:00
Gwendal Roué f2ea4e91db CHANGELOG 2023-04-10 11:32:12 +02:00
Gwendal Roué 1add9a9752 Fix incorrect test 2023-04-10 11:31:19 +02:00
Gwendal Roué 17c3f82f50 Remove weird Xcode error regarding the Scripts "project" 2023-04-10 11:31:19 +02:00
Gwendal Roué 52a3d6ba23 Move the "Recommended Practices for Designing Record Types" to DocC 2023-04-10 09:51:38 +02:00
Gwendal Roué 54007a9ce1 Refactor demo apps for enhanced configuration management 2023-04-09 11:40:40 +02:00
Gwendal Roué 77d8a46039 Remove obsolete TODOs 2023-04-08 12:30:55 +02:00
Gwendal Roué f6e695a21d More explicit any/some 2023-04-08 12:01:59 +02:00
Gwendal Roué 3184334535 Merge branch 'development' 2023-04-01 17:22:35 +02:00
Gwendal Roué 12e3923af1 v6.10.1 2023-04-01 16:01:43 +02:00
Gwendal Roué b81e858ca0 Better fix for #1357
Previous fix would not correctly address #1357 when invalid double-quoted identifiers are interpreted as string literals (Configuration.acceptsDoubleQuotedStringLiterals = true, or SQLCipher 3)
2023-04-01 14:59:42 +02:00
Gwendal Roué 82f300e534 GitHub actions: Xcode 14.2 2023-04-01 14:30:57 +02:00
Gwendal Roué 9df1cfd110 CHANGELOG 2023-04-01 14:12:50 +02:00
Gwendal Roué 373fe467d6 Fix failing test for #1357 2023-04-01 14:09:50 +02:00
Gwendal Roué 81eb6b128f Failing test for #1357 2023-04-01 14:09:50 +02:00
Gwendal Roué c7ee12eff7 Remove deprecated swiftlint rule 2023-04-01 13:14:45 +02:00
Gwendal Roué 89330daa52 Use xcbeautify when available 2023-04-01 13:05:43 +02:00
Gwendal Roué e408bd17d8 Fix Swiftlint warning 2023-04-01 13:04:52 +02:00
Gwendal Roué 99ddc5e13c Makefile: add explicit macOS destinations 2023-04-01 12:56:44 +02:00
Gwendal Roué 4c0cc84c2d Improve DatabaseEventPredicate usage with SQLITE_ENABLE_PREUPDATE_HOOK 2023-03-31 08:02:04 +02:00
Gwendal Roué 4762f8bb36 Fix spawnConcurrentRead documentation 2023-03-29 13:02:49 +02:00
Gwendal Roué 7e6f71912c Enhance DatabaseQueue read-only transactions 2023-03-29 13:02:31 +02:00
Gwendal Roué 6b311941b1 Remove WWDCCompanion from the release process 2023-03-22 18:40:48 +01:00
Gwendal Roué 5facc24ebb Fix compiler warnings for Swift 5.8 2023-03-22 18:40:37 +01:00
Gwendal Roué 018ae03f8e Improve DatabaseEventPredicate usage 2023-03-22 08:30:21 +01:00
Gwendal Roué 52aef76b63 Fix Swiftlint warning 2023-03-22 08:25:37 +01:00
Gwendal Roué 2fa5ca767f WALSnapshot is only available when the SQLite feature is
Since #1350 we no longer need to expose it and check for failures at runtime.
2023-03-20 15:05:17 +01:00
Gwendal Roué a1b76f9e06 Fix typo 2023-03-20 09:21:50 +01:00
Gwendal Roué 2d19cab2b5 Merge branch 'development' 2023-03-20 07:53:38 +01:00
Gwendal Roué a551fbf443 v6.10.0 2023-03-20 07:53:28 +01:00
Gwendal Roué c6e220a531 Merge pull request #1350 from groue/dev/long-lived-read-only-transaction
DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts
2023-03-20 07:50:30 +01:00
Gwendal RouéandRogerio de Paula Assis 600d1b84b6 Update GRDB/Core/SerializedDatabase.swift
Co-authored-by: Rogerio de Paula Assis <rog@anz.com>
2023-03-20 07:02:00 +01:00
Gwendal Roué 5629cfe6ff Fix documentation 2023-03-19 13:56:56 +01:00
Gwendal Roué 5d9b9edfe1 Fix asyncWALSnapshotTransaction usage.
We must use its result asynchronously.
2023-03-19 12:39:48 +01:00
Gwendal Roué 449c243a36 Rename persistentReaderConnections to dbConfiguration.persistentReadOnlyConnections 2023-03-18 11:08:56 +01:00
Gwendal Roué 6ca4986bc2 CHANGELOG 2023-03-17 13:52:29 +01:00
Gwendal Roué 063877d49c Configuration.persistentReaderConnections 2023-03-17 13:52:29 +01:00
Gwendal Roué 2f4d0c4588 CHANGELOG 2023-03-17 13:52:29 +01:00
Gwendal Roué 0a544dc0d2 Cleanup relationships between SerializedDatabase, WALSnapshotTransaction, and DatabasePool
SerializedDatabase hides its allowsUnsafeTransactions property, and makes it thread-safe by protecting it inside its serialized dispatch queue.

WALSnapshotTransaction always notifies when the reader connection is no longer used, and reuses the "isInsideTransaction" wording.
2023-03-17 13:52:29 +01:00
Gwendal Roué d64274474b ValueObservation: stop creating a new connection on start
Since #1248, ValueObservation on DatabasePool creates a new database connection when it starts. #1256 has revealed that opening a connection can take too much time, which unfortunate consequences: the first value is notified too late, and we block the main thread when the observation is started in the `.immediate` scheduling :-/

In this commit, ValueObservation on DatabasePool just uses one of the available readers, thus avoiding creating a new connection.

When WAL snapshots are available, a long-running read-only transaction is kept opened on this reader, until we can start observing the write transactions, compare database versions, and perform a fetch+notification if and only if the database was modified.

When WAL snapshots are not available (Xcode 14.0 and macOS, or specific SQLCipher or SQLite builds), a double notification of the initial value is always performed, since we can't prove that the database was not changed between the initial fetch and the write access.
2023-03-17 13:52:29 +01:00
Gwendal Roué e66dfacab8 WALSnapshotTransaction 2023-03-17 13:52:29 +01:00
Gwendal Roué 0d4c6e592e SerializedDatabase.allowsUnsafeTransactions 2023-03-17 13:52:29 +01:00
Gwendal Roué 5d7fdeae5a Fix compiler warnings in tests 2023-03-17 13:52:01 +01:00
Gwendal Roué 378c6785ea Clarification on the truncate optimization 2023-03-16 18:44:46 +01:00
Gwendal Roué 6d392f0a87 Use DatabaseError.connectionIsClosed() where appropriate 2023-03-16 13:44:08 +01:00
Gwendal Roué 7c81c37e1f Move DatabaseRegionObservation documentation in an extension file 2023-03-15 16:51:46 +01:00
Gwendal Roué 3f876978a1 Move TransactionObserver documentation in an extension file 2023-03-15 16:51:46 +01:00
Gwendal Roué a0ed1bfd33 Move ValueObservation documentation in an extension file 2023-03-15 16:51:46 +01:00
Gwendal Roué be41d2dd03 Merge branch 'development' 2023-03-14 08:33:07 +01:00
Gwendal Roué e6c3a8d07a v6.9.2 2023-03-14 08:32:58 +01:00
Gwendal Roué 5e41ca7e4e CHANGELOG 2023-03-14 08:12:38 +01:00
Gwendal Roué 0f942c014c Cleanup 2023-03-14 08:10:56 +01:00
Gwendal Roué 40bebda712 Merge pull request #1349 from JonLz/fix-migrations-docs
Fix Migrations.md example so it compiles
2023-03-13 20:35:21 +01:00
Jon Lazar 37fd4c18b0 Update Migrations.md
Fix closure parameter syntax so that the example compiles.
2023-03-13 15:26:07 -04:00
Gwendal Roué d5a41bd11b Disable SQLITE_STATIC optimization when there are too many arguments 2023-03-13 19:33:52 +01:00
Gwendal Roué c22fc202a9 Fix typo 2023-03-13 08:06:07 +01:00
Gwendal Roué a0f14d816a Merge branch 'development' 2023-03-12 18:18:06 +01:00
Gwendal Roué ad33dfcfbf v6.9.1 2023-03-12 18:17:48 +01:00
Gwendal Roué 840fa3b5da RecordError DocC 2023-03-12 18:14:38 +01:00
Gwendal Roué 397a008237 More links to DocC reference 2023-03-12 18:01:24 +01:00
Gwendal Roué f7559d4c76 Moved row adapters doc into DocC 2023-03-12 17:25:16 +01:00
Gwendal Roué 8cd71ac832 Fix TableRecord.databaseSelection sample code 2023-03-12 17:18:28 +01:00
Gwendal Roué 0ffd25bc74 Fix documentation typo 2023-03-12 16:33:10 +01:00
Gwendal Roué ff7f9073fc Add links to DocC reference 2023-03-12 16:32:54 +01:00
Gwendal Roué 93616775f6 Merge branch 'development' 2023-03-12 12:48:30 +01:00
Gwendal Roué 81751625e0 v6.9.0 2023-03-12 12:48:19 +01:00
Gwendal Roué 9798f9f9fa Update Package.resolved for demo apps 2023-03-12 12:40:38 +01:00
Gwendal Roué db165581ea Merge pull request #1348 from groue/dev/argument-optimization
SQLite argument binding optimization
2023-03-12 11:56:57 +01:00
Gwendal Roué b4e851aa49 More statement arguments documentation 2023-03-12 10:59:38 +01:00
Gwendal Roué 0169e340dc CHANGELOG 2023-03-11 16:40:47 +01:00
Gwendal Roué 1d5d1aea68 Upgrade performance tests dependencies 2023-03-11 12:10:25 +01:00
Gwendal Roué 0c333b6e22 Performance improvements 2023-03-11 12:10:25 +01:00
Gwendal Roué 6a24d835d3 Performance tests for various statement arguments strategies 2023-03-11 12:10:25 +01:00
Gwendal Roué 3382280cc3 Statement.execute(arguments:) uses temporary bindings
Inspired by @helje5 in https://hachyderm.io/@helge@mastodon.social/109978514220902036

Thank you!!

Now, onto cursors!
2023-03-11 12:10:25 +01:00
Gwendal Roué 60fa8a630f Improve Statement.databaseRegion documentation 2023-03-11 12:08:17 +01:00
Gwendal Roué 9ba64c2426 Statement argument validation: fix wrong documentation and strenghten tests 2023-03-11 09:12:37 +01:00
Gwendal Roué 29b5b99b89 Fix typos 2023-03-11 08:00:23 +01:00
Gwendal Roué 725d38ea06 Fix typo 2023-03-07 11:08:00 +01:00
Gwendal Roué 6509f7ed40 Improve DatabaseValueConvertible documentation 2023-03-06 08:22:29 +01:00
Gwendal Roué 67bdc740bd DatabaseValueConvertible and collections: move the rationale out of the user-facing documentation. 2023-03-06 08:03:08 +01:00
Gwendal Roué 1e2b454c4c Enhance wording 2023-03-05 17:14:06 +01:00
Gwendal Roué a77f9d3f6a CHANGELOG 2023-03-05 13:52:26 +01:00
Gwendal Roué 229bd98b9c Enhance Database Connection DocC overview 2023-03-05 13:51:14 +01:00
Gwendal Roué 692eac43a9 Fix typos 2023-03-05 07:44:12 +01:00
Gwendal Roué 4f398a3457 Prepared statements documentation is now hosted in the Statement DocC 2023-03-04 17:08:12 +01:00
Gwendal Roué 44c13e5bff Make sure Statement.reset(withArguments:) resets 2023-03-04 16:28:45 +01:00
Gwendal Roué 7b2393f2cd Cleanup 2023-03-04 15:23:19 +01:00
Gwendal Roué 67dfdc1bbb Move DatabaseValueConvertible.swift DocC in an extension file 2023-03-04 15:19:55 +01:00
Gwendal Roué cc8ed5ccb5 Enhanced DocC for DatabaseValueConvertible
Also:
- Redirect the "Custom Value Types" README chapter to DatabaseValueConvertible documentation.
- Document how to support Tagged https://github.com/pointfreeco/swift-tagged
2023-03-04 14:51:46 +01:00
Gwendal Roué 441823d5f4 Enhance discoverability of the Database Sharing guide
https://github.com/groue/GRDB.swift/discussions/1343
2023-03-04 12:19:21 +01:00
Gwendal Roué 1e5ee4b292 Fix Xcode 14.3 beta 2 warnings 2023-03-04 11:53:41 +01:00
Gwendal Roué 159a34bdf2 Demo apps: bump GRDBQuery to 0.6.0 2023-03-04 10:03:51 +01:00
Gwendal Roué e936d6b42d Fix DatabaseError documentation 2023-03-02 06:58:33 +01:00
Gwendal Roué cc567f2555 Expose the fts5_api structure 2023-03-01 08:23:36 +01:00
Gwendal Roué b3763ad08e RecordCursor: same documation as all cursors 2023-02-26 10:26:03 +01:00
Gwendal Roué c824b42757 Restore busy timeout tests
In the context of #1339
2023-02-25 10:56:56 +01:00
Gwendal Roué d3862c0424 Merge branch 'development' 2023-02-24 13:22:53 +01:00
Gwendal Roué f6cb77a489 v6.8.0 2023-02-24 13:11:18 +01:00
Gwendal Roué a1faa88579 Merge pull request #1338 from groue/dev/TimestampedRecord
TimestampedRecord sample code
2023-02-24 13:03:48 +01:00
Gwendal Roué 43ff278748 Improve transactionDate and transactionClock documentation 2023-02-23 08:34:09 +01:00
Gwendal Roué 5ed44b94bc More improvements to RecordTimestamps.md 2023-02-23 07:59:08 +01:00
Gwendal Roué e683df3494 Tweak wording and explore more timestamp handling scenarios 2023-02-22 14:10:28 +01:00
Gwendal Roué 9f0bd4944b Cleanup 2023-02-22 08:10:28 +01:00
Gwendal Roué 3fab2db88d RecordTimestamps.md organization 2023-02-22 08:07:27 +01:00
Gwendal Roué 5f013b6ee7 Layout for Xcode doc reader 2023-02-22 07:17:53 +01:00
Gwendal Roué 734d911416 Fix typo 2023-02-22 06:18:13 +01:00
Gwendal Roué 86bde428bf Make TimestampedRecord a subprotocol of MutablePersistableRecord 2023-02-22 06:13:32 +01:00
Gwendal Roué c5045dbe7a TimestampedRecord.updateChangesWithTimestamp 2023-02-21 22:48:37 +01:00
Gwendal Roué b0d73f3126 EncodableRecord.databaseChanges(modify:) 2023-02-21 22:48:37 +01:00
Gwendal Roué 9e2eb6c599 Enhance TimestampedRecord
In particular, `touch` performs an update on disk, just like the unix command.
2023-02-21 21:42:36 +01:00
Gwendal Roué 3bf73e9f66 TimestampedRecord demo 2023-02-21 08:51:03 +01:00
Gwendal Roué 9bd26a5a1b Improve Modification Timestamp documentation 2023-02-20 13:30:29 +01:00
Gwendal Roué 84f5a91f7b Improve Modification Timestamp documentation 2023-02-20 13:23:36 +01:00
Gwendal Roué c9ae697a44 Remove obsolete documentation about FTS5 2023-02-19 21:30:41 +01:00
Gwendal Roué e76cda27dc Merge branch 'development' 2023-02-19 20:00:51 +01:00
Gwendal Roué 2618c9fa1e v6.7.0 2023-02-19 19:58:05 +01:00
Gwendal Roué 522e4be817 Merge pull request #1336 from groue/dev/FTS5
Enable FTS5 by default
2023-02-19 19:53:37 +01:00
Gwendal Roué ff8b9e5cb8 CHANGELOG 2023-02-19 18:42:08 +01:00
Gwendal Roué 38c9ec29f5 Enable FTS5 by default in CocoaPods 2023-02-19 18:25:16 +01:00
Gwendal Roué 3b0cf1fb0b FTS5 DocC 2023-02-19 17:38:19 +01:00
Gwendal Roué dc4f10ecb0 Remove Xcode warning 2023-02-19 12:10:17 +01:00
Gwendal Roué 012ed8133f Enable FTS5 by default in SPM 2023-02-19 12:10:09 +01:00
Gwendal Roué d0314e0db8 Enable FTS5 by default in GRDB.xcodeproj 2023-02-19 12:03:49 +01:00
Gwendal Roué 850db8f2e9 Fix #1327 2023-02-18 15:11:34 +01:00
Gwendal Roué 44ec63dbe2 Merge pull request #1331 from groue/dev/transactionDate
Transaction Date
2023-02-18 14:42:51 +01:00
Gwendal Roué e9afb04b1e Test that transaction date is reset after a rollback error 2023-02-18 12:19:56 +01:00
Gwendal Roué 72216beacb Enhance wording 2023-02-18 12:06:11 +01:00
Gwendal Roué 6500a97f88 Documentation 2023-02-18 11:58:46 +01:00
Gwendal Roué 3c71a6deea "Record Timestamps and Transaction Date" documentation chapter 2023-02-18 11:52:21 +01:00
Gwendal Roué e4421c509c Improve transactionDate documentation 2023-02-18 10:18:10 +01:00
Gwendal Roué c8339db68b CHANGELOG 2023-02-18 10:17:10 +01:00
Gwendal Roué 961b3a9cad Database.transactionDate must be called from a valid DispatchQueue 2023-02-18 08:31:05 +01:00
Gwendal Roué efa8f0e69d Configuration.transactionClock is experimental as well 2023-02-18 08:31:05 +01:00
Gwendal Roué 93928a791a Tests for Transaction Date 2023-02-18 08:31:05 +01:00
Gwendal Roué f649d9e19e Transaction Date 2023-02-18 08:31:05 +01:00
Gwendal Roué 31350672c7 CHANGELOG 2023-02-17 12:37:28 +01:00
Gwendal Roué 17906dc505 Table SQL interpolation
Addresses https://github.com/groue/GRDB.swift/issues/1332
2023-02-14 08:58:26 +01:00
Gwendal Roué f8f586a98c More BRAG 2023-02-10 10:07:35 +01:00
Gwendal Roué 302fc69f3a TableDefinition.primaryKey(["a", "b"]) is no longer sunsetted
People need it to define the primary key on non-consecutive columns: https://github.com/groue/GRDB.swift/discussions/1326
2023-02-10 08:11:02 +01:00
Gwendal Roué 0045592891 Merge pull request #1328 from ytti/master
Update README.md
2023-02-10 07:58:25 +01:00
ytti 69105e6f80 Update README.md
In SQLCipher passphrase as Data example, fix the use of Data instance
2023-02-09 09:36:03 +02:00
Gwendal Roué aff924a72b Upgrade Swiftlint and fix warnings 2023-02-04 11:23:14 +01:00
Gwendal Roué abaa14db83 Fix typo 2023-01-30 08:41:32 +01:00
Gwendal Roué 9b113fb548 Fix documentation 2023-01-30 08:00:47 +01:00
Gwendal Roué ac214e6760 SE-0345: if let shorthand for shadowing an existing optional variable 2023-01-30 08:00:47 +01:00
Gwendal Roué d3c289a320 Availability checks cleanup 2023-01-22 12:37:40 +01:00
Gwendal Roué c64e9f947b Merge pull request #1320 from baekteun/refactor/availabilityMacOS
UPDATE :: OSX -> macOS in Availability Check
2023-01-22 12:16:20 +01:00
Gwendal Roué 7a790c1f23 Enhance test for StatementArguments initializer from [Any]
Also, this removes a Swift 5.8 warning.
2023-01-20 17:05:58 +01:00
Gwendal Roué bc9190a1dc Document expected deprecation warnings
This addresses #1321
2023-01-17 07:44:49 +01:00
baegteun a9feac1339 ♻️ :: OSX -> macOS in Availability Check 2023-01-17 13:58:37 +09:00
Gwendal Roué 846939d632 Merge pull request #1316 from baekteun/master
✏️ :: replace OSX -> macOS in document
2023-01-16 07:56:52 +01:00
Gwendal Roué ba68e3b02d Merge branch 'development' 2023-01-15 15:30:52 +01:00
Gwendal Roué 59f98ae1fd v6.6.1 2023-01-15 15:30:40 +01:00
Gwendal Roué 590158ca3e Update license for 2023 2023-01-15 15:24:30 +01:00
Gwendal Roué 7d7724c3aa Link to Mastodon account 2023-01-15 15:21:37 +01:00
Gwendal Roué 76a065af6d Merge pull request #1317 from groue/dev/fix-1315
Fix removal of prefetched associations
2023-01-15 15:12:17 +01:00
Gwendal Roué 2976e81a95 Fix failing test for #1315 2023-01-15 13:39:05 +01:00
Gwendal Roué fb547c1a15 Failing test for #1315 2023-01-15 13:27:04 +01:00
Gwendal Roué 38ce06d263 OrderedDictionary.description 2023-01-14 12:33:41 +01:00
Gwendal Roué 3794e7e801 DatabasePromise.description 2023-01-14 12:21:08 +01:00
baegteun 557ad3d3d3 OS X -> macOS in Remake or CHANGELOG.md 2023-01-14 11:43:27 +09:00
baegteun 70a35afad8 OSX -> macOS in CHANGELOG.md 2023-01-14 11:39:13 +09:00
baegteun 4a5713502f OSX.gitignore -> macOS.gitignore 2023-01-14 11:38:02 +09:00
Gwendal Roué c3cc998fc1 Merge branch 'development' 2022-12-29 14:12:13 +01:00
Gwendal Roué 0f0f33d0d1 v6.6.0 2022-12-29 14:06:18 +01:00
Gwendal Roué 0b92c856ae Upgrade demo apps 2022-12-29 14:06:18 +01:00
Gwendal Roué 6e2e1f4889 Update documentation links 2022-12-29 14:06:18 +01:00
Gwendal Roué 0dd17a9a16 Turn ValueObservationScheduler into a protocol 2022-12-29 12:38:06 +01:00
Gwendal Roué 4100b0627f DatabaseCursor DocC 2022-12-18 11:58:03 +01:00
Gwendal Roué c50cfd937e DocC: DatabaseQueue and DatabasePool 2022-12-18 11:45:28 +01:00
Gwendal Roué 3d7170f1bc DocC: Configuration 2022-12-17 10:11:36 +01:00
Gwendal Roué 2c5a86479a DocC: Transactions and Savepoints 2022-12-17 10:11:36 +01:00
Gwendal Roué 119f226610 DocC: GeneratedColumnQualification 2022-12-12 08:42:18 +01:00
Gwendal Roué d2db26d570 Merge pull request #1301 from groue/dev/xcode-14.2
CI Cleanup
2022-12-10 16:50:44 +01:00
Gwendal Roué 82ed41b700 Remove junk from Makefile 2022-12-10 15:17:44 +01:00
Gwendal Roué 639eadbad2 CI: more Xcode 14.1 2022-12-10 14:20:42 +01:00
Gwendal Roué 4ff3221feb CI: explicit iOS and tvOS tests 2022-12-10 14:04:00 +01:00
Gwendal Roué a61a769da9 CI: explicit macOS tests 2022-12-10 13:26:53 +01:00
Gwendal Roué 04bdafd448 Makefile change triggers Github workflow 2022-12-10 13:19:10 +01:00
Gwendal Roué 5fa5e62d0e CHANGELOG 2022-12-10 13:06:39 +01:00
Gwendal Roué 1d5f05351a Merge pull request #1304 from groue/dev/generated-columns
Expose generated columns with availability checks
2022-12-10 13:04:09 +01:00
Gwendal Roué 05da03ab1a Expose generated columns with availability checks 2022-12-10 11:32:23 +01:00
Gwendal Roué 7b63ddf542 Merge branch 'development' 2022-12-05 11:19:16 +01:00
Gwendal Roué 13860219be v6.5.0 2022-12-05 11:18:59 +01:00
Gwendal Roué 4cbf442cc8 Merge pull request #1299 from groue/dev/find
Record.find() convenience methods
2022-11-30 22:48:58 +01:00
Gwendal Roué 2bde3e11bc Tests for find(_🔑) and find(_🆔) 2022-11-30 21:39:44 +01:00
Gwendal Roué 5ab7bfb229 recordNotFound returns an error instead of Never
https://forums.swift.org/t/methods-that-throw-and-return-never/61715
2022-11-30 21:33:15 +01:00
Gwendal Roué 520766a74e CHANGELOG 2022-11-30 20:07:42 +01:00
Gwendal Roué 6c16a9a4e5 Document the find method 2022-11-30 20:02:24 +01:00
Gwendal Roué 726022d5a5 Support for legacy urls 2022-11-30 19:52:55 +01:00
Gwendal Roué 4a4ff9950c FetchableRecord.find() methods 2022-11-30 19:36:25 +01:00
Gwendal Roué afc578db7f TableRecord.recordNotFound() methods 2022-11-30 19:36:08 +01:00
Gwendal Roué df3bd46346 Rename PersistenceError to RecordError 2022-11-30 19:11:07 +01:00
Gwendal Roué 08ec50f44b Enhance documentation for explicit rowid support 2022-11-28 21:09:48 +01:00
Gwendal Roué 156ed53588 Remove obsolete documentation comment 2022-11-28 21:05:30 +01:00
Gwendal Roué f9cfadce78 CHANGELOG 2022-11-28 20:57:48 +01:00
Gwendal Roué 2269a82479 CHANGELOG 2022-11-28 18:43:26 +01:00
Gwendal Roué 8330469ac3 Merge branch 'development' 2022-11-28 17:14:48 +01:00
Gwendal Roué 72f56a1b03 v6.4.0 2022-11-28 13:29:23 +01:00
Gwendal Roué cbd05c9037 Fix documentation link 2022-11-28 13:28:35 +01:00
Gwendal Roué a27c34e635 CHANGELOG 2022-11-28 13:19:56 +01:00
Gwendal Roué 35019f7a36 Merge pull request #1297 from groue/experimental/expose-CSQLite
SPM: expose the CSQLite product
2022-11-28 11:40:28 +01:00
Gwendal Roué 69e4706549 Expose CSQLite as a SPM product 2022-11-28 10:37:39 +01:00
Gwendal Roué 65bd4d90c2 Enhance DatabaseRegionObservation documentation 2022-11-28 08:36:30 +01:00
Gwendal Roué 7343912ac3 Fix broken links 2022-11-28 08:31:45 +01:00
Gwendal Roué 409bd3bb26 Move Database Observation documentation to DocC 2022-11-28 08:27:12 +01:00
Gwendal Roué fed4833764 Move DatabaseRegionObservation documentation to DocC 2022-11-27 18:45:48 +01:00
Gwendal Roué e3cc15707a Move ValueObservation documentation to DocC 2022-11-27 18:27:26 +01:00
Gwendal Roué 5302b98a15 http -> https 2022-11-27 15:12:57 +01:00
Gwendal Roué ef019bb9da CHANGELOG 2022-11-27 15:05:45 +01:00
Gwendal Roué 35e60f2b97 Precision 2022-11-27 14:48:43 +01:00
Gwendal Roué 2e2b79a3a9 The technique for exposing rowids to record types has moved to DocC 2022-11-27 14:29:14 +01:00
Gwendal Roué 7bd1992e61 Fix ergonomics issue with the definition of compound primary key
If the user would forget the PrimaryKeyDefinition, the primary was not defined:

try db.create(table: "membership") { t in
    // WRONG: pk is unused
    t.primaryKey { pk in
        t.column("playerId", .integer)
        t.column("teamId", .text)
    }
}

The fix is to remove the PrimaryKeyDefinition:

try db.create(table: "membership") { t in
    t.primaryKey {
        t.column("playerId", .integer)
        t.column("teamId", .text)
    }
}
2022-11-27 14:09:25 +01:00
Gwendal Roué f8728bbed8 Enhance documentation 2022-11-27 13:01:42 +01:00
Gwendal Roué f774aa7c07 Fix tests for named in-memory database 2022-11-27 12:46:59 +01:00
Gwendal Roué 7a9b8093ed Fix Swiftlint warnings 2022-11-27 12:46:23 +01:00
Gwendal Roué c7df15faf5 CHANGELOG 2022-11-27 12:41:00 +01:00
Gwendal Roué f5ebf0de4d Use primary key definitions with NOT NULL constraint by default 2022-11-27 12:35:47 +01:00
Gwendal Roué cd16e921fe Tests for primary key definition with NOT NULL constraint by default 2022-11-27 11:47:56 +01:00
Gwendal Roué 8b8e480391 Primary key definition with NOT NULL constraint by default 2022-11-27 11:32:38 +01:00
Gwendal Roué 3074b61cb7 Move schema documentation to DocC 2022-11-27 11:07:13 +01:00
Gwendal Roué d91e6c2db6 Add schema recommendations to DatabaseSchema.md 2022-11-26 17:09:58 +01:00
Gwendal Roué a0bfbafd9c Add tests for MutablePersistableRecord on tables without explicit primary key 2022-11-26 16:27:27 +01:00
Gwendal Roué 4e4699ebed Improve inline documentation 2022-11-26 16:26:46 +01:00
Gwendal Roué 6295f4609e More precise WALSnapshot creation errors 2022-11-25 08:31:47 +01:00
Gwendal Roué e430b4ebd7 DatabaseSnapshotReader reentrant read is not unsafe 2022-11-25 08:15:14 +01:00
Gwendal Roué 4ff8928dc4 Simplify declaration of ValueObservation factory methods (SE-0267) 2022-11-23 19:46:00 +01:00
Gwendal Roué 10596e17bf Cleanup snapshot configurations 2022-11-23 19:42:12 +01:00
Gwendal Roué 392e9e447d Shared in-memory databases 2022-11-23 18:32:57 +01:00
Gwendal Roué e8f1e76958 Enhance documentation 2022-11-18 17:45:51 +01:00
Gwendal Roué 131f414a75 Enhance DatabaseSchema.md 2022-11-18 13:49:28 +01:00
Gwendal Roué d4cefc984f Update documentation index 2022-11-18 13:33:28 +01:00
Gwendal Roué 2dce8d533e Project organization 2022-11-18 13:33:28 +01:00
Gwendal Roué dc43607921 Cleanup 2022-11-18 13:33:28 +01:00
Gwendal Roué 0ba3dff901 Rewrite availability check for WAL snapshots
Also, enable WAL snapshots with SQLCipher, if SQLITE_ENABLE_SNAPSHOT is set.
2022-11-18 13:33:28 +01:00
Gwendal Roué fcf8ac43b7 Delete obsolete comment 2022-11-18 12:41:15 +01:00
Gwendal Roué 9b4d76ca37 Robustness: DatabaseSnapshotPool discards connections that have lost the snapshot 2022-11-18 08:53:39 +01:00
Gwendal Roué 9b663e3bcc Pool can discard elements after use 2022-11-18 08:52:52 +01:00
Gwendal Roué 847386860f Fix test compilation on Xcode 14
Grrr
2022-11-17 22:48:13 +01:00
Gwendal Roué 8a42c11624 DatabaseSnapshotPool documentation 2022-11-17 22:38:41 +01:00
Gwendal Roué e4c5cc3451 Test that DatabaseSnapshotPool can be used from ValueObservation 2022-11-17 22:04:06 +01:00
Gwendal Roué 79d4db7827 More DatabaseSnapshotPool tests 2022-11-17 21:56:01 +01:00
Gwendal Roué b1770e89b7 Introduce DatabaseSnapshotReader 2022-11-17 20:11:58 +01:00
Gwendal Roué 12d656d3a1 Let SQLite check if DatabaseSnapshotPool can be created 2022-11-17 20:01:17 +01:00
Gwendal Roué 0bc49460d7 DatabaseSnapshotPool uses its own pool of connections
In the previous implementation, the snapshot pool would use the same reader connections as the database pool. This would create problem with reentrant reads. Let's make things simple, and not share any database connection.
2022-11-17 18:36:17 +01:00
Gwendal Roué 2743ded335 Merge pull request #1293 from groue/experimental/WALSnapshotToken
Enable concurrent reads from a WAL snapshot
2022-11-14 20:53:26 +01:00
Gwendal Roué e129df15db Fix tests for Xcode 14.0 2022-11-14 19:29:17 +01:00
Gwendal Roué c4c0b1ce90 Test and fix unsafe and async DatabaseSnapshotPool 2022-11-14 19:10:52 +01:00
Gwendal Roué 9ac8c0703d Remove dead code 2022-11-14 19:02:10 +01:00
Gwendal Roué 433ed36a4b More documentation about transactions 2022-11-14 18:51:39 +01:00
Gwendal Roué c23b93d71b Document that reentrant database accesses use the current database connection when possible 2022-11-14 18:38:33 +01:00
Gwendal Roué b8bc8273a9 Turn snapshot tokens into a proper reader: DatabaseSnapshotPool 2022-11-14 18:22:13 +01:00
Gwendal Roué bcb70855d5 Enhance WALSnapshotToken documentation 2022-11-14 10:42:09 +01:00
Gwendal Roué eaf8dc239a Simplify WALSnapshotToken creation 2022-11-14 10:39:48 +01:00
Gwendal Roué 6864e6b2fb Enhance registerAccess(to:) documentation 2022-11-14 08:47:58 +01:00
Gwendal Roué 4b21704258 CHANGELOG 2022-11-13 18:35:59 +01:00
Gwendal Roué a71eb3d662 Introduce WALSnapshotToken 2022-11-13 18:28:54 +01:00
Gwendal Roué dffe56f8a9 Simplify ValueReducer definition 2022-11-13 18:09:06 +01:00
Gwendal Roué 4871304c60 Enable WALSnapshot on macOS (Xcode 14.1+) 2022-11-13 15:29:44 +01:00
Gwendal Roué a6f9b1c4b7 CHANGELOG 2022-11-13 10:55:31 +01:00
Gwendal Roué cbac0e7286 Enhance Configuration.threadingMode documentation 2022-11-13 10:54:40 +01:00
Gwendal Roué 997d6cb677 DatabaseSnapshot does not require the WAL mode
One can create a snapshot from a read-only pool on a non-WAL database, and that's OK. The snaphost still sees an unchanging database content (but other connections can't write).
2022-11-13 10:54:40 +01:00
Gwendal Roué 51230834c8 Configuration.maximumReaderCount can be queried
This is useful for tools that adapt their own inner scheduling to the actual capacity for concurrent reads.
2022-11-13 10:54:40 +01:00
Gwendal Roué 638e586dbc Expose Database.registerAccess(to:)
This helps tools that intend to declare an observed region without directly accessing it. This will be necessary for (future) snapshot-based observations that postpone actual database access.
2022-11-13 10:54:40 +01:00
Gwendal Roué 6dc4d50e00 Expose Configuration.readQoS and writeQoS
This helps tools that perform their own asynchronous jobs that depend on database scheduling. By using the same QoS as the database, they won't create priority inversion or similar scheduling misuses.
2022-11-12 11:55:37 +01:00
Gwendal Roué 5d50e396c1 Enhance Configuration documentation 2022-11-12 11:55:37 +01:00
Gwendal Roué 981d42aed6 Execute SPM tests in parallel 2022-11-12 11:55:37 +01:00
Gwendal Roué 8ffceb49c8 Document SPI_BUILDER 2022-11-11 15:14:59 +01:00
Gwendal Roué b14ef2112c Fix documentation typo 2022-11-11 12:55:35 +01:00
Gwendal Roué 2d31ed4618 Merge branch 'development' 2022-11-11 11:34:48 +01:00
Gwendal Roué 5e7b604ecd v6.3.1 2022-11-11 11:34:02 +01:00
Gwendal Roué 90ec3c188b Host documentation on SPI 2022-11-11 11:34:02 +01:00
Gwendal Roué 1625bc83f8 Documentation organization 2022-11-11 11:34:02 +01:00
Gwendal Roué be9740b5f6 Discourage usage of reentrant by linking to the related doc 2022-11-10 08:50:41 +01:00
Gwendal Roué f914fe73ff DocC Concurrency Resources 2022-11-10 08:34:54 +01:00
Gwendal Roué 57b07515c7 Rename GRDB_DOCC_PLUGIN to SPI_BUILDER
This addresses https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/2122#issuecomment-1305649066
2022-11-09 21:56:19 +01:00
Gwendal Roué 9d03c1ae61 DocC: Single-Row Tables 2022-11-09 21:54:17 +01:00
Gwendal Roué 3014ddb00a Enhance Documentation 2022-11-09 21:52:22 +01:00
Gwendal Roué 85b2e113b2 Relocate DatabaseSnapshot documentation 2022-11-09 17:16:03 +01:00
Gwendal Roué c5a0598cea DocC: Concurrency Guides 2022-11-09 13:22:53 +01:00
Gwendal Roué 5242fe10f6 Enhance Documentation 2022-11-09 13:22:53 +01:00
Gwendal Roué 71880a9b8e Enhance Documentation 2022-11-09 13:20:08 +01:00
Gwendal Roué 14fb1945be Fix documentation 2022-11-08 22:57:48 +01:00
Gwendal Roué 33cdf6f270 Extract <doc:DatabaseSchema> 2022-11-08 19:28:13 +01:00
Gwendal Roué ca079cab17 TODO 2022-11-08 19:28:09 +01:00
Gwendal Roué 0873474a17 DocC: SQL 2022-11-08 18:22:03 +01:00
Gwendal Roué bfe2450da5 Fix typo 2022-11-08 08:53:59 +01:00
Gwendal Roué 19b0b6af3e http -> https 2022-11-08 08:45:37 +01:00
Gwendal Roué cdf480ef1f Migrations guide cleanup 2022-11-08 08:41:10 +01:00
Gwendal Roué da3059f0a8 fix typos and wordings 2022-11-08 05:43:09 +01:00
Gwendal Roué 754ced7b5e Enhance DocC output for ForeignKeyViolation 2022-11-07 22:50:50 +01:00
Gwendal Roué fb81ec6792 Migrations Guide in now a DocC article 2022-11-07 22:44:37 +01:00
Gwendal Roué 1be868c4b0 Fix documentation typo 2022-11-07 09:16:50 +01:00
Gwendal Roué 4dda8d7650 Host DocC on Github pages
SPI will be up soon, but we have to fix the dead links currently published on the master branch

https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/discussions/2120
2022-11-07 08:14:39 +01:00
Gwendal Roué 16fe4331f2 make doc generates DocC for hosting on Github pages
Example: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb
2022-11-07 08:14:39 +01:00
Gwendal Roué 5ff2ad9e71 Merge branch 'development' 2022-11-06 20:47:53 +01:00
Gwendal Roué f5259af512 v6.3.0 2022-11-06 20:47:03 +01:00
Gwendal Roué 2dd2d2db35 Makefile no longer needs to be updated on each release 2022-11-06 20:46:53 +01:00
Gwendal Roué 9fd3e822e5 More links to future SPI-hosted pages 2022-11-06 20:45:48 +01:00
Gwendal Roué edbfc7749c Merge pull request #1291 from groue/dev/DocC
DocC inline documentation
2022-11-06 20:36:46 +01:00
Gwendal Roué 2aa7e3c79f Makefile: support for Xcode 14.1 2022-11-06 19:42:49 +01:00
Gwendal Roué 3592db997a Makefile: allow disabling min iOS destination 2022-11-06 19:05:38 +01:00
Gwendal Roué 4307f6a680 Fix Swiftlint warnings 2022-11-06 18:43:00 +01:00
Gwendal Roué b7b83a965b Update the Swift Package Index manifest file 2022-11-06 18:11:18 +01:00
Gwendal Roué fcfecc5a73 Update Release Process 2022-11-06 18:09:49 +01:00
Gwendal Roué 39a76ff929 Links to future SPI-hosted pages 2022-11-06 18:09:09 +01:00
Gwendal Roué aef2d087ae CHANGELOG 2022-11-06 17:50:40 +01:00
Gwendal Roué 0b12e89e62 DocC: AssociationAggregate 2022-11-06 17:18:27 +01:00
Gwendal Roué 0379947ab1 Rename DocC article about SQL 2022-11-06 16:57:27 +01:00
Gwendal Roué 2e5cf546c6 DocC: RowAdapter 2022-11-06 16:45:13 +01:00
Gwendal Roué 0c011b970b Add missing experimental notices 2022-11-06 16:31:12 +01:00
Gwendal Roué a08a86cc76 Update CONTRIBUTING.md 2022-11-06 16:24:34 +01:00
Gwendal Roué 29a21302a2 Generate documentation in ~/Sites/GRDB 2022-11-06 16:02:36 +01:00
Gwendal Roué 13c804d1cc DocC 2022-11-06 16:02:36 +01:00
Gwendal Roué 811d287bd9 Row.withUnsafeData 2022-11-06 16:02:36 +01:00
Gwendal Roué 1818534513 DocC 2022-11-06 16:02:36 +01:00
Gwendal Roué 8d316dc969 Test insertAndFetch with IGNORE policy 2022-11-06 16:02:36 +01:00
Gwendal Roué 38e7e649c7 Upgrade GRDBPerformance dependencies 2022-10-29 17:10:16 +02:00
Gwendal Roué 3df9e8e5c1 Merge branch 'development' 2022-10-29 16:49:28 +02:00
Gwendal Roué c98d918bf6 v6.2.0 2022-10-29 15:36:01 +02:00
Gwendal Roué c197e2f520 Don't run unicode61 tokenizer categories tests before SQLite 3.25.0 2022-10-29 15:04:09 +02:00
Gwendal Roué 13b3f1d741 Github workflow: use Xcode 14.0.1 2022-10-29 14:35:54 +02:00
Gwendal Roué ad011a0974 CHANGELOG 2022-10-29 14:21:33 +02:00
Gwendal Roué a89dad2554 Fix Swiftlint warnings 2022-10-29 14:21:33 +02:00
Gwendal Roué 4f4553f4f0 Regression tests for tokenizer arguments quoting 2022-10-29 14:21:33 +02:00
Gwendal Roué 9b505bb34b Fix quoting of FTS5 tokenizer arguments
Tokenizer arguments only need to be quoted ("foo" -> "'foo'") when we generate SQL for a tokenizer. They must not be quoted when we instantiate a tokenizer with the fts5_tokenizer.xCreate function.

This commit fixes tokenizer instantiation by not quoting arguments when we call the fts5_tokenizer.xCreate function.

Before this fix, the FTS5Tokenizer.tokenize(query:) method would return incorrect tokens.
2022-10-29 14:21:33 +02:00
Gwendal Roué 6c841bf96e Merge pull request #1289 from idkclub/categories
Add support for passing in categories to the unicode61 tokenizer
2022-10-29 14:08:47 +02:00
Jon 76b05369ff Add support for passing in categories to the unicode61 tokenizer 2022-10-21 16:21:07 -04:00
Gwendal Roué e79b6a5622 Fix typo 2022-10-21 08:50:01 +02:00
Gwendal Roué 13e1f4d7c2 Merge branch 'development' 2022-10-20 14:08:36 +02:00
Gwendal Roué 8aaf1af9f0 v6.1.0 2022-10-20 13:23:37 +02:00
Gwendal Roué 3b10e1df41 CHANGELOG 2022-10-20 13:19:54 +02:00
Gwendal Roué 6caa27cb20 Merge pull request #1288 from jcavar/feature/strict-support
Add support for .strict table option in 3.37+
2022-10-20 13:00:07 +02:00
Gwendal Roué 6ca3bb051a make smokeTest checks SQLCipher 3
It's better to quickly catch failures to support SQLCipher 3.
2022-10-20 08:49:48 +02:00
Gwendal Roué 901d010ab3 Restore the test that strict tables won't accept ill-typed values. 2022-10-20 08:46:49 +02:00
Gwendal Roué 3c4ff5b26e Single test for strict tables
Also, skip the test for old SQLCipher version.
2022-10-20 08:46:49 +02:00
Gwendal Roué 2ade133b50 Move availability check below doc comment 2022-10-20 08:27:46 +02:00
Josip Cavar c57e76be52 Add support for .strict table option in 3.37+ 2022-10-19 15:55:46 +02:00
Gwendal Roué 9531a7f8fc More specialization 2022-09-17 15:49:28 +02:00
Gwendal Roué 9e3eebf4c2 Merge pull request #1279 from daveverwer/add-spi-documentation
Added an external documentation link for the Swift Package Index
2022-09-17 12:46:35 +02:00
Gwendal Roué 1221cb703a Update link to documentation 2022-09-17 12:45:55 +02:00
Dave Verwer 59b40de83e Added a Swift Package Index manifest with an external documentation link. 2022-09-14 12:15:46 +01:00
Gwendal Roué 0ac435744a Merge branch 'development' 2022-09-09 11:50:22 +02:00
Gwendal Roué 589e53b231 v6.0.0 2022-09-09 11:40:39 +02:00
Gwendal Roué 125f112fb7 CHANGELOG 2022-09-09 11:34:58 +02:00
Gwendal Roué c6aa323cd8 Skip flaky test 2022-09-09 09:50:25 +02:00
Gwendal Roué 1c7b618a89 Parallelizable tests 2022-09-09 09:33:57 +02:00
Gwendal Roué d3ad7acd59 No WALSnapshot on macOS and macOS Catalyst
Fix #1276
2022-09-09 08:16:55 +02:00
Gwendal Roué 82b4d90a82 Xcode 14 RC doesn't ship with the Swift 5.6 stdlib
https://forums.swift.org/t/xcode-14-rc-cannot-specialize-protocol-type/60171
2022-09-09 08:16:55 +02:00
Gwendal Roué 2a3318ef9a ALTER TABLE DROP COLUMN is properly reported with SQLITE_ALTER_TABLE for SQLite 3.38+ 2022-09-07 08:51:05 +02:00
Gwendal Roué f2c46784a6 ArrayRowImpl is checked Sendable 2022-09-07 08:50:32 +02:00
Gwendal Roué 9340fdc7c2 DatabaseValue.Storage is checked Sendable 2022-09-07 08:02:34 +02:00
Gwendal Roué b0f7493765 BREAKING: rename request methods that build a DatabasePromise
This creates an opportunity for future `request.filter { ... }` apis that look like standard ones. Why not `Player.filter { $0.score > 1000 }` eventually, perhaps with code generation?
2022-09-06 22:56:40 +02:00
Gwendal Roué 30234fde62 CHANGELOG 2022-09-06 08:54:29 +02:00
Gwendal Roué fdbcb07452 Fix #1275 2022-09-06 08:25:21 +02:00
Gwendal Roué dced16bdce Update SQLiteCustom to v3.39.3 2022-09-05 20:43:51 +02:00
Gwendal Roué 849be02906 Remove useless Xcode requirements in documentation
GRDB 6 requires Xcode 14+, Swift concurrency is always available.
2022-09-05 20:32:50 +02:00
Gwendal Roué b3f5b892a6 CHANGELOG 2022-09-05 08:46:05 +02:00
Gwendal Roué 65efc413fe Fix for failing test for #1274
https://github.com/groue/GRDB.swift/discussions/1274
2022-09-05 08:43:43 +02:00
Gwendal Roué f3b8b7221c Failing test for #1274
https://github.com/groue/GRDB.swift/discussions/1274
2022-09-05 08:42:29 +02:00
Gwendal Roué f04a02731d Add defaultLocalization to GRDB package
This solves the "manifest property 'defaultLocalization' not set; it is required in the presence of localized resources" error
2022-09-04 14:09:35 +02:00
Gwendal Roué 6add38e3e5 BREAKING: Allow ValueObservation to perform different kinds of fetch
We're interested in allowing observations to build values based on snapshots
2022-09-04 12:06:17 +02:00
Gwendal Roué 202b3e5620 Encapsulate ValueObservation database accesses
Also, enhance Database.isolated(readOnly:) by not creating a savepoint if the database is already inside a transaction.
2022-09-04 10:11:22 +02:00
Gwendal Roué 49cce0aa8a CHANGELOG 2022-08-29 14:22:04 +02:00
Gwendal Roué ccf3486827 CHANGELOG 2022-08-29 14:21:01 +02:00
Gwendal Roué cb93979a44 Update CONTRIBUTING.md
It needed to be updated for cross-platform targets
2022-08-28 14:52:31 +02:00
Gwendal Roué 628ac58535 Merge branch 'development' 2022-08-28 13:45:17 +02:00
Gwendal Roué 373f95a6cb v6.0.0-beta.4 2022-08-28 13:44:35 +02:00
Gwendal Roué f2859ff8bf Use SQLITE_OPEN_EXRESCODE when available 2022-08-28 12:50:47 +02:00
Gwendal Roué e2b412afc8 Merge branch 'dev/TableInfo' into development 2022-08-28 12:49:59 +02:00
Gwendal Roué 040e5d9d87 WITHOUT ROWID check: prefer PRAGMA table_list when available
This avoids the undesired errors described in #945.
2022-08-28 12:28:39 +02:00
Gwendal Roué 189430c1fe PRAGMA table_list 2022-08-28 12:28:39 +02:00
Gwendal Roué 3d77a8da86 Update the manual installation documentation 2022-08-28 09:59:52 +02:00
Gwendal Roué c40256600a Update playgrounds doc 2022-08-28 09:49:34 +02:00
Gwendal Roué b617f432c0 Merge branch 'dev/cross-platform-targets' into development 2022-08-27 14:43:33 +02:00
Gwendal Roué 72ef13f4fb CHANGELOG 2022-08-27 14:43:06 +02:00
Gwendal Roué 535f44c463 Update the GRDB6 migration guide 2022-08-27 14:42:57 +02:00
Gwendal Roué 4c10899a3c Single Cross-Platform Target 2022-08-27 13:43:44 +02:00
Gwendal Roué 524ee1d098 Merge pull request #1271 from groue/dev/SQLite-3.39.2
Bump custom SQLite builds v3.39.2
2022-08-27 12:27:56 +02:00
Gwendal Roué 973b679baa CHANGELOG 2022-08-27 12:27:14 +02:00
Gwendal Roué 0321c79c2d Update SQLiteCustom to v3.39.2 2022-08-27 12:16:59 +02:00
Gwendal Roué e82a03615f Merge branch 'development' 2022-08-25 19:11:29 +02:00
Gwendal Roué 51c9071b3d v6.0.0-beta.3 2022-08-25 19:11:20 +02:00
Gwendal Roué 91e5f838d3 Merge branch 'dev/GRDB6-singleton-record' into development 2022-08-25 19:10:09 +02:00
Gwendal Roué d026232cbf CHANGELOG 2022-08-25 19:09:51 +02:00
Gwendal Roué c2e4aaf51d Throw SQLITE_MISUSE in case of programmer error in the aroundXxx callbacks
While writing SingletonRecordTest.swift, I tried the solution below, in order to turn a failed update into an insert:

    func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
        do {
            _ = try update()
        } catch {
            insert(db)
        }
    }

But this can't work. This `insert(db)` is unable to provide the information we need in `update()`: the result of the eventual RETURNING clause, and the PersistenceSuccess that contains the persisted PersistenceContainer.

So we now detect two misuses: 1) not calling the action method, and 2) not rethrowing the error of the action method.
2022-08-25 19:05:27 +02:00
Gwendal Roué 05b81df614 Update the migration guide with the actions to perform on customized records 2022-08-25 19:05:27 +02:00
Gwendal Roué 3e4b04d4d1 Test the "Single-Row Tables" guide 2022-08-25 19:05:27 +02:00
Gwendal Roué 56cdaabd9c Update the "Single-Row Tables" guide 2022-08-25 19:05:27 +02:00
Gwendal Roué c65a19c50f Merge pull request #1268 from groue/dev/issue-1267
Fix SQL generation of CHECK constraints.
2022-08-25 08:31:53 +02:00
Gwendal Roué 5247a1537c CHANGELOG 2022-08-25 08:31:20 +02:00
Gwendal Roué 58f970701f BREAKING: Fix failing test for #1267
The regression was probably due to a bad interaction between Implicitly Opened Existentials (SE-0352) and Opaque Parameter Declarations (SE-0341) which GRDB 6 now uses in a lot of places.

Considering the sample code below:

    try db.create(table: ...) { t in
      t.column(...).check { $0 != Column(...) }
    }

- The `check` method accepts a closure that returns `any SQLExpressible` (the same as GRDB 5)
- The `!=` SQL comparison operator is `(some SQLSpecificExpressible, some SQLSpecificExpressible) -> SQLExpression`, when it was `(SQLSpecificExpressible, SQLSpecificExpressible) -> SQLExpression` in GRDB 5

The compiler has started preferring interpreting the != operator as Column's Equatable implementation, instead of the `!=` SQL comparison operator

We force the compiler to use the SQL comparison operator by removing the Equatable conformance from Column. It was introduced in a70b42c, as a support for a feature that has been removed since then.

This is a breaking change, but this also is an improvement. Now `column1 != column2` has a single meaning, and the library is less prone to similar regressions in the future.
2022-08-25 08:26:37 +02:00
Gwendal Roué 980f5247f0 Failing test for #1267 2022-08-25 08:12:32 +02:00
Gwendal Roué d70032c483 Merge branch 'development' 2022-08-23 22:17:06 +02:00
Gwendal Roué 14321e411c v6.0.0-beta.2 2022-08-23 22:16:37 +02:00
Gwendal Roué d3d2ad1b91 Merge branch 'dev/upsert-documentation' into development 2022-08-23 22:10:33 +02:00
Gwendal Roué 55f3c2f510 CHANGELOG 2022-08-23 22:05:23 +02:00
Gwendal Roué ffa183821c UPSERT documentation 2022-08-23 22:05:23 +02:00
Gwendal Roué 327911d057 Upsert: add support for conflict target and assignments 2022-08-23 20:02:17 +02:00
Gwendal Roué c6657b7063 ColumnAssignment that does nothing
A cool upsert feature is to overwrite an existing value in case of conflict, but another cool upsert feature is to NOT overwrite an existing value. This commit makes it possible to create a ColumnAssignement that does nothing.
2022-08-23 20:02:17 +02:00
Gwendal Roué 2a5626efea Replace if let x = x with if let x 2022-08-22 20:40:00 +02:00
Gwendal Roué 6bf346ccf5 Merge branch 'development' 2022-08-21 21:57:30 +02:00
Gwendal Roué 1036dd4d6e v6.0.0-beta 2022-08-21 21:56:51 +02:00
Gwendal Roué 48f14c7a8c Merge pull request #1221 from groue/GRDB6/development
GRDB 6
2022-08-21 21:44:19 +02:00
Gwendal Roué 2789444acd Enable UPSERT and RETURNING with SQLCipher 2022-08-21 21:22:34 +02:00
Gwendal Roué 8f8b273424 CHANGELOG organization 2022-08-21 21:22:34 +02:00
Gwendal Roué 37f0a0bb9a BREAKING: throwing EncodableRecord.encode(to:) 2022-08-21 21:22:34 +02:00
Gwendal Roué d2dd18b3e5 Remove note and warning icons
Those are handled by Github now:
https://github.com/community/community/discussions/16925
2022-08-21 21:22:34 +02:00
Gwendal Roué 422e0ae85a BREAKING: Handles both commits and rollbacks
Replace afterNextTransactionCommit(_:) with afterNextTransaction(onCommit:onRollback:)
2022-08-21 21:22:34 +02:00
Gwendal Roué 8f562d3e11 NEW: Upsert 2022-08-21 21:22:34 +02:00
Gwendal Roué a702fe6bc9 BREAKING: persistence callbacks, and support for RETURNING
- Replace performInsert, performUpdate, etc with callbacks: willInsert, aroundInsert, didInsert, etc.
- Always call didInsert, even with INSERT OR IGNORE
- Explicit conflict resolution in persistence methods
- Add ...AndFetch... methods
2022-08-21 21:22:34 +02:00
Gwendal Roué 0ed9367b26 BREAKING: DatabaseCursor no longer exposes its prepared statement 2022-08-21 21:22:34 +02:00
Gwendal Roué eda403bd31 StatementArguments is Hashable 2022-08-21 21:22:34 +02:00
Gwendal Roué c553d2d69e Documentation 2022-08-21 21:22:34 +02:00
Gwendal Roué 5243db7fbc Spelling 2022-08-21 21:22:34 +02:00
Gwendal Roué 4ced8c78e7 Less "iff" (some people think this is a typo)
iff = if and only if
2022-08-21 21:22:34 +02:00
Gwendal Roué c38d903f4d Make RequestProtocols.swift easier to read 2022-08-21 21:22:34 +02:00
Gwendal Roué 1239c14e6d Explicit initializers for HasOneThrough and HasManyThrough associations 2022-08-21 21:22:34 +02:00
Gwendal Roué 5004994344 TODO 2022-08-21 21:22:34 +02:00
Gwendal Roué c86581dedc Make SQLQueryGenerator.swift easier to read 2022-08-21 21:22:34 +02:00
Gwendal Roué 546bba17fb Make LockedBox.swift easier to read 2022-08-21 21:22:34 +02:00
Gwendal Roué 27b65c9a80 BREAKING: Starting DatabaseRegionObservation returns a cancellable 2022-08-21 21:22:34 +02:00
Gwendal Roué 1bfba945d3 Fix invalid Swift syntax in documentation 2022-08-21 21:22:34 +02:00
Gwendal Roué 4c73456f86 Make SQL.swift easier to read 2022-08-21 21:22:34 +02:00
Gwendal Roué 84940af3dc Cleanup statement separator character set 2022-08-21 21:22:34 +02:00
Gwendal Roué e0786537db BREAKING: replace Int32 with CInt everywhere it is possible 2022-08-21 21:22:34 +02:00
Gwendal Roué 496c2ae359 Make Database+Statements.swift easier to read 2022-08-21 21:22:34 +02:00
Gwendal Roué 5b7c58faf4 Make Database+Schema.swift easier to read 2022-08-21 21:22:34 +02:00
Gwendal Roué 0658808028 Make Database.swift easier to read
Enhance documentation, and rename some types and variables.
2022-08-21 21:22:34 +02:00
Gwendal Roué fb6ea57d74 Don’t setup database observation in read-only connections.
Observation of read-only connections has turned useless since read-only transactions are no longer reported to TransactionObserver, in #1213
2022-08-21 21:22:34 +02:00
Gwendal Roué 0879311646 Make TransactionObserver.swift easier to read
Add some documentation, and rename some types and variables.
2022-08-21 21:22:34 +02:00
Gwendal Roué 2f2cccacf9 Remove UI tests of demo apps, since GRDBQuery is tested on its own
(Don't test the framework)
2022-08-21 21:22:34 +02:00
Gwendal Roué e5d10ed8c1 fix async AppDatabaseTests tests 2022-08-21 21:22:34 +02:00
Gwendal Roué 070ee2c796 Makefile: disable -warn-concurrency and -enable-actor-data-race-checks
This creates issues with Xcode 14 beta 4
2022-08-21 21:22:34 +02:00
Gwendal Roué 9a9406a69d SE-0353: Constrained Existential Types
https://github.com/apple/swift-evolution/blob/main/proposals/0353-constrained-existential-types.md
2022-08-21 21:22:34 +02:00
Gwendal Roué b2eafd4a13 SE-0361: Extensions on bound generic types
https://github.com/apple/swift-evolution/blob/main/proposals/0361-bound-generic-extensions.md
2022-08-21 21:22:34 +02:00
Gwendal Roué 36892fee55 BREAKING: Bump minimum SQLite version to 3.19.3 2022-08-21 21:22:34 +02:00
Gwendal Roué 49a66e197b Foster some FetchRequest<...> in the documentation 2022-08-21 21:22:34 +02:00
Gwendal Roué 80ec31f588 BREAKING: remove DerivableRequest.limit(_:offset:) 2022-08-21 21:22:34 +02:00
Gwendal Roué c26ed6c280 NEW: throw decoding errors 2022-08-21 21:22:34 +02:00
Gwendal Roué eb98541923 Documentation 2022-08-21 21:22:34 +02:00
Gwendal Roué 895964de16 BREAKING: Throwing FetchableRecord.init(row:) 2022-08-21 21:22:34 +02:00
Gwendal Roué 927fc21f00 NEW: ValueObservation.map accepts a throwing closure
This will allow us to call a throwing FetchableRecord.init(row:) from this operator
2022-08-21 21:22:34 +02:00
Gwendal Roué a15f731042 BREAKING: remove Record.copy()
This will allow FetchableRecord.init(row:) to throw
2022-08-21 21:22:34 +02:00
Gwendal Roué 3000cd3c7f TODO 2022-08-21 21:22:34 +02:00
Gwendal Roué 2011776cbe Remove misleading comments 2022-08-21 21:22:34 +02:00
Gwendal Roué 33a039717c Refer to UIApplication notifications by their names
It looks like FB9801372 was fixed
2022-08-21 21:22:34 +02:00
Gwendal Roué a20d543bcf Swiftlint: disable the for_where rule 2022-08-21 21:22:34 +02:00
Gwendal Roué 55445dcc7c NEW: RangeReplaceableCollection.append(contentsOf: cursor) 2022-08-21 21:22:34 +02:00
Gwendal Roué 34a4fa6444 TODO 2022-08-21 21:22:34 +02:00
Gwendal Roué dba7f1b2dc BREAKING: turn Cursor.isEmpty into a property
https://github.com/apple/swift-evolution/blob/main/proposals/0310-effectful-readonly-properties.md
2022-08-21 21:22:34 +02:00
Gwendal Roué 180c8975ac Stop using #filePath 2022-08-21 21:22:34 +02:00
Gwendal Roué 11a6d53d8a SE-0326: closure result type inference
https://github.com/apple/swift-evolution/blob/main/proposals/0326-extending-multi-statement-closure-inference.md
2022-08-21 21:22:34 +02:00
Gwendal Roué 42987dd849 Cleanup filter(rawKeys:) 2022-08-21 21:22:34 +02:00
Gwendal Roué 7ffc332327 BREAKING: replace selectID() with selectPrimaryKey(as:)
Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type:

    struct Player: Identifiable, MutablePersistableRecord {
        var id: Int64?
    }

    Player.selectID() // QueryInterface<Int64?>

This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.

Instead, we introduce selectPrimaryKey(as:), which allows the user to provide the desired type.

    Player.selectPrimaryKey(as: Int64.self) // QueryInterface<Int64>
2022-08-21 21:22:34 +02:00
Gwendal Roué a9fcf1b9c1 SE-0335, SE-0341, SE-0346, SE-0352, SE-0358: some, any, primary associated types 2022-08-21 21:22:34 +02:00
Gwendal Roué c0c6b34869 SE-0346: primary associated types 2022-08-21 21:22:34 +02:00
Gwendal Roué dd55175978 SE-0345: if let x { }
https://github.com/apple/swift-evolution/blob/main/proposals/0345-if-let-shorthand.md
2022-08-21 21:22:34 +02:00
Gwendal Roué 58293befc9 BREAKING: Optional is a database value like others 2022-08-21 21:22:34 +02:00
Gwendal Roué 458e1e2675 BREAKING: throwing DatabaseQueue() initializer
As a consequence, FTS3.tokenize(_:) is a throwing method as well.
2022-08-21 21:22:33 +02:00
Gwendal Roué 6f0d45eedb BREAKING: throwing DatabaseWriter.barrierWriteWithoutTransaction
It used to be rethrowing, but it was then unable to deal with closed databases.

The async version is modified accordingly: it accepts a Result<Database, Error>, instead of a raw Database.

DatabaseMigrator.asyncMigrate is impacted as well: it accepts a Result<Database, Error>, instead of a (Database, Error?) tuple.
2022-08-21 19:21:57 +02:00
Gwendal Roué fe225fe452 BREAKING: Remove deprecated methods 2022-08-21 19:21:57 +02:00
Gwendal Roué 78b9c543a3 Swift 5.7 required: SPM testing convenience
Make it possible to test SQLITE_ENABLE_FTS5 and SQLITE_ENABLE_PREUPDATE_HOOK with `make test_SPM`.

This is very handy because Xcode 14 beta 3 has difficulties testing GRDBCustom.
2022-08-21 19:21:57 +02:00
Gwendal Roué 86de843bda Swift 5.7 required: Xcode 14 updates 2022-08-21 19:21:57 +02:00
Gwendal Roué 20dcab75c7 Swift 5.7 required: SPM resources 2022-08-21 19:21:57 +02:00
Gwendal Roué 23cbf13af0 Swift 5.7 required: Availability checks 2022-08-21 19:21:57 +02:00
Gwendal Roué 6da7d47394 Swift 5.7 required: Remove compiler checks 2022-08-21 19:21:57 +02:00
Gwendal Roué fcb037bdf0 Swift 5.7 required: Bump deployment targets 2022-08-21 19:21:57 +02:00
Gwendal Roué df0ae43c5f Swift 5.7 required: Sendable 2022-08-21 19:21:26 +02:00
Gwendal Roué fc59b45493 Swift 5.7 required: Package.swift 2022-08-21 19:21:26 +02:00
Gwendal Roué a22113faa5 Swift 5.7 required: podspec 2022-08-21 19:21:26 +02:00
Gwendal Roué d1a32d1950 Swift 5.7 required: Makefile 2022-08-21 19:21:26 +02:00
Gwendal Roué e150ca6864 Migration guide to GRDB 6 2022-08-21 19:21:26 +02:00
Gwendal Roué 9d7e27ced1 Add support for index origin 2022-07-25 08:07:27 +02:00
Gwendal Roué df7ba20ff2 Test columnInfos(in:) for views 2022-07-24 15:17:20 +02:00
Gwendal Roué 8dc0168841 Database.sqliteConnection setter is private 2022-07-24 15:14:35 +02:00
Gwendal Roué 23f4254ae3 Merge branch 'development' 2022-07-09 18:28:22 +02:00
Gwendal Roué 2df6a17c1c v5.26.0 2022-07-09 18:27:57 +02:00
Gwendal Roué 5aeee0e429 CHANGELOG 2022-07-09 17:17:27 +02:00
Gwendal Roué 3a61a8a0e0 Merge pull request #1253 from george-signal/george-signal/optional-memory-management
Make memory management optional.
2022-07-09 17:14:11 +02:00
Gwendal Roué e0766449f1 Fix compilation error on iOS Xcode 13.3.1.app, macOS 12, Swift 5.6 2022-07-09 16:14:37 +02:00
Gwendal Roué c1e752132c Document why DatabasePool.releaseMemory() needs a barrier 2022-07-09 14:28:09 +02:00
Gwendal Roué 6ab90a03c4 Document releaseMemoryEventually and automaticMemoryManagement 2022-07-09 14:00:00 +02:00
Gwendal Roué 23fa42a3e4 Make Database.releaseMemory() public
This allows us to document how to release memory asynchronously with a DatabaseQueue (in the next commit)
2022-07-09 13:55:39 +02:00
Gwendal Roué 07eaeee123 automaticMemoryManagement tests check for actual connection closing 2022-07-09 13:39:39 +02:00
Gwendal Roué 0bfb4de02d Enhance DatabaseQueue automatic memory management
We have async methods, now: no need to use a global dispatch queue.
2022-07-09 13:39:11 +02:00
Gwendal Roué d72b7109ad DatabasePool automatic memory management no longer uses any reader barrier
This fixes the failing `testDatabasePoolDoesNotPreventConcurrentReadsOnPressureEvent` test
2022-07-09 13:39:11 +02:00
Gwendal Roué e1a63a4c05 Introduce DatabasePool.releaseMemoryEventually 2022-07-09 13:33:01 +02:00
Gwendal Roué caab403282 Failing test for concurrent read on memory warning 2022-07-09 13:31:15 +02:00
George Nachman bbe94a9607 Make memory management optional.
Memory management may not be desirable for all
users of GRDB. `DatabasePool.releaseMemory`
creates a barrier which may cause normally fast
readers to block for a long time. If this is not a
desirable tradeoff, the new
`automaticMemoryManagement` flag in
`Configuration` allows you to disable this feature
of GRDB.
2022-07-05 15:27:55 -07:00
Gwendal Roué 84bee1977e Merge pull request #1248 from groue/dev/WALSnapshot
Avoid double notification of the initial value for ValueObservation on DatabasePool
2022-06-30 20:35:52 +02:00
Gwendal Roué 0aa561e61c [skip-ci] CHANGELOG 2022-06-30 19:32:35 +02:00
Gwendal Roué b1b51c01f8 [skip-ci] Xcode drives me crazy 2022-06-30 19:32:24 +02:00
Gwendal Roué cc5196757d Fix for Xcode 12.4 2022-06-30 19:22:23 +02:00
Gwendal Roué 0e9766373d Merge pull request #1246 from sameer4/patch-1
Update AssociationsBasics.md
2022-06-30 10:43:50 +02:00
Sameer aacaa433c9 Update AssociationsBasics.md
Fixed a typo
2022-06-30 12:51:53 +05:00
Gwendal Roué 44ec3535c2 Documentation 2022-06-24 16:48:38 +02:00
Gwendal Roué 38c0d68db7 WALSnapshot
SQLITE_ENABLE_SNAPSHOT is available from Xcode 14 :-)
2022-06-24 16:48:38 +02:00
Gwendal Roué f3cc4add9f Merge pull request #1240 from danielinoa/patch-1
Fix inline documentation typo in Row
2022-06-12 14:47:16 +02:00
Daniel Inoa 432670e13a Fix documentation typo in Row 2022-06-12 05:14:28 -07:00
Gwendal Roué 3ba13b0af6 Merge pull request #1239 from groue/dependabot/github_actions/actions/checkout-3
Bump actions/checkout from 2 to 3
2022-06-12 08:32:19 +02:00
dependabot[bot] 1a6228e2c5 Bump actions/checkout from 2 to 3
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-06-11 15:37:15 +00:00
Gwendal Roué e02f2c8aba Merge branch 'development' 2022-06-11 17:35:55 +02:00
Gwendal Roué c0e9c8746d v5.25.0 2022-06-11 17:35:39 +02:00
Gwendal Roué d1cba5e5c8 TODO 2022-06-11 17:35:39 +02:00
Gwendal Roué bf824bf68c Makefile: support for Xcode 14.0 2022-06-11 14:59:02 +02:00
Gwendal Roué 5e5b44aa7f Fix Swiftlint build phase 2022-06-11 14:59:02 +02:00
Gwendal Roué 806919b5be Merge pull request #1235 from groue/dev/raise-default-qos
Raise default Quality of Service to .userInitiated
2022-06-08 23:35:48 +02:00
Gwendal Roué a289aecc3c CHANGELOG 2022-06-08 08:13:12 +02:00
Gwendal Roué 3f7adec072 Default qos is .userInitiated
Addresses #1234
2022-06-08 08:12:47 +02:00
Gwendal Roué c9f3a1e17f CHANGELOG 2022-06-08 08:12:30 +02:00
Gwendal Roué cf2a79e12f Merge pull request #1228 from turrisxyz/Dependabot-GitHub-Actions
chore: Included githubactions in the dependabot config
2022-06-08 08:09:37 +02:00
Gwendal Roué a0212eb129 [skip ci] Early mention of the async accesses 2022-06-07 19:32:39 +02:00
Gwendal Roué d5470b7278 Merge pull request #1233 from GetToSet/ethanwong/fix-xcode-14-warning
Fix warnings of redundant conformance constraint on Xcode 14.
2022-06-07 09:33:44 +02:00
Ethan Wong cd6960f5e9 Fix warnings of redundant conformance constraint on Xcode 14. 2022-06-07 11:35:37 +08:00
naveen f72859b5b2 chore: Included githubactions in the dependabot config
This should help with keeping the GitHub actions updated on new releases. This will also help with keeping it secure.

Dependabot helps in keeping the supply chain secure https://docs.github.com/en/code-security/dependabot

GitHub actions up to date https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot

https://github.com/ossf/scorecard/blob/main/docs/checks.md#dependency-update-tool
Signed-off-by: naveen <172697+naveensrinivasan@users.noreply.github.com>
2022-06-01 01:30:32 +00:00
Gwendal Roué b947065d25 Merge pull request #1226 from turrisxyz/Pinned-Dependencies-GitHub
chore: Set permissions for GitHub actions
2022-05-31 08:12:22 +02:00
naveen 11f95806c4 chore: Set permissions for GitHub actions
Restrict the GitHub token permissions only to the required ones; this way, even if the attackers will succeed in compromising your workflow, they won’t be able to do much.

- Included permissions for the action. https://github.com/ossf/scorecard/blob/main/docs/checks.md#token-permissions

https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions

https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs

[Keeping your GitHub Actions and workflows secure Part 1: Preventing pwn requests](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/)

Signed-off-by: naveen <172697+naveensrinivasan@users.noreply.github.com>
2022-05-31 00:30:47 +00:00
Gwendal Roué 2ac5c77353 Merge branch 'development' 2022-05-26 13:32:23 +02:00
Gwendal Roué 2a849d380c v5.24.1 2022-05-26 13:31:48 +02:00
Gwendal Roué fd31632203 Bump GRDBPerformance dependencies 2022-05-26 13:31:48 +02:00
Gwendal Roué 4a98a53dad CHANGELOG 2022-05-26 12:09:42 +02:00
Gwendal Roué 952ee0a137 Rename Pool.async to asyncGet 2022-05-25 17:25:43 +02:00
Gwendal Roué ee92db9d6f Pool has a QoS 2022-05-25 17:21:50 +02:00
Gwendal Roué de4266499c Configuration.readQoS 2022-05-25 17:19:41 +02:00
Gwendal Roué 4b7a9bbe7b CI: raise timeouts 2022-05-25 09:27:01 +02:00
Gwendal Roué 184d5aa4af CI: raise timeouts 2022-05-25 09:01:39 +02:00
Gwendal Roué 6c48e492d1 CI: raise timeouts 2022-05-24 21:58:46 +02:00
Gwendal Roué 26fedd2702 CI: raise timeouts 2022-05-24 20:47:34 +02:00
Gwendal Roué 06216fd875 Merge pull request #1225 from groue/dev/thread-limit
Prevent heavy DatabasePool concurrent reads from creating too many threads
2022-05-24 20:46:54 +02:00
Gwendal Roué 42050e5e28 CHANGELOG 2022-05-24 19:54:51 +02:00
Gwendal Roué 9ed309b470 Fix failing tests for number of threads created by DatabasePool 2022-05-24 19:31:22 +02:00
Gwendal Roué 00d1a80b31 Failing tests for number of threads created by DatabasePool 2022-05-24 19:31:09 +02:00
Gwendal Roué aaf3efe6df Merge pull request #1163 from groue/dev/ci
Tests with GitHub actions
2022-05-24 08:18:57 +02:00
Gwendal Roué d8f2989542 Split SQLCipher clear/encrypted tests 2022-05-23 14:20:26 +02:00
Gwendal Roué 28543109ea Rename CI jobs 2022-05-23 08:18:09 +02:00
Gwendal Roué 63c2bd0876 Raise SQLCipher CI timeouts 2022-05-23 08:17:12 +02:00
Gwendal Roué 59bd10b1b5 Raise all CI timeouts 2022-05-22 18:05:13 +02:00
Gwendal Roué 758f561fbf Raise timeout threshold for SQLCipher CI tests 2022-05-22 17:31:45 +02:00
Gwendal Roué 40b0e98eb5 Delete obsolete Travis setup files 2022-05-22 16:47:21 +02:00
Gwendal Roué 2ec0a4c69d More tests 2022-05-22 16:47:20 +02:00
Gwendal Roué ca43f1e803 Test macOS, All Xcodes and Swifts 2022-05-18 16:40:39 +02:00
Gwendal Roué 0a7e7d1e5c Makefile: support for Xcode 13.4 2022-05-18 13:48:24 +02:00
Gwendal Roué 1260980150 Remove return keywords 2022-05-18 08:14:19 +02:00
Gwendal Roué f0cfde682e Update outdated documentation 2022-05-18 08:12:00 +02:00
Gwendal Roué 096a3b2f0f Merge pull request #1217 from GetToSet/development
Update doc issue on TableRequest.filter(keys:).
2022-05-16 11:03:17 +02:00
Ethan Wong f313a43ef9 Update doc issue on TableRequest.filter(keys:). 2022-05-07 13:32:31 +08:00
Gwendal Roué fead2ea634 Merge branch 'development' 2022-05-01 11:43:49 +02:00
Gwendal Roué 5b254eec16 v5.24.0 2022-05-01 11:43:14 +02:00
Gwendal Roué 3632edb238 Mention SwiftUI support in the README 2022-05-01 11:36:26 +02:00
Gwendal Roué 752415b5fb Merge pull request #1213 from groue/dev/fix-1209
Fix crash when the number of active ValueObservations is high
2022-05-01 08:25:56 +02:00
Gwendal Roué f17a786165 CHANGELOG 2022-04-30 16:07:04 +02:00
Gwendal Roué b89ce00361 Document that read-only transactions are not notified 2022-04-30 16:06:59 +02:00
Gwendal Roué c5eba4741d Test that read-only transactions are not notified 2022-04-30 15:42:57 +02:00
Gwendal Roué fb18a3938f Database.isolated(readOnly: true) avoids triggering database observation
Fix failing test for #1209
2022-04-30 15:27:20 +02:00
Gwendal Roué 5082207bb0 Don't notify read-only transactions 2022-04-30 15:27:20 +02:00
Gwendal Roué 06b5367053 Default transaction kind is .deferred in read-only connections
This applies to both connections open in read-only mode, and pragma query_only.
2022-04-30 14:29:31 +02:00
Gwendal Roué 819ee588c9 Failing test for #1209 2022-04-30 14:26:04 +02:00
Gwendal Roué 1b3f1ed393 Fix typo 2022-04-30 13:26:25 +02:00
Gwendal Roué f0fe7e86ca Merge pull request #1212 from groue/MartinP7r-patch-1
Fix apple docs links
2022-04-29 12:18:03 +02:00
Martin Pfundmair dd5ce280b5 Fix apple docs links 2022-04-29 16:10:03 +09:00
Matt Gallagher 744aa825a3 Merge pull request #1203 from EvanHahn/fix-changelog-links
Fix changelog links
2022-04-20 12:25:10 +10:00
Evan Hahn 24f3de9dfa Fix changelog links
This change:

1. Makes all links use HTTPS (there were a few that used insecure HTTP)
2. Corrects a few links, which previously went to the wrong place

It was easy to find HTTP links—a simple search. I wrote a silly script,
to be run in the browser console, to find the rest:

```js
(() => {
  for (const a of document.getElementsByTagName("a")) {
    if (!/^#\d+$/.test(a.innerText)) {
      continue;
    }

    const id = a.innerText.slice(1);
    const expectedPullHref = `https://github.com/groue/GRDB.swift/pull/${id}`;
    const expectedIssueHref = `https://github.com/groue/GRDB.swift/issues/${id}`;

    if (a.href !== expectedPullHref && a.href !== expectedIssueHref) {
      console.error(`"${a.innerText}" has an invalid href, ${a.href}`);
    }
  }
})();
```

Hope this helps!
2022-04-19 18:30:53 -05:00
Gwendal Roué 4472d3a60e Merge branch 'development' 2022-04-16 10:10:05 +02:00
Gwendal Roué dc03adb4e2 v5.23.0 2022-04-16 10:09:45 +02:00
Gwendal Roué dea9bedacb Merge pull request #1200 from groue/dev/require-swift-5.6-for-concurrency
Require Swift 5.6 Compiler for Concurrency Support
2022-04-14 07:11:17 +02:00
Gwendal Roué 83d243853b CHANGELOG 2022-04-13 23:21:38 +02:00
Gwendal Roué 209192d3a5 Require Swift 5.6 Compiler for Concurrency Support 2022-04-13 23:07:33 +02:00
Gwendal Roué 15c06e0374 Merge branch 'development' 2022-04-02 14:56:09 +02:00
Gwendal Roué 0324f592dc v5.22.2 2022-04-02 14:55:54 +02:00
Gwendal Roué 051787b17f Merge pull request #1196 from layoutSubviews/development
Fix a crash when an observation is quickly cancelled
2022-04-02 14:50:38 +02:00
Gwendal Roué feebc07101 Documentation 2022-04-02 13:21:26 +02:00
Renaud Lienhart 80c15c6ef6 Fix a crash when an observation is quickly cancelled 2022-03-31 10:55:00 +11:00
Gwendal Roué 9014b3ebd0 Fix #1192 2022-03-26 14:48:27 +01:00
Gwendal Roué bec58a32d4 And fix typo... 2022-03-26 12:54:00 +01:00
Gwendal Roué b66374670c CHANGELOG: add 5.22.1 in the list of releases 2022-03-26 12:53:11 +01:00
Gwendal Roué f3992a034d Merge branch 'development' 2022-03-26 11:52:33 +01:00
Gwendal Roué 8b120fa9b6 v5.22.1 2022-03-26 11:52:17 +01:00
Gwendal Roué 8b58ec4cee Merge branch 'dev/issue1194' into development 2022-03-26 11:46:03 +01:00
Gwendal Roué 9b7b603a69 Documentation 2022-03-26 11:44:33 +01:00
Gwendal Roué a3a26bf88f Fix #1194 2022-03-26 11:43:44 +01:00
Gwendal Roué 770484b78d Failing test for #1194 2022-03-26 11:33:10 +01:00
Gwendal Roué fafa74c246 Fix ValueObservation.publisher documentation 2022-03-22 19:24:06 +01:00
Gwendal Roué 62450b5817 Bump performance comparison dependencies 2022-03-22 18:00:21 +01:00
Gwendal Roué e9b8df68ee Merge branch 'development' 2022-03-22 17:38:18 +01:00
Gwendal Roué 9fa831b6bb v5.22.0 2022-03-22 16:41:40 +01:00
Gwendal Roué 43e1871005 Fix for Xcode 12.4 2022-03-22 13:46:09 +01:00
Gwendal Roué 8a6e784428 Fix for Xcode 12.5.1
Without this change, the compiler would crash with Abort trap: 6
2022-03-22 09:26:12 +01:00
Gwendal Roué 727ca68b98 CHANGELOG 2022-03-22 08:36:24 +01:00
Gwendal Roué fb3e08aba8 Merge pull request #1186 from benrb/databaseerror-message
DatabaseError provide error message as localizedFailureReason
2022-03-22 08:26:14 +01:00
Ben Barnett 1c614e8de6 Test localizedFailureReason is not nil
-localizedFailureReason can be nil in some cases, but not in the one we are testing here
2022-03-20 08:23:35 +00:00
Ben Barnett 3f0a8e6730 Provide error message as a failure reason 2022-03-20 08:07:39 +00:00
Gwendal Roué 6916a8feca #1183 cleanup 2022-03-18 03:36:20 +01:00
Gwendal Roué e08dfdb0bf Merge pull request #1183 from groue/dev/strong-observation
Starting a ValueObservation keeps a strong reference on the database connection.
2022-03-17 19:17:03 +01:00
Gwendal Roué 6236b8a068 Move Headers build phase before Compile Sources
This prevents a build error when running tests with Xcode 13.3:

error: Cycle inside GRDBiOS; building could produce unreliable results. This usually can be resolved by moving the target's Headers build phase before Compile Sources.
2022-03-17 18:50:11 +01:00
Gwendal Roué 55dea6f9d2 Makefile: support for Xcode 13.3 2022-03-17 18:44:30 +01:00
Gwendal Roué cdb08988f4 CHANGELOG 2022-03-17 18:44:30 +01:00
Gwendal Roué 881bbd3f0d Update documentation 2022-03-17 18:44:30 +01:00
Gwendal Roué 6ab3fea8fb Refactor ValueObservation 2022-03-17 18:44:30 +01:00
Gwendal Roué 287ceb8b07 Documentation & cleanup 2022-03-17 18:44:30 +01:00
Gwendal Roué 4eefb9afbe Merge pull request #1184 from GetToSet/ethanwong/update-row-adapter-doc
Update RowAdapter doc to cover all concrete adapters.
2022-03-17 18:05:09 +01:00
Ethan Wong 4ea04ec978 Update RowAdapter doc to cover all concrete adapters. 2022-03-18 00:59:16 +08:00
Gwendal Roué c30b49117b If a scope is found, there is no point searching for prefetched rows 2022-03-04 12:04:02 +01:00
Gwendal Roué ec975819b7 Fix for container.decodeNil(forKey:) in the context of including(all:) 2022-03-04 11:55:53 +01:00
Gwendal Roué b974dfa9a7 Use fetchSet when available 2022-03-04 11:40:42 +01:00
Gwendal Roué e19f21be99 TODO 2022-03-04 10:28:23 +01:00
Gwendal Roué 9b0e41ad58 Details about date formats 2022-02-13 12:27:27 +01:00
Gwendal Roué d40474d2b7 Merge branch 'development' 2022-02-06 12:14:25 +01:00
Gwendal Roué 685074932e v5.21.0 2022-02-06 12:14:05 +01:00
Gwendal Roué f1a23bacc0 Extend the thank you notice 2022-02-06 12:10:35 +01:00
Gwendal Roué fbef103f01 CHANGELOG 2022-02-06 12:09:27 +01:00
Gwendal Roué fc9f0bcad1 Wording 2022-02-06 10:20:06 +01:00
Gwendal Roué 1929e96d11 Merge pull request #1165 from BeehiveInnovations/development
Add dynamic library to products to support dynamic linking
2022-02-06 10:13:31 +01:00
Gwendal Roué 9d4eb8a6dd test_install_SPM_Dynamic_Project: use a destination
Otherwise `make test_install_SPM_Dynamic_Project` uses a default destination, which CAN be the current mac, and thus require code signing:

% make test_install_SPM_Dynamic_Project
...
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:macOS, arch:arm64, variant:Designed for [iPad,iPhone], ... }
{ platform:iOS, id:dvtdevice-DVTiPhonePlaceholder-iphoneos:placeholder, name:Any iOS Device }
...
❌  error: Signing for "ios-dynamic" requires a development team. Select a development team in the Signing & Capabilities editor. (in target 'ios-dynamic' from project 'ios-dynamic')
** BUILD FAILED **
2022-02-06 10:00:58 +01:00
Fahad 3914a9ec21 Updated Makefile. Updated code-signing team 2022-02-06 01:25:34 +04:00
Fahad 29bacc138c Replaced test project with iOS project 2022-02-06 01:14:19 +04:00
Beehive InnovationsandGwendal Roué ba866359b2 Update README.md
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2022-02-03 23:11:54 +04:00
Beehive InnovationsandGwendal Roué ffced55d3c Update README.md
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2022-02-03 22:52:10 +04:00
Beehive Innovations 74caa96dcb Undo and use automatic
More clarity on this now - helps compile optimize and skip producing a `.a` static library entirely.
2022-02-03 22:13:12 +04:00
Beehive Innovations f6bea21e80 The first target should explicitly say static
Otherwise the behavior is undefined since omitting the type may at some point in time cause Xcode to pull it in as dynamic (when they fix their dependency resolution).
2022-02-03 21:44:06 +04:00
Fahad 27f6125099 Dynamic library test added 2022-02-03 13:36:52 +04:00
Beehive Innovations 70ea2027e4 Renamed dynamic library name
In line with naming standard used by other libraries
2022-02-03 13:11:24 +04:00
Beehive Innovations e28658c574 Updated SPM installation instructions
Added note about static / dynamic
2022-02-03 13:09:52 +04:00
fahad@guidedways.com c184b76849 Add dynamic library to products to allows dynamic linking 2022-02-03 09:25:42 +04:00
Gwendal Roué d23d74f65f Merge pull request #1164 from groue/dev/migrator-is-not-concurrent
Drop async apis from DatabaseMigrator
2022-02-01 18:17:02 +01:00
Gwendal Roué 984a5b4c4c CHANGELOG 2022-02-01 16:55:05 +01:00
Gwendal Roué 8e84beee36 Fix Swift 5.6 warnings 2022-02-01 10:08:24 +01:00
Gwendal Roué 95ce4a3f8a Drop async apis from DatabaseMigrator
This is because DatabaseMigrator can't be Sendable as long as it runs migrations that embed non-@Sendable closures.
2022-02-01 09:53:20 +01:00
Gwendal Roué 98ca653c6a Merge branch 'development' 2022-02-01 09:07:15 +01:00
Gwendal Roué e5a8e130d7 v5.20.0 2022-02-01 07:44:09 +01:00
Gwendal Roué 72e8dd2816 Cleanup 2022-01-31 20:20:02 +01:00
Gwendal Roué b5338650db Bump performance comparison dependencies 2022-01-31 19:23:55 +01:00
Gwendal Roué 75f72472ff Cleanup 2022-01-31 08:37:57 +01:00
Gwendal Roué 09f7d4d952 Complete #1161 2022-01-30 15:27:11 +01:00
Gwendal Roué c1c3cf6605 Merge pull request #1162 from groue/dev/fix-truncate-optimization
Fix truncate optimization handling
2022-01-30 15:26:14 +01:00
Gwendal Roué fc7f24ef6e Test case insensitivity of truncation optimization prevention 2022-01-30 14:57:37 +01:00
Gwendal Roué 3d0b34590f Fix typo 2022-01-30 14:49:31 +01:00
Gwendal Roué 2d6c2873e0 CHANGELOG 2022-01-30 14:42:22 +01:00
Gwendal Roué 4e65425c00 Cleanup 2022-01-30 14:41:29 +01:00
Gwendal Roué b82f92f726 Test for cursor next() followed by forEach() 2022-01-30 14:33:22 +01:00
Gwendal Roué b8c0e9d2c2 Fix failing test for cached statement which does not prevent the truncate optimization 2022-01-30 14:24:28 +01:00
Gwendal Roué b2df255306 Failing test for cached statement which does not prevent the truncate optimization 2022-01-30 14:12:46 +01:00
Gwendal Roué c60b8cfc53 Refactor prevention of truncate optimization
We now always use the same authorizer, which is always ready to prevent truncate optimization depending on the current transaction observers.
2022-01-30 14:07:43 +01:00
Gwendal Roué 9dc6fbd7f9 Fix #1159 2022-01-30 12:27:19 +01:00
Gwendal Roué 9a4e1f7806 Merge pull request #1161 from groue/dev/write-target-queue
Target DispatchQueue for non-read-only database connections
2022-01-30 12:07:25 +01:00
Gwendal Roué 5dde1409ad CHANGELOG 2022-01-29 17:54:33 +01:00
Gwendal Roué 936fd3ed5f Test that DatabaseMigrator.eraseDatabaseOnSchemaChange does not deadlock on Configuration.writeTargetQueue 2022-01-29 17:47:30 +01:00
Gwendal Roué ed4471c5b9 Configuration.writeTargetQueue 2022-01-29 17:45:21 +01:00
Gwendal Roué dd025a14e4 Merge pull request #1160 from groue/dev/privacy
Hide statement arguments by default
2022-01-29 16:29:58 +01:00
Gwendal Roué 29808e51ff Fix typo 2022-01-29 16:06:22 +01:00
Gwendal Roué 426044154c Fix public statement arguments for system SQLite 2022-01-29 15:54:39 +01:00
Gwendal Roué d69db0b9a1 CHANGELOG 2022-01-29 15:32:21 +01:00
Gwendal Roué 914bd14cd1 CHANGELOG 2022-01-29 15:27:44 +01:00
Gwendal Roué b5395a097c Documentation 2022-01-29 15:27:40 +01:00
Gwendal Roué 99c596f778 Fix DatabaseError public initializer 2022-01-29 15:21:44 +01:00
Gwendal Roué fd22fac5c0 Don't shed too much light on expandedSQL & expandedDescription properties 2022-01-29 15:12:41 +01:00
Gwendal Roué 6e3a15ebed Statement.description no longer contains statement arguments 2022-01-29 14:57:18 +01:00
Gwendal Roué bb8b39f7fd Documentation for public statement arguments 2022-01-29 14:54:47 +01:00
Gwendal Roué fc5138ae91 Configuration.publicStatementArguments
This flags allows database errors and trace events to hide or show statement arguments by default.
2022-01-28 13:57:12 +01:00
Gwendal Roué d3985c7ebf TraceEvent.description no longer contains statement arguments
Use TraceEvent.expandedDescription in order to see statements arguments
2022-01-27 19:30:00 +01:00
Gwendal Roué 9f0ba49c93 DatabaseError.description no longer contains statement arguments
Use DatabaseError.expandedDescription in order to see statements arguments
2022-01-27 19:30:00 +01:00
Gwendal Roué 09922c34ff Code formatting 2022-01-23 12:24:34 +01:00
Gwendal Roué 3826003d93 TODO 2022-01-23 10:51:15 +01:00
Gwendal Roué 9baa72cfd7 Mention association annotation methods in the main README 2022-01-21 13:48:51 +01:00
Gwendal Roué aacc69f485 Fix typos 2022-01-21 13:43:44 +01:00
Gwendal Roué 301fb34702 Fix failing test for including(all:) on limited request and composite primary keys 2022-01-21 13:42:42 +01:00
Gwendal Roué 6444285ee2 Failing test for including(all:) on limited request and composite primary keys 2022-01-21 13:39:40 +01:00
Gwendal Roué bd42dc69f0 CHANGELOG 2022-01-19 19:27:50 +01:00
Gwendal Roué 14d8763a84 Merge branch 'development' 2022-01-19 16:20:21 +01:00
Gwendal Roué c46e8257d8 v5.19.0 2022-01-19 16:18:59 +01:00
Gwendal Roué 948c7870bd Merge pull request #1151 from freak4pc/fk-docs
Fix documentation for foreignKeysEnabled
2022-01-19 15:50:16 +01:00
Shai MishaliandGwendal Roué fa896eee23 Update GRDB/Core/Configuration.swift
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2022-01-19 16:46:55 +02:00
Shai Mishali c4023ccf0a Fix documentation for foreignKeysEnabled 2022-01-19 15:48:11 +02:00
Gwendal Roué fe92b93f0b CHANGELOG 2022-01-19 08:15:19 +01:00
Gwendal Roué 28109a3947 Merge pull request #1144 from TimAEllis/feature/add-drop-column
Add drop column support
2022-01-19 08:06:24 +01:00
Gwendal Roué 124cba1b21 Work around missing SQLITE_ALTER_TABLE action 2022-01-19 07:29:16 +01:00
Gwendal Roué ca47426c61 Merge pull request #1149 from BB9z/fix-typos
Fix typos
2022-01-19 06:31:12 +01:00
Gwendal Roué 90c85c6703 TODO 2022-01-19 06:25:33 +01:00
BB9z 6d3f309cad Fix typos 2022-01-19 00:10:42 +08:00
Gwendal Roué 06dbaba7cc Add failing test for schema cache invalidation 2022-01-18 08:50:42 +01:00
Timothy Ellis daf44d9baa Exposed drop(column:) to custom builds and cipher 2022-01-18 10:11:12 +11:00
Timothy Ellis 187a661626 Updated to reflect drop column 2022-01-17 10:31:11 +11:00
Timothy Ellis 55302cb937 Added test for drop column 2022-01-17 10:02:23 +11:00
Timothy Ellis 869d776962 Added drop column support 2022-01-17 10:02:04 +11:00
Gwendal Roué b53b43b1fc Cleanup 2022-01-16 14:50:55 +01:00
Gwendal Roué 42d29b305e Cleanup 2022-01-16 13:54:03 +01:00
Gwendal Roué 8f100a6395 Document that GRDB/SQLCipher must be the only pod
Addresses #1141
2022-01-16 10:49:02 +01:00
Gwendal Roué 44dd21690f Merge pull request #1139 from groue/dev/more-1124
Deal with authorization callbacks from more cursors
2022-01-14 18:43:13 +01:00
Gwendal Roué 6d31190c3f DatabaseCursor.forEach() honors the _isDone flag 2022-01-14 18:31:16 +01:00
Gwendal Roué 549f7ec66e Cleanup and cursor profiling tests 2022-01-14 18:25:30 +01:00
Gwendal Roué 3eea2967b3 Improve error message 2022-01-14 17:49:17 +01:00
Gwendal Roué 8e6827070f Improve documentation 2022-01-14 13:47:54 +01:00
Gwendal Roué d105b35750 More #1124-related documentation 2022-01-14 13:29:34 +01:00
Gwendal Roué 149d5ac151 Fix GRDBProfiling 2022-01-14 13:13:34 +01:00
Gwendal Roué ed6c5438b9 Move DatabaseCursor state to Statement 2022-01-14 13:13:34 +01:00
Gwendal Roué bd67153095 Fix #1124 for more cursors 2022-01-13 14:28:04 +01:00
Gwendal Roué 3fff6b2f51 Fix typo 2022-01-13 07:29:38 +01:00
Gwendal Roué 62a0b1c148 Fix typo 2022-01-09 19:03:31 +01:00
Gwendal Roué dfca044433 Merge branch 'development' 2022-01-09 18:56:04 +01:00
Gwendal Roué 78df734f51 v5.18.0 2022-01-09 17:36:31 +01:00
Gwendal Roué e72b7e4597 Merge pull request #1133 from groue/dev/strict-tables
Support for STRICT tables
2022-01-09 17:22:50 +01:00
Gwendal Roué fb6c695658 CHANGELOG 2022-01-09 17:12:17 +01:00
Gwendal Roué a1c0c6d1f3 Update documentation for the new table/index creation options 2022-01-09 17:01:37 +01:00
Gwendal Roué 68f3e5586b Test strict tables, and table/index creation options 2022-01-09 17:01:37 +01:00
Gwendal Roué 8760033045 Update the list of extended result codes from SQLite 3.37.2
This updated list contains SQLITE_CONSTRAINT_DATATYPE, introduced with strict tables.
2022-01-09 17:01:37 +01:00
Gwendal Roué b2fabf5fc3 Strict tables need REAL and ANY column types 2022-01-09 17:01:37 +01:00
Gwendal Roué 95f1d83d78 The .strict table creation option
The .strict table creation option

The .strict table creation option
2022-01-09 17:01:37 +01:00
Gwendal Roué 790c054a28 Fix Swiftlint warnings 2022-01-09 14:43:27 +01:00
Gwendal Roué 06a5d6f44b Merge pull request #1132 from groue/dev/sqlite-3.72.2
Bump custom SQLite builds v3.72.2
2022-01-09 14:42:28 +01:00
Gwendal Roué 3145a916a0 CHANGELOG 2022-01-09 14:33:33 +01:00
Gwendal Roué 94ff9f3e45 The casing of ColumnInfo.type depends on the SQLite version 2022-01-09 14:28:00 +01:00
Gwendal Roué c172dac909 Update test for SQLite to v3.37.2 2022-01-09 14:21:51 +01:00
Gwendal Roué 5b7ba122e8 Bump custom SQLite to v3.37.2 2022-01-09 14:06:27 +01:00
Gwendal Roué 0513e0acf8 Enhance wording in the pull request template 2022-01-09 13:42:22 +01:00
Gwendal Roué b3d49de023 Mention CONTRIBUTING in the pull request template 2022-01-09 13:41:11 +01:00
Gwendal Roué 779e2c202f Merge pull request #1128 from groue/dev/issue-1124
Deal with authorization callbacks from cursors of FetchableRecord
2022-01-09 13:38:20 +01:00
Gwendal Roué be45781cf9 CHANGELOG 2022-01-09 13:31:03 +01:00
Gwendal Roué c7d816b860 Merge branch 'development' into dev/issue-1124 2022-01-09 13:27:54 +01:00
Gwendal Roué a0f6f7a9ab Merge pull request #1129 from groue/dev/detached-column
Detached columns
2022-01-09 13:27:04 +01:00
Gwendal Roué 86c0180487 CHANGELOG 2022-01-09 13:17:29 +01:00
Gwendal Roué 80c11d0bc4 Merge branch 'development' into dev/detached-column 2022-01-09 13:13:31 +01:00
Gwendal Roué 66602ba2e2 CHANGELOG 2022-01-09 13:13:11 +01:00
Gwendal Roué 8fdcc020e0 Documentation 2022-01-08 14:09:14 +01:00
Gwendal Roué 1bb2029e74 Fix #1124 by dealing with authorizers 2022-01-08 13:51:41 +01:00
Gwendal Roué fc0e1bede1 Methods that fully consume a cursor prefer forEach to next
This allows custom forEach implementations to wrap the full consumption of a cursor
2022-01-08 13:50:14 +01:00
Gwendal Roué 823af1944e Cursor.forEach is a customization point 2022-01-08 13:47:54 +01:00
Gwendal Roué 2093b477df Failing test for #1124 2022-01-08 13:18:32 +01:00
Gwendal Roué 29cd08cba4 Fix typo 2022-01-07 15:01:29 +01:00
Gwendal Roué 76523db5b9 Removed undesired :nodoc: comment 2022-01-07 14:58:42 +01:00
Gwendal Roué c0305853bc Enhance fatal error message for reversed literal ordering terms 2022-01-07 14:43:57 +01:00
Gwendal Roué 5d51f2a884 New Embedding SQL in Query Interface Requests chapter 2022-01-07 14:41:15 +01:00
Gwendal Roué bdf54e80a9 Mention detached columns in the documentation of expression.forKey(_:) 2022-01-07 13:30:27 +01:00
Gwendal Roué e799c8534e ColumnExpression.detached 2022-01-07 10:07:15 +01:00
Gwendal Roué 536ad2ebff Merge branch 'master' into development 2022-01-07 10:06:42 +01:00
Gwendal Roué 972f45295f Request make smokeTest to pass before submitting a pull request. 2022-01-07 10:06:21 +01:00
Gwendal Roué b96bd52c38 Merge branch 'dev/issue-1074-incremental_backup_api' into development 2022-01-06 18:36:31 +01:00
Gwendal Roué 2af0a74676 Fix SQLCipher 3 and 4 test projects 2022-01-06 14:13:25 +01:00
Gwendal Roué 4aa37f6169 Expert users need raw access to expert values 2022-01-06 13:52:09 +01:00
Gwendal Roué 37571525e6 Merge branch 'development' into dev/issue-1074-incremental_backup_api 2022-01-06 13:45:26 +01:00
Gwendal Roué 911b2a76d8 Merge pull request #1121 from byohay/feature/fix-variables-with-spaces
GRDB: quote PROJECT_DIR and SRCROOT environment variables.
2021-12-31 14:32:29 +01:00
Gwendal Roué 54b13de632 Merge pull request #1120 from jnross/joe/fix-typo
Fix typos of the word "default"
2021-12-31 13:56:56 +01:00
Ben Yohay 4a3232199f GRDB: quote PROJECT_DIR and SRCROOT environment variables.
Using those variables without quoting will yield unexpected results if
they contain spaces.
2021-12-29 14:40:56 +02:00
Joseph Ross bf28abbb25 Fix typos of the word "default" 2021-12-28 14:49:33 -08:00
Gwendal Roué c945504a34 Addition and substraction are not bijective functions (due to floating point rounding errors) 2021-12-21 11:13:28 +01:00
Gwendal Roué 8217966215 Table creation methods accept throwing closures 2021-12-21 09:26:55 +01:00
Gwendal Roué c96a74658c TODO 2021-12-19 12:34:16 +01:00
Gwendal Roué 042e220f49 Rewrite CONTRIBUTING.md 2021-12-18 14:31:02 +01:00
Michael Allman a71639159b Add DatabaseBackupProgress and update the documentation 2021-12-15 01:52:25 -05:00
Gwendal Roué d633927999 Merge branch 'development' 2021-12-14 19:33:32 +01:00
Gwendal Roué 8df7020ad7 v5.17.0 2021-12-14 19:32:51 +01:00
Gwendal Roué bc95c5c977 Performance tests: upgrade dependencies 2021-12-14 19:15:59 +01:00
Gwendal Roué ef4709d3f0 Fix async vaccum(info:) tests by using the same encryption level for the destination database 2021-12-14 14:21:16 +01:00
Gwendal Roué e1984721dc Merge pull request #1079 from groue/dev/async
Async / Await
2021-12-14 13:29:02 +01:00
Gwendal Roué 469898c5df CHANGELOG 2021-12-14 13:15:22 +01:00
Gwendal Roué 0207aef4dc CHANGELOG 2021-12-14 12:48:48 +01:00
Gwendal Roué d7604d2174 Merge branch 'development' into dev/async 2021-12-14 12:46:49 +01:00
Gwendal Roué 89421c92fb More support for inclusion checks with explicit collation
This commit addresses https://github.com/groue/GRDB.swift/issues/1094

The position of the `collating` method is now irrelevant in all those cases:

// name COLLATE NOCASE IN ('foo', 'bar')
["foo", "bar"].contains(Column("name")).collating(.nocase)
["foo", "bar"].contains(Column("name").collating(.nocase))

// name BETWEEN 'foo' AND 'bar' COLLATE NOCASE
("foo"..."bar").contains(Column("name")).collating(.nocase)
("foo"..."bar").contains(Column("name").collating(.nocase))

// (name >= 'foo' COLLATE NOCASE) AND (name < 'bar' COLLATE NOCASE)
("foo"..<"bar").contains(Column("name")).collating(.nocase)
("foo"..<"bar").contains(Column("name").collating(.nocase))
2021-12-14 12:45:50 +01:00
Gwendal Roué 0cf4c4efba Merge branch 'development' into dev/async 2021-12-12 17:00:08 +01:00
Gwendal Roué 710142edc0 CHANGELOG 2021-12-12 16:44:43 +01:00
Gwendal Roué 7001b60cf7 More support for association existence check
New: support for associated tables WITHOUT ROWID with a compound primary key
New: support for associated views

Checking for the existence of associated CTEs is still not implemented (it fails with "table does not exist" error).
2021-12-12 16:43:40 +01:00
Gwendal Roué dcc2d211b2 Database.primaryKey() fails for views 2021-12-12 16:14:25 +01:00
Gwendal Roué 340203686d ValueObservation.removeDuplicates(by:) 2021-12-12 15:12:34 +01:00
Gwendal Roué ae609cec3b Support for the TOTAL SQL aggregate function 2021-12-12 14:46:43 +01:00
Gwendal Roué 8ba89a398a Add ABS and LENGTH SQL functions on association aggregates 2021-12-12 14:27:41 +01:00
Gwendal Roué 95b3f447e4 Revert "Make sure Inflections.default is lazily loaded, even in optimized release builds"
This reverts commit c62ccf1de7 (aimed at fixing #755).

We can do this because https://github.com/apple/swift/pull/30445 is present in the Swift 5.3 release https://github.com/apple/swift/releases/tag/swift-5.3-RELEASE
2021-12-12 13:57:34 +01:00
Gwendal Roué bc2a66e40f Don't throw any error when checking if a table is WITHOUT ROWID 2021-12-12 13:29:02 +01:00
Gwendal Roué cb32a0d0cc CHANGELOG 2021-12-12 12:56:53 +01:00
Gwendal Roué effc991de1 Deprecate DatabaseRegion.init(table:)
This commit reverts #510
2021-12-12 12:36:27 +01:00
Gwendal Roué 3049b88fea Merge pull request #1110 from maxhumber/patch-1
Minor changes to a tip in the README
2021-12-12 10:27:13 +01:00
Max Humber c39db96521 Minor changes to a tip in the README 2021-12-11 15:28:02 -05:00
Gwendal Roué d7514f84f1 Disable concurrency check flags by default 2021-12-10 12:40:08 +01:00
Gwendal Roué 1b62e06c4a Expose Sendable conformance to Swift 5.5
But async apis are still only exposed to Swift 5.5.2.

Sendable conformances are helpful for users of Xcode < 13.2.
2021-12-10 08:08:47 +01:00
Michael Allman bedf2dbcd4 Revise and correct some names and backup code documentation 2021-12-08 10:23:11 -08:00
Michael Allman 13e195db40 Revise incremental backup API to report progress via a throwing callback
function
2021-12-08 09:37:10 -08:00
Michael Allman 087ad10086 Add an API to track progress of and cancel backups in progress, for both
the DatabaseReader/DatabaseWriter API and Database API
2021-12-08 09:37:10 -08:00
Michael Allman f012c011b1 Import the Foundation framework in DatabaseReader.swift, which is required to get the Progress class 2021-12-08 09:37:10 -08:00
Michael Allman f829d46b7f Change default backup page step size from 5 to 100, which is the value used in the sqlite3 cli .backup command 2021-12-08 09:37:10 -08:00
Michael Allman ab6f18e46d Initial commit of code to implement progress-reporting database backups 2021-12-08 09:37:10 -08:00
Gwendal Roué 9579671c02 Remove a concurrency-related warning 2021-12-08 18:16:36 +01:00
Gwendal Roué 01f4c04c4d DatabaseReader is Sendable 2021-12-08 18:12:28 +01:00
Gwendal Roué 7ac78a8ec1 Share concurrency check flags with tests 2021-12-08 18:11:44 +01:00
Gwendal Roué 97e00ab44f Fix async test for SQLCipher VACUUM INTO 2021-12-08 13:18:12 +01:00
Gwendal Roué 33d9ca0e97 UIApplication notification names are isolated to @MainActor
I believe this is incorrect: FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)

Meanwhile, just use the string version.

A workaround based on a MainActor-isolated task can't work due to conflict between compiler version and minimum iOS target:

    #if compiler(>=5.5) && canImport(_Concurrency)
    if #available(...) { // Check for availability of concurrency runtime
        Task { @MainActor [weak self] in
            NotificationCenter.default.addObserver(..., name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
        }
    } else {
        // IMPOSSIBLE CASE: No access to Task, no access to notification names
    }
    #else
    NotificationCenter.default.addObserver(..., name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
    #endif
2021-12-08 12:48:19 +01:00
Gwendal Roué b2985b77c4 Concurrency check flags depend on Xcode version
Xcode 12 won't accept those flags. And we only need them starting Xcode 13.2
2021-12-08 12:00:32 +01:00
Gwendal Roué ec882e8126 Enable concurrency check flags by default 2021-12-08 11:18:54 +01:00
Gwendal Roué 61b0df8017 Enable async APIs on Xcode 13.2+ only
Xcode 13.1 won't have access to async apis. This simplifies our availability checks.

The techniques were inspired from:

- https://github.com/swift-server/guides/blob/main/docs/concurrency-adoption-guidelines.md#api-design
- https://github.com/swift-server/guides/blob/main/docs/concurrency-adoption-guidelines.md#backwards-compatibility-of-declarations-and-checked-swift-concurrency
2021-12-08 11:17:40 +01:00
Gwendal Roué 103266d70c Merge branch 'development' into dev/async 2021-12-08 08:00:49 +01:00
Gwendal Roué 3f02724e60 RowDecodingError is Sendable
Xcode 13.2 RC won't compile unless we make a Sendable copy of the row that could not be decoded.
2021-12-08 07:59:43 +01:00
Gwendal Roué ca05a93c98 Merge pull request #1107 from tcwalther/tw-fix-db-create-index-docstring
Fix docstring for Database.create(index: ...)
2021-12-07 13:32:26 +01:00
Thomas Walther 48f6cee7a6 Fix docstring for Database.create(index: ...) 2021-12-07 13:20:14 +01:00
Gwendal Roué 8ed16f4440 Fix some compiler warnings with -Xfrontend -warn-concurrency
https://twitter.com/olebegemann/status/1467893554915782668
2021-12-07 09:23:37 +01:00
Gwendal Roué 6ec3ebc398 Merge branch 'development' into dev/async 2021-12-06 18:04:35 +01:00
Gwendal Roué 86d0fedfbb Fix wording 2021-12-05 17:08:15 +01:00
Gwendal Roué 0330365d49 Merge branch 'development' 2021-12-05 16:59:59 +01:00
Gwendal Roué ca2f36781e v5.16.0 2021-12-05 16:59:37 +01:00
Gwendal Roué 6c7f71f620 Fix typo 2021-12-05 16:47:32 +01:00
Gwendal Roué 60bf5d30b0 Merge pull request #1106 from groue/dev/annotated-with-association
Sugar for fetching only a few columns of associated records
2021-12-05 16:41:49 +01:00
Gwendal Roué 94caf4ba97 todo: find a way to prefix the selection with the association key 2021-12-05 15:53:59 +01:00
Gwendal Roué a7002e1e09 Enhance "Columns Selected by an Association" 2021-12-05 15:22:07 +01:00
Gwendal Roué 54a991b3b9 Emphasize sections 2021-12-05 15:15:38 +01:00
Gwendal Roué 54ca12437a CHANGELOG 2021-12-05 15:10:25 +01:00
Gwendal Roué 3298cca75f Rewrite the Joining And Prefetching Associated Records chapter 2021-12-05 15:10:25 +01:00
Gwendal Roué 4fe0b687d2 Documentation for annotated(withOptional:), annotated(withRequired:) 2021-12-05 15:04:51 +01:00
Gwendal Roué 9df0f4cdbd Inline documentation for annotated(withOptional:), annotated(withRequired:) 2021-12-05 15:04:44 +01:00
Gwendal Roué e1dc24ac93 Update examples with Team/Player 2021-12-04 10:01:31 +01:00
Gwendal Roué 88e60ed0c6 Update FAQ: How do I select only one column of an associated record? 2021-12-04 09:50:16 +01:00
Gwendal Roué b4ca103002 Tests for annotated(withOptional:), annotated(withRequired:) 2021-12-04 09:49:23 +01:00
Gwendal Roué 564c4cef5c annotated(withOptional:), annotated(withRequired:) 2021-12-03 19:24:56 +01:00
Gwendal Roué 7a77a1fd06 Merge branch 'development' 2021-12-02 19:43:04 +01:00
Gwendal Roué c7291db360 v5.15.0 2021-12-02 18:48:36 +01:00
Gwendal Roué a52d1b1d21 Merge pull request #1102 from groue/dev/ValueObservation-explicit-region-tracking
Explicit tracked region for ValueObservation
2021-12-02 18:40:40 +01:00
Gwendal Roué 89b1783220 TrackingMode is a property of ValueObservation
No reducer changes the tracking mode, so let's simplify the code.
2021-12-02 17:22:18 +01:00
Gwendal Roué 76d2168988 Extend the general description of ValueObservation behavior
Link to the ability to track something which is not the fetched region.
2021-12-02 17:22:18 +01:00
Gwendal Roué e419bb55ca Enhance documentation of DatabaseRegion 2021-12-02 17:22:18 +01:00
Gwendal Roué 06eb45db65 Documentation for ValueObservation(region:fetch:) 2021-12-02 17:22:18 +01:00
Gwendal Roué 6180e4b815 Fix for Swift 5.3 2021-12-02 17:22:18 +01:00
Gwendal Roué 85747935c8 ValueObservation can track an explicit database region 2021-12-02 17:22:18 +01:00
Gwendal Roué 36fba9a79a TODO: deprecate DatabaseRegion(table:)
We have `Table` now, wich is DatabaseRegionConvertible.

This deprecation will revert https://github.com/groue/GRDB.swift/pull/510
2021-12-02 17:21:58 +01:00
Gwendal Roué 6240585a03 Make sure ValueObservation fetches in an isolated transaction
Previously, ValueObservation could fetch in a non-isolated way. When an external connection would commit changes, we could fetch inconsistent values. Here we make sure ValueObservation always fetch in an isolated way.
2021-12-02 09:46:02 +01:00
Gwendal Roué ad66fbc666 ValueObserver documentation 2021-12-02 09:46:02 +01:00
Gwendal Roué e69092ca6a Add DatabaseRegionConvertible to Table 2021-12-02 09:45:38 +01:00
Gwendal Roué bb2ce74125 Add helper method Database.isolated(readOnly:) 2021-12-02 09:45:28 +01:00
Gwendal Roué 06bf3980b6 Fix documentation links 2021-12-02 09:17:36 +01:00
Gwendal Roué 97d4a60148 Merge branch 'development' into dev/async
# Conflicts:
#	Documentation/DemoApps/GRDBDemoiOS/README.md
#	Documentation/DemoApps/README.md
2021-11-27 12:05:24 +01:00
Gwendal Roué 6dc7367853 Merge branch 'development' 2021-11-25 18:29:23 +01:00
Gwendal Roué 4228df9c06 v5.14.0 2021-11-25 18:23:31 +01:00
Gwendal Roué ca9fd1f8e6 CHANGELOG 2021-11-25 18:18:15 +01:00
Gwendal Roué 1fbf2f8693 GRDBCombineDemo uses the GRDBQuery package 2021-11-25 17:26:19 +01:00
Gwendal Roué 811c41af6d @Query has been exported to https://github.com/groue/GRDBQuery 2021-11-25 15:25:40 +01:00
Gwendal Roué 5d87609f4b Ignore .swiftpm 2021-11-25 15:08:53 +01:00
Gwendal Roué a9036a4563 Ignore .swiftpm 2021-11-25 14:49:37 +01:00
Gwendal Roué 988c7bb62f Query documentation 2021-11-25 13:56:07 +01:00
Gwendal Roué 51182fc862 Query documentation 2021-11-25 13:55:00 +01:00
Gwendal Roué 485509a8cc Query documentation 2021-11-25 13:47:27 +01:00
Gwendal Roué a81f80cddb Query documentation 2021-11-25 13:46:50 +01:00
Gwendal Roué d590a06212 Query documentation 2021-11-25 12:39:50 +01:00
Gwendal Roué b3a1497791 Query documentation 2021-11-25 12:38:27 +01:00
Gwendal Roué c7f0a80a91 Query documentation 2021-11-25 10:52:10 +01:00
Gwendal Roué 068081d043 Query documentation 2021-11-25 10:37:06 +01:00
Gwendal Roué 01ba7de2f9 Query documentation 2021-11-25 10:16:38 +01:00
Gwendal Roué 10e784bee3 Query documentation 2021-11-25 10:11:35 +01:00
Gwendal Roué 21c6c9c794 Query documentation 2021-11-25 09:49:19 +01:00
Gwendal Roué dec515aceb Query documentation 2021-11-25 09:42:21 +01:00
Gwendal Roué 9be04da707 Query documentation 2021-11-25 09:41:25 +01:00
Gwendal Roué 6b02b4ca02 Rename Query generic parameter to Request 2021-11-25 09:37:40 +01:00
Gwendal Roué 5983473aa5 Query documentation 2021-11-25 09:33:24 +01:00
Gwendal Roué 1c4456a9fc Query documentation 2021-11-25 09:28:59 +01:00
Gwendal Roué 82a2776acd Query documentation 2021-11-25 09:14:54 +01:00
Gwendal Roué c7fb5cb3e3 Query demo README 2021-11-24 20:48:56 +01:00
Gwendal Roué f726b670f9 Polish Query demo app 2021-11-24 20:18:37 +01:00
Gwendal Roué 62e710b9b1 Cleanup Query demo app 2021-11-24 19:16:39 +01:00
Gwendal Roué 66f953a21a Rename Query demo app 2021-11-24 17:19:07 +01:00
Gwendal Roué ceed45cf22 QuerySideEffect demo 2021-11-24 09:40:15 +01:00
Gwendal Roué 13a040ae1b CHANGELOG 2021-11-18 08:39:01 +01:00
Gwendal Roué d8b83fba12 improve compilation time 2021-11-18 08:34:59 +01:00
Gwendal Roué 93c4249619 ForeignKeyViolation.databaseError(_:) 2021-11-16 08:51:33 +01:00
Gwendal Roué ebc8524706 Add missing public qualifiers 2021-11-16 08:45:34 +01:00
Gwendal Roué ea41f34f3d Quote table name in raw SQL query 2021-11-16 08:40:16 +01:00
Gwendal Roué 861ca5f022 Merge branch 'development' into dev/async 2021-11-07 16:30:37 +01:00
Gwendal Roué 59f9482aa7 Fix links to documentation images 2021-11-07 16:29:17 +01:00
Gwendal Roué 8658b7bc10 Merge branch 'development' 2021-11-07 16:20:59 +01:00
Gwendal Roué 42eeb54d6f v5.13.0 2021-11-07 16:06:50 +01:00
Gwendal Roué fe32981e0e Performance report: fallback for hardware name
The https://apple.stackexchange.com/a/98089 technique does not work on my mac
2021-11-07 16:06:50 +01:00
Gwendal Roué 0c9de25a8c Bump number of operations performed by performance tests
Apple Silicon and SSD are too fast, and we need to display higher numbers
2021-11-07 16:06:50 +01:00
Gwendal Roué 2b5d3f1d72 Upgrade Realm version in performance tests 2021-11-07 16:06:50 +01:00
Gwendal Roué 9da2e66e46 Fix flaky test 2021-11-07 14:58:18 +01:00
Gwendal Roué 8bf45e5452 Remove debugging code 2021-11-07 14:46:36 +01:00
Gwendal Roué d85168dd3c Query cleanup 2021-11-07 13:47:04 +01:00
Gwendal Roué 7ed103d5e4 Documentation 2021-11-07 13:25:50 +01:00
Gwendal Roué b44a9eb470 Extract @Query into its own package 2021-11-07 12:03:55 +01:00
Gwendal Roué d240d8c5f0 Fix typo 2021-11-07 11:58:51 +01:00
Gwendal Roué 74f268a378 Makefile: test_GRDBAsyncDemo 2021-11-07 11:49:42 +01:00
Gwendal Roué f74ce91a17 Merge branch 'development' into dev/async
# Conflicts:
#	CHANGELOG.md
#	Documentation/Concurrency.md
#	README.md
2021-11-07 11:47:01 +01:00
Gwendal Roué 23a9b6e1ae Makefile: test BUILD_LIBRARY_FOR_DISTRIBUTION & XCFramework 2021-11-07 11:13:35 +01:00
Gwendal Roué 03822bdf99 Makefile: skip test_framework_GRDBtvOS_minTarget until simulator is installed 2021-11-07 10:45:03 +01:00
Gwendal Roué b0c77a5e0f Makefile: tests for demo apps 2021-11-07 10:41:12 +01:00
Gwendal Roué af2d65ef49 Fix Swiftlint warnings 2021-11-07 10:32:00 +01:00
Gwendal Roué 72271b0299 CHANGELOG 2021-11-07 10:07:46 +01:00
Gwendal Roué b5433803ef Makefile: support for Xcode 13.1 2021-11-07 10:03:42 +01:00
Gwendal Roué 037443e600 Wording 2021-11-07 09:36:50 +01:00
Gwendal Roué 19b182b6a8 Remove the immediate transactions advice
It has write transactions fail faster, but it also has writes that only read, or writes that do nothing fail - for no good reason.
2021-11-07 09:20:38 +01:00
Gwendal Roué 0955ac3001 New concurrent read illustration 2021-11-07 09:14:23 +01:00
Gwendal Roué ff7773cf41 Wording 2021-11-07 08:29:24 +01:00
Gwendal Roué 8a0cbb63f5 Wording 2021-11-07 08:25:24 +01:00
Gwendal Roué d3e55cf8f6 wording 2021-11-07 08:23:47 +01:00
Gwendal Roué 7af3858ff6 More robust DatabasePool.close() test 2021-11-07 08:17:48 +01:00
Gwendal Roué c3bbd3d6f8 CHANGELOG 2021-11-07 08:17:46 +01:00
Gwendal Roué eb9d0bce58 Documentation 2021-11-07 08:16:58 +01:00
Gwendal Roué 716e223844 Fix typo 2021-11-06 17:09:12 +01:00
Gwendal Roué 1df5d834e8 Wording 2021-11-06 17:06:51 +01:00
Gwendal Roué 05b03ef56c Wording 2021-11-06 17:02:47 +01:00
Gwendal Roué 06827de207 All fetches are stale 2021-11-06 17:00:19 +01:00
Gwendal Roué 1070b9bd9d Exercise guarantees in context 2021-11-06 16:05:05 +01:00
Gwendal Roué de4c06478d New Concurrency Images 2021-11-06 16:00:40 +01:00
Gwendal Roué 78d5b4abaa Doc of completion block-based async accesses 2021-11-06 12:39:05 +01:00
Gwendal Roué 5e89d08fd0 Layout Concurrency Guide 2021-11-06 12:27:19 +01:00
Gwendal Roué 3d5b436a81 CHANGELOG 2021-11-06 12:23:54 +01:00
Gwendal Roué 1738ad34cd Extract the Concurrency Guide 2021-11-06 12:23:54 +01:00
Gwendal Roué 65668cfc8e Documentation 2021-11-06 11:22:16 +01:00
Gwendal Roué 9249efbe6f Fix UIKit warnings 2021-11-06 09:43:38 +01:00
Gwendal Roué 913860f3ce UUID encoding strategies uppercaseString and lowercaseString
This commit was influenced by https://forums.swift.org/t/53058
2021-11-04 20:33:55 +01:00
Gwendal Roué 088f76db9e Merge pull request #1095 from groue/dev/foreign-keys-checks
Precise foreign key checks for migrations
2021-11-04 19:38:56 +01:00
Gwendal Roué 454dd73c4c CHANGELOG 2021-11-04 18:52:19 +01:00
Gwendal Roué c81a4dbf32 Distinguish "FOREIGN KEY constraint failed" from "FOREIGN KEY constraint violation" errors 2021-11-04 18:44:44 +01:00
Gwendal Roué 127c4e0440 Rename methods that check foreign keys 2021-11-04 18:26:24 +01:00
Gwendal Roué ffdc80646e Documentation 2021-11-04 16:12:46 +01:00
Gwendal Roué 7e9a2f5a73 Fix typo 2021-11-04 15:12:24 +01:00
Gwendal Roué 8a36f4d94e Clean up tests 2021-11-04 15:10:41 +01:00
Gwendal Roué 63ba4fb294 Rename unsafeWithoutDeferredForeignKeyChecks to disablingDeferredForeignKeyChecks 2021-11-04 15:10:33 +01:00
Gwendal Roué d0997efbb6 Documentation 2021-11-04 14:27:34 +01:00
Gwendal Roué 6193c6aa00 foreignKeyViolations() and checkForeignKeyViolations() 2021-11-04 14:19:11 +01:00
Gwendal Roué b66b907fbc Documentation 2021-11-03 14:56:59 +01:00
Gwendal Roué 51c15e9db6 Precise handling of foreign key checks in migrations 2021-11-03 13:26:24 +01:00
Gwendal Roué 0a8967ccde move applied migration identifiers table creation to the top of migrations execution
https://github.com/zdnk/GRDB.swift/commit/51ff937397248355d4b264aedfd5a8f05893a2b8

Thanks @zdnk :-)
2021-11-03 08:33:09 +01:00
Gwendal Roué 19fd58f64f Documentation 2021-11-02 21:48:51 +01:00
Gwendal Roué 19c7ec568c Documentation 2021-11-02 21:42:44 +01:00
Gwendal Roué bc8a31dcd2 Documentation 2021-11-02 20:33:03 +01:00
Gwendal Roué 2273efa07f Improve documentation of persistence methods 2021-11-02 08:13:34 +01:00
Gwendal Roué 62f568d932 Merge branch 'development' into dev/async 2021-11-02 06:02:29 +01:00
Gwendal Roué 1aab03b02a Fix close() test
The behavior of sqlite3_close_v2() depends on SQLite version. Don't test this behavior.
2021-11-01 19:55:31 +01:00
Gwendal Roué 1646dfc49b Fix FAQ organization 2021-11-01 10:28:31 +01:00
Gwendal Roué 640a67257f Documentation for async DatabaseMigrator.migrate() 2021-11-01 10:19:03 +01:00
Gwendal Roué 5be27dd90a CHANGELOG 2021-11-01 10:08:19 +01:00
Gwendal Roué 485ce79293 More ValueObservation async cancellation test 2021-11-01 09:45:16 +01:00
Gwendal Roué 5725d9db21 Refactor the ValueObservation async cancellation test 2021-11-01 08:03:00 +01:00
Gwendal Roué 7897c6a799 asyncUnsafeRead handle closed connection 2021-11-01 07:25:26 +01:00
Gwendal Roué 5f549ef6af Cleanup with Table 2021-11-01 07:22:09 +01:00
Gwendal Roué ac94a2f90e Merge branch 'development' into dev/async 2021-10-31 19:35:13 +01:00
Gwendal Roué 15b38353bc Add experimental warning to the documentation of async methods 2021-10-31 19:35:05 +01:00
Gwendal Roué a7c1a99866 Fix wording 2021-10-31 18:48:26 +01:00
Gwendal Roué 1a87faacfa Merge branch 'development' into dev/async 2021-10-31 18:32:03 +01:00
Gwendal Roué 5cc881138e CHANGELOG 2021-10-31 18:31:32 +01:00
Gwendal Roué 5e56a4465c close() documentation 2021-10-31 18:27:08 +01:00
Gwendal Roué 20cb50f52d Public close() method 2021-10-31 18:12:13 +01:00
Gwendal Roué b4f30784f4 Support for SwiftLint installed via Homebrew on Apple Silicon 2021-10-31 15:32:26 +01:00
Gwendal Roué 0f0c345ebb Fix markdown format 2021-10-31 14:38:10 +01:00
Gwendal Roué 1ee2c8097a SharedValueObservation is experimental 2021-10-31 13:55:18 +01:00
Gwendal Roué 3e58f35f1e I'm so fed up with this
https://developer.apple.com/forums/thread/663975
2021-10-31 13:54:53 +01:00
Gwendal Roué f70b75633c Documentation: fix typo 2021-10-31 12:34:09 +01:00
Gwendal Roué 3a44311b95 Documentation: fix typos and wordings 2021-10-31 12:33:17 +01:00
Gwendal Roué e0a6f43101 Documentation: async/await examples 2021-10-31 12:30:44 +01:00
Gwendal Roué 0c8c8cb1f4 Concurrency Guide: fix wordings 2021-10-31 12:22:23 +01:00
Gwendal Roué fa8598d1e8 Async/Await support is experimental 2021-10-31 11:50:05 +01:00
Gwendal Roué 6cf5a2c33d Merge branch 'development' into dev/async
# Conflicts:
#	CHANGELOG.md
2021-10-31 11:48:27 +01:00
Gwendal Roué 9790d05795 CHANGELOG 2021-10-31 11:29:32 +01:00
Gwendal Roué 273b9befd8 Update documentation for date and uuid encoding strategies 2021-10-31 11:26:27 +01:00
Gwendal Roué 31a5180a58 CHANGELOG 2021-10-31 11:09:22 +01:00
Gwendal Roué 8076e7c725 Fix failing tests for key/id encoding strategies 2021-10-31 11:07:17 +01:00
Gwendal Roué 4cc3768344 Failing tests for key/id encoding strategies 2021-10-31 11:04:01 +01:00
Gwendal Roué 0317c4e454 Reuse screenshot of Combine demo 2021-10-31 06:06:55 +01:00
Gwendal Roué db78c22904 Demo app requirements 2021-10-31 06:04:46 +01:00
Gwendal Roué 6b36c74de9 Concurrency: move saved(_:) and inserted(_:) suggestion to a FAQ 2021-10-31 06:03:35 +01:00
Gwendal Roué 51ab275714 Concurrency: suggest saved(_:) and inserted(_:) 2021-10-30 23:44:30 +02:00
Gwendal Roué b9e1f4604e Concurrency Guide: fix wordings 2021-10-30 23:20:29 +02:00
Gwendal Roué 0b853c5447 Concurrency Guide: fix wordings 2021-10-30 21:08:02 +02:00
Gwendal Roué 691ee8f7fd Concurrency Guide: fix typos and wordings 2021-10-30 20:38:48 +02:00
Gwendal Roué c755dc70ef Restrict async/await to Xcode 13.1+ 2021-10-30 20:09:39 +02:00
Gwendal Roué 9cc30018b6 CHANGELOG 2021-10-30 19:52:09 +02:00
Gwendal Roué 4616ef5229 Remove Concurrency guide from main README 2021-10-30 19:47:57 +02:00
Gwendal Roué 10a741a346 Concurrency Guide 2021-10-30 19:47:57 +02:00
Gwendal Roué 3c78029b3c SwiftUI demo apps: PlayerEditionView saves player when back button is pressed 2021-10-25 19:07:40 +02:00
Gwendal Roué 3ea6fb2201 Merge branch 'development' into dev/async 2021-10-25 18:23:00 +02:00
Gwendal Roué de7d5f42d4 Clarify the benefits of shared observations 2021-10-25 08:47:50 +02:00
Gwendal Roué 450a7c2d71 SharedValueObservation async sequence 2021-10-24 17:47:08 +02:00
Gwendal Roué 2542ad7de8 Reuse ValueObservationStart, and move BufferingPolicy to AsyncValueObservation 2021-10-24 17:33:32 +02:00
Gwendal Roué 2a665df672 Merge branch 'development' into dev/async 2021-10-24 17:13:16 +02:00
Gwendal Roué bddbc31733 Merge pull request #1088 from groue/dev/shareValueObservation
Shared ValueObservation
2021-10-24 17:11:31 +02:00
Gwendal Roué 92e4c8f785 I want a new keyboard ASAP 2021-10-24 17:06:25 +02:00
Gwendal Roué 909afc0233 Fix typo 2021-10-24 17:05:10 +02:00
Gwendal Roué d73228a812 Documentation 2021-10-24 17:04:07 +02:00
Gwendal Roué 76cac45720 Fix typo 2021-10-24 16:35:32 +02:00
Gwendal Roué 22a4f08f40 CHANGELOG 2021-10-24 16:25:18 +02:00
Gwendal Roué ae0edde7c5 Documentation 2021-10-24 16:22:47 +02:00
Gwendal Roué c62e4fd94c Documentation 2021-10-24 16:17:46 +02:00
Gwendal Roué 7690db9284 Documentation 2021-10-24 16:15:46 +02:00
Gwendal Roué 2f212b8a5f SharedValueObservation error handling 2021-10-24 15:46:32 +02:00
Gwendal Roué abc6c55e14 Documentation 2021-10-24 15:17:52 +02:00
Gwendal Roué 450ff62392 Fix SQLCipher tests 2021-10-24 14:03:39 +02:00
Gwendal Roué a5dd61ff13 Fix availability checks in tests
Fix `make test_framework_GRDBiOS_minTarget` with Xcode 13
2021-10-24 13:41:07 +02:00
Gwendal Roué c3618e0cf0 SharedValueObservation publisher 2021-10-24 12:38:00 +02:00
Gwendal Roué a3a804fa82 Upgrade CombineExpectations 2021-10-24 12:37:28 +02:00
Gwendal Roué 8ccaf59d4d Default SharedValueObservation extent: .whileObserved 2021-10-23 17:47:12 +02:00
Gwendal Roué 9e0b1b3ded SharedValueObservation 2021-10-23 17:23:48 +02:00
Gwendal Roué 0a65399a7b Merge branch 'development' into dev/async 2021-10-23 12:48:33 +02:00
Gwendal Roué 618969ab2a More tests for optional collections from prefetched rows 2021-10-23 12:46:30 +02:00
Gwendal Roué 53c662d179 Decode optional collections from prefetched rows
This allows to define records that only decode to-many associations when they are eager-loaded.

See https://github.com/groue/GRDB.swift/issues/1084#issuecomment-948880910
2021-10-23 12:40:55 +02:00
Gwendal Roué 02f71cfecc AsyncValueObservation: let user control buffering policy 2021-10-20 08:16:24 +02:00
Gwendal Roué 00cd547ea6 UIKit demo app: use UIAction 2021-10-19 20:12:26 +02:00
Gwendal Roué 66bbf15f58 UIKit demo app: use @IBSegueAction 2021-10-19 19:30:23 +02:00
Gwendal Roué dbb19979d6 Demo app: prefer tracking over trackingConstantRegion
For those specific player requests, trackingConstantRegion is _correct_. But readers may blindly copy and paste, and use trackingConstantRegion when they should not.

So the demo apps prefer the unoptimized but always-correct `tracking` method instead.
2021-10-19 08:57:45 +02:00
Gwendal Roué 0d8d40d683 Demo apps: document why we use .immediate observation scheduling 2021-10-19 08:55:41 +02:00
Gwendal Roué 5d69d2a35b All demo apps provide unbounded read-only access to the database
Also, UIKit app now does not have to deal with an initial asynchronous delivery of players
2021-10-19 08:54:48 +02:00
Gwendal Roué 128399871a Demo projects organization 2021-10-19 08:15:14 +02:00
Gwendal Roué 4dd5677755 Demo apps: rename newRandom to makeRandom 2021-10-19 08:03:56 +02:00
Gwendal Roué dbf3335188 Demo apps: prefer inserted(_:) over mutating a temp variable 2021-10-19 08:02:09 +02:00
Gwendal Roué 048082f4b2 Demo apps: prefer isEmpty(db) over fetchCount(db) == 0 2021-10-19 07:58:03 +02:00
Gwendal Roué 6a980f90da Async sequence is unsuitable for preventing flash of missing content
See https://forums.swift.org/t/52862 for a longer explanation.

Fortunately, we can base @Query on Combine publishers, which do not have this problem.
2021-10-18 08:41:44 +02:00
Gwendal Roué e4bfea8bcc Use inserted(_:) in order to avoid a temporary variable 2021-10-17 21:25:19 +02:00
Gwendal Roué 329a7c8301 @Query cleanup & documentation 2021-10-17 14:09:53 +02:00
Gwendal Roué 1ff5159d40 Add the MIT license to Query.swift
This file is designed to be copied into user apps: make sure the license comes along.
2021-10-17 13:38:28 +02:00
Gwendal Roué d6f8a9a9ea UIKit demo app is iOS15+/watchOS8+ 2021-10-17 13:26:42 +02:00
Gwendal Roué c711efc7e0 Combine demo app is iOS15+ 2021-10-17 13:26:42 +02:00
Gwendal Roué 01d2bc89a9 Cleanup async demo app 2021-10-17 13:26:42 +02:00
Gwendal Roué 6bcee422b7 Improve tests of async demo app 2021-10-17 13:26:42 +02:00
Gwendal Roué 07faea9cfe Restore demo app tests 2021-10-17 13:26:42 +02:00
Gwendal Roué b76950f695 Follow EnvironmentValues.managedObjectContext example: appDatabase is not optional 2021-10-17 13:26:42 +02:00
Gwendal Roué b9e79791a3 Modernize syntax 2021-10-17 13:26:42 +02:00
Gwendal Roué 533cef692f Use SwiftUI Label 2021-10-17 13:26:42 +02:00
Gwendal Roué 0bed585fd0 Use dismiss from SwiftUI environment 2021-10-17 13:26:42 +02:00
Gwendal Roué 54bef0bba6 Workaround "flash of missing content" https://forums.swift.org/t/52862 2021-10-17 13:26:42 +02:00
Gwendal Roué a7820f9a35 Cleanup 2021-10-17 13:26:42 +02:00
Gwendal Roué bd89311f4d Refactor Query for async sequences 2021-10-17 13:26:41 +02:00
Gwendal Roué 1e17bf011f Refactor Query for AppDatabase access 2021-10-17 13:26:41 +02:00
Gwendal Roué ed8ff31b3e GRDBAsyncDemo 2021-10-17 13:26:41 +02:00
Gwendal Roué 0ead20cdd6 All async apis are experimental 2021-10-17 13:26:41 +02:00
Gwendal Roué 2ad6131d08 Require canImport(_Concurrency)
This fixes the build for macOS 11.5
2021-10-17 13:26:41 +02:00
Gwendal Roué 646782d499 test AsyncValueObservation with all DatabaseQueue & Pool
Also use .trackingConstantRegion since it triggers optimizations
2021-10-17 13:24:10 +02:00
Gwendal Roué a888c46b1a New: AsyncValueObservation 2021-10-17 13:24:10 +02:00
Gwendal Roué 046d1d6355 -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks 2021-10-17 13:24:10 +02:00
Gwendal Roué 8936ef6a40 DatabaseMigrator async methods
migrate(_:)
migrate(_:upTo:)
2021-10-17 13:24:10 +02:00
Gwendal Roué 8754b10a40 Documentation of DatabaseWriter async methods 2021-10-17 13:24:10 +02:00
Gwendal Roué 1f73c20ae2 DatabaseWriter async methods
write, writeWithoutTransaction, barrierWriteWithoutTransaction, erase, vacuum, vacuum(into:)
2021-10-17 13:24:10 +02:00
Gwendal Roué a827188881 async DatabaseReader.unsafeRead 2021-10-17 13:23:34 +02:00
Gwendal Roué 64be4763f2 async DatabaseReader.read 2021-10-17 13:23:34 +02:00
Gwendal Roué 20a1c8666e Merge pull request #1078 from groue/dev/qol
More convenience methods
2021-10-17 13:21:22 +02:00
Gwendal Roué e6f00a7c4b CHANGELOG 2021-10-17 13:11:06 +02:00
Gwendal Roué aa05148a18 Documentation 2021-10-17 13:05:07 +02:00
Gwendal Roué 94c86211bc Add inserted and saved in the list of record methods 2021-10-17 13:00:13 +02:00
Gwendal Roué b4570c0e84 Fix typos in Table documentation 2021-10-17 12:56:24 +02:00
Gwendal Roué 8c9ac0ecd2 Documentation for exists, isEmpty, saved, inserted 2021-10-17 12:28:42 +02:00
Gwendal Roué 5f44162abe Rename request.exists(_:) to isEmpty(_:) 2021-10-17 12:27:19 +02:00
Gwendal Roué 55b938a1f5 Test exists(_:), exists(_🔑) and exists(_🆔) 2021-10-17 12:27:19 +02:00
Gwendal Roué 235ea2e689 Test saved(_:) and inserted(_:) 2021-10-17 12:27:19 +02:00
Gwendal Roué 7a046fb27e exists(_:) quality of life improvements 2021-10-17 12:27:19 +02:00
Gwendal Roué cbd68099a9 inserted(_:) and saved(_:) quality of life improvements 2021-10-17 12:27:19 +02:00
Gwendal Roué 6d44c05f3b DatabasePool.erase() prevents concurrent reads until it has completed 2021-10-13 14:46:47 +02:00
Gwendal Roué fe6d4665ee CHANGELOG 2021-10-12 18:32:38 +02:00
Gwendal Roué 0c6c2c7eb4 Merge pull request #1076 from groue/dev/require-swift-5.3
Require Swift 5.3
2021-10-12 18:29:44 +02:00
Gwendal Roué 03fe178439 Bump Xcode compatibility version of projects (Xcode 12+) 2021-10-11 17:13:26 +02:00
Gwendal Roué ff126c1543 SE-0276 Multi-Pattern Catch Clauses 2021-10-11 16:24:38 +02:00
Gwendal Roué 038c320f07 Require Swift 5.3. 2021-10-11 16:18:29 +02:00
Gwendal Roué ba88a150c0 Improve inline doc of database access methods 2021-10-11 15:50:06 +02:00
Gwendal Roué 32df5e27c3 Test for DatabaseRegionObservation tracking DatabaseRegion.fullDatabase 2021-10-01 11:13:41 +02:00
Gwendal Roué 2d4398798a SE-0299 for DatabaseRegionConvertible.fullDatabase 2021-10-01 11:13:20 +02:00
Gwendal Roué 32b2923e89 Merge branch 'development' 2021-09-25 19:44:17 +02:00
Gwendal Roué dbb4668033 v5.12.0 2021-09-25 19:13:10 +02:00
Gwendal Roué abcbf72421 CHANGELOG 2021-09-25 19:13:10 +02:00
Gwendal Roué 6724862eea Bump min iOS version to 11.0
This drops support for 32 bit devices
Fix #1059
Fix #1033
2021-09-25 19:13:10 +02:00
Gwendal Roué 79c5c1d1ba Failing test for #1059
Xcode 13, make test_install_SPM_ios_release
2021-09-25 19:13:10 +02:00
Gwendal Roué bc9ea84bb2 Merge pull request #1052 from jason-gabriele/fix-swift-error
Change init to fix Swift error
2021-09-22 10:34:43 +02:00
Gwendal Roué c0d70f9ef0 Refactor FTS5 tokenization in order to support custom tokenizers 2021-09-21 19:34:06 +02:00
Gwendal Roué bcd65f534b CHANGELOG 2021-09-20 17:55:56 +02:00
Gwendal Roué 7ae5010353 Document the tokenize(_:) method 2021-09-20 17:53:59 +02:00
Gwendal Roué 46eceb5e28 Document prefix-based FTS patterns 2021-09-20 17:47:17 +02:00
Gwendal Roué dfe519ea9b Build FTS patterns from prefixes 2021-09-20 17:35:47 +02:00
Gwendal Roué b0b8872798 Expose FTS tokenization methods 2021-09-20 17:14:07 +02:00
jason fbc0ee77bb Change init to fix Swift error 2021-09-08 13:57:24 -07:00
Gwendal Roué 1acf8e4b1e Merge branch 'development' 2021-09-03 14:59:18 +02:00
Gwendal Roué 042fbe958d v5.11.0 2021-09-03 14:59:02 +02:00
Gwendal Roué e4bc3da4d7 Merge pull request #1029 from sberrevoets/master
Column coding strategies for Codable records
2021-09-03 14:55:20 +02:00
Gwendal Roué cc23263897 Update thank you notice 2021-09-03 14:51:01 +02:00
Gwendal Roué c7e05caf86 CHANGELOG 2021-09-03 14:50:53 +02:00
Gwendal Roué dabdb0d590 Merge branch 'development' into pr-1029 2021-09-03 14:37:29 +02:00
Gwendal Roué 14ca47f84d CHANGELOG 2021-09-03 14:37:14 +02:00
Gwendal Roué d63429ea23 DatabaseMigrator.migrations 2021-09-03 14:31:46 +02:00
Gwendal Roué 87e9a0d0e0 Add license 2021-08-30 19:21:37 +02:00
Gwendal Roué d2e7485b02 Thorough testing of DatabaseColumnDecodingStrategy with including(all:)
We make sure strategies are correctly applied for each involved record type.
2021-08-29 14:14:31 +02:00
Gwendal Roué c23d977759 Thorough testing of DatabaseColumnDecodingStrategy with including(optional:) and including(required:)
We make sure strategies are correctly applied for each involved record type.
2021-08-29 14:12:23 +02:00
Gwendal Roué 0842e11281 Thourough testing of DatabaseColumnDecodingStrategy 2021-08-29 13:53:22 +02:00
Gwendal Roué e6e2536f6b Reverse DatabaseColumnDecodingStrategy
It does not convert coding keys to columns, but columns to CodingKeys, exactly as JSONDecoder.KeyDecodingStrategy
2021-08-29 13:52:36 +02:00
Gwendal Roué 86e4adf860 Spot a design flaw 2021-08-29 10:08:08 +02:00
Gwendal Roué c36aa2bfda Fix typo 2021-08-29 09:59:49 +02:00
Gwendal Roué 427a00582f Rename keyDecodingStrategy to columnDecodingStrategy 2021-08-29 09:55:06 +02:00
Gwendal Roué 6f024373b3 Fix failing test 2021-08-29 09:51:31 +02:00
Gwendal Roué 76f8b5547f Failing test 2021-08-29 09:51:24 +02:00
Gwendal Roué e60a31f401 Fix failing test 2021-08-29 09:40:32 +02:00
Gwendal Roué 8846ea3c25 Failing test 2021-08-29 09:40:16 +02:00
Gwendal Roué d567630966 Column decoding strategy only applies to columns 2021-08-29 08:55:39 +02:00
Gwendal Roué 5a04183baf Fix test name 2021-08-29 08:55:06 +02:00
Gwendal Roué 8aa640f84b Documentation: Column Names Coding Strategies 2021-08-29 08:41:46 +02:00
Gwendal Roué 42045ad8fb Merge remote-tracking branch 'origin/development' into pr1029 2021-08-29 08:37:13 +02:00
Gwendal Roué 0914b56c41 Add mark 2021-08-29 08:31:36 +02:00
Gwendal Roué 33e2c379db Make it clear that strategies apply to columns only
...and not to row scopes or prefetched records
2021-08-28 16:24:53 +02:00
Gwendal Roué 06763e47d2 Share convertToSnakeCase() 2021-08-28 16:05:41 +02:00
Gwendal Roué 5f23d97903 Add the custom strategies 2021-08-28 15:50:34 +02:00
Gwendal Roué 03a8e03a92 Documentation
Doc of cases is copied from JSONDecoder.KeyDecodingStrategy and JSONEncoder.KeyEncodingStrategy
2021-08-28 15:48:31 +02:00
Gwendal Roué 987b8a48e5 Key coding strategies transform keys into columns
They are not String transformers
2021-08-28 15:41:12 +02:00
Gwendal Roué cbc24751d1 Merge pull request #1046 from groue/dev/issue1043
Improve performance of by-index row decoding
2021-08-28 15:28:19 +02:00
Gwendal Roué e0b397fd4e Upgrade versions of compared libraries 2021-08-28 14:55:18 +02:00
Gwendal Roué c26df67e78 Raise the number of iterations for more precise average 2021-08-28 14:54:51 +02:00
Gwendal Roué ae60de399e Inline GRDBPrecondition 2021-08-28 14:54:51 +02:00
Gwendal Roué b06dc5dc77 Do not inline RowDecodingError.valueMismatch creation 2021-08-28 14:54:51 +02:00
Gwendal Roué c0c8eec75d Replace _checkedIndex with _checkIndex
That's what the stdlib Array does
2021-08-28 14:54:51 +02:00
Gwendal Roué 151a457251 Inline StatementColumnConvertible decoding 2021-08-28 14:53:54 +02:00
Gwendal Roué fc4b55dd97 Restore compilation flags to their pristine state
This reverts an undesired change in 0511fec001
2021-08-26 17:30:30 +02:00
Gwendal Roué ba41c22304 Merge branch 'development' 2021-08-22 16:18:55 +02:00
Gwendal Roué 04c18e3fd6 v5.10.0 2021-08-22 16:18:25 +02:00
Gwendal Roué 28f2aa1423 Upgrade performance comparison dependencies 2021-08-22 16:18:25 +02:00
Gwendal Roué 5ecc069bb4 TODO 2021-08-22 13:34:07 +02:00
Gwendal Roué 47934cc858 TODO 2021-08-22 12:44:54 +02:00
Gwendal Roué 0511fec001 SE-0299: enhance access to Column.rowID 2021-08-22 12:42:53 +02:00
Gwendal Roué 14b5eea277 CHANGELOG 2021-08-22 11:12:10 +02:00
Gwendal Roué c7294af809 Merge pull request #1038 from GetToSet/development
Add match operator in ColumnExpression for FTS5.
2021-08-22 11:10:02 +02:00
Gwendal Roué 8eff518850 Documentation for FTS5 column matching 2021-08-22 11:03:54 +02:00
Gwendal Roué 48ef691897 Disallow FTS5 column matching against NULL
SQLite just throws a syntax error
2021-08-22 11:03:18 +02:00
Ethan Wong 836432c4ce Add tests of column matching expression for fts5 2021-08-22 16:30:07 +08:00
Ethan Wong 2f3311cd1e Add match operator in ColumnExpression for FTS5 2021-08-22 16:12:39 +08:00
Gwendal Roué 8f7a2b6a8e Documentation: Combine and Data Consistency 2021-08-21 18:18:57 +02:00
Gwendal Roué 7ae35068c4 Merge pull request #1037 from groue/dev/BUILD_LIBRARY_FOR_DISTRIBUTION
Support BUILD_LIBRARY_FOR_DISTRIBUTION
2021-08-21 17:34:32 +02:00
Gwendal Roué 6639e9c598 CHANGELOG 2021-08-21 15:55:37 +02:00
Gwendal Roué e6cdbb156d FAQ: Does GRDB support library evolution and ABI stability 2021-08-21 15:48:17 +02:00
Gwendal Roué e2c9734df1 Specialize StatementColumnConvertible cursors 2021-08-21 15:48:07 +02:00
Gwendal Roué 18e9b1b9aa Specialize StatementColumnConvertible decoding 2021-08-21 14:53:11 +02:00
Gwendal Roué 59c4d42076 Remove test warnings with BUILD_LIBRARY_FOR_DISTRIBUTION 2021-08-21 14:08:46 +02:00
Gwendal Roué 665770c50c Remove all ABI annotations 2021-08-21 13:14:54 +02:00
Gwendal Roué f36f4aaf74 Deprecate count(_ counted: SQLSelectable) 2021-08-21 12:44:14 +02:00
Gwendal Roué 2858b803d0 Remove useless <Void> qualifiers
SQLRequest and CommonTableExpression are <Row> by default
2021-08-21 12:25:04 +02:00
Gwendal Roué faf100dbba Merge pull request #1036 from groue/dev/github-action
Basic GitHub action
2021-08-21 12:10:53 +02:00
Gwendal Roué 8af2b4bf1b Basic GitHub action 2021-08-21 12:06:09 +02:00
Gwendal Roué 253c878367 Cleanup 2021-08-17 08:30:51 +02:00
Gwendal Roué f5b1219549 SQLStatementCursor no longer allocates a copy of the sql C string
Based on https://forums.swift.org/t/stable-pointer-into-a-c-string-without-copying-it/51244
2021-08-16 18:59:55 +02:00
Gwendal Roué eda960de58 Merge branch 'development' 2021-08-15 19:12:58 +02:00
Gwendal Roué f0443a63eb v5.9.0 2021-08-15 19:12:48 +02:00
Gwendal Roué 24b978c3bb Update thank you notice 2021-08-15 14:33:03 +02:00
Gwendal Roué 3d180183a4 CHANGELOG 2021-08-15 14:32:51 +02:00
Gwendal Roué 98930d7f1d Merge pull request #1025 from DrawboardLtd/value-observer-reducer-locking
Added locking around `reducer` to mitigate Release build crashes.
2021-08-15 14:23:18 +02:00
Gwendal Roué adc16ea7dc Protect mutating TextOutputStream with a lock
This change addresses https://github.com/groue/GRDB.swift/pull/1025#issuecomment-898894618
2021-08-15 13:03:37 +02:00
Scott Berrevoets 79abf62a47 Fix name and convert Decodables as well 2021-08-14 21:45:35 -07:00
Scott Berrevoets 4ab7f1cf3e Add support for encoding as well 2021-08-12 20:12:10 -07:00
Scott Berrevoets cdc7805471 Add option for converting snake case
This adds an option to convert column names from snake case to camel
case, similar to how JSONDecoder works. In fact, the implementation here
is largely based on JSONDecoder's implementation.
2021-08-12 20:11:54 -07:00
Renaud Lienhart 7791e300d2 Use the ValueObserver.synchronized() helper 2021-08-06 09:27:39 +10:00
Matt Gallagher 8350dced55 Added locking around reducer to mitigate Release build crashes. 2021-08-06 09:10:29 +10:00
Gwendal Roué 97221c7bd6 Documentation 2021-07-31 09:39:24 +02:00
Gwendal Roué eb6895207e Remove Swiftlint warnings 2021-07-30 16:14:03 +02:00
Gwendal Roué d93b2f16e4 Remove the promising swiftlint rule that catches urls in doc comments
It yields false positives.

https://github.com/groue/GRDB.swift/pull/1012#issuecomment-889919351
2021-07-30 16:12:47 +02:00
Gwendal Roué f09a5e105d CHANGELOG 2021-07-30 14:34:38 +02:00
Gwendal Roué e6f6a11277 Merge pull request #1019 from groue/dev/merge-statements
Merge prepared statement types, and introduce statement cursor
2021-07-30 14:31:48 +02:00
Gwendal Roué fe95d07062 Documentation 2021-07-30 14:25:49 +02:00
Gwendal Roué dc3fac95db allStatements() can build statements without any arguments 2021-07-30 14:24:08 +02:00
Gwendal Roué be0a2c01e1 More allStatements() documentation 2021-07-30 13:55:59 +02:00
Gwendal Roué f232dfde27 CHANGELOG 2021-07-30 13:44:23 +02:00
Gwendal Roué e1dd96603b Test that cursors can trigger transaction observers
This is important because users will start executing database modifications with fetching methods, now that they have db.allStatement().
2021-07-30 13:41:52 +02:00
Gwendal Roué f2296c065a Test that cursors can invalidate schema cache
This is important because users will start executing DROP statements with fetching methods, now that they have db.allStatement().
2021-07-30 13:02:36 +02:00
Gwendal Roué 096eeffecf More allStatements() documentation 2021-07-30 12:54:52 +02:00
Gwendal Roué 6bbec1495d fix typo 2021-07-30 08:53:31 +02:00
Gwendal Roué a60fe170de Document allStatements() 2021-07-30 08:51:57 +02:00
Gwendal Roué 5cd34da6ca Use allStatements() from makeStatement() 2021-07-30 08:50:15 +02:00
Gwendal Roué a4acbf4854 Tests consuming values from allStatements() 2021-07-29 23:04:02 +02:00
Gwendal Roué c9eb67dae8 Database.allStatements(sql:literal:)
Addresses #1015
2021-07-29 22:41:49 +02:00
Gwendal Roué bf601e6810 Merge SelectStatement and UpdateStatement
Addresses #1015
2021-07-29 20:20:15 +02:00
Gwendal Roué c45f681813 Update thank you notice 2021-07-21 08:41:10 +02:00
Gwendal Roué 6a2645e0be CHANGELOG 2021-07-21 08:40:53 +02:00
Gwendal Roué 96108a5b9b Merge pull request #1012 from ZevEisenberg/add-brackets-to-urls
Add brackets to urls in doc comments to make them clickable
2021-07-21 07:53:58 +02:00
Zev Eisenberg a6e0d47d61 Add lint rule to catch URLs in doc comments that are not wrapped in angle brackets. 2021-07-20 21:10:36 -04:00
Zev Eisenberg 8b060e6b09 Add angle brackets to URLs to make them clickable in Xcode's rendered documentation. 2021-07-20 20:53:58 -04:00
Gwendal Roué f0a99a9100 Merge pull request #1010 from tternes/tt-add-vacuum-into
Add VACUUM INTO Support
2021-07-20 20:15:33 +02:00
Gwendal Roué 6cc45202a0 Enable vacuum(into:) with SQLCipher 2021-07-20 20:02:18 +02:00
Gwendal Roué 368594b051 Disable VACUUM INTO tests when not available 2021-07-20 19:42:40 +02:00
Gwendal Roué 8d4416d02e Update thank you notice 2021-07-20 19:36:49 +02:00
Gwendal Roué 6db245efe5 CHANGELOG 2021-07-20 19:35:59 +02:00
Gwendal Roué c115b6a92d Explain why vacuum(into:) is not available on DatabaseReader 2021-07-20 19:31:22 +02:00
Thaddeus Ternes dc40da1ef2 Improvements based on PR feedback 2021-07-19 21:59:43 -05:00
Gwendal Roué 374595d89e Merge pull request #1009 from kaishin/patch-1
Remove extra dot at the end of reference URL
2021-07-19 18:49:23 +02:00
Gwendal Roué 2d05dd488c Update TODO.md 2021-07-19 11:42:26 +02:00
Thaddeus Ternes 7d0c8c6657 Refactor tests, fix inline documentation parameter value 2021-07-12 02:28:49 -05:00
Thaddeus Ternes ed9fb39982 Add inline documentation 2021-07-12 01:26:34 -05:00
Thaddeus Ternes b28f75c5a2 Add VACUUM INTO support to DatabaseWriter 2021-07-12 01:19:45 -05:00
Reda Lemeden 1ac364defb Remove extra dot at the end of reference URL 2021-07-12 02:11:34 +02:00
Gwendal Roué e19de4e42e Merge branch 'dev/codable-database-value' into development 2021-07-04 19:29:47 +02:00
Gwendal Roué 57cf9b45b6 Add missing Foundation import for SPM 2021-07-04 19:28:27 +02:00
Gwendal Roué d772e8da3a CHANGELOG 2021-07-04 18:37:44 +02:00
Gwendal Roué ad48aa6eec Document the default DatabaseValueConvertible+Codable implementation 2021-07-04 18:36:56 +02:00
Gwendal Roué 620eb6f21c Default DatabaseValueConvertible+Codable implementation uses the JSON format 2021-07-04 17:34:31 +02:00
Gwendal Roué 653837bb02 Merge branch 'master' into development 2021-07-04 12:05:30 +02:00
Gwendal Roué 3de6f51427 Document that cipher_plaintext_header_size disables the salt 2021-07-01 09:12:57 +02:00
Gwendal Roué 9456fe809d Fix for Xcode 11.4 2021-06-27 16:36:18 +02:00
Gwendal Roué e907bc2686 Fix tvOS 14.5 simulator for Travis 2021-06-27 16:11:37 +02:00
Gwendal Roué e386553c18 Update Makefile for Xcode 12.5 2021-06-27 16:04:58 +02:00
Gwendal Roué 3b435d018f Use Xcode 12.5 on Travis 2021-06-27 15:54:56 +02:00
Gwendal Roué b5de7a907a Update link to 0xdead10cc documentation 2021-06-27 15:43:32 +02:00
Gwendal Roué e5bb488b00 CHANGELOG 2021-06-27 15:39:21 +02:00
Gwendal Roué 76852c1f9c Improve documentation about handling of NULL in foreign keys 2021-06-27 15:36:43 +02:00
Gwendal Roué 2f36fc06f5 Fix failing tests for #999 2021-06-27 15:36:12 +02:00
Gwendal Roué ff576d945c Failing tests for #999 2021-06-27 15:35:44 +02:00
Gwendal Roué 0098369e29 Simplify Refinable 2021-06-27 13:11:26 +02:00
Gwendal Roué fb5a3ba388 CHANGELOG 2021-06-22 08:27:38 +02:00
Gwendal Roué 98f398cd75 Deemphasize Table 2021-06-22 08:26:55 +02:00
Gwendal Roué f2dbbee428 Merge pull request #993 from groue/dev/Table
QueryInterfaceRequest builder with dynamic table/view name
2021-06-22 08:15:46 +02:00
Gwendal Roué f54467af3c Fix test for batch deletion of Identifiable type with Optional ID 2021-06-21 18:26:35 +02:00
Gwendal Roué 8c361acd7f Update documentation: batch delete/updates are available on TableRecord 2021-06-21 18:21:04 +02:00
Gwendal Roué bdfd5ce277 Table: batch delete & update
Also, MutablePersistableRecord is no longer necessary for such operations. TableRecord is enough.
2021-06-21 18:08:27 +02:00
Gwendal Roué 120c973e29 Refactor test for association from CTE to Table 2021-06-20 14:31:45 +02:00
Gwendal Roué 17ee1debdc Test associations from TableRecord to Table 2021-06-20 14:26:21 +02:00
Gwendal Roué b154998ae6 Fix documentation 2021-06-20 11:57:53 +02:00
Gwendal Roué eedd3af59b Test association from CTE to Table 2021-06-20 11:54:55 +02:00
Gwendal Roué c5b6325cf6 Table documentation 2021-06-20 11:39:14 +02:00
Gwendal Roué 629840f6f2 Table.fetchCount(_:) 2021-06-20 11:37:59 +02:00
Gwendal Roué e7ef3e1867 Prevent aggregate misuse
I wrote association.max("id") when I meant association.max(Column("id"))
2021-06-20 11:08:24 +02:00
Gwendal Roué 32bbee9c8a Tests for Table Associations 2021-06-20 11:07:38 +02:00
Gwendal Roué 9def48f4f6 Tests for Table 2021-06-19 17:31:40 +02:00
Gwendal Roué 92d10e2713 Table fetching methods 2021-06-19 17:31:23 +02:00
Gwendal Roué 3d855a6a90 Table request methods 2021-06-19 15:25:14 +02:00
Gwendal Roué d7971d76e7 Introduce Table 2021-06-19 14:30:04 +02:00
Gwendal Roué 220d221ea6 CHANGELOG 2021-06-19 14:03:37 +02:00
Gwendal Roué 2ce588ad76 Cached statements from a SQL literal
Addresses https://github.com/groue/GRDB.swift/issues/985#issuecomment-859570434
2021-06-19 13:57:53 +02:00
Gwendal Roué 7050e3cc48 Naive fix for #983 2021-06-19 13:31:30 +02:00
Gwendal Roué fed0b6b136 CHANGELOG 2021-06-19 13:24:27 +02:00
Gwendal Roué e3674ccdf2 Documentation for selectID() 2021-06-19 13:21:13 +02:00
Gwendal Roué 046564dab6 Fix #991 2021-06-19 13:05:24 +02:00
Gwendal Roué d6069888b8 Update thank you notice 2021-06-19 12:24:31 +02:00
Gwendal Roué a9ea79dba9 CHANGELOG 2021-06-19 12:24:23 +02:00
Gwendal Roué 18083165a1 Merge pull request #989 from pp5x/pp5x/fts-synchronize-if-not-exists
FTS: add support of ifNotExists in synchronize()
2021-06-19 12:20:13 +02:00
Gwendal Roué 1aeb10439f synchronize: failing test for FTS5 ifNotExists support 2021-06-17 19:30:24 +02:00
Gwendal Roué 1a2de126ce Fix #988 2021-06-17 19:30:03 +02:00
Pierre Pagnoux d8cb3066a1 synchronize: failing test for ifNotExists support 2021-06-15 17:35:45 +02:00
Gwendal Roué c3b3d2eeb8 Fix Xcode 13 beta 1 compilation warnings 2021-06-08 05:54:45 +02:00
Gwendal Roué 52b1727bb3 Fix Xcode 13 beta 1 compilation error 2021-06-08 05:54:31 +02:00
Gwendal Roué a328349514 Thank you notice 2021-05-31 14:04:02 +02:00
Gwendal Roué 5666ffb4a7 CHANGELOG 2021-05-31 14:03:56 +02:00
Gwendal Roué e6ef8740eb Merge branch 'master' into development 2021-05-31 13:58:51 +02:00
Gwendal Roué df6c2e2b05 Merge pull request #980 from jroselightricks/feature/spelling
Fix spelling succesful -> successful.
2021-05-31 13:58:25 +02:00
Jonathan Rose ae7f83dc40 Fix spelling succesful -> successful. 2021-05-31 14:28:28 +03:00
Gwendal Roué 1693a706e0 Skip tests that do not support encrypted databases 2021-05-29 13:26:17 +02:00
Gwendal Roué af13c91744 Merge branch 'development' 2021-05-16 15:25:33 +02:00
Gwendal Roué b5dea2164f v5.8.0 2021-05-16 15:25:15 +02:00
Gwendal Roué 148897ad73 Simplify 2021-05-04 07:27:21 +02:00
Gwendal Roué 095bfde072 CHANGELOG 2021-05-02 18:05:13 +02:00
Gwendal Roué fabdb73785 Merge pull request #967 from steipete/peter/selectStatement-Debug
Make SelectStatement conform to CustomStringConvertible
2021-05-02 18:03:44 +02:00
Gwendal Roué f30f970cf2 Merge pull request #973 from groue/dev/issue-971
Restore access to attached databases from record types
2021-05-02 10:12:58 +02:00
Gwendal Roué 1c2499528c Merge branch 'development' into dev/issue-971 2021-05-02 10:12:41 +02:00
Gwendal Roué 766e731bf9 Merge pull request #974 from groue/dev/issue-965
Provide access to included associations when root table is not selected
2021-05-02 10:11:12 +02:00
Gwendal Roué b9496a01e1 Simplify FAQ now that Statement conforms to CustomStringConvertible 2021-05-02 10:07:07 +02:00
Gwendal Roué 1554c80fdb Statement.sql checks correct scheduling 2021-05-02 10:02:21 +02:00
Gwendal Roué 61ee7cc3f7 Move SelectStatement.description to Statement 2021-05-02 10:01:44 +02:00
Gwendal Roué 0f481e7867 CHANGELOG 2021-05-01 17:32:02 +02:00
Gwendal Roué ed3397176a Documentation 2021-05-01 17:28:49 +02:00
Gwendal Roué 5f4c64ceda Fix failing tests for #965 2021-05-01 17:00:12 +02:00
Gwendal Roué e5a810105a Failing tests for #965 2021-05-01 16:59:38 +02:00
Gwendal Roué a46b2ad127 Fix "cannot ATTACH database within transaction" error in older versions of SQLite 2021-05-01 15:08:36 +02:00
Gwendal Roué 3ccac4098a CHANGELOG 2021-05-01 15:06:08 +02:00
Gwendal Roué a4e8bbe2da Add test for cross-attached-databases association 2021-05-01 14:55:53 +02:00
Gwendal Roué 52bc7eb7c6 Cleanup 2021-05-01 14:40:20 +02:00
Gwendal Roué e8802fb010 Fix #971 2021-05-01 14:32:01 +02:00
Gwendal Roué 885f43dbad Failing tests for #971 2021-05-01 14:27:44 +02:00
Peter Steinberger 5dfab017e5 Make SelectStatement conform to CustomStringConvertible 2021-04-22 14:12:10 +02:00
Gwendal Roué 35d6ac0041 CHANGELOG 2021-04-18 18:21:22 +02:00
Gwendal Roué eae64b587a Documentation 2021-04-18 17:25:05 +02:00
Gwendal Roué fb6ae07722 Documentation 2021-04-18 17:22:08 +02:00
Gwendal Roué 491e17f62e Documentation 2021-04-18 17:21:13 +02:00
Gwendal Roué f521002e74 Documentation 2021-04-18 17:17:30 +02:00
Gwendal Roué bbaee79618 Documentation 2021-04-18 17:10:47 +02:00
Gwendal Roué 64951c84d7 Documentation 2021-04-18 17:08:02 +02:00
Gwendal Roué 5996b64469 Documentation 2021-04-18 17:00:55 +02:00
Gwendal Roué 65b2fecdfc Documentation 2021-04-18 16:56:38 +02:00
Gwendal Roué 232086e50e Documentation 2021-04-18 16:41:53 +02:00
Gwendal Roué 8f7feda27c Documentation 2021-04-18 16:31:44 +02:00
Gwendal Roué 6aa6c4d4b5 Documentation 2021-04-18 16:19:06 +02:00
Gwendal Roué afc360cf78 Documentation 2021-04-18 16:13:42 +02:00
Gwendal Roué 5673d73738 Documentation 2021-04-18 16:09:22 +02:00
Gwendal Roué 4a894f2b43 Documentation 2021-04-18 16:05:35 +02:00
Gwendal Roué 83cd6d1469 Change Query Interface Organization picture 2021-04-18 14:28:48 +02:00
Gwendal Roué 0b2e5d836f Query Interface Organization 2021-04-18 14:26:46 +02:00
Gwendal Roué b9576aedbe SQLCollection is not public 2021-04-18 11:41:11 +02:00
Gwendal Roué 2f549d21bf Can't articulate distinctive features yet 2021-04-18 11:28:56 +02:00
Gwendal Roué 4d6958b52a Documentation 2021-04-17 20:55:21 +02:00
Gwendal Roué 588b2677e7 Documentation 2021-04-17 20:52:26 +02:00
Gwendal Roué 66e52eea40 Documentation 2021-04-17 20:46:29 +02:00
Gwendal Roué 975cbaa7e8 MyPlayground setup 2021-04-17 20:31:27 +02:00
Gwendal Roué 9e265f7ebc Documentation 2021-04-17 20:19:33 +02:00
Gwendal Roué 37522f3766 Documentation 2021-04-17 19:55:01 +02:00
Gwendal Roué 4980beda69 Documentation 2021-04-17 16:47:28 +02:00
Gwendal Roué 69b9c7331f Documentation 2021-04-17 16:46:16 +02:00
Gwendal Roué 28375f5c1a Organization image 2021-04-17 16:41:37 +02:00
Gwendal Roué e019617a50 Documentation 2021-04-17 16:21:11 +02:00
Gwendal Roué 8ff0c456dc Documentation 2021-04-17 16:13:49 +02:00
Gwendal Roué 744b0c5661 Documentation 2021-04-17 16:10:28 +02:00
Gwendal Roué c6003143c4 Documentation 2021-04-17 16:04:51 +02:00
Gwendal Roué b0545bcfb0 CHANGELOG 2021-04-17 15:52:17 +02:00
Gwendal Roué 3976feb6ab Query Interface Organization 2021-04-17 15:52:11 +02:00
Gwendal Roué 002399ff1a Remove limit(_:offset:) from documentation 2021-04-17 15:44:53 +02:00
Gwendal Roué cdc21531fc Query Interface Organization 2021-04-17 15:41:03 +02:00
Gwendal Roué 7afe011b69 Improve documentation 2021-04-17 15:38:30 +02:00
Gwendal Roué 12809f5891 Fix duplicate file warning 2021-04-17 13:22:27 +02:00
Gwendal Roué 7fd51f440a Warn about DerivableRequest.limit(_:offset:)
We can't deprecate it because the compiler emits a warning on acceptable request.limit() calls :-(
2021-04-17 13:22:08 +02:00
Gwendal Roué 4f0d3b31e1 SQLRequest is SQLRequest<Row> unless stated otherwise 2021-04-17 12:53:20 +02:00
Gwendal Roué 36039fb6a3 Documentation 2021-04-17 12:48:18 +02:00
Gwendal Roué e66e59cd21 Remove misleading documentation
Limiting to-many associations does not do what this false documentation is saying
2021-04-15 18:24:54 +02:00
Gwendal Roué a3279c9f63 Distinctive Features 2021-04-15 18:02:43 +02:00
Gwendal Roué 5ed64ea8f8 CHANGELOG 2021-04-14 20:13:58 +02:00
Gwendal Roué 62763ece52 Documentation for LIKE ESCAPE 2021-04-14 20:12:02 +02:00
Gwendal Roué c50f698eae Add support for the ESCAPE clause of the LIKE operator
Address #962
2021-04-14 20:06:54 +02:00
Gwendal Roué 31e2b01c10 Merge branch 'development' 2021-04-11 16:32:47 +02:00
Gwendal Roué 7fd786955c v5.7.4 2021-04-11 16:17:39 +02:00
Gwendal Roué af13283aa7 Update thank you notice 2021-04-11 15:48:56 +02:00
Gwendal Roué 6a5d196c2d CHANGELOG 2021-04-11 15:47:32 +02:00
Gwendal Roué 6959ac80b5 Merge pull request #960 from MartinP7r/userinfo_tests
adds test for userInfo being applied to database encoder/decoder
2021-04-11 15:40:03 +02:00
Martin Pfundmair 0c4e483e9e adds test for userInfo in EncodableRecord.databaseJSONDecoder()
Making sure that `databaseEncodingUserInfo` is being applied to `FetchableRecord.databaseJSONDecoder()`

This tries to cover the other half of the changes in PR groue#958
2021-04-11 09:29:33 +09:00
Gwendal Roué f9c162b657 CHANGELOG 2021-04-10 18:16:53 +02:00
Gwendal Roué c0f537c5e6 Merge pull request #956 from groue/dev/observation-case-insensitivity
Fix case-sensitivity of region-based database observation
2021-04-10 18:12:03 +02:00
Martin Pfundmair 8895d590a0 adds test for userInfo in FetchableRecord.databaseJSONDecoder()
Making sure that databaseDecodingUserInfo is being applied to FetchableRecord.databaseJSONDecoder()

This tries to cover some of the changes in PR groue#958
2021-04-11 00:02:09 +09:00
Gwendal Roué a44c518e31 Fix DatabaseRegion tests for tvOS 10.2 2021-04-10 16:27:46 +02:00
Gwendal Roué 0571d9b3b8 Fix DatabaseRegion tests for iOS 10.3.1 2021-04-10 16:27:45 +02:00
Gwendal Roué c0a3e61253 DatabaseRegion is now case-preserving and case-insensitive 2021-04-10 16:27:45 +02:00
Gwendal Roué c02901b335 Fix canonicalName(_:ofType:) 2021-04-10 16:27:45 +02:00
Gwendal Roué ee2d6d8074 CaseInsensitiveIdentifier should help 2021-04-10 16:27:45 +02:00
Gwendal Roué b51dc81c3a Failing tests for #954 2021-04-10 16:27:45 +02:00
Gwendal Roué 47199ed72b Merge branch 'master' into development 2021-04-10 16:26:55 +02:00
Gwendal Roué 28bddb04fa Merge pull request #955 from steipete/peter/query-base
Ensure Query can be updated
2021-04-10 16:20:14 +02:00
Gwendal Roué c34615ced3 Document that @steipete's test has turned moot
We don't 100% need to address this now, but we 100% need to remember this in the future.
2021-04-10 16:10:02 +02:00
Gwendal Roué a5ffc52dbe Restore the barebone app setup
Leave the AppView(initialOrdering:) initializer, though, so that readers can get some inspiration.
2021-04-10 15:45:00 +02:00
Gwendal Roué fd61a5f1ea Remove 14.5 IPHONEOS_DEPLOYMENT_TARGET
Tests succeed on 14.4, and 14.0 target does not generate any Xcode warning
2021-04-10 15:37:18 +02:00
Gwendal Roué 0f70e9d9c9 Remove all DEVELOPMENT_TEAM from demo app 2021-04-10 15:35:42 +02:00
Gwendal Roué d4f1102976 Document how AppDatabase.makeShared() supports test
This helps readers understand the purpose of those lines, and remove them if they are not interested.
2021-04-10 15:07:02 +02:00
Martin Pfundmair 1591948c10 Merge pull request #958 from Rightpoint/userinfo-fix
Always add userInfo to databaseJSONDecoder and databaseJSONEncoder
2021-04-10 15:21:52 +09:00
Chris Ballinger 43de1c24a7 Add userInfo to databaseJSONDecoder and databaseJSONEncoder 2021-04-08 13:11:59 -07:00
Peter Steinberger 481f6e93e5 Add UI test to show late-changing of Query 2021-04-08 10:41:20 +02:00
Peter Steinberger 6887441264 Ensure Query can be updated 2021-04-07 15:32:59 +02:00
Gwendal Roué e017eddf4f Merge branch 'development' 2021-04-05 17:00:08 +02:00
Gwendal Roué 53d75c37aa v5.7.3 2021-04-05 16:59:44 +02:00
Gwendal Roué 331990ce33 CHANGELOG 2021-04-05 16:54:56 +02:00
Gwendal Roué 63a52acb34 Merge pull request #953 from groue/dev/refactor-SwiftUI-demo
Refactor the SwiftUI demo app
2021-04-05 16:51:17 +02:00
Gwendal Roué 6958a10a08 Refactor the SwiftUI demo application 2021-04-05 15:28:45 +02:00
Martin Pfundmair 5d14b3d6db Merge pull request #952 from holsety/tiny/typo
Fix a tiny typo
2021-04-05 08:00:44 +09:00
hlst de0709163c Fix a tiny typo 2021-04-05 06:31:56 +08:00
Gwendal Roué 8c872fccfc End of experiment. But we squeezed a few more cycles :-) 2021-04-04 13:50:17 +02:00
Martin Pfundmair 46867877fd Merge pull request #951 from alexwlchan/patch-1
Fix a typo: "bet set" ~> "be set"
2021-04-04 09:25:09 +09:00
Alex Chan 622ecda283 Fix a typo: "bet set" ~> "be set" 2021-04-03 21:06:05 +01:00
Gwendal Roué 5f9911ff0d Performance tests for optimized records 2021-04-03 18:02:15 +02:00
Gwendal Roué eaf830c05c Fix paths in performance report 2021-04-03 16:47:53 +02:00
Gwendal Roué 064dec5095 Upgrade Realm 2021-04-03 16:26:27 +02:00
Gwendal Roué 89521a7288 Improve statement binding performance 2021-04-03 14:52:22 +02:00
Gwendal Roué 76d4e38cd1 CHANGELOG and thank you notice for #950 2021-04-02 08:29:25 +02:00
Gwendal Roué c56a56a2f3 Merge pull request #950 from MartinP7r/fix/json-column-memory
Fix memory consumption when encoding JSON columns
2021-04-02 08:26:21 +02:00
Martin Pfundmair 02d3518194 adds autoreleasepool for databaseJSONEncoder
when encoding json columns in order to prevent memory build up
2021-04-01 18:40:19 +09:00
Gwendal Roué 67892d7cdb CHANGELOG 2021-03-29 06:12:17 +02:00
Gwendal Roué 0e091124a2 v5.7.2 2021-03-29 06:09:24 +02:00
Gwendal Roué 2402185235 Make SQLLiteral public 2021-03-29 06:08:44 +02:00
Gwendal Roué f406062b81 Merge pull request #948 from xAlien95/patch-1
Fix documentation typo
2021-03-29 06:06:17 +02:00
Stefano De Carolis 7bf25925c7 Fix documentation typo 2021-03-29 02:25:10 +02:00
Gwendal Roué 8dd8a57de3 v5.7.1 2021-03-28 15:33:58 +02:00
Gwendal Roué fa8a8f0b87 Add fixit for SQLLiteral 2021-03-28 15:31:23 +02:00
Gwendal Roué fa2c489ee4 Fix typo 2021-03-28 10:20:35 +02:00
Gwendal Roué 2cb0baf88e Merge branch 'development' 2021-03-28 10:17:20 +02:00
Gwendal Roué 1ab23dfa52 v5.7.0 2021-03-28 10:16:20 +02:00
Gwendal Roué bd29585461 Wording 2021-03-28 10:12:55 +02:00
Gwendal Roué f1cd6dbae8 CHANGELOG 2021-03-28 09:56:47 +02:00
Gwendal Roué a91d9b23e0 Merge pull request #947 from Rightpoint/codable-access
Allow access to Encoder from KeyedEncodingContainer
2021-03-28 09:51:57 +02:00
Gwendal Roué 7eb348cb2a [skip travis] New Identifiable Records documentation chapter 2021-03-28 08:39:43 +02:00
Gwendal Roué ab4ae144ac [skip travis] Simplify Record introduction 2021-03-28 07:51:12 +02:00
Gwendal Roué 09899e9bcf filter(id:) does not accept optionals 2021-03-28 06:48:22 +02:00
Gwendal Roué 2625653532 Improve documentation of the EXISTS operator 2021-03-27 22:49:58 +01:00
Gwendal Roué ea26dea687 Fix typo 2021-03-27 22:20:30 +01:00
Gwendal Roué 4a17281bd7 Fix typo 2021-03-27 22:09:11 +01:00
Gwendal Roué e9ba3e6ccc Fix typo 2021-03-27 22:08:20 +01:00
Gwendal Roué 9692410e7d CHANGELOG 2021-03-27 22:07:09 +01:00
Gwendal Roué b69dfb1709 Document the type-safe extensions to Identifiable records 2021-03-27 22:07:04 +01:00
Gwendal Roué 4307eedbc0 Update demo apps with the new type-safe primary key methods 2021-03-27 21:10:34 +01:00
Gwendal Roué 521f9e498a deleteOne(_🆔) and deleteAll(_:ids:) 2021-03-27 21:07:01 +01:00
Gwendal Roué e7ce5f13e7 Tests for rowid filtering of Identifiable types 2021-03-27 21:06:01 +01:00
Gwendal Roué 55c0abef8b Tests for id filtering of Identifiable types 2021-03-27 19:46:03 +01:00
Gwendal Roué 9489174b98 Filter by id for Identifiable types with optional ID type 2021-03-27 18:47:16 +01:00
Gwendal Roué b086b99821 Filter by id for Identifiable types 2021-03-27 17:43:01 +01:00
Chris Ballinger 984dea156c Allow access to Encoder and Decoder from KeyedCodingContainer 2021-03-27 08:57:44 -07:00
Gwendal Roué 1297a781fd Better fatal error messages for unimplemented features 2021-03-27 16:41:23 +01:00
Gwendal Roué c4f9ddd688 Simplify handling of collated expressions 2021-03-27 16:34:37 +01:00
Gwendal Roué fcff9b34ba Make sure empty migrator publisher is async as well 2021-03-27 15:23:30 +01:00
Gwendal Roué 914ad1b882 Address #945 by running a distinctive query
When a user finds this query in the error log, it will be easier for everybody to understand why it happens.
2021-03-27 14:56:08 +01:00
Gwendal Roué b13922b76e Database schema cache distinguishes the main from the temp schema
Addresses https://github.com/groue/GRDB.swift/pull/946#issuecomment-805756799
2021-03-27 14:50:25 +01:00
Gwendal Roué f6f4839e07 Document that WITHOUT ROWID tables can't be tracked (#945) 2021-03-27 11:50:38 +01:00
Gwendal Roué c5aeec3385 Documentation 2021-03-23 18:33:02 +01:00
Gwendal Roué 21b22ab3fb Travis: check old Xcode version first 2021-03-21 16:38:26 +01:00
Gwendal Roué 39eb57fe64 Fix for Xcode 11.4 2021-03-21 16:36:54 +01:00
Gwendal Roué bbacfd5ec1 Wording 2021-03-21 16:32:35 +01:00
Gwendal Roué 7bbec01dec Remove references to GRDBObjc 2021-03-21 14:25:19 +01:00
Gwendal Roué 969f28945c Focus 2021-03-21 14:20:25 +01:00
Gwendal Roué 869f6cb3b3 Focus 2021-03-21 14:19:49 +01:00
Gwendal Roué 607e53b04e Add an "In a glance" usage section 2021-03-21 14:14:15 +01:00
Gwendal Roué 051fdb37b6 Rename SQLLiteral to SQL 2021-03-21 13:33:49 +01:00
Gwendal Roué db963cbbb2 TODO 2021-03-21 13:05:45 +01:00
Gwendal Roué 13120063e0 TODO 2021-03-21 13:01:00 +01:00
Gwendal Roué be02e920d2 Dry up number documentation 2021-03-21 12:58:52 +01:00
Gwendal Roué 901b9c6fe6 More NSNumber/NSDecimalNumber tests 2021-03-21 12:58:11 +01:00
Gwendal Roué 64f5e6bdca Always use Decimal(string:) when decoding strings 2021-03-21 12:57:50 +01:00
Gwendal Roué 178727fd5b CHANGELOG 2021-03-20 20:22:40 +01:00
Gwendal Roué 791a8ed41b Update documentation for NSNumber, NSDecimalNumber, and Decimal 2021-03-20 20:14:31 +01:00
Gwendal Roué d9083a7bf5 Support for Foundation.Decimal 2021-03-20 20:11:26 +01:00
Gwendal Roué e355af3584 Decode NSNumber from textual database values 2021-03-20 17:15:16 +01:00
Gwendal Roué 5b39494125 TODO 2021-03-20 15:51:06 +01:00
Gwendal Roué 4f709e8e4f CHANGELOG 2021-03-20 15:51:01 +01:00
Gwendal Roué 63448fb0bc Documentation for EXISTS 2021-03-20 15:47:00 +01:00
Gwendal Roué 989a0e82eb Test for EXISTS expression 2021-03-20 15:46:46 +01:00
Gwendal Roué 8ba05a011d EXISTS expression 2021-03-20 15:24:32 +01:00
Gwendal Roué 659e6a53bb Documentation 2021-03-20 14:40:17 +01:00
Gwendal Roué 8a7ab17349 TODO 2021-03-20 14:37:54 +01:00
Gwendal Roué 3113e20f69 CHANGELOG 2021-03-20 14:37:13 +01:00
Gwendal Roué e44dc8486a Documentation for asynchronous migrations 2021-03-20 14:33:37 +01:00
Gwendal Roué 21a2206443 Remove asynchronous migration to target identifier
Migrating up to a specific identifier is a test-oriented use case: it does not need any async version.
2021-03-20 14:20:41 +01:00
Gwendal Roué f38c2ff754 Test DatabasePublishers.Migrate 2021-03-20 14:12:09 +01:00
Gwendal Roué 8ad880e20d DatabaseMigrator publisher 2021-03-20 14:11:43 +01:00
Gwendal Roué 50cec3fce7 Asynchronous migrations tests 2021-03-20 13:27:40 +01:00
Gwendal Roué c9c652dddc DatabaseMigrator async migrations 2021-03-20 13:25:43 +01:00
Gwendal Roué edde38837e TODO 2021-03-20 12:21:53 +01:00
Gwendal Roué c4443eead8 SELECT * FROM cte is no longer a special case, because SQLGenerationContext knows about the available CTEs 2021-03-19 19:06:47 +01:00
Gwendal Roué 7c023d5c1f CHANGELOG 2021-03-18 19:30:50 +01:00
Gwendal Roué 99a06f1c05 CHANGELOG 2021-03-18 19:29:02 +01:00
Gwendal Roué 0c2b5318bf Documentation 2021-03-18 19:28:46 +01:00
Gwendal Roué c47316a846 Documentation 2021-03-18 19:25:07 +01:00
Gwendal Roué 529b042b8a Database.makeSelectStatement(literal:) tests 2021-03-18 19:24:37 +01:00
Gwendal Roué 5aa1184e68 Database.makeSelectStatement(literal:) 2021-03-18 19:24:24 +01:00
Gwendal Roué a912c5cbe5 Documentation 2021-03-18 18:53:16 +01:00
Gwendal Roué 3753bd8d6d Database.makeUpdateStatement(literal:) tests 2021-03-18 18:48:22 +01:00
Gwendal Roué a6f7d9ba86 Database.makeUpdateStatement(literal:) accepts all arguments, or no arguments 2021-03-18 18:48:06 +01:00
Gwendal Roué fdc47d7158 Database.makeUpdateStatement(literal:) 2021-03-18 17:08:25 +01:00
Gwendal Roué 8aa4807f9b CHANGELOG 2021-03-17 21:57:49 +01:00
Gwendal Roué 339fbdf1ce Literal column alteration 2021-03-17 21:54:56 +01:00
Gwendal Roué ada972d78d Documentation 2021-03-17 21:31:35 +01:00
Gwendal Roué 085c8f5953 Literal table and constraint definition 2021-03-17 20:26:49 +01:00
Gwendal Roué 1f4db99a37 Documentation fix 2021-03-17 20:26:10 +01:00
Gwendal Roué 076813826f CHANGELOG 2021-03-17 19:01:04 +01:00
Gwendal Roué fcb6049381 Test SQLLiteral protocols in practice 2021-03-17 18:21:44 +01:00
Gwendal Roué 4c88d792f0 Documentation 2021-03-14 14:13:29 +01:00
Gwendal Roué 9d64a32814 Improve SQLLiteral documentation 2021-03-14 13:26:16 +01:00
Gwendal Roué 77db650464 More SQLLiteral interpolation test 2021-03-14 13:08:10 +01:00
Gwendal Roué 0e8a42aedc Tests for interpretations of SQLLiteral
If those tests break, we have introduced a breaking change.
2021-03-14 12:57:15 +01:00
Gwendal Roué 8ad096ae35 Refactor column counting for improved testability 2021-03-14 11:49:35 +01:00
Gwendal Roué ac436a2770 Make SQLLiteral less painful to use 2021-03-14 11:09:29 +01:00
Gwendal Roué 0133ff9056 Merge pull request #938 from michaelkirk/patch-1
fix small typos
2021-03-13 07:56:31 +01:00
Michael Kirk 178fb8688a fix small typos 2021-03-12 15:53:35 -08:00
Gwendal Roué 0b5f7e960b [skip travis] Mention key-value tables as a valid alternative
Inspired from https://twitter.com/dhartbit/status/1370434943956959238
2021-03-12 19:30:42 +01:00
Gwendal Roué ae3c491661 Merge branch 'development' 2021-03-12 17:47:50 +01:00
Gwendal Roué 8548d7a727 v5.6.0 2021-03-12 17:12:41 +01:00
Gwendal Roué daab7aef2c Fix typo 2021-03-12 15:37:29 +01:00
Gwendal Roué ba9b4db197 Fix typo 2021-03-12 15:33:35 +01:00
Gwendal Roué cab795a4a9 Wording 2021-03-12 15:32:00 +01:00
Gwendal Roué b331a715ef CHANGELOG 2021-03-12 15:30:31 +01:00
Gwendal Roué 48e214b4b3 Link to demo app tests 2021-03-12 14:42:51 +01:00
Gwendal Roué 65beb24d41 Simplify 2021-03-12 14:33:01 +01:00
Gwendal Roué e1c7150714 Documentation 2021-03-12 14:26:43 +01:00
Gwendal Roué cc93f43ee4 Better introduction to DerivableRequest
Also reintroduce extensions to QueryInterfaceRequest
2021-03-12 14:24:47 +01:00
Gwendal Roué 33174fce8e Documentation 2021-03-12 14:00:31 +01:00
Gwendal Roué cb8611587c Fix Swiftlint warning 2021-03-12 13:48:41 +01:00
Gwendal Roué 6e7555514a More collection initializers from cursors
- support for minimumCapacity
- support for Dictionary (cursors with unique keys)
2021-03-12 13:48:25 +01:00
Gwendal Roué 8b1efb2c80 Single-Row Tables guide 2021-03-12 11:31:32 +01:00
Gwendal Roué 8388486289 TODO 2021-03-12 08:32:32 +01:00
Gwendal Roué c3dcd7636e Merge pull request #936 from groue/dev/more-eager-loading
Complete Associations and the DerivableRequest Protocol
2021-03-11 19:35:39 +01:00
Gwendal Roué 464b77bdcd Improve "Record Types Hide Intimate Database Details" 2021-03-10 13:25:25 +01:00
Gwendal Roué fe437fb7e3 Improve "Record Types Hide Intimate Database Details" 2021-03-10 13:21:25 +01:00
Gwendal Roué 1a2a6898eb Improve "Record Types Hide Intimate Database Details" 2021-03-10 13:07:16 +01:00
Gwendal Roué de2a37fb89 Improve "Record Types Hide Intimate Database Details" 2021-03-10 13:06:05 +01:00
Gwendal Roué 1d5604815d Improve "Record Types Hide Intimate Database Details" 2021-03-10 13:05:11 +01:00
Gwendal Roué 4de5059373 Improve "Record Types Hide Intimate Database Details" 2021-03-10 12:55:25 +01:00
Gwendal Roué 850040c51e Fix typo 2021-03-10 09:02:00 +01:00
Gwendal Roué eb0983facd Wording 2021-03-10 08:59:40 +01:00
Gwendal Roué 9e974a4c96 Fix typo 2021-03-10 08:58:39 +01:00
Gwendal Roué 609fcf6a6d CHANGELOG 2021-03-10 08:57:46 +01:00
Gwendal Roué 5e61d38272 Add a Record Types Hide Intimate Database Details chapter 2021-03-10 08:56:53 +01:00
Gwendal Roué cdbca5d215 Fix sample code 2021-03-09 08:29:14 +01:00
Gwendal Roué 9bda5fc41b Move the Further Refinements to Associations chapter 2021-03-09 08:27:29 +01:00
Gwendal Roué 04d35381a6 Documentation 2021-03-09 07:57:57 +01:00
Gwendal Roué 1f27e724c9 Open a door 2021-03-09 07:21:43 +01:00
Gwendal Roué b22afd7f17 CHANGELOG 2021-03-08 21:56:47 +01:00
Gwendal Roué ed3d1e1ac4 selectOnly() clears the isDistinct flag 2021-03-08 21:36:09 +01:00
Gwendal Roué 4521e6b37d Make filterPromise an optional promise instead of a promise of optional
This way, filterPromise and havingExpressionPromise have the same type
2021-03-08 21:25:27 +01:00
Gwendal Roué 42718db49d Documentation 2021-03-08 21:11:36 +01:00
Gwendal Roué e08df854dd Lower the tone about record responsabilities 2021-03-08 20:50:17 +01:00
Gwendal Roué f4b7d99aab Remove warning about associations that use CTEs 2021-03-08 19:59:47 +01:00
Gwendal Roué 4dd8042894 Make it possible to decode arrays of scalars from including(all:) 2021-03-08 14:21:35 +01:00
Gwendal Roué 4583bbfa90 Test for joined associations that use CTEs 2021-03-08 14:10:43 +01:00
Gwendal Roué a655974eb0 Let joined associations use CTEs 2021-03-08 14:10:38 +01:00
Gwendal Roué d4fc1d9566 Update documentation for the new Association/DerivableRequest powers 2021-03-08 08:36:32 +01:00
Gwendal Roué f9b554d00a Merge AggregateJoinableRequest into DerivableRequest
Also put distinct(), limit(_:offset:) and with(_:) into DerivableRequest
2021-03-08 07:55:20 +01:00
Gwendal Roué 6b733cfc0a Tests for including(all:) with distinct, limited, grouped, and cte-decorated associations 2021-03-07 20:32:21 +01:00
Gwendal Roué f0aec27095 AssociationToMany: distinct(), limit(_:offset:), with(_:) 2021-03-07 20:25:30 +01:00
Gwendal Roué 092b0d0e44 Move with(cte) methods to the file it belongs to 2021-03-07 19:58:15 +01:00
Gwendal Roué d2a22ddd97 Make sure joined associations do not use prefetched to-many features
One can't join a distinct, grouped, or limited association.
2021-03-07 19:56:04 +01:00
Gwendal Roué 9c6ff6a1c0 Simplifly association aggregates
We don't need any promise. We used to, but SQLExpression.fastPrimaryKey has been introduced since then.
2021-03-07 19:36:08 +01:00
Gwendal Roué a4dca3390a AggregateJoinableRequest is the new protocol that supports aggregate annotations
AssociationToMany is a subprotocol of AggregateJoinableRequest :-)
2021-03-07 19:15:09 +01:00
Gwendal Roué ea6a052b73 Merge all SQLRelation properties 2021-03-07 17:12:44 +01:00
Gwendal Roué f49fab0cff Merge SQLQuery into SQLRelation 2021-03-07 14:37:53 +01:00
Gwendal Roué 37faf0a1fd Upgrade obsolete documentation 2021-03-07 14:20:28 +01:00
Gwendal Roué 4b5a6b503a TODO 2021-03-07 13:12:28 +01:00
Gwendal Roué 2a85b1230b Merge pull request #934 from groue/dev/issue-932
Fix a crash in the ValueObservation publisher
2021-03-07 12:12:44 +01:00
Gwendal Roué 3eb17fdbb7 CHANGELOG 2021-03-07 12:11:50 +01:00
Gwendal Roué 5400217bb6 ReceiveValuesOnSubscription forwards cancellation
Fixes #932
2021-03-07 12:10:35 +01:00
Gwendal Roué 71083a5586 Merge pull request #933 from groue/dev/issue-931
Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
2021-03-07 12:09:04 +01:00
Gwendal Roué 37279dfad2 CHANGELOG 2021-03-06 14:20:11 +01:00
Gwendal Roué 8be0976bd1 Fix #931 2021-03-06 14:01:56 +01:00
Gwendal Roué 7623a96034 Failing test for #931 2021-03-06 13:34:27 +01:00
Gwendal Roué 424df6dee3 TODO 2021-03-06 13:25:59 +01:00
Gwendal Roué 48b6faa45e Improve documentation of Configuration.prepareDatabase 2021-03-06 13:25:52 +01:00
Gwendal Roué bac7b6b0e5 Refactor function calls
and make it possible to express other DISTINCT aggregates than COUNT: SUM(DISTINCT ...), etc.
2021-03-06 13:25:25 +01:00
Gwendal Roué 174766925a Remove warning 2021-03-03 20:04:08 +01:00
Gwendal Roué 9d5cb15380 SQLExpression documentation & cleanup 2021-03-03 20:03:56 +01:00
Gwendal Roué 284ebbd3ef [skip travis] Update thank you notice 2021-03-03 14:09:23 +01:00
Gwendal Roué 3b6cf4c12b Merge branch 'development' 2021-03-03 13:00:39 +01:00
Gwendal Roué 2329a5c7b4 v5.5.0 2021-03-03 13:00:21 +01:00
Gwendal Roué 8f50d70703 Merge pull request #930 from groue/dev/issue-929
Fix SQL generation for `COLLATE`, `IN`, `NOT IN`
2021-03-03 07:56:14 +01:00
Gwendal Roué d2d515658e CHANGELOG 2021-03-02 20:21:51 +01:00
Gwendal Roué 72123494ca Add test for NOT IN and collated expressions 2021-03-02 20:16:15 +01:00
Gwendal Roué 7b81fd1bff Fix documentation for #929 2021-03-02 20:12:38 +01:00
Gwendal Roué 5ea7296e7a Add support for subquery.contains(collated expression) 2021-03-02 20:09:24 +01:00
Gwendal Roué 279b00f890 Fix failing tests for #929 2021-03-02 20:03:19 +01:00
Gwendal Roué 01d71d6f35 Failing tests for #929 2021-03-02 20:02:46 +01:00
Gwendal Roué 96df69b3fb Add fundamental test for #929 2021-03-02 19:06:18 +01:00
Gwendal Roué b17fce357d Merge pull request #925 from groue/dev/RowDecodingError
Foundation for decoding errors
2021-03-01 09:03:20 +01:00
Gwendal Roué 37dfd95ae1 Symmetry with StatementColumnConvertible 2021-02-26 19:31:41 +01:00
Gwendal Roué b834b9876d Data.fastDecodeNoCopyIfPresent can not fail 2021-02-26 18:51:14 +01:00
Gwendal Roué 7f48e66fdc Reduce inlined code 2021-02-26 18:50:47 +01:00
Gwendal Roué b7c57dc7f2 Attempt at clarifying the (complex) decoding api
The difficulty is due to fast decoding of StatementColumnConvertible, and non-copied Data, from raw SQLite statement.

We want it to be inlinable, and possible in nested rows.

Added missing tests for nested rows
2021-02-25 20:45:12 +01:00
Gwendal Roué cb2405a8b9 RowDecodingError 2021-02-21 14:21:04 +01:00
Gwendal Roué 4398777f07 TODO 2021-02-20 17:03:17 +01:00
Gwendal Roué 6e8285e4ec CHANGELOG 2021-02-20 13:02:30 +01:00
Gwendal Roué aceaaf24d2 Paranoid: Wrap DatabaseQueue.read in a transaction
This guarantees snapshot isolation even in case of external connections
2021-02-20 12:59:27 +01:00
Gwendal Roué 64bb63e304 CommonTableExpression has an implicit Row RowDecoder 2021-02-20 12:47:13 +01:00
Gwendal Roué a681ccf2b9 Fix: DatabaseQueue.read is throws, not rethrows 2021-02-20 11:55:19 +01:00
Gwendal Roué 8c8a25a73b Spot the possible improvement on SQLRelation children 2021-02-20 11:42:54 +01:00
Gwendal Roué d419d23368 Tests for SQLRelation children 2021-02-19 16:28:22 +01:00
Gwendal Roué 081500b5ce TODO 2021-02-19 13:26:18 +01:00
Gwendal Roué 7dd36ecc0f Tests for SQLRelation children 2021-02-19 07:36:33 +01:00
Gwendal Roué 10a16ac6f0 Rename .allNotPrefetched to .bridge 2021-02-18 08:42:01 +01:00
Gwendal Roué d7f61fa0f5 Documentation 2021-02-18 07:58:10 +01:00
Gwendal Roué 3665a533cf Add missing tests for has-many through association with three steps 2021-02-17 20:04:35 +01:00
Gwendal Roué c9332a8c9e Fix typo 2021-02-17 20:03:59 +01:00
Gwendal Roué e40534942c format 2021-02-17 18:19:52 +01:00
Gwendal Roué de52856cf3 Aliasing is not qualifying 2021-02-17 18:11:00 +01:00
Gwendal Roué 0dd345eb91 SQLQuery no longer depends on SQLExpressible and other high-level protocols 2021-02-17 18:00:53 +01:00
Gwendal Roué c4620aa587 SQLRelation no longer depends on SQLExpressible and _JoinableRequest
Those are one level up
2021-02-17 17:43:57 +01:00
Gwendal Roué bda63c70bf Document the type of variables 2021-02-17 13:51:23 +01:00
Gwendal Roué 3407715599 CHANGELOG 2021-02-17 13:47:15 +01:00
Gwendal Roué 7eaf579c18 Update CommonTableExpression documentation about the implicit Void RowDecoder 2021-02-17 13:44:51 +01:00
Gwendal Roué 488849535e CommonTableExpression has an implicit Void RowDecoder 2021-02-17 13:22:28 +01:00
Gwendal Roué 15b892af6e Implement filters with SQLExpression? instead of [SQLExpression]
Those arrays were introduced so that we can generate nicer sql: `a AND b AND c`, instead of `(a AND b) AND c`.

This flattening is provided by the && operator and `SQLExpression.associativeBinary`, so those arrays are no longer needed.
2021-02-17 08:45:57 +01:00
Gwendal Roué cceb24a1e5 Merge branch 'development' 2021-02-15 19:17:27 +01:00
Gwendal Roué bea454a0b9 v5.4.0 2021-02-15 19:16:06 +01:00
Gwendal Roué 276fb2d698 Performance tests: upgrade dependencies 2021-02-15 18:54:32 +01:00
Gwendal Roué 8e3046b00f Move Sequence.joined(operator:) back to SQLSpecificExpressible
`[1, 2, 3].joined(operator: .add)` is not supported. It would pollute autocompletion.

This commit fixes a regression introduced in 920417b.
2021-02-15 18:16:18 +01:00
Gwendal Roué 8a5790ed8b Move SQLSelectable and SQLOrderingTerm down from SQLExpressible to SQLSpecificExpressible 2021-02-15 14:01:42 +01:00
Gwendal Roué fd6f5ec525 CHANGELOG 2021-02-15 13:55:58 +01:00
Gwendal Roué 987d549ff0 Remove obsolete test in demo app 2021-02-15 07:59:48 +01:00
Gwendal Roué f57e724ef6 Merge pull request #922 from groue/experiments/enums
Refactor query interface implementation
2021-02-15 07:22:42 +01:00
Gwendal Roué 920417beb3 Replace protocols with enums 2021-02-14 18:28:15 +01:00
Gwendal Roué 2a016ac4f5 TODO 2021-02-12 18:47:37 +01:00
Gwendal Roué ba3a3f7c38 Move definition of TableRecord to CTE associations 2021-02-09 18:14:35 +01:00
Gwendal Roué ae6f5dd0f5 Extract ForeignKey 2021-02-09 18:14:35 +01:00
Gwendal Roué 7914805524 Remove TableRecord requirements for QueryInterfaceRequest aggregates 2021-02-09 18:14:35 +01:00
Gwendal Roué 5c2f113631 TODO 2021-02-08 13:07:02 +01:00
Gwendal Roué d3df3ed5ec Makefile: support for Xcode 12.4 and Big Sur
Bump min iOS and tvOS versions to 11.4 because Big Sur does not support older simulators:

$ xcrun simctl list runtimes
iOS 10.3 (10.3.1 - 14E8301) - com.apple.CoreSimulator.SimRuntime.iOS-10-3 (unavailable, The iOS 10.3 simulator runtime is not supported on hosts after macOS 10.15.99.)
tvOS 10.2 (10.2 - 14W260) - com.apple.CoreSimulator.SimRuntime.tvOS-10-2 (unavailable, The tvOS 10.2 simulator runtime is not supported on hosts after macOS 10.15.99.)
2021-02-07 17:23:10 +01:00
Gwendal Roué 40389ee102 Decouple associations from their origin database table
This allows us to create an association without providing the origin table name, and thus to build association without TableRecord.
2021-02-07 16:01:34 +01:00
Gwendal Roué edc8c2aeea Fix sample code 2021-01-30 09:52:35 +01:00
Gwendal Roué f9ad87e54f Documentation 2021-01-29 19:49:55 +01:00
Gwendal Roué a6a10270a0 TODO 2021-01-29 08:11:16 +01:00
Gwendal Roué 9a1ff5e9a0 BRAG 2021-01-28 19:09:46 +01:00
Gwendal Roué 7151648279 Cleanup demo apps 2021-01-28 08:44:34 +01:00
Gwendal Roué 921c629a5e Documentation: Adding support for missing SQL functions or operators 2021-01-28 08:43:14 +01:00
Gwendal Roué 25b2a0392d SQL interpolation supports embedding collations into SQL literals 2021-01-28 08:39:40 +01:00
Gwendal Roué cb7aa3c14f TODO 2021-01-28 08:36:14 +01:00
640 changed files with 80554 additions and 35872 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
source 'https://rubygems.org'
gem 'xcpretty'
gem 'xcpretty-travis-formatter'
gem 'cocoapods', '~> 1.7'
+7 -5
View File
@@ -3,10 +3,12 @@
### Pull Request Checklist
<!--
Please verify that your pull request checks those boxes:
Please check the boxes that apply to your pull request:
-->
- [ ] 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.
- [ ] CONTRIBUTING: You have read https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md
- [ ] BRANCH: This pull request is submitted against the `development` branch.
- [ ] DOCUMENTATION: Inline documentation has been updated.
- [ ] DOCUMENTATION: README.md or another dedicated guide has been updated.
- [ ] TESTS: Changes are tested.
- [ ] TESTS: The `make smokeTest` terminal command runs without failure.
+6
View File
@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
+173
View File
@@ -0,0 +1,173 @@
# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md
name: "GRDB CI"
on:
push:
branches:
- master
- development
paths:
- 'GRDB/**'
- 'Tests/**'
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
pull_request:
paths:
- 'GRDB/**'
- 'Tests/**'
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
concurrency:
group: ${{ github.ref_name }}
cancel-in-progress: true
permissions:
contents: read
jobs:
Framework:
name: Framework
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.2,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
destination: "OS=16.1,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
destination: "OS=16.0,name=iPhone 14"
name: "iOS"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
name: SPM
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
name: "Xcode 14.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
name: SQLCipher3
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
name: SQLCipher4
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
name: CustomSQLite
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
name: XCFramework
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_archive_GRDBOSX_xcframework
+4 -1
View File
@@ -1,4 +1,4 @@
## https://github.com/github/gitignore/blob/master/Global/OSX.gitignore
## https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
.DS_Store
.AppleDouble
@@ -112,3 +112,6 @@ Tests/SPM/Packages
# Ruby
.ruby-version
# Test products
Tests/products
+4
View File
@@ -0,0 +1,4 @@
version: 1
builder:
configs:
- documentation_targets: [GRDB]
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,134 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1410"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB_GRDBTests"
BuildableName = "GRDB_GRDBTests"
BlueprintName = "GRDB_GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB"
BuildableName = "GRDB"
BlueprintName = "GRDB"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB-dynamic"
BuildableName = "GRDB-dynamic"
BlueprintName = "GRDB-dynamic"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDBTests"
BuildableName = "GRDBTests"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CSQLite"
BuildableName = "CSQLite"
BlueprintName = "CSQLite"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDBTests"
BuildableName = "GRDBTests"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GRDB_GRDBTests"
BuildableName = "GRDB_GRDBTests"
BlueprintName = "GRDB_GRDBTests"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+120 -120
View File
@@ -26,126 +26,6 @@ git:
jobs:
include:
###########################################
## Test GRDB Xcode 12.2
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.2 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.2
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.2
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.2
# Manual Install
- name: "Test Installation Xcode 12.2 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_manual
# Travis is much too slow, and always fail this job
# # CocoaPods Lint
# - name: "Test Installation Xcode 12.2 - CocoaPods Lint"
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode12.2
# script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.2 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_customSQLite
###########################################
## Test GRDB Xcode 11.4
@@ -159,3 +39,123 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBiOS_minTarget
###########################################
## Test GRDB Xcode 12.5
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.2"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.5 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.5 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.5 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.5
- name: "Test GRDBCustom Xcode 12.5 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.5
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.5
# Manual Install
- name: "Test Installation Xcode 12.5 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_manual
# Travis is much too slow, and always fail this job
# # CocoaPods Lint
# - name: "Test Installation Xcode 12.5 - CocoaPods Lint"
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode12.5
# script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.5 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.5 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.5 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.5 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.5 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_customSQLite
+46
View File
@@ -4,6 +4,52 @@ Here is a list of people who were happy to meet GRDB :-)
---
https://twitter.com/DamienPetrilli/status/1623922310976786433
> I can't overstate how much more productive I am since I ditched the obsolete Core Data framework and started to use GRDB instead.
>
> The hard stuff is doable, and the simple stuff is even simpler, as it should be.
---
https://twitter.com/fullqueuedev/status/1603350969357684736
> Yes, I much prefer GRDB. I’ve tested many SQLite wrappers over the years 💜
---
https://twitter.com/cassiuspacheco/status/1574948903857770497
> SQLite using @groue’s GRDB, no brainer! Awesome documentation, support and beautifully designed.
---
https://twitter.com/simrandotdev/status/1552004471122587649
> We get Core Data from Apple which is the worst library to deal with.
> Then there is Realm which is nice but again you do not get the RAW SQL power as it is its own type of Db.
> Then comes the most beautiful library every written which is very close to Room called GRDB.
---
https://twitter.com/bellebcooper/status/1534070340850094080
> When I first started using GRDB I didn't know SQL or much at all about databases 😬 So I've always really liked the query API. But these days I really appreciate that you support raw SQL too, because it gives me more control and freedom when I need it. 👍👍👍
---
https://twitter.com/mikeash/status/1504810545429499909
> Another cool library using SQL interpolation!
---
https://twitter.com/swiftkarim/status/1354753451377483781
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
---
https://twitter.com/peres/status/1352219836508729346
> Just the occasional reminder that GRDB and its documentation is the gold standard. That's it.
+701 -48
View File
@@ -5,39 +5,78 @@ All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
#### 6.x Releases
- `6.11.x` Releases - [6.11.0](#6110)
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
- `6.8.x` Releases - [6.8.0](#680)
- `6.7.x` Releases - [6.7.0](#670)
- `6.6.x` Releases - [6.6.0](#660) - [6.6.1](#661)
- `6.5.x` Releases - [6.5.0](#650)
- `6.4.x` Releases - [6.4.0](#640)
- `6.3.x` Releases - [6.3.0](#630) - [6.3.1](#631)
- `6.2.x` Releases - [6.2.0](#620)
- `6.1.x` Releases - [6.1.0](#610)
- `6.0.x` Releases - [6.0.0](#600)
- `6.0.0` Betas - [6.0.0-beta](#600-beta) - [6.0.0-beta.2](#600-beta2) - [6.0.0-beta.3](#600-beta3) - [6.0.0-beta.4](#600-beta4)
#### 5.x Releases
- `5.26.x` Releases - [5.26.0](#5260) - [5.26.1](#5261)
- `5.25.x` Releases - [5.25.0](#5250)
- `5.24.x` Releases - [5.24.0](#5240) - [5.24.1](#5241)
- `5.23.x` Releases - [5.23.0](#5230)
- `5.22.x` Releases - [5.22.0](#5220) - [5.22.1](#5221) - [5.22.2](#5222)
- `5.21.x` Releases - [5.21.0](#5210)
- `5.20.x` Releases - [5.20.0](#5200)
- `5.19.x` Releases - [5.19.0](#5190)
- `5.18.x` Releases - [5.18.0](#5180)
- `5.17.x` Releases - [5.17.0](#5170)
- `5.16.x` Releases - [5.16.0](#5160)
- `5.15.x` Releases - [5.15.0](#5150)
- `5.14.x` Releases - [5.14.0](#5140)
- `5.13.x` Releases - [5.13.0](#5130)
- `5.12.x` Releases - [5.12.0](#5120)
- `5.11.x` Releases - [5.11.0](#5110)
- `5.10.x` Releases - [5.10.0](#5100)
- `5.9.x` Releases - [5.9.0](#590)
- `5.8.x` Releases - [5.8.0](#580)
- `5.7.x` Releases - [5.7.0](#570) - [5.7.1](#571) - [5.7.2](#572) - [5.7.3](#573) - [5.7.4](#574)
- `5.6.x` Releases - [5.6.0](#560)
- `5.5.x` Releases - [5.5.0](#550)
- `5.4.x` Releases - [5.4.0](#540)
- `5.3.x` Releases - [5.3.0](#530)
- `5.2.x` Releases - [5.2.0](#520)
- `5.1.x` Releases - [5.1.0](#510)
- `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502) | [5.0.3](#503)
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) | [5.0.0-beta.11](#500-beta11)
- `5.0.x` Releases - [5.0.0](#500) - [5.0.1](#501) - [5.0.2](#502) - [5.0.3](#503)
- `5.0.0` Betas - [5.0.0-beta](#500-beta) - [5.0.0-beta.2](#500-beta2) - [5.0.0-beta.3](#500-beta3) - [5.0.0-beta.4](#500-beta4) - [5.0.0-beta.5](#500-beta5) - [5.0.0-beta.6](#500-beta6) - [5.0.0-beta.7](#500-beta7) - [5.0.0-beta.8](#500-beta8) - [5.0.0-beta.9](#500-beta9) - [5.0.0-beta.10](#500-beta10) - [5.0.0-beta.11](#500-beta11)
#### 4.x Releases
- `4.14.x` Releases - [4.14.0](#4140)
- `4.13.x` Releases - [4.13.0](#4130)
- `4.12.x` Releases - [4.12.0](#4120) | [4.12.1](#4121) | [4.12.2](#4122)
- `4.12.x` Releases - [4.12.0](#4120) - [4.12.1](#4121) - [4.12.2](#4122)
- `4.11.x` Releases - [4.11.0](#4110)
- `4.10.x` Releases - [4.10.0](#4100)
- `4.9.x` Releases - [4.9.0](#490)
- `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481)
- `4.8.x` Releases - [4.8.0](#480) - [4.8.1](#481)
- `4.7.x` Releases - [4.7.0](#470)
- `4.6.x` Releases - [4.6.0](#460) | [4.6.1](#461) | [4.6.2](#462)
- `4.6.x` Releases - [4.6.0](#460) - [4.6.1](#461) - [4.6.2](#462)
- `4.5.x` Releases - [4.5.0](#450)
- `4.4.x` Releases - [4.4.0](#440)
- `4.3.x` Releases - [4.3.0](#430)
- `4.2.x` Releases - [4.2.0](#420) | [4.2.1](#421)
- `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411)
- `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401)
- `4.2.x` Releases - [4.2.0](#420) - [4.2.1](#421)
- `4.1.x` Releases - [4.1.0](#410) - [4.1.1](#411)
- `4.0.x` Releases - [4.0.0](#400) - [4.0.1](#401)
#### 3.x Releases
- `3.7.x` Releases - [3.7.0](#370)
- `3.6.x` Releases - [3.6.0](#360) | [3.6.1](#361) | [3.6.2](#362)
- `3.6.x` Releases - [3.6.0](#360) - [3.6.1](#361) - [3.6.2](#362)
- `3.5.x` Releases - [3.5.0](#350)
- `3.4.x` Releases - [3.4.0](#340)
- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331)
- `3.3.x` Releases - [3.3.0](#330) - [3.3.1](#331)
- `3.3.0` Betas - [3.3.0-beta1](#330-beta1)
- `3.2.x` Releases - [3.2.0](#320)
- `3.1.x` Releases - [3.1.0](#310)
@@ -49,18 +88,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- `2.9.x` Releases - [2.9.0](#290)
- `2.8.x` Releases - [2.8.0](#280)
- `2.7.x` Releases - [2.7.0](#270)
- `2.6.x` Releases - [2.6.0](#260) | [2.6.1](#261)
- `2.6.x` Releases - [2.6.0](#260) - [2.6.1](#261)
- `2.5.x` Releases - [2.5.0](#250)
- `2.4.x` Releases - [2.4.0](#240) | [2.4.1](#241) | [2.4.2](#242)
- `2.3.x` Releases - [2.3.0](#230) | [2.3.1](#231)
- `2.4.x` Releases - [2.4.0](#240) - [2.4.1](#241) - [2.4.2](#242)
- `2.3.x` Releases - [2.3.0](#230) - [2.3.1](#231)
- `2.2.x` Releases - [2.2.0](#220)
- `2.1.x` Releases - [2.1.0](#210)
- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) | [2.0.3](#203)
- `2.0.x` Releases - [2.0.0](#200) - [2.0.1](#201) - [2.0.2](#202) - [2.0.3](#203)
#### 1.x Releases
- `1.3.x` Releases - [1.3.0](#130)
- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122)
- `1.2.x` Releases - [1.2.0](#120) - [1.2.1](#121) - [1.2.2](#122)
- `1.1.x` Releases - [1.1.0](#110)
- `1.0.x` Releases - [1.0.0](#100)
@@ -68,6 +107,620 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
---
## 6.11.0
Released April 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.2...v6.11.0)
- **New**: [#1361](https://github.com/groue/GRDB.swift/pull/1361) `DatabaseMigrator.eraseDatabaseOnSchemaChange` ignores internal schema objects
## 6.10.2
Released April 10, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
## 6.10.1
Released April 1, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1)
- **Fixed**: [#1357](https://github.com/groue/GRDB.swift/pull/1357) `QueryInterfaceRequest.fetchCount` no longer executes invalid SQL queries for some requests.
## 6.10.0
Released March 20, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts.
## 6.9.2
Released March 14, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.9.1...v6.9.2)
- **Fixed**: [#1349](https://github.com/groue/GRDB.swift/pull/1349) by [@JonLz](https://github.com/JonLz): Fix Migrations.md example so it compiles
- **Fixed**: Avoid the risk for pathologically deep stack trace, or stack overflow, introduced by [#1348](https://github.com/groue/GRDB.swift/pull/1348).
## 6.9.1
Released March 12, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
- **Documentation Updates**: Moved more README chapters into DocC:
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
## 6.9.0
Released March 12, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.8.0...v6.9.0)
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
## 6.8.0
Released February 24, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.7.0...v6.8.0)
- **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code
- **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes.
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
## 6.7.0
Released February 19, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.6.1...v6.7.0)
- **Fixed**: [#1316](https://github.com/groue/GRDB.swift/pull/1316) and [#1320](https://github.com/groue/GRDB.swift/pull/1320) by [@baekteun](https://github.com/baekteun): Replace "OSX" with "macOS".
- **Fixed**: [#1328](https://github.com/groue/GRDB.swift/pull/1328) by [@ytti](https://github.com/ytti): Fix documentation about Data passphrases.
- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version.
- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date
- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
- Added support for `Table` in SQL interpolation.
## 6.6.1
Released January 15, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.6.0...v6.6.1)
- **Fixed**: [#1317](https://github.com/groue/GRDB.swift/pull/1317) by [@groue](https://github.com/groue): Fix handling of multiple deep prefetched associations
## 6.6.0
Released December 29, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.5.0...v6.6.0)
- **New**: [#1304](https://github.com/groue/GRDB.swift/pull/1304) by [@groue](https://github.com/groue): Expose generated columns with availability checks
## 6.5.0
Released December 5, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.4.0...v6.5.0)
- **New**: [#1299](https://github.com/groue/GRDB.swift/pull/1299) by [@groue](https://github.com/groue): Record.find() convenience methods
## 6.4.0
Released November 28, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.3.1...v6.4.0)
- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot.
- **New**: [#1297](https://github.com/groue/GRDB.swift/pull/1297) by [@groue](https://github.com/groue): SPM: expose the CSQLite product.
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)).
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
- **New**: Multiple improvements to the DocC documentation.
## 6.3.1
Released November 11, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.3.0...v6.3.1)
- **New**: DocC documentation is hosted at https://swiftpackageindex.com/groue/GRDB.swift/documentation
## 6.3.0
Released November 6, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.2.0...v6.3.0)
- **New**: [#1291](https://github.com/groue/GRDB.swift/pull/1291) by [@groue](https://github.com/groue): DocC inline documentation
- **New**: The `Row.dataNoCopy` methods are deprecated. Use `Row.withUnsafeData` instead.
## 6.2.0
Released October 28, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.1.0...v6.2.0)
- **New**: [#1289](https://github.com/groue/GRDB.swift/pull/1289) by [@arkie](https://github.com/arkie): Add support for passing in categories to the FTS5 unicode61 tokenizer (SQLite 3.25+)
- **Fixed**: The `FTS5Tokenizer.tokenize(query:)` method no longer returns incorrect results for certain tokenizer arguments.
## 6.1.0
Released October 20, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0...v6.1.0)
- **New**: [#1288](https://github.com/groue/GRDB.swift/pull/1288) by [@jcavar](https://github.com/jcavar): Support for strict tables
## 6.0.0
Released September 9, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.4...v6.0.0)
- **New**: Bump custom SQLite builds v3.39.3
- **Fixed**: [#1274](https://github.com/groue/GRDB.swift/discussions/1274) Fixed a bug with HasManyThrough associations when the "through" association has the same association key as the association itself.
- **Fixed**: [#1275](https://github.com/groue/GRDB.swift/issues/1275) Enhance error message for some requests involving associations on common table expressions.
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/issues/1276) Fix build error with Xcode 14.0 RC (14A309)
- **Breaking Change**: Request methods that accept a closure with a `Database` argument have been renamed with the `WhenConnected` suffix: `request.filterWhenConnected { db in ... }`, etc.
## 6.0.0-beta.4
Released August 28, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.3...v6.0.0-beta.4)
- **New**: [#1271](https://github.com/groue/GRDB.swift/pull/1271) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.39.2
- **New**: [SQLITE_OPEN_EXRESCODE](https://www.sqlite.org/c3ref/open.html), when available, exposes [extended result codes](README.md#databaseerror) when opening a database connection.
- **Fixed**: [PRAGMA table_list](https://www.sqlite.org/pragma.html#pragma_table_list), when available, makes it possible for GRDB to detect [WITHOUT ROWID](https://www.sqlite.org/withoutrowid.html) tables without [polluting the SQLite error log](https://github.com/groue/GRDB.swift/issues/945).
- **Breaking Change**: The`GRDB.xcodeproj` or `GRDBCustom.xcodeproj` projects now define cross-platforms targets.
- **Documentation Update**: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) describes how to update applications that directly embed the `GRDB.xcodeproj` or `GRDBCustom.xcodeproj` project.
- **Documentation Update**: [Custom SQLite Builds](CustomSQLiteBuilds.md) was updated for the new cross-platform target defined by the `GRDBCustom.xcodeproj` project.
## 6.0.0-beta.3
Released August 25, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.2...v6.0.0-beta.3)
- **Fix**: [#1268](https://github.com/groue/GRDB.swift/pull/1268) by [@groue](https://github.com/groue): Fix SQL generation of CHECK constraints
- **Breaking Change**: The `Column` type is no longer `Equatable`
- **Documentation Update**: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) describes in detail how to update records that customize their persistence methods.
- **Documentation Update**: The [Single-Row Tables](Documentation/SingleRowTables.md) guide was updated for the new persistence callbacks.
## 6.0.0-beta.2
Released August 23, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta...v6.0.0-beta.2)
- **New**: Extended UPSERT apis with the ability to define the conflict target, and the assignments performed in case of conflicts.
- **Documentation Update**: A new [Upsert](README.md#upsert) chapter describes upserts in detail.
## 6.0.0-beta
Released August 21, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v6.0.0-beta)
### New
Upgrading your app can bring improvements: check [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) for some suggestions.
- :star: Support for [`UPSERT`](https://www.sqlite.org/lang_UPSERT.html): `player.upsert(db)`, etc. See [Persistence Methods](README.md#persistence-methods).
- :star: Support for the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. See [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause).
- :star: [Persistence Callbacks](README.md#persistence-callbacks) allow record types to customize persistence methods: `didInsert`, `willSave`, etc.
- :star: Better support for unexpected database values. Where GRDB 5 would crash during encoding and decoding database values, GRDB 6 has learned to throw errors instead. Record protocols throw decoding and encoding errors, and value requests throw errors on invalid inputs.
- Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md).
- All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc.
- You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`.
- `ValueObservation.map` now accepts a throwing closure argument.
### Documentation Updates
- :star: **[Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)**: suggestions for improving your applications, and guidance for handling the breaking changes.
- The [Persistence Methods](README.md#persistence-methods) chapter introduces the `upsert` method.
- The [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause) chapter introduces persistence methods that fetch inserted, updated and deleted values.
- The [Persistence Callbacks](README.md#persistence-callbacks) chapter introduces the callback invoked from persistence methods, such as `didInsert`, `willSave`, etc.
- The [DatabaseRegionObservation](README.md#databaseregionobservation) chapter was updated for the new `DatabaseRegionObservation.start` method.
- The [Transaction Hook](README.md#transaction-hook) chapter describes the new `Database.afterNextTransaction(onCommit:onRollback:)` method.
- The [Value Queries](README.md#value-queries) chapter explains how to distinguish a request that returns no value from a request that fetches a NULL value.
### Breaking Changes
- Removed deprecated methods
- :star: Bumped requirements:
- Swift 5.7+ and Xcode 14+ are required.
- iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ / SQLite 3.19.3+ are required.
- :star: Record protocols were refactored:
- The `FetchableRecord.init(row:)` initializer can now throw errors.
- The `EncodableRecord.encode(to:)` method can now throw errors.
- Record types can no longer override persistence methods. You use [Persistence Callbacks](README.md#persistence-callbacks) instead.
- Various breaking changes:
- The in-memory `DatabaseQueue()` initializer can now throw errors.
- The `selectID()` method is replaced with `selectPrimaryKey(as:)`.
- `Cursor.isEmpty` is now a throwing property, instead of a method.
- The `Record.copy()` method was removed, without replacement.
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
- The `DatabaseRegionObservation.extent` property was removed.
- The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`.
- The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
## 5.26.1
Released September 8, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v5.26.1)
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/issues/1276) Fix build error with Xcode 14.0 RC (14A309)
## 5.26.0
Released July 9, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0)
- **New**: [#1248](https://github.com/groue/GRDB.swift/pull/1248) by [@groue](https://github.com/groue): Avoid double notification of the initial value for ValueObservation on DatabasePool
- **New**: [#1253](https://github.com/groue/GRDB.swift/pull/1253) by [@george-signal](https://github.com/george-signal): Make memory management optional
- **Fixed**: DatabasePool no longer prevents database reads when UIKit posts `UIApplication.didReceiveMemoryWarningNotification` (see [#1253](https://github.com/groue/GRDB.swift/pull/1253) for more information).
## 5.25.0
Released June 11, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.24.1...v5.25.0)
- **New**: [#1226](https://github.com/groue/GRDB.swift/pull/1226) by [@naveensrinivasan](https://github.com/naveensrinivasan): Included githubactions in the dependabot config
- **New**: [#1228](https://github.com/groue/GRDB.swift/pull/1228) by [@naveensrinivasan](https://github.com/naveensrinivasan): Set permissions for GitHub actions
- **New**: [#1235](https://github.com/groue/GRDB.swift/pull/1235) by [@groue](https://github.com/groue): Raise default Quality of Service to `.userInitiated`.
- **Fixed**: [#1233](https://github.com/groue/GRDB.swift/pull/1233) by [@GetToSet](https://github.com/GetToSet): Fix warnings of redundant conformance constraint on Xcode 14.
## 5.24.1
Released May 26, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.24.0...v5.24.1)
- **Fixed**: [#1217](https://github.com/groue/GRDB.swift/pull/1217) by [@GetToSet](https://github.com/GetToSet): Fix doc issue on TableRequest.filter(keys:).
- **Fixed**: [#1225](https://github.com/groue/GRDB.swift/pull/1225) by [@groue](https://github.com/groue): Prevent heavy DatabasePool concurrent reads from creating too many threads
## 5.24.0
Released May 1, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.23.0...v5.24.0)
- **Fixed**: [#1203](https://github.com/groue/GRDB.swift/pull/1203) by [@EvanHahn](https://github.com/EvanHahn): Fix changelog links
- **Fixed**: [#1212](https://github.com/groue/GRDB.swift/pull/1212) by [@MartinP7r](https://github.com/MartinP7r): Fix apple docs links
- **Fixed**: [#1213](https://github.com/groue/GRDB.swift/pull/1213) by [@groue](https://github.com/groue): Fix crash when the number of active ValueObservations is high
- **Breaking Change**: Transactions performed during a read-only database access are no longer notified to transaction observers. This is, strictly speaking, a breaking change. However it should have no impact since read-only transactions have very little interest.
## 5.23.0
Released April 16, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.22.2...v5.23.0)
- **Breaking Change**: [#1200](https://github.com/groue/GRDB.swift/pull/1200) by [@groue](https://github.com/groue): Require Swift 5.6 Compiler for experimental Concurrency Support
## 5.22.2
Released April 2, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.22.1...v5.22.2)
- **Fixed** a 5.22.0 regression: [#1196](https://github.com/groue/GRDB.swift/pull/1196) by [@layoutSubviews](https://github.com/layoutSubviews): Fix a crash when an observation is quickly cancelled
## 5.22.1
Released March 26, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.22.0...v5.22.1)
- **Fixed** a 5.22.0 regression: [#1194](https://github.com/groue/GRDB.swift/issues/1194) ValueObservation could deadlock when the database is configured with a serial target DispatchQueue.
## 5.22.0
Released March 22, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.21.0...v5.22.0)
- **New**: [#1186](https://github.com/groue/GRDB.swift/pull/1186) by [@benrb](https://github.com/benrb): DatabaseError provide error message as localizedFailureReason
- **Breaking Change**: [#1183](https://github.com/groue/GRDB.swift/pull/1183) by [@groue](https://github.com/groue): Starting a ValueObservation keeps a strong reference on the database connection.
## 5.21.0
Released February 6, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.20.0...v5.21.0)
- **New**: [#1165](https://github.com/groue/GRDB.swift/pull/1165) by [@guidedways](https://github.com/guidedways): Support dynamic linking via Swift Package Manager
- **Breaking Change**: [#1164](https://github.com/groue/GRDB.swift/pull/1164) by [@groue](https://github.com/groue): Drop experimental async apis from DatabaseMigrator
## 5.20.0
Released February 1, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.19.0...v5.20.0)
- **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests.
- **Fixed**: [#1162](https://github.com/groue/GRDB.swift/pull/1162) by [@groue](https://github.com/groue): Fix truncate optimization handling.
- **New**: [#1160](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Hide statement arguments by default.
- **New**: [#1161](https://github.com/groue/GRDB.swift/pull/1161) by [@groue](https://github.com/groue): Target DispatchQueue for non-read-only database connections.
- **Documentation Update**: The [Database Configuration](README.md#database-configuration) chapter explains how to opt in for public statement arguments in DEBUG builds.
## 5.19.0
Released January 19, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.18.0...v5.19.0)
- **New**: [#1144](https://github.com/groue/GRDB.swift/pull/1144) by [@TimAEllis](https://github.com/TimAEllis): Add drop column support
- **Fixed**: [#1139](https://github.com/groue/GRDB.swift/pull/1139) by [@groue](https://github.com/groue): Deal with authorization callbacks from more cursors
- **Fixed**: [#1149](https://github.com/groue/GRDB.swift/pull/1149) by [@BB9z](https://github.com/BB9z): Fix typos
## 5.18.0
Released January 9, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.17.0...v5.18.0)
- **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups
- **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns
- **New**: [#1132](https://github.com/groue/GRDB.swift/pull/1132) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.37.2
- **New**: [#1133](https://github.com/groue/GRDB.swift/pull/1133) by [@groue](https://github.com/groue): Support for STRICT tables
- **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos
- **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables
- **Fixed**: [#1128](https://github.com/groue/GRDB.swift/pull/1128) by [@groue](https://github.com/groue): Deal with authorization callbacks from cursors of FetchableRecord
- **Documentation Update**: A new [Embedding SQL in Query Interface Requests](README.md#embedding-sql-in-query-interface-requests) chapter describes the ways to leverage your SQL skills and extend GRDB apis.
## 5.17.0
Released December 14, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.16.0...v5.17.0)
- **New**: :star: [#1079](https://github.com/groue/GRDB.swift/pull/1079) by [@groue](https://github.com/groue): Async / Await
- **New**: `DatabaseRegion(table: tableName)` is deprecated. Use `Table(tableName)` instead.
- **New**: The `ABS` and `LENGTH` SQL functions are now available on association aggregates, through `abs(aggregate)` and `length(aggregate)`.
- **New**: Support for the [`TOTAL` aggregate function](https://www.sqlite.org/lang_aggfunc.html#sumunc). You can use `total` in Swift, at all places `sum` is available.
- **New**: `ValueObservation.removeDuplicates(by:)` with a closure argument.
- **New**: Testing for the existence of an associated record with `TableAlias.exists` now supports associated views, and associated tables WITHOUT ROWID that have a compound primary key.
- **Fixed**: `Database.primaryKey(_:)` throws when given the name of a view.
- **Documentation Update**: :star: The [Concurrency Guide](Documentation/Concurrency.md) was updated for the new support for asynchronous Swift.
- **Documentation Update**: :star: [GRDBAsyncDemo](Documentation/DemoApps/GRDBAsyncDemo/README.md) is a new SwiftUI demo app that uses the new async apis.
- **Documentation Update**: A new FAQ gives hints for avoiding a [Mutation of captured var in concurrently-executing code](README.md##mutation-of-captured-var-in-concurrently-executing-code) compiler error.
- **Documentation Update**: [#1107](https://github.com/groue/GRDB.swift/pull/1107) by [@tcwalther](https://github.com/tcwalther): Fix docstring for Database.create(index: ...)
- **Documentation Update**: [#1110](https://github.com/groue/GRDB.swift/pull/1110) by [@maxhumber](https://github.com/maxhumber): Minor changes to a tip in the README
## 5.16.0
Released December 5, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.15.0...v5.16.0)
- **New**: [#1106](https://github.com/groue/GRDB.swift/pull/1106) by [@groue](https://github.com/groue): Sugar for fetching only a few columns of associated records
- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter was fully rewritten. The joining methods `including(required:)` and others are much more detailed, with an exploration of frequent use cases.
- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter introduces the new `annotated(withRequired:)` and `annotated(withOptional:)` joining methods.
- **Documentation Update**: The new [Choosing a Joining Method Given the Shape of the Decoded Type](Documentation/AssociationsBasics.md#choosing-a-joining-method-given-the-shape-of-the-decoded-type) chapter helps choosing a joining method, given the shape of the fetched data.
## 5.15.0
Released December 2, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.14.0...v5.15.0)
- **Fixed**: `ValueObservation` now always fetches fresh values in an isolated fashion. This prevents all risks of fetching inconsistent data even if an external connection modifies the database.
- **New**: `Table` now conforms to `DatabaseRegionConvertible`. You can write `DatabaseRegionObservation(tracking: Table("player"))`.
- **New**: [#1102](https://github.com/groue/GRDB.swift/pull/1102) by [@groue](https://github.com/groue): Explicit tracked region for ValueObservation
## 5.14.0
Released November 25, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.13.0...v5.14.0)
- **Fix**: `ForeignKeyViolation.failureDescription(_:)` now accepts table names that require quoting.
- **Fix**: Add missing `public` qualifier on `ForeignKeyViolation` properties.
- **New**: `ForeignKeyViolation.databaseError(_:)` turns a foreign key violation into a `DatabaseError`.
- **Documentation Update**: the demo apps were modernized for iOS 15+. The SwiftUI demo app now uses the [GRDBQuery](https://github.com/groue/GRDBQuery) package in order to update its views according to the database content.
## 5.13.0
Released November 7, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.12.0...v5.13.0)
- **Breaking Change**: [#1076](https://github.com/groue/GRDB.swift/pull/1076) by [@groue](https://github.com/groue): Require Swift 5.3 and Xcode 12
- **New**: :star: [#1088](https://github.com/groue/GRDB.swift/pull/1088) by [@groue](https://github.com/groue): Shared ValueObservation
- **New**: :star: [#1095](https://github.com/groue/GRDB.swift/pull/1095) by [@groue](https://github.com/groue): Precise foreign key checks for migrations
- **New**: [#1078](https://github.com/groue/GRDB.swift/pull/1078) by [@groue](https://github.com/groue): Non-mutating persistence methods `saved` and `inserted`, and existence-checking methods `isEmpty` and `exists`
- **New**: `DatabasePool.erase()` prevents concurrent reads until it has completed.
- **New**: The `close()` method allows precise closing of database connections.
- **New**: Filtering records by single-column primary key now properly encodes dates and uuids according to the customized strategies (`filter(id:)`, `deleteAll(_:keys:)`, etc.)
- **New**: `DatabaseUUIDEncodingStrategy.lowercaseString` can encode UUID as a lowercased string. For clarity, the `string` strategy has been deprecated and renamed `uppercaseString`.
- **Documentation Update**: :star: The [Concurrency Guide](Documentation/Concurrency.md) got a major overhaul.
- **Documentation Update**: :star: A new [ValueObservation Sharing](README.md#valueobservation-sharing) chapter describes how to share database observations and spare database resources.
- **Documentation Update**: :star: The [Migrations](Documentation/Migrations.md) guide tells how you can mitigate slow foreign key checks during schema changes.
- **Documentation Update**: The [Date and UUID Coding Strategies](README.md#date-and-uuid-coding-strategies) chapter describes the new support for date and uuid primary key coding in requests by single-column primary key.
- **Documentation Update**: A new [Testing for Record Existence](README.md#testing-for-record-existence) chapter describes the new `request.isEmpty(_:)`, `Record.exists(_:id:)` and `Record.exists(_:key:)` methods.
## 5.12.0
Released September 25, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.11.0...v5.12.0)
- **Breaking Change**: Minimum iOS version is now iOS 11.0, and 32-bits devices are no longer supported. This fixes issues introduced by Xcode 13 ([#1033](https://github.com/groue/GRDB.swift/issues/1033), [#1059](https://github.com/groue/GRDB.swift/issues/1059)).
- **New**: `FTS3Pattern(matchingAllPrefixesIn:)` and `FTS5Pattern(matchingAllPrefixesIn:)` let you build full-text search patterns suitable for prefix queries.
- **New**: `FTS3.tokenize(_:)` and `FTS5Tokenizer.tokenize(_:)` let you tokenize input strings.
- **Documentation Update**: Full-text search documentation was updated for the new search pattern initializers ([FTS3/4](Documentation/FullTextSearch.md#fts3pattern), [FTS5](Documentation/FullTextSearch.md#fts5pattern)), and tokenization methods ([FTS3/4](Documentation/FullTextSearch.md#fts3-and-fts4-tokenization), [FTS5](Documentation/FullTextSearch.md#fts5-tokenization)).
## 5.11.0
Released September 3, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.10.0...v5.11.0)
- **Fixed**: Version 5.10.0, when embedded as an Xcode project, would enable the FTS5 full-text engine on system versions that do not provide it.
- **New**: [#1046](https://github.com/groue/GRDB.swift/pull/1046) by [@groue](https://github.com/groue): Improve performance of by-index row decoding
- **New**: [#1029](https://github.com/groue/GRDB.swift/pull/1029) by [@sberrevoets](https://github.com/sberrevoets), [@groue](https://github.com/groue): Column coding strategies for Codable records
## 5.10.0
Released August 22, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.9.0...v5.10.0)
- **New**: [#1036](https://github.com/groue/GRDB.swift/pull/1036) by [@groue](https://github.com/groue): Restore minimal CI tests
- **New**: [#1037](https://github.com/groue/GRDB.swift/pull/1037) by [@groue](https://github.com/groue): Support BUILD_LIBRARY_FOR_DISTRIBUTION
- **New**: [#1038](https://github.com/groue/GRDB.swift/pull/1038) by [@GetToSet](https://github.com/GetToSet): Add match operator in ColumnExpression for FTS5
- **New**: With Swift 5.5+, enhance access to `Column.rowID`. Row and PersistenceContainer subscripts now accept `row[.rowID]` and `container[.rowID]` ([SE-0299](https://github.com/apple/swift-evolution/blob/main/proposals/0299-extend-generic-static-member-lookup.md))
- **Documentation Update**: A new [Combine and Data Consistency](Documentation/Combine.md#combine-and-data-consistency) chapter explains how to make sure database publishers do not break important database invariants.
## 5.9.0
Released August 15, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.8.0...v5.9.0)
- **Fixed**: [#980](https://github.com/groue/GRDB.swift/pull/980) by [@jroselightricks](https://github.com/jroselightricks): Fix spelling
- **Fixed**: [#989](https://github.com/groue/GRDB.swift/pull/989) by [@pp5x](https://github.com/pp5x): FTS: add support of ifNotExists in synchronize()
- **Fixed**: [#999](https://github.com/groue/GRDB.swift/issues/999): `request(for: association)` no longer crashes when the foreign key contains a NULL value.
- **Fixed**: [#1025](https://github.com/groue/GRDB.swift/issues/1025) by [@mattgallagher](https://github.com/mattgallagher): Fix ValueObservation crash
- **Fixed**: Fix thread unsafety in `ValueObservation.print()`
- **New**: The `selectID()` method is now available for [Identifiable Records](README.md#identifiable-records)
- **New**: Cached prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
```swift
let updateStatement = try db.cachedStatement(literal: "INSERT ...")
// ~~~~~~~
```
- **New**: [#993](https://github.com/groue/GRDB.swift/pull/993) by [@groue](https://github.com/groue): QueryInterfaceRequest builder with dynamic table/view name
- **New**: Types that adopt both `DatabaseValueConvertible` and `Codable` now profit from automatic JSON encoding and decoding.
- **New**: [#1010](https://github.com/groue/GRDB.swift/pull/1010) by [@tternes](https://github.com/tternes): Add VACUUM INTO Support
- **New**: [#1012](https://github.com/groue/GRDB.swift/pull/1012) by [@ZevEisenberg](https://github.com/ZevEisenberg): Add brackets to urls in doc comments to make them clickable
- **New**: [#1019](https://github.com/groue/GRDB.swift/pull/1019) by [@groue](https://github.com/groue): Merge prepared statement types, and introduce statement cursor
- **Documentation Update**: The [Requests](README.md#requests) chapter was updated for the new `Table` type that can build requests without any record type.
- **Documentation Update**: The [Custom Value Types](README.md#custom-value-types) chapter was extended about the new support for codable value types encoded as JSON arrays or objects.
- **Documentation Update**: The [Fetching Methods](README.md#fetching-methods) and [Prepared Statements](README.md#prepared-statements) chapters have been updated for the unique `Statement` class, and the new `Database.allStatements()` method.
## 5.8.0
Released May 16, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.7.4...v5.8.0)
- **New**: Support for the `ESCAPE` clause with the `LIKE` operator.
- **New**: You can now define an `SQLRequest` without any generic qualifier (which defaults to `Row`):
```swift
let request = SQLRequest("SELECT ...")
```
- **New**: [#967](https://github.com/groue/GRDB.swift/pull/967) by [@steipete](https://github.com/steipete): Make SelectStatement conform to CustomStringConvertible
- **Fixed**: The `DerivableRequest.limit(_:offset:)` method was ill-designed, and removed from the documentation. It is unfortunately impossible to deprecate it without triggering warnings on the legit use cases (on `QueryInterfaceRequest`).
- **Fixed**: [#973](https://github.com/groue/GRDB.swift/pull/973): Restore access to attached databases from record types
- **Fixed**: [#974](https://github.com/groue/GRDB.swift/pull/974): Provide access to included associations when root table is not selected
- **Documentation Update**: A new [Query Interface Organization](Documentation/QueryInterfaceOrganization.md) document reveals the relationship between the various components of the GRDB query builder.
## 5.7.4
Released April 11, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.7.3...v5.7.4)
- **New**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
- **Fixed**: [#955](https://github.com/groue/GRDB.swift/pull/955) by [@steipete](https://github.com/steipete): Robustness of @Query in the SwiftUI demo app
- **Fixed**: [#956](https://github.com/groue/GRDB.swift/pull/956): Fix case-sensitivity of region-based database observation
- **New**: [#958](https://github.com/groue/GRDB.swift/pull/958) by [@chrisballinger](https://github.com/chrisballinger): Always add userInfo to databaseJSONDecoder and databaseJSONEncoder
- **New**: [#960](https://github.com/groue/GRDB.swift/pull/960) by [@MartinP7r](https://github.com/MartinP7r): Add tests for userInfo being applied to database encoder/decoder
## 5.7.3
Released April 5, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.7.2...v5.7.3)
- **Fixed**: [#950](https://github.com/groue/GRDB.swift/pull/950) by [@MartinP7r](https://github.com/MartinP7r): Fix memory consumption when encoding JSON columns
- **Fixed**: [#951](https://github.com/groue/GRDB.swift/pull/951) by [@alexwlchan](https://github.com/alexwlchan): Fix documentation typo
- **Fixed**: [#952](https://github.com/groue/GRDB.swift/pull/952) by [@holsety](https://github.com/holsety): Fix documentation typo
- **Documentation Update**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
#### 5.7.2
- **Fixed**: Really fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
#### 5.7.1
- **Fixed**: Fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
## 5.7.0
Released March 28, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.6.0...v5.7.0)
- **New**: [#947](https://github.com/groue/GRDB.swift/pull/947) by [@chrisballinger](https://github.com/chrisballinger): Allow access to Encoder from KeyedEncodingContainer
- **New**: Record types that adopt the standard [Identifiable](https://developer.apple.com/documentation/swift/identifiable) protocol have gained type-safe methods that deal with the primary key. For example:
```swift
let player = try Player.fetchOne(db, id: 42)
try Player.deleteAll(db, ids: [1, 2, 3])
```
See the new [Identifiable Records](README.md#identifiable-records) documentation chapter for more information.
- **New**: `SQLLiteral` has more use cases than initialy expected, and is renamed `SQL`.
- **New**: [`SQL` literal](Documentation/SQLInterpolation.md#sql-literal) can now be directly used as an expression, an ordering term, or a selection item.:
```swift
let name = "O'Brien"
let request = Player
.select(SQL("id, score"), ...)
.filter(SQL("name = \(name)") && ...)
.order(SQL("score DESC"), ...)
```
- **New**: Table creation DSL now supports columns and constraints defined with raw SQL String or [SQL literal](Documentation/SQLInterpolation.md#sql-literal):
```swift
try db.create(table: "player") do { t in
t.column(sql: "id INTEGER PRIMARY KEY AUTOINCREMENT")
t.column(literal: "name TEXT DEFAULT \("Anonymous")")
t.constraint(sql: "CHECK (LENGTH(name) > 0)")
t.constraint(literal: "CHECK (LENGTH(name) <= \(100))")
}
```
- **New**: Prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
```swift
let updateStatement = try db.makeUpdateStatement(literal: "INSERT ...")
let selectStatement = try db.makeSelectStatement(literal: "SELECT ...")
// ~~~~~~~
```
- **New**: [DatabaseMigrator](Documentation/Migrations.md#asynchronous-migrations) can now asynchronously migrate a database. A Combine publisher is also available.
- **New**: Added support for the `EXISTS` and `NOT EXISTS` subquery operators. See the updated [SQL Operators](README.md#sql-operators) documentation.
- **New**: `Foundation.Decimal` can now be stored in the database, and all Foundation number types can be decoded from decimal numbers stored as strings. See the [NSNumber, NSDecimalNumber, and Decimal](README.md#nsnumber-nsdecimalnumber-and-decimal) chapter for details.
## 5.6.0
Released March 12, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.5.0...v5.6.0)
- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher
- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol
- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc (see [Cursors](README.md#cursors)).
- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936).
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions.
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter of good practices: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details).
- **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state.
## 5.5.0
Released March 3, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0)
- **New**: You can now define common table expressions without any generic qualifier (which defaults to `Row`):
```swift
let cte = CommonTableExpression(...)
```
The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly.
- **New**: `DatabaseQueue` reading methods are now wrapped in a deferred transaction. This guarantees snapshot isolation in case of concurrent writes performed by external connections, and makes `DatabaseQueue` a type suitable for shared databases.
- **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`.
- **Fixed**: [#930](https://github.com/groue/GRDB.swift/pull/930): Fix SQL generation for `COLLATE`, `IN`, `NOT IN`
## 5.4.0
Released February 15, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0)
- **Breaking Change**: The query interface was refactored and some types such as `SQLExpression` are no longer a protocol.
This may break some applications that rely on Swift type inference, such as in the following example:
```swift
// No longer compiles
let values = [Column("score"), Column("score") + Column("bonus")]
```
The fix is to add an explicit declaration of the desired type:
```swift
// A possible fix
let values: [SQLExpressible] = [Column("score"), Column("score") + Column("bonus")]
```
Occurrences of such code breakage should be very rare.
- **New**: [SQL Interpolation](Documentation/SQLInterpolation.md) supports embedding collations into SQL literals:
```swift
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY email COLLATION \(.nocase)"
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY name COLLATION \(.localizedCompare)"
```
- **Documentation update**: [Adding support for missing SQL functions or operators](README.md#adding-support-for-missing-sql-functions-or-operators) explains how to extend the query interface when needed.
- **Documentation update**: The [Demo Applications](Documentation/DemoApps/) now provide tests for the database access layer.
## 5.3.0
@@ -133,7 +786,7 @@ Released September 27, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/co
Released September 20, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.11...v5.0.0)
- **Fixed**: [#838](https://github.com/groue/GRDB.swift/issues/838): Have indexed colums inherit the `ifNotExists` flag from table creation.
- **Fixed**: [#838](https://github.com/groue/GRDB.swift/issues/838): Have indexed columns inherit the `ifNotExists` flag from table creation.
## 5.0.0-beta.11
@@ -284,7 +937,7 @@ Released May 2, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v
GRDB 5 is a release focused on **Swift 5.2**, and **removing technical debt**.
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](http://github.com/groue/GRDBCombine), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](https://github.com/groue/GRDBCombine), and [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
New features include support for SQL subqueries, and a simplified handling of database errors. The most demanding users will also find it easier to switch between the system SQLite, SQLCipher, and custom SQLite builds.
@@ -2002,7 +2655,7 @@ It comes with new features, but also a few breaking changes, and a set of update
- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database ([#321](https://github.com/groue/GRDB.swift/pull/321)).
- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
- Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.23.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)).
- Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)).
- Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)).
@@ -2187,7 +2840,7 @@ Released January 29, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
**New**
- Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.22.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)`
- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`,
@@ -2241,7 +2894,7 @@ Released January 18, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](https://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
- `Row` adopts RandomAccessCollection
@@ -2328,7 +2981,7 @@ Released January 11, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
let player = try request.fetchOne(db) // Player?
```
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
This feature has been introduced in order to ease the use of [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB):
```swift
// New
@@ -2397,7 +3050,7 @@ Released December 3, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
}
```
- [#281](https://github.com/groue/GRDB.swift/pull/280): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
- [#281](https://github.com/groue/GRDB.swift/pull/281): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
**Breaking Change**
@@ -2428,7 +3081,7 @@ Released November 5, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
**New**
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.21.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
## 2.2.0
@@ -2461,7 +3114,7 @@ Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
### New
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.20.1](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
```swift
@@ -2605,7 +3258,7 @@ Released September 16, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/co
### New
New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects:
New features have been added in order to plug a few holes and support the [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](https://github.com/groue/GRDBObjc) companion projects:
- Persistable records can export themselves as dictionaries:
@@ -2868,7 +3521,7 @@ Released August 18, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compa
**New**
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.20.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
**API diff**
@@ -2899,7 +3552,7 @@ Released July 19, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare
**Fixed**
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.19.3](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
```swift
@@ -3083,7 +3736,7 @@ It comes with breaking changes, but the good news is that they are the last (unt
As a matter of fact, GRDB 1.0 still supports Xcode 8.1 and Swift 3.0. But future versions are free to use Swift 3.1 features, and will require Xcode 8.3+.
The targetted operating systems are unchanged: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+
The targetted operating systems are unchanged: iOS 8.0+ / macOS 10.9+ / watchOS 2.0+
- **[Record types](https://github.com/groue/GRDB.swift#records) have their `persistentDictionary` property replaced with the `encode(to:)` method:**
@@ -3213,7 +3866,7 @@ Released May 28, 2017
**New**
- Upgrade custom SQLite builds to [v3.19.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.19.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade SQLCipher to v3.4.1 ([announcement](https://discuss.zetetic.net/t/sqlcipher-3-4-1-release/1962), [changelog](https://github.com/sqlcipher/sqlcipher/blob/master/CHANGELOG.md))
- A [large test suite](https://travis-ci.org/groue/GRDB.swift) that runs on Travis-CI, thanks to [@swiftlyfalling](https://github.com/swiftlyfalling) in [PR #213](https://github.com/groue/GRDB.swift/pull/213)
@@ -3303,7 +3956,7 @@ Released April 6, 2017
**New**
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](http://reactivex.io) programming.
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](https://reactivex.io) programming.
**Breaking Changes**
@@ -3318,8 +3971,8 @@ Released April 3, 2017
**New**
- Support for Xcode 8.3 and Swift 3.1 (Xcode 8.1 and Swift 3 are still supported).
- Upgrade custom SQLite builds to [v3.18.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Support for [reactive](http://reactivex.io) extensions:
- Upgrade custom SQLite builds to [v3.18.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Support for [reactive](https://reactivex.io) extensions:
- `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements).
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation)
- `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
@@ -3413,7 +4066,7 @@ Released January 10, 2017
- `Row` adopts the Hashable protocol
- [FetchedRecordsController](https://github.com/groue/GRDB.swift#fetchedrecordscontroller) now outputs request changes on all platforms, for both table and collection views. Merged [#160](https://github.com/groue/GRDB.swift/pull/160) by [@kdubb](https://github.com/kdubb).
- Upgrade custom SQLite builds to [v3.16.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.16.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
**Breaking Changes**
@@ -3579,7 +4232,7 @@ Released December 4, 2016
**New**
- Upgrade custom SQLite builds to [v3.15.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.15.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
## 0.92.1
@@ -3816,7 +4469,7 @@ Released November 5, 2016
**New**
- Upgrade custom SQLite builds to [v3.15.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.15.1](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
**Fixed**
@@ -3904,7 +4557,7 @@ Released October 16, 2016
}
```
- Upgrade custom SQLite builds to [v3.15.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Upgrade custom SQLite builds to [v3.15.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
**Breaking Change**
@@ -3957,7 +4610,7 @@ Released October 8, 2016
try Book.deleteOne(db, key: 1)
```
- Upgrade custom SQLite builds to [v3.14.2](http://www.sqlite.org/changes.html).
- Upgrade custom SQLite builds to [v3.14.2](https://www.sqlite.org/changes.html).
**Breaking Changes**
@@ -4006,7 +4659,7 @@ Released September 16, 2016
**New**
- Upgrade custom SQLite builds to [v3.14.1](http://www.sqlite.org/changes.html).
- Upgrade custom SQLite builds to [v3.14.1](https://www.sqlite.org/changes.html).
**Fixed**
@@ -4891,11 +5544,11 @@ Released May 17, 2016
**Fixed**
- Restored support for iOS before 8.2 and OS X before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51).
- Restored support for iOS before 8.2 and macOS before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51).
**Breaking Changes**
- Support for advanced migrations is not available until iOS 8.2 and OS X 10.10:
- Support for advanced migrations is not available until iOS 8.2 and macOS 10.10:
```diff
struct DatabaseMigrator {
@@ -4951,7 +5604,7 @@ Released May 10, 2016
**New**
- `FetchedRecordsController` is now exposed in OSX CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller))
- `FetchedRecordsController` is now exposed in macOS CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller))
**Fixed**
@@ -5084,7 +5737,7 @@ Released April 5, 2016
**Fixed**
- Restored CocoaPods support for iOS 8+ and OS X 10.9+
- Restored CocoaPods support for iOS 8+ and macOS 10.9+
## 0.56.0
@@ -5093,7 +5746,7 @@ Released April 5, 2016
**New**
- The new framework GRDBCipher embeds [SQLCipher](http://sqlcipher.net) and can encrypt databases ([documentation](https://github.com/groue/GRDB.swift#encryption))
- The new framework GRDBCipher embeds [SQLCipher](https://www.zetetic.net/sqlcipher/) and can encrypt databases ([documentation](https://github.com/groue/GRDB.swift#encryption))
- `DatabaseQueue.path` and `DatabasePool.path` give the path to the database.
**Fixed**
@@ -5127,7 +5780,7 @@ Released March 31, 2016
Released March 29, 2016
This release restores CocoaPods support for iOS 9.0+ and OSX 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or OSX 10.9+ in a further release.
This release restores CocoaPods support for iOS 9.0+ and macOS 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or macOS 10.9+ in a further release.
## 0.54.0
@@ -5595,7 +6248,7 @@ Record ([documentation](https://github.com/groue/GRDB.swift#record-class)):
- `Record.reload()` has been removed. You have to provide your own implementation, should you need reloading.
- `Record.init(row: Row)` has been renamed `Record.init(_ row: Row)` (unlabelled row argument).
- `Record.updateFromRow()` has been removed. Override `init(_ row: Row)` instead.
- `Record.didInsertWithRowID(_:forColumn:)` should be overriden by Record subclasses that are interested in their row ids.
- `Record.didInsertWithRowID(_:forColumn:)` should be overridden by Record subclasses that are interested in their row ids.
- `Record.databaseEdited` has been renamed `hasPersistentChangedValues`.
- `Record.databaseChanges` has been renamed `persistentChangedValues` and now returns `[String: DatabaseValue?]`, the dictionary of old values for changed columns.
@@ -6026,7 +6679,7 @@ Released August 25, 2015
**Fixed**
- Reduced iOS Deployment Target to 8.0, and OSX Deployment Target to 10.9.
- Reduced iOS Deployment Target to 8.0, and macOS Deployment Target to 10.9.
- `DatabaseQueue.inTransaction()` is now declared as `rethrows`.
**Breaking changes**
@@ -6043,11 +6696,11 @@ Released August 18, 2015
- `RowModel.exists(db)` returns whether a row model has a matching row in the database.
- `Statement.arguments` property gains a public setter.
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](https://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
**Breaking changes**
- `UpdateStatement.Changes` has been renamed `DatabaseChanges` ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss)).
- `UpdateStatement.Changes` has been renamed `DatabaseChanges` ([#6](https://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss)).
## 0.7.0
+99 -328
View File
@@ -1,328 +1,99 @@
Contributing to GRDB
====================
**Thank you for coming!**
This guide is a set of tips and guidelines for contributing to the GitHub repository [groue/GRDB.swift](https://github.com/groue/GRDB.swift).
- [Report Bugs]
- [Ask Questions]
- [Suggest an Enhancement]
- [Submit a Pull Request]
- [Sponsoring and Professional Support]
- [Suggested Contributions]
- [Non-Goals]
### Report Bugs
Please make sure the bug is not already reported by searching existing [issues](https://github.com/groue/GRDB.swift/issues).
If you're unable to find an existing issue addressing the problem, [open a new one](https://github.com/groue/GRDB.swift/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.
### Ask Questions
The information you are looking for is maybe already available. Check out:
- the [FAQ](README.md#faq)
- the [general documentation](README.md#documentation)
- the [answered questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=label%3Aquestion+)
If not, your questions are welcome in the [GRDB forums](https://forums.swift.org/c/related-projects/grdb), or in a new [GitHub issue](https://github.com/groue/GRDB.swift/issues/new).
### Suggest an Enhancement
Your idea may already be listed in [Suggested Contributions], waiting for someone to pick it up.
If not, contact [@groue](http://twitter.com/groue) on Twitter, or [open a new issue](https://github.com/groue/GRDB.swift/issues/new).
### Submit a Pull Request
Discuss your idea first, so that your changes have a good chance of being merged in.
Submit your pull request against the `development` branch.
Pull requests that include tests for modified and new functionalities, inline documentation, and relevant updates to the main README.md are merged faster, because you won't have to wait for somebody else to complete your contribution.
### Sponsoring and Professional Support
GRDB is free. It is openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
When you have specific development or support needs, and are willing to financially contribute to GRDB, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
## Suggested Contributions
You'll find below various ideas for enhancing and extending GRDB, in various areas. Your ideas can be added to this list: [Suggest an Enhancement].
Legend:
- :baby: **Starter Task**: get familiar with GRDB internals
- :muscle: **Hard**: there are implementation challenges
- :pencil: **Documentation**
- :fire: **Experimental**: let's invent the future!
- :bowtie: **Public API Challenge**: we'll need a very good public API
- :hammer: **Tooling**: GRDB and its environment
- :question: **Unknown Difficulty**
The ideas, in alphabetical order:
- [Associations]
- [CloudKit]
- [Concurrency]
- [Custom FTS5 Auxiliary Functions]
- [Date and Time Functions]
- [Decode NSDecimalNumber from Text Columns]
- [Documentation]
- [Full Text Search Demo Application]
- [JSON]
- [Linux]
- [More SQL Generation]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Typed Expressions]
### Associations
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
Associations can be enhanced in several ways. See the "Known Issues" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
### CloudKit
:bowtie: Public API Challenge :question: Unknown Difficulty :fire: Experimental
Integration with [CloudKit](https://developer.apple.com/icloud/cloudkit/) is a rich, interesting, and useful topic.
It is likely that CloudKit support would exist in a separate companion library.
Starting points:
- [caiyue1993/IceCream](https://github.com/caiyue1993/IceCream)
- [mentrena/SyncKit](https://github.com/mentrena/SyncKit)
- [nofelmahmood/Seam](https://github.com/nofelmahmood/Seam)
- [Sorix/CloudCore](https://github.com/Sorix/CloudCore)
- [Synchronizing data with CloudKit](https://medium.com/@guilhermerambo/synchronizing-data-with-cloudkit-94c6246a3fda)
- WWDC CloudKit sessions, including [CloudKit Best Practices](https://developer.apple.com/videos/play/wwdc2016/231/)
### Concurrency
:bowtie: Public API Challenge :muscle: Hard :pencil: Documentation
GRDB has a strong focus on safe concurrency. Not only safe as "does not crash", but safe as "actively protects your application data". The topic is discussed in (too) many places:
- [Concurrency Guide](README.md#concurrency)
- [Why Adopt GRDB?](https://github.com/groue/GRDB.swift/blob/master/Documentation/WhyAdoptGRDB.md#strong-and-clear-multi-threading-guarantees)
- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
- [Good Practices for Designing Record Types](https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md#fetch-in-time)
- [Comparison between GRDB and Core Data concurrency](https://github.com/groue/GRDB.swift/issues/405)
Despite this abundant documention, I regularly meet developers who don't think about eventual multi-threading gotchas, and don't design their application against them.
This can be explained:
- Some developers disregard potential multi-threading bugs such as data races, even if the fix is "easy". Such bugs may never happen during the development of an application. They may only impact a few users in production. It is always easier not to think about them.
- Databases are often seen as plain CRUD tools, and some developers are not familiar with topics like isolation or transactions. This is especially true for developers who have experience in a managed ORM such as Core Data or Realm, or web frameworks like Rails or Django: switching to an unmanaged relational database is not an easy task.
- Not all applications need to be multi-threaded.
And this creates improvement opportunities:
- Better documentation of GRDB concurrency
- The introduction of an "ultra-safe" concurrency mode. Maybe something that restricts all database accesses to the main thread, like [FCModel](https://github.com/marcoarment/FCModel). Maybe in a separate companion library.
### Custom FTS5 Auxiliary Functions
:question: Unknown Difficulty
The SQLite documentation provides [this description](https://www.sqlite.org/fts5.html) of FTS5 auxiliary functions:
> An application may use FTS5 auxiliary functions to retrieve extra information regarding the matched row. For example, an auxiliary function may be used to retrieve a copy of a column value for a matched row with all instances of the matched term surrounded by html <b></b> tags.
Applications can define their own [custom FTS5 auxiliary functions](https://www.sqlite.org/fts5.html#custom_auxiliary_functions) with SQLite, but GRDB does not yet provide any Swift API for that.
See issue [#421](https://github.com/groue/GRDB.swift/issues/421) for more information.
### Date and Time Functions
:baby: Starter Task
Believe it or not, no one has ever asked support for SQLite [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). There is surely room for a nice Swift API that makes them available.
For more ideas, see:
- [SQLite Core Functions](https://www.sqlite.org/lang_corefunc.html)
- [SQLite Aggregate Functions](https://www.sqlite.org/lang_aggfunc.html)
- [SQLite JSON functions](https://www.sqlite.org/json1.html) and [JSON], below.
Functions are defined in [GRDB/QueryInterface/Support/SQLFunctions.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/QueryInterface/Support/SQLFunctions.swift).
### Decode NSDecimalNumber from Text Columns
:baby: Starter Task
NSDecimalNumber currently only decodes integer and float decimal values. It would be nice if NSDecimalNumber would decode text values as well:
```swift
let number = try NSDecimalNumber.fetchOne(db, "SELECT '12.3'")!
print(number) // prints 12.3
```
NSNumber and NSDecimalNumber support is found in [GRDB/Core/Support/Foundation/NSNumber.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/Core/Support/Foundation/NSNumber.swift)
### Documentation
:baby: Starter Task :pencil: Documentation
General documentation can always be improved so that it reaches its goal: helping developers building applications.
- English: the documentation has mostly been written by [@groue](http://github.com/groue) who is not a native English speaker.
- Clarity: any chapter that is not crystal clear should be enhanced.
- Audience: documentation should talk to several populations of developers, from beginners who need positive guidance, to SQLite experts who need to build trust.
- Typos
- Inaccuracies
- etc.
Inline documentation, the one which is embedded right into the source code and is displayed by Xcode when one alt-clicks an identifier, deserves the same care.
If you are a good writer, your help will be very warmly welcomed.
### Full Text Search Demo Application
:baby: Starter Task :pencil: Documentation
There exists a GRDB demo app for the FTS5 full-text engine: [WWDCCompanion](https://github.com/groue/WWDCCompanion).
This application downloads the transcripts of WWDC sessions, and lets its user type keywords and find matching sessions, sorted by relevance.
The problem is that this demo app breaks every year :sweat_smile:
We'd need instead to index a stable corpus, in order to ease the maintenance of this demo app.
### JSON
:bowtie: Public API Challenge :baby: Starter Task
[Codable Records] are granted with automatic JSON encoding and decoding of their complex properties. But there is still room for improvements. For example, could we put the [SQLite JSON1 extension](https://www.sqlite.org/json1.html) to some good use?
### Linux
:muscle: Hard :hammer: Tooling
Swift on Linux is currently focused on the server (Vapor, Perfect, Kitura). While general server support is a [non-goal](#non-goals) of GRDB, there exists read-only servers, and Linux GUI applications, too. Linux is thus a desired platform.
### More SQL Generation
:bowtie: Public API Challenge :question: Unknown Difficulty
There are several SQLite features that GRDB could natively support:
- [ALTER TABLE ... RENAME COLUMN ... TO ...](https://www.sqlite.org/lang_altertable.html)
- [ATTACH DATABASE](https://www.sqlite.org/lang_attach.html)
- [UPSERT](https://www.sqlite.org/lang_UPSERT.html)
- [INSERT INTO ... SELECT ...](https://www.sqlite.org/lang_insert.html)
- [WITH RECURSIVE ...](https://www.sqlite.org/lang_with.html)
- [RTree](https://sqlite.org/rtree.html)
- [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.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
Sometimes one needs, in lldb, a console similar to the [Command Line Shell For SQLite](https://www.sqlite.org/cli.html).
### SQLCipher in a Shared App Container
:question: Unknown Difficulty
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
### Typed Expressions
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
The compiler currently does not spot type mistakes in query interface requests:
```swift
Player.filter(Column("name") == "Arthur") // OK
Player.filter(Column("name") == 1) // Sure
Player.filter(Column("name") == Date()) // Legit
```
This weak typing also prevents natural-looking Swift code from producing the expected results:
```swift
// Performs arithmetic additions instead of string concatenation
Player.select(Column("firstName") + " " + Column("lastName"))
```
It would be interesting to see what typed expressions could bring to GRDB.
## Non-Goals
GRDB is a "toolkit for SQLite databases, with a focus on application development".
This definition is the reason why GRDB can provide key features such as sharp multi-threading, database observation, and first-class support for raw SQL.
Features that blur this focus are non-goals:
- Support for MySQL, PostgreSQL, or other database engines
- Support for Servers
[Ask Questions]: #ask-questions
[Associations]: #associations
[CloudKit]: #cloudkit
[Codable Records]: README.md#codable-records
[Custom FTS5 Auxiliary Functions]: #custom-fts5-auxiliary-functions
[Database Observation]: #database-observation
[Date and Time Functions]: #date-and-time-functions
[Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns
[Documentation]: #documentation
[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
[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
[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
[Submit a Pull Request]: #submit-a-pull-request
[Suggest an Enhancement]: #suggest-an-enhancement
[Suggested Contributions]: #suggested-contributions
[Typed Expressions]: #typed-expressions
[persistence methods]: README.md#persistence-methods
[PersistableRecord]: README.md#persistablerecord-protocol
[Record Comparison]: README.md#record-comparison
[Requesting Associated Records]: Documentation/AssociationsBasics.md#requesting-associated-records
[ValueObservation]: README.md#valueobservation
How you can Contribute
======================
- [Contribute to the GRDB codebase]
- [Answer issues and contribute to discussions]
- [Financial support and sponsoring]
## Contribute to the GRDB codebase
1. **Install** the following tools:
- For running tests:
- Ruby
- [CocoaPods](https://cocoapods.org) (gem)
- [xcpretty](https://github.com/xcpretty/xcpretty) (gem)
- For contributing code:
- [Swiftlint](https://github.com/realm/SwiftLint) (present in the `$PATH` or in `/opt/homebrew/bin/`)
2. **Clone the `development` branch on your machine.**
3. **Run `make SQLiteCustom` in the terminal**, at the root of the repository.
This step is not strictly necessary if you do not plan to work on custom SQLite builds. But it will avoid a lot of warnings in Xcode.
4. **Open `GRDB.xcworkspace`.** This workspace contains six projects:
- `GRDB.xcodeproj`: the project which contains the GRDB framework and test targets. The sources are organized in two groups:
- `GRDB`: GRDB sources
- `Tests`: GRDB tests
- `GRDBCustom.xcodeproj`: the project which builds GRDB with a custom SQLite build.
- `GRDBProfiling.xcodeproj`: a project which helps profiling GRDB with Instruments. No code here is really precious.
- `GRDBDemoiOS.xcodeproj`, `GRDBCombineDemo.xcodeproj`, `GRDBAsyncDemo.xcodeproj`: the demo apps.
To work with `GRDBCustom.xcodeproj`:
- Make sure Xcode is installed in `/Applications`.
- Run `make SQLiteCustom` in the terminal so that SQLite sources are present.
5. **Run tests**
You can run tests from `GRDB.xcworkspace`, after selecting your scheme (`GRDB` from `GRDB.xcodeproj` or `GRDBCustom` from `GRDBCustom.xcodeproj`).
Before submitting a pull request, please run in the terminal:
```sh
make smokeTest
```
The "smoke tests" perform minimal testing of the system SQLite, SQLCipher, custom SQLite builds, as well as SPM integration.
Before a release, the full test suite must pass:
```sh
make test
```
The full test suite performs many more checks, such as the ability to archive an XCFramework, various installation methods, the demo apps, etc.
6. **Please respect the existing coding style**
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
- Spaces, not tabs.
- Whitespace-only lines are not trimmed.
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
- No Swiftlint warning after a build.
7. **Please provide documentation for your changes**
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
8. **Open a pull request with your changes (targeting the `development` branch)!**
9. **If you are granted a push access to the repository**, check [ReleaseProcess.md](Documentation/ReleaseProcess.md) in order to publish a new GRDB version.
## Answer issues and contribute to discussions
Answering [issues](https://github.com/groue/GRDB.swift/issues), participating in [discussions](https://github.com/groue/GRDB.swift/discussions) and in the [forum](https://forums.swift.org/c/related-projects/grdb/36) is a great way to help, get familiar with the library, and shape its direction.
## Financial support and sponsoring
GRDB is free, and openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
Support is free as well, as long as it happens publicly, and is available to everyone as well as internet search engines. This excludes the private channels of social networks, closed environments such as Slack, etc.
When you have specific development or support needs, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
You can also [sponsor @groue via GitHub](https://github.com/sponsors/groue).
[Contribute to the GRDB codebase]: #contribute-to-the-grdb-codebase
[Answer issues and contribute to discussions]: #answer-issues-and-contribute-to-discussions
[Financial support and sponsoring]: #financial-support-and-sponsoring
+1 -1
View File
@@ -1,4 +1,4 @@
Sharing a Database in an App Group Container
============================================
This guide [has moved](SharingADatabase.md).
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
+646 -111
View File
@@ -26,6 +26,7 @@ GRDB Associations
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
- [Fetching Values from Associations]
@@ -88,7 +89,7 @@ struct BookInfo {
let books = try Book.fetchAll(db)
let bookInfos = books.map { book -> BookInfo in
let author = try Author.fetchOne(db, key: book.authorId)
let author = try Author.fetchOne(db, id: book.authorId)
return BookInfo(book: book, author: author)
}
```
@@ -129,7 +130,7 @@ let request = Book.including(optional: Book.author)
let bookInfos = BookInfo.fetchAll(db, request)
```
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter.
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
## Required Protocols
@@ -510,7 +511,7 @@ When using class names composed of two or more words, the table name should use
| Mouse | mouse | `mouse`, `mice`, `maxMouseSize` |
| Person | person | `person`, `people`, `personCount` |
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](http://github.com/groue/GRDB.swift/issues).
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](https://github.com/groue/GRDB.swift/issues).
See [The Structure of a Joined Request] for more information.
@@ -648,7 +649,7 @@ Here is the recommended [migration] for the **[HasOne]** association:
```swift
migrator.registerMigration("Countries") { db in
try db.create(table: "country") { t in
t.column("code", .text).primaryKey() // (1)
t.primaryKey("code", .text) // (1)
t.column("name", .text)
}
try db.create(table: "demographics") { t in
@@ -711,9 +712,9 @@ struct Author: TableRecord {
}
```
> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
> **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
>
> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
> **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
@@ -781,6 +782,7 @@ Fetch requests do not visit the database until you fetch values from them. This
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
@@ -840,108 +842,513 @@ let novels = try author
## Joining And Prefetching Associated Records
**You build requests that involve several records with the following "joining methods":**
You build requests that involve associations with one of the following "joining methods":
- `joining(optional: association)`
- `joining(required: association)`
- `including(optional: association)`
- `including(required: association)`
- `including(all: associationToMany)`
- Prefetch associated records:
- [`including(required:)`]
- [`including(optional:)`]
- [`including(all:)`]
- Prefetch only a few columns of an associated record:
- [`annotated(withRequired:)`]
- [`annotated(withOptional:)`]
- [`including(all:)`]
- Join associated records without prefetching:
- [`joining(required:)`]
- [`joining(optional:)`]
- [Choosing a Joining Method Given the Shape of the Decoded Type]
Before we describe them in detail, let's see a few requests they can build:
### `including(required:)`
For example, fetch books along with their author:
```swift
/// All authors with their respective books
let request = Author
.including(all: Author.books)
/// All books with their respective author
let request = Book
.including(required: Book.author)
/// All books with their respective author, sorted by title
let request = Book
.order(Column("title"))
.including(required: Book.author)
/// All books written by a French author
let request = Book
.joining(required: Book.author.filter(Column("countryCode") == "FR"))
// SELECT book.*, author.*
// FROM book
// JOIN author ON author.id = book.authorId
let request = Book.including(required: Book.author)
```
The pattern is always the same: you start from a base request, that you extend with one of the joining methods.
This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
**To choose the joining method you need, you ask yourself two questions:**
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author // The required associated record
}
let bookInfos = try Book
.including(required: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** The association key is, by default, the name of the associated database table. This can be configured with the association `forKey(_:)` method:
```swift
struct Author: TableRecord {
static let databaseTableName = "writer"
}
struct Book: TableRecord {
// Replace the default "writer" association key with "author"
static let author = belongsTo(Author.self).forKey("author")
}
// Fetch all books along with their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author // Matches the "author" association key
}
let bookInfos = try Book
.including(required: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all books along with the name and country of their author
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book
var author: PartialAuthor
}
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
But if you'd rather avoid this extra partial type, prefer [`annotated(withRequired:)`]:
```swift
// Fetch all books along with the country of their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var country: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `including(optional:)`
For example, fetch books along with their eventual author:
```swift
// SELECT book.*, author.*
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.including(optional: Book.author)
```
This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. The associated record can be missing: it is "optional".
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author? // The optional associated record
}
let bookInfos = try Book
.including(optional: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** See [`including(required:)`] for more information.
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all books along with the name and country of their eventual author
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book
var author: PartialAuthor?
}
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
But if you'd rather avoid this extra partial type, prefer [`annotated(withOptional:)`]:
```swift
// Fetch all books along with the country of their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var country: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `including(all:)`
For example, fetch authors along with their books:
```swift
// SELECT author.* FROM author
// SELECT book.* FROM book WHERE authorId IN (...)
let request = Author.including(all: Author.books)
```
This method accepts any to-many association ([HasMany] or [HasManyThrough]). It has the base record fetched along with all its associated records, which are "included" in the fetched results.
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all authors along with their books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author // The base record
var books: [Book] // A collection of associated records
}
let authorInfos = try Author
.including(all: Author.books)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
The associated records can be stored into an Array as in the above example, but also a Set, and generally speaking any decodable Swift collection.
**The CodingKey for the `AuthorInfo.books` property must match the association key of the `Author.books` association.** The association key is, by default, the pluralized name of the associated database table. This can be configured with the association `forKey(_:)` method:
```swift
struct Book: TableRecord {
static let databaseTableName = "publication"
}
struct Author: TableRecord {
// Replace the default "publications" association key with "books"
static let books = hasMany(Book.self).forKey("books")
}
// Fetch all authors along with their books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var books: [Book] // Matches the "books" association key
}
let authorInfos = try Author
.including(all: Author.books)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
**When you only need a few columns of the associated records**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all authors along with the titles and years of their books
struct AuthorInfo: Decodable, FetchableRecord {
struct PartialBook: Decodable {
var title: String
var year: Int
}
var author: Author
var books: [PartialBook]
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
When you need a single column of the associated records, avoid the extra partial type, and instead use the association `forKey(_:)` method in order to match the name of the decoded property:
```swift
// Fetch all authors along with the titles of their books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookTitles: [String]
}
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
### `annotated(withRequired:)`
For example, fetch books along with the name and country of their author:
```swift
// SELECT book.*, author.name, author.country
// FROM book
// JOIN author ON author.id = book.authorId
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
```
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with the name and country of their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var name: String // A column of the required associated record
var country: String // A column of the required associated record
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
```swift
// Fetch all books along with the name of their author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var authorName: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `annotated(withOptional:)`
For example, fetch books along with the name and country of their eventual author:
```swift
// SELECT book.*, author.name, author.country
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
```
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional".
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with the name of their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var name: String? // A column of the optional associated record
var country: String? // A column of the optional associated record
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
```swift
// Fetch all books along with the name of their eventual author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var authorName: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
### `joining(required:)`
For example, fetch books by French authors:
```swift
// SELECT book.*
// FROM book
// JOIN author ON author.id = book.authorId
// AND author.country = 'France'
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
```
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required".
To fetch results from such a request, you do not need to define a dedicated record type:
```swift
// Fetch all books by French authors
let books = try Book
.joining(required: Book.author.filter(Column("country") == "France"))
.fetchAll(db)
```
### `joining(optional:)`
```swift
// SELECT book.*
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.joining(optional: Book.author)
```
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. The associated record can be missing: it is "optional".
This method has no observable effect unless the associated record is used in a way or another. We'll see examples later in this documentation.
### Choosing a Joining Method Given the Shape of the Decoded Type
In the description of the [joining methods] above, we have seen that you need to define dedicated record types in order to prefetch associated records. Each joining method needs a dedicated record type that has a specific shape.
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
- [`including(required:)`]
1. Should the associated records be fetched along with the base records?
If yes, use `including(...)`. Otherwise, use `joining(...)`.
For example, to load books with their respective author, you use `including(required:)`:
```swift
// All books with their respective author
let request = Book
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author // The associated record
}
let bookInfos = try Book
.including(required: Book.author)
// This request can feed the following record:
struct BookInfo: FetchableRecord, Decodable {
var book: Book
var author: Author // the required associated author
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
And to load authors with their respective books, you use `including(all:)`:
```swift
// All authors with their respective books
let request = Author
.including(all: Author.books)
// This request can feed the following record:
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var books: [Book] // all associated books
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book // The base record
var author: PartialAuthor // The partial associated record
}
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
On the other side, to load all books written by a French author, you sure need to filter authors, but you don't need them to be present in the fetched results. You prefer `joining`:
```swift
// All books written by a French author
let request = Book
.joining(required: Book.author.filter(Column("countryCode") == "FR"))
// This request feeds the Book record:
let books: [Book] = try request.fetchAll(db)
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
2. For to-one associations, should the request allow missing associated records?
If yes, choose the `optional` variant. Otherwise, choose `required`.
For example, to load all books with their respective authors, even if the book has no recorded author, you'd use `including(optional:)`:
- [`annotated(withRequired:)`]
```swift
// All books with their respective (eventual) authors
let request = Book
.including(optional: Book.author)
// This request can feed the following record:
struct BookInfo: FetchableRecord, Decodable {
var book: Book
var author: Author? // the optional associated author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var authorName: String // A column of the associated record
var country: String // A column of the associated record
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
let bookInfos = try Book
.annotated(withRequired: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
- [`including(optional:)`]
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author? // The eventual associated record
}
let bookInfos = try Book
.including(optional: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
You can remember to use `optional` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `required`.
```swift
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
var country: String
}
var book: Book // The base record
var author: PartialAuthor? // The eventual partial associated record
}
Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through.
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
- [`annotated(withOptional:)`]
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins.
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var authorName: String? // A column of the eventual associated record
var country: String? // A column of the eventual associated record
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
- [`including(all:)`]
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author // The base record
var books: [Book] // A collection of associated records
}
let authorInfos = try Author
.including(all: Author.books)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
```swift
struct AuthorInfo: Decodable, FetchableRecord {
struct PartialBook: Decodable {
var title: String
var year: Int
}
var author: Author // The base record
var books: [PartialBook] // A collection of partial associated records
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author // The base record
var bookTitles: [String] // A collection of one column of the associated records
}
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
## Combining Associations
@@ -1028,7 +1435,7 @@ struct BookInfo: FetchableRecord, Decodable {
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
```
> :warning: **Warning**: you can not currently chain a required association behind an optional association:
> **Warning**: you can not currently chain a required association behind an optional association:
>
> ```swift
> // Not implemented
@@ -1044,7 +1451,7 @@ let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
**You can filter associated records.**
The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
```swift
// SELECT book.*
@@ -1103,7 +1510,7 @@ let sortedAuthor = Book.author.order(Column("name"))
let request = Book.including(required: sortedAuthor)
```
When you sort both the base record on the associated record, the request is sorted on the base record first, and on the associated record next:
When you sort both the base record and the associated record, the request is sorted on the base record first, and on the associated record next:
```swift
// SELECT book.*, person.*
@@ -1221,10 +1628,9 @@ let teamInfos = try Team
.fetchAll(db)
```
## Columns Selected by an Association
By default, associated records include all their columns:
By default, associated records, like all records, include all their columns:
```swift
// SELECT book.*, author.*
@@ -1235,7 +1641,9 @@ let request = Book.including(required: Book.author)
**The selection can be changed for each individual request, or for all requests including a given type.**
To specify the selection of an associated record in a specific request, use the `select` method:
To specify the default selection for a given record type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
To specify the selection in a specific request, use the `select` method:
```swift
// SELECT book.*, author.id, author.name
@@ -1245,7 +1653,105 @@ let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
let request = Book.including(required: restrictedAuthor)
```
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
In order to fetch from such requests of partial records, see the documentation of the [joining methods].
## Further Refinements to Associations
Associations support more refinements:
- `distinct`
Fetch all authors with the kinds of books they write (novels, poems, plays, etc):
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKinds: Set<Book.Kind>
}
let distinctBookKinds = Author.books
.select(Column("kind"))
.distinct()
.forKey("bookKinds")
let authorInfos: [AuthorInfo] = try Author
.including(all: distinctBookKinds)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- `group`, `having`
Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc):
```swift
struct BookKindInfo: Decodable {
var kind: Book.Kind
var maxYear: Int
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKindInfos: [BookKindInfo]
}
let bookKindInfos = Author.books
.select(
Column("kind"),
max(Column("year")).forKey("maxYear"))
.group(Column("kind"))
.forKey("bookKindInfos")
let authorInfos: [AuthorInfo] = try Author
.including(all: bookKindInfos)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Association Aggregates]
Fetch all authors with their awarded books:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var awardedBooks: [Book]
}
let awardedBooks = Author.books
.having(Book.awards.isEmpty == false)
.forKey("awardedBooks")
let authorInfos: [AuthorInfo] = try Author
.including(all: awardedBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Common Table Expressions]
Association can use their own CTEs:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var specialBooks: [Book]
}
let specialCTE = CommonTableExpression(...)
let specialBooks = Author.books
.with(specialCTE)
... // use the CTE in the book association
.forKey("specialBooks")
let authorInfos = try Author
.including(all: specialBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
> **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
## Table Aliases
@@ -1317,7 +1823,7 @@ let request = Book.aliased(bookAlias)
.filter(sql: "b.publishDate >= a.deathDate")
```
> :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
> **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
>
> ```swift
> // Fatal error: A TableAlias most not be used to refer to multiple tables
@@ -1326,7 +1832,7 @@ let request = Book.aliased(bookAlias)
> let people = Person.aliased(alias)...
> ```
>
> :point_up: **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records:
> **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records:
>
> ```swift
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
@@ -1393,7 +1899,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
```swift
// Author requests
extension DerivableRequest where RowDecoder == Author {
extension DerivableRequest<Author> {
/// Filters authors by country
func filter(country: String) -> Self {
filter(Column("country") == country)
@@ -1401,7 +1907,7 @@ extension DerivableRequest where RowDecoder == Author {
}
// Book requests
extension DerivableRequest where RowDecoder == Book {
extension DerivableRequest<Book> {
/// Filters books by author country
func filter(authorCountry: String) -> Self {
joining(required: Book.author.filter(country: country))
@@ -1494,7 +2000,7 @@ Each association included in the request can feed a property of the decoded reco
- [Decoding a Joined Request with a Decodable Record]
- [Decoding a Joined Request with FetchableRecord]
- [Debugging Request Decoding]
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
## The Structure of a Joined Request
@@ -1659,8 +2165,8 @@ struct BookInfo: FetchableRecord {
var country: Country?
var coverImage: CoverImage?
init(row: Row) {
book = Book(row: row)
init(row: Row) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
coverImage = row["coverImage"]
@@ -1694,8 +2200,8 @@ struct AuthorInfo: FetchableRecord {
var author: Author
var books: [Book]
init(row: Row) {
author = Author(row: row)
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
}
}
@@ -1825,6 +2331,7 @@ for info in authorInfos {
- `books.max(column)`
- `books.average(column)`
- `books.sum(column)`
- `books.total(column)`
### Annotating a Request with Aggregates
@@ -1873,6 +2380,9 @@ The default name is built from the aggregating method, the **[association key](#
| `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` |
| `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` |
| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` |
| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ |
¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions.
Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever).
@@ -2147,6 +2657,23 @@ Aggregates can be modified and combined with Swift operators:
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
```
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
<details>
<summary>SQL</summary>
```sql
SELECT "team".*, ABS(MAX("player"."score"))
FROM "team"
LEFT JOIN "player" ON ("player"."teamId" = "team"."id")
GROUP BY "team"."id"
```
</details>
```swift
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
```
### Isolation of Multiple Aggregates
@@ -2316,7 +2843,7 @@ let request = Book.all().filter(country: "ES")
Those methods are defined on extensions to the `DerivableRequest` protocol:
```swift
extension DerivableRequest where RowDecoder == Author {
extension DerivableRequest<Author> {
func filter(country: String) -> Self {
filter(Column("country") == country)
}
@@ -2326,14 +2853,14 @@ extension DerivableRequest where RowDecoder == Author {
}
}
extension DerivableRequest where RowDecoder == Book {
extension DerivableRequest<Book> {
func filter(country: String) -> Self {
joining(required: Book.author.filter(country: country))
}
}
```
See [Good Practices for Designing Record Types] for more information.
See [Recommended Practices for Designing Record Types] for more information.
## Known Issues
@@ -2380,8 +2907,6 @@ See [Good Practices for Designing Record Types] for more information.
.including(required: Passport.citizen))
```
Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality.
---
This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
@@ -2392,7 +2917,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides.
**GRDB**
Copyright (C) 2015-2020 Gwendal Roué
Copyright (C) 2015-2023 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:
@@ -2433,9 +2958,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
[Self Joins]: #self-joins
[Ordered Associations]: #ordered-associations
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: Migrations.md
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[Record]: ../README.md#records
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Associations and the Database Schema]: #associations-and-the-database-schema
@@ -2450,6 +2976,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Requesting Associated Records]: #requesting-associated-records
[requests for associated records]: #requesting-associated-records
[Joining And Prefetching Associated Records]: #joining-and-prefetching-associated-records
[joining methods]: #joining-and-prefetching-associated-records
[Filtering Associations]: #filtering-associations
[Sorting Associations]: #sorting-associations
[Columns Selected by an Association]: #columns-selected-by-an-association
@@ -2469,18 +2996,26 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
[DerivableRequest Protocol]: #derivablerequest-protocol
[Known Issues]: #known-issues
[Row Adapters]: ../README.md#row-adapters
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
[query interface requests]: ../README.md#requests
[TableRecord]: ../README.md#tablerecord-protocol
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
[regular aggregating methods]: ../README.md#fetching-aggregated-values
[Record class]: ../README.md#record-class
[EncodableRecord]: ../README.md#persistablerecord-protocol
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Codable Records]: ../README.md#codable-records
[persistence methods]: ../README.md#persistence-methods
[database observation tools]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[FAQ]: ../README.md#faq-associations
[common table expressions]: CommonTableExpressions.md
[Common Table Expressions]: CommonTableExpressions.md
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
[`including(required:)`]: #includingrequired
[`including(optional:)`]: #includingoptional
[`including(all:)`]: #includingall
[`annotated(withRequired:)`]: #annotatedwithrequired
[`annotated(withOptional:)`]: #annotatedwithoptional
[`joining(required:)`]: #joiningrequired
[`joining(optional:)`]: #joiningoptional
[Choosing a Joining Method Given the Shape of the Decoded Type]: #choosing-a-joining-method-given-the-shape-of-the-decoded-type
+113 -37
View File
@@ -7,6 +7,7 @@ GRDB ❤️ Combine
- [Demo Application]
- [Asynchronous Database Access]
- [Database Observation]
- [Combine and Data Consistency]: take care when you combine database publishers together
## Usage
@@ -46,6 +47,19 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
</details>
<details>
<summary><strong>Asynchronously migrate the database</strong></summary>
This publisher migrates a database:
```swift
// DatabasePublishers.Migrate
let migrator: DatabaseMigrator = ...
let publisher = migrator.migratePublisher(dbQueue)
```
</details>
<details>
<summary><strong>Observe changes in database values</strong></summary>
@@ -99,11 +113,12 @@ let cancellable = publisher.sink(
# Asynchronous Database Access
GRDB provide publishers that perform asynchronous database accesses.
GRDB provide publishers that perform asynchronous database accesses:
- [`readPublisher(receiveOn:value:)`]
- [`writePublisher(receiveOn:updates:)`]
- [`writePublisher(receiveOn:updates:thenRead:)`]
- [`migratePublisher(_:receiveOn:)`]
#### `DatabaseReader.readPublisher(receiveOn:value:)`
@@ -125,7 +140,7 @@ When you use a [database pool], reads are generally non-blocking, unless the max
This publisher can be subscribed from any thread. A new database access starts on every subscription.
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
The fetched value is published on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
@@ -176,7 +191,7 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](../README.md#advanced-databasepool) for more information.
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention.
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
@@ -190,6 +205,7 @@ It completes on the main queue, unless you provide a specific [scheduler] to the
Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter.
- [`ValueObservation.publisher(in:scheduling:)`]
- [`SharedValueObservation.publisher()`]
- [`DatabaseRegionObservation.publisher(in:)`]
@@ -210,11 +226,11 @@ This publisher has the same behavior as ValueObservation:
- It notifies an initial value before the eventual changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
- It stops emitting any value after the database connection is closed. But it never completes.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
- It only completes when it is cancelled.
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
@@ -232,38 +248,21 @@ This publisher has the same behavior as ValueObservation:
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
:warning: **ValueObservation and Data Consistency**
#### `SharedValueObservation.publisher()`
When you compose ValueObservation publishers together with the [combineLatest](https://developer.apple.com/documentation/combine/publisher/3333677-combinelatest) operator, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
Instead, compose requests together into **one single** ValueObservation, as below:
[SharedValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
```swift
struct HallOfFame {
var totalPlayerCount: Int
var bestPlayers: [Player]
}
let sharedObservation = ValueObservation
.tracking { db in try Player.fetchAll(db) }
.shared(in: dbQueue)
// DATA CONSISTENCY GUARANTEED
let hallOfFamePublisher = ValueObservation
.tracking { db -> HallOfFame in
let totalPlayerCount = try Player.fetchCount(db)
let bestPlayers = try Player
.order(Column("score").desc)
.limit(10)
.fetchAll(db)
return HallOfFame(
totalPlayerCount: totalPlayerCount,
bestPlayers: bestPlayers)
}
.publisher(in: dbQueue)
// A publisher with output [Player] and failure Error
let publisher = sharedObservation.publisher()
```
See [ValueObservation] for more information.
This publisher has the same behavior as SharedValueObservation.
#### `DatabaseRegionObservation.publisher(in:)`
@@ -306,23 +305,100 @@ try dbQueue.write { db in
See [DatabaseRegionObservation] for more information.
## Combine and Data Consistency
When you compose database publishers together with Combine operators such as `combineLatest` or `zip`, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together.
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent eventual concurrent database writes from messing with your app, and introduce bugs.
To this end, remember that *all database publishers can perform several requests*.
In the example below, we are totally sure that the published `HallOfFame` values will never contain inconsistent values, because it is produced by one and only one publisher:
```swift
struct HallOfFame {
// Invariant: bestPlayers.count <= totalPlayerCount
var totalPlayerCount: Int
var bestPlayers: [Player]
}
// CORRECT: DATA CONSISTENCY GUARANTEED
let hallOfFamePublisher = ValueObservation
.tracking { db -> HallOfFame in
// 1st request
let totalPlayerCount = try Player.fetchCount(db)
// 2nd request
let bestPlayers = try Player
.order(Column("score").desc)
.limit(10)
.fetchAll(db)
// 100% guaranteed
assert(bestPlayers.count <= totalPlayerCount)
// Merge results together
return HallOfFame(
totalPlayerCount: totalPlayerCount,
bestPlayers: bestPlayers)
}
.publisher(in: dbQueue)
```
Compare with the incorrect version that combines two database publishers together:
```swift
// OK
let totalPlayerCountPublisher = ValueObservation
.tracking(Player.fetchCount)
.publisher(in: dbQueue)
// OK
let bestPlayerPublisher = ValueObservation
.tracking(Player
.order(Column("score").desc)
.limit(10)
.fetchAll)
.publisher(in: dbQueue)
// NOT OK: DATA CONSISTENCY NOT GUARANTEED
let hallOfFamePublisher = totalPlayerCountPublisher
.combineLatest(bestPlayerPublisher)
.map(HallOfFame.init(totalPlayerCount:bestPlayers))
let cancellable = hallOfFamePublisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { hallOfFame in
// ASSERTION MAY FAIL if some players are deleted
// at the wrong time
assert(hallOfFame.bestPlayers.count <= hallOfFame.totalPlayerCount)
})
```
[Database Connections]: ../README.md#database-connections
[Usage]: #usage
[Asynchronous Database Access]: #asynchronous-database-access
[Combine]: https://developer.apple.com/documentation/combine
[Database Changes Observation]: ../README.md#database-changes-observation
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[Database Observation]: #database-observation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[Combine and Data Consistency]: #combine-and-data-consistency
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
[SQLite]: http://sqlite.org
[ValueObservation]: ../README.md#valueobservation
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
[configured]: ../README.md#databasepool-configuration
[database pool]: ../README.md#database-pools
[database queue]: ../README.md#database-queues
[database snapshot]: ../README.md#database-snapshots
[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
[database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
+51 -62
View File
@@ -16,7 +16,7 @@ In this guide, you will learn how to:
- [Fetch Values From Common Table Expressions]
- Join CTEs with [Associations to Common Table Expressions]
> :point_up: **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
> **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
## Define Common Table Expressions
@@ -29,7 +29,7 @@ The CTE request can be provided as a [query interface request]:
```swift
// WITH playerName AS (SELECT name FROM player) ...
let playerNameCTE = CommonTableExpression<Void>(
let playerNameCTE = CommonTableExpression(
named: "playerName",
request: Player.select(Column("name")))
```
@@ -40,27 +40,27 @@ You can feed a CTE with raw SQL as well (second and third examples use [SQL Inte
let name = "O'Brien"
// WITH playerName AS (SELECT 'O''Brien') ...
let playerNameCTE = CommonTableExpression<Void>(
let playerNameCTE = CommonTableExpression(
named: "playerName",
sql: "SELECT ?", arguments: [name])
// WITH playerName AS (SELECT 'O''Brien') ...
let playerNameCTE = CommonTableExpression<Void>(
let playerNameCTE = CommonTableExpression(
named: "playerName",
literal: "SELECT \(name)")
// WITH playerName AS (SELECT 'O''Brien') ...
let request: SQLRequest<String> = "SELECT \(name)"
let playerNameCTE = CommonTableExpression<Void>(
let request = SQLRequest("SELECT \(name)")
let playerNameCTE = CommonTableExpression(
named: "playerName",
request: requests)
request: request)
```
All CTEs can be provided with explicit column names:
```swift
// WITH pair(a, b) AS (SELECT 1, 2) ...
let pairCTE = CommonTableExpression<Void>(
let pairCTE = CommonTableExpression(
named: "pair",
columns: ["a", "b"],
sql: "SELECT 1, 2")
@@ -71,7 +71,7 @@ Recursive CTEs need the `recursive` flag. The example below selects all integers
```swift
// WITH RECURSIVE counter(x) AS
// (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000)
let counterCTE = CommonTableExpression<Int>(
let counterCTE = CommonTableExpression(
recursive: true,
named: "counter",
columns: ["x"],
@@ -82,9 +82,7 @@ let counterCTE = CommonTableExpression<Int>(
""")
```
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
As you can see in all above examples, `CommonTableExpression` is a generic type: `CommonTableExpression<Void>`, `CommonTableExpression<Int>`. The generic argument (`Void`, `Int`) turns useful when you [join common table expressions](#associations-to-common-table-expressions), or when you [fetch values directly from a common table expression](#fetch-values-from-common-table-expressions). Otherwise, you can just use `Void`.
> **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
## Embed Common Table Expressions in Requests
@@ -103,7 +101,7 @@ We first build a `CommonTableExpression`:
```swift
let name = "O'Brien"
let playerNameCTE = CommonTableExpression<Void>(
let playerNameCTE = CommonTableExpression(
named: "playerName",
literal: "SELECT \(name)")
```
@@ -128,13 +126,13 @@ let request = Player
.filter(Column("name") == playerNameCTE.all())
```
> :point_up: **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
>
> :point_up: **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
>
> :point_up: **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
>
> :point_up: **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
>
> ```swift
> cte.all().select(...).filter(...).group(...).order(...)
@@ -184,48 +182,37 @@ try Player
In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method.
`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. You can also fetch from it, but only as long as it is provided with the definition of the CTE.
`cte.all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests.
This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`.
You can also fetch from `cte.all()`, as long as the request is given the definition of the CTE: `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`:
The generic type of `CommonTableExpression<...>` now turns out useful, so that you can fetch the desired outcome (database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records)).
For example, let's fetch a range of integer:
This request, of type `QueryInterfaceRequest<Row>`, can fetch raw database [rows](../README.md#row-queries):
```swift
func counterRequest(range: ClosedRange<Int>) -> QueryInterfaceRequest<Int> {
// WITH RECURSIVE counter(x) AS
// (VALUES(...) UNION ALL SELECT x+1 FROM counter WHERE x<...)
// SELECT * FROM counter
let counter = CommonTableExpression<Int>(
recursive: true,
named: "counter",
columns: ["x"],
literal: """
VALUES(\(range.lowerBound)) \
UNION ALL \
SELECT x+1 FROM counter WHERE x < \(range.upperBound)
""")
return counter.all().with(counter)
}
let values = try dbQueue.read { db in
try counterRequest(range: 3...7).fetchAll(db)
}
print(values) // prints "[3, 4, 5, 6, 7]"
let cte = CommonTableExpression(...)
let request = cte.all().with(cte)
let rows = try request.fetchAll(db) // [Row]
```
When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method:
In order to fetch something else, such as simple [values](../README.md#value-queries), or custom [records](../README.md#records), you have two possible options:
```swift
let cte: CommonTableExpression<Void> = ...
let rows: [Row] = try dbQueue.read { db in
try cte.all().with(cte)
.asRequest(of: Row.self)
.fetchAll(db)
}
```
1. Use the `asRequest(of:)` method:
```swift
let cte = CommonTableExpression(...)
let request = cte.all().with(cte).asRequest(of: Player.self)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
let players = try request.fetchAll(db) // [Player]
```
2. Provide the fetched type to the cte itself:
```swift
let cte = CommonTableExpression<Player>(...)
// ~~~~~~~~
let request = cte.all().with(cte)
let players = try request.fetchAll(db) // [Player]
```
## Associations to Common Table Expressions
@@ -247,7 +234,7 @@ Parent.including(optional: childAssociation)
Parent.including(required: childAssociation)
```
> :point_up: **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
> **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
CTE associations are generally built with the `association(to:on:)` method, which needs:
@@ -337,7 +324,7 @@ We can now define the CTE for the latest messages:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
let latestMessageCTE = CommonTableExpression<Void>(
let latestMessageCTE = CommonTableExpression(
named: "latestMessage",
request: latestMessageRequest)
```
@@ -378,9 +365,9 @@ And we can fetch the data that feeds our application screen:
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, our go-to `CommonTableExpression<Void>` CTEs can work against type safety. So when you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your `CommonTableExpression` with a type instead of `Void`.
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
>
> You can use an existing record type, or an ad-hoc enum. For example:
> To do so, you can use an existing record type, or an ad-hoc enum. For example:
>
> ```swift
> enum CTE1 { }
@@ -389,9 +376,9 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
> enum CTE2 { }
> let cte2 = CommonTableExpression<CTE2>(...)
>
> let assoc1 = BaseRecord.association(to: cte1, on: ...)
> let assoc2 = cte1.association(to: cte2, on: ...)
> let assoc3 = cte2.association(to: FarRecord.self, on: ...)
> let assoc1 = BaseRecord.association(to: cte1, on: ...) // from BaseRecord to CTE1
> let assoc2 = cte1.association(to: cte2, on: ...) // from CTE1 to CTE2
> let assoc3 = cte2.association(to: FarRecord.self, on: ...) // from CTE2 to FarRecord
>
> // WITH ...
> // SELECT base.* FROM base
@@ -400,12 +387,14 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
> // JOIN far ON ...
> let request = BaseRecord
> .with(cte1).with(cte2)
> .joining(required: assoc1
> .joining(required: assoc2
> .joining(required: assoc3)))
> .joining(required: assoc1. // OK
> .joining(required: assoc2. // OK
> .joining(required: assoc3))) // OK
>
> // Compiler error
> let request = BaseRecord.joining(required: assoc2)
> let request = BaseRecord
> .joining(required: assoc2) // Not OK
> .joining(required: assoc3) // Not OK
> ```
[query interface request]: ../README.md#requests
+4
View File
@@ -0,0 +1,4 @@
:twisted_rightwards_arrows: Concurrency
=======================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+5 -5
View File
@@ -3,9 +3,9 @@ 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.33.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.39.3](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).
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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
@@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
@@ -111,9 +111,9 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
6. Add the `GRDBCustom` target in the **Target Dependencies** section of the **Build Phases** 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**.
7. Add the `GRDBCustom.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**:
@@ -0,0 +1,609 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
56519DCA274FC8E900ED16D8 /* GRDBQuery in Frameworks */ = {isa = PBXBuildFile; productRef = 56519DC9274FC8E900ED16D8 /* GRDBQuery */; };
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
567C3E1A2520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */; };
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; };
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; };
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
56F8A13527359A5A0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A13427359A5A0011ACBE /* GRDB */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
remoteInfo = GRDBAsyncDemo;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
567C3E502520B70E0011F6E9 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBAsyncDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoApp.swift; sourceTree = "<group>"; };
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = "<group>"; };
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
56F8A12E27359A350011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
56026C9525B8A7D000D1DF3F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E132520B6DE0011F6E9 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56519DCA274FC8E900ED16D8 /* GRDBQuery in Frameworks */,
56F8A13527359A5A0011ACBE /* GRDB in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */ = {
isa = PBXGroup;
children = (
56026C9C25B8A7D000D1DF3F /* Info.plist */,
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
56717251261B334D00423B6F /* PlayerRequestTests.swift */,
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
);
path = GRDBAsyncDemoTests;
sourceTree = "<group>";
};
56185BC125B8047D00B9C30F /* Resources */ = {
isa = PBXGroup;
children = (
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
);
path = Resources;
sourceTree = "<group>";
};
567C3E0D2520B6DE0011F6E9 = {
isa = PBXGroup;
children = (
567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */,
56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
567C3E172520B6DE0011F6E9 /* Products */,
567C3E4D2520B70E0011F6E9 /* Frameworks */,
56F8A12E27359A350011ACBE /* GRDB.swift */,
);
sourceTree = "<group>";
};
567C3E172520B6DE0011F6E9 /* Products */ = {
isa = PBXGroup;
children = (
567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */,
56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */ = {
isa = PBXGroup;
children = (
567C3E222520B6DF0011F6E9 /* Info.plist */,
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */,
567C3E542520B75C0011F6E9 /* Persistence.swift */,
567C3E532520B75C0011F6E9 /* Player.swift */,
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
56185BC125B8047D00B9C30F /* Resources */,
567C3E582520B75C0011F6E9 /* Views */,
);
path = GRDBAsyncDemo;
sourceTree = "<group>";
};
567C3E1F2520B6DF0011F6E9 /* Preview Content */ = {
isa = PBXGroup;
children = (
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */,
);
path = "Preview Content";
sourceTree = "<group>";
};
567C3E4D2520B70E0011F6E9 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
567C3E582520B75C0011F6E9 /* Views */ = {
isa = PBXGroup;
children = (
567C3E5A2520B75C0011F6E9 /* AppView.swift */,
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */,
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */,
56717239261B23C800423B6F /* PlayerList.swift */,
);
path = Views;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoTests" */;
buildPhases = (
56026C9425B8A7D000D1DF3F /* Sources */,
56026C9525B8A7D000D1DF3F /* Frameworks */,
56026C9625B8A7D000D1DF3F /* Resources */,
);
buildRules = (
);
dependencies = (
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */,
);
name = GRDBAsyncDemoTests;
productName = GRDBAsyncDemoTests;
productReference = 56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBAsyncDemo" */;
buildPhases = (
567C3E122520B6DE0011F6E9 /* Sources */,
567C3E132520B6DE0011F6E9 /* Frameworks */,
567C3E142520B6DE0011F6E9 /* Resources */,
567C3E502520B70E0011F6E9 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
56F8A13127359A540011ACBE /* PBXTargetDependency */,
);
name = GRDBAsyncDemo;
packageProductDependencies = (
56F8A13427359A5A0011ACBE /* GRDB */,
56519DC9274FC8E900ED16D8 /* GRDBQuery */,
);
productName = GRBCombineDemo;
productReference = 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 1250;
LastUpgradeCheck = 1200;
TargetAttributes = {
56026C9725B8A7D000D1DF3F = {
CreatedOnToolsVersion = 12.3;
TestTargetID = 567C3E152520B6DE0011F6E9;
};
567C3E152520B6DE0011F6E9 = {
CreatedOnToolsVersion = 12.0;
};
};
};
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */;
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 567C3E0D2520B6DE0011F6E9;
packageReferences = (
56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */,
);
productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */,
56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
56026C9625B8A7D000D1DF3F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E142520B6DE0011F6E9 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */,
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */,
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */,
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
56026C9425B8A7D000D1DF3F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
567C3E122520B6DE0011F6E9 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
5671723A261B23C800423B6F /* PlayerList.swift in Sources */,
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */,
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */,
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */,
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
567C3E1A2520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */;
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
};
56F8A13127359A540011ACBE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
productRef = 56F8A13027359A540011ACBE /* GRDB */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
567C3E752520BB650011F6E9 /* Localizable.stringsdict */ = {
isa = PBXVariantGroup;
children = (
567C3E762520BB650011F6E9 /* en */,
);
name = Localizable.stringsdict;
sourceTree = "<group>";
};
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
567C3E782520BB650011F6E9 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
56026C9F25B8A7D000D1DF3F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBAsyncDemo.app/GRDBAsyncDemo";
};
name = Debug;
};
56026CA025B8A7D000D1DF3F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBAsyncDemo.app/GRDBAsyncDemo";
};
name = Release;
};
567C3E232520B6DF0011F6E9 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
567C3E242520B6DF0011F6E9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
567C3E262520B6DF0011F6E9 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBAsyncDemo/Preview Content\"";
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
};
name = Debug;
};
567C3E272520B6DF0011F6E9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBAsyncDemo/Preview Content\"";
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
56026C9F25B8A7D000D1DF3F /* Debug */,
56026CA025B8A7D000D1DF3F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
567C3E232520B6DF0011F6E9 /* Debug */,
567C3E242520B6DF0011F6E9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBAsyncDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
567C3E262520B6DF0011F6E9 /* Debug */,
567C3E272520B6DF0011F6E9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/groue/GRDBQuery";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 0.6.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
56519DC9274FC8E900ED16D8 /* GRDBQuery */ = {
isa = XCSwiftPackageProductDependency;
package = 56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */;
productName = GRDBQuery;
};
56F8A13027359A540011ACBE /* GRDB */ = {
isa = XCSwiftPackageProductDependency;
productName = GRDB;
};
56F8A13427359A5A0011ACBE /* GRDB */ = {
isa = XCSwiftPackageProductDependency;
productName = GRDB;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "grdbquery",
"kind" : "remoteSourceControl",
"location" : "https://github.com/groue/GRDBQuery",
"state" : {
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
"version" : "0.6.0"
}
}
],
"version" : 2
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,10 +14,10 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
BuildableName = "GRDBAsyncDemo.app"
BlueprintName = "GRDBAsyncDemo"
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -26,17 +26,17 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
BuildableName = "GRDBtvOSTests.xctest"
BlueprintName = "GRDBtvOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
BuildableName = "GRDBAsyncDemoTests.xctest"
BlueprintName = "GRDBAsyncDemoTests"
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -51,15 +51,23 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
BuildableName = "GRDBAsyncDemo.app"
BlueprintName = "GRDBAsyncDemo"
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</MacroExpansion>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -67,15 +75,16 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
BuildableName = "GRDB.framework"
BlueprintName = "GRDBtvOS"
ReferencedContainer = "container:GRDB.xcodeproj">
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
BuildableName = "GRDBAsyncDemo.app"
BlueprintName = "GRDBAsyncDemo"
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</MacroExpansion>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
@@ -0,0 +1,235 @@
import Foundation
import GRDB
import os.log
/// A database of players.
///
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
/// Provides access to the database.
///
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
/// can use a fast in-memory `DatabaseQueue`.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
}
// Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please provide a name"
}
}
}
/// Saves (inserts or updates) a player. When the method returns, the
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) async throws {
if player.name.isEmpty {
throw ValidationError.missingName
}
player = try await dbWriter.write { [player] db in
try player.saved(db)
}
}
/// Delete the specified players
func deletePlayers(ids: [Int64]) async throws {
try await dbWriter.write { db in
_ = try Player.deleteAll(db, ids: ids)
}
}
/// Delete all players
func deleteAllPlayers() async throws {
try await dbWriter.write { db in
_ = try Player.deleteAll(db)
}
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() async throws {
try await dbWriter.write { db in
if try Player.all().isEmpty(db) {
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
try player.updateChanges(db) {
$0.score = Player.randomScore()
}
}
}
}
}
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbWriter.write { db in
if try Player.all().isEmpty(db) {
try createRandomPlayers(db)
}
}
}
private static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
Player(id: nil, name: "David", score: 4),
Player(id: nil, name: "Elena", score: 1),
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
_ = try player.inserted(db) // insert but ignore inserted id
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
}
}
// MARK: - Database Access: Reads
// This demo app does not provide any specific reading method, and instead
// gives an unrestricted read-only access to the rest of the application.
// In your app, you are free to choose another path, and define focused
// reading methods.
extension AppDatabase {
/// Provides a read-only access to the database
var reader: DatabaseReader {
dbWriter
}
}
@@ -0,0 +1,40 @@
import GRDBQuery
import SwiftUI
@main
struct GRDBAsyncDemoApp: App {
var body: some Scene {
WindowGroup {
AppView().environment(\.appDatabase, .shared)
}
}
}
// MARK: - Give SwiftUI access to the database
//
// Define a new environment key that grants access to an AppDatabase.
//
// The technique is documented at
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
private struct AppDatabaseKey: EnvironmentKey {
static var defaultValue: AppDatabase { .empty() }
}
extension EnvironmentValues {
var appDatabase: AppDatabase {
get { self[AppDatabaseKey.self] }
set { self[AppDatabaseKey.self] = newValue }
}
}
// In this demo app, views observe the database with the @Query property
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
// define a dedicated initializer for `appDatabase` access, so we comply:
extension Query where Request.DatabaseContext == AppDatabase {
/// Convenience initializer for requests that feed from `AppDatabase`.
init(_ request: Request) {
self.init(request, in: \.appDatabase)
}
}
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<true/>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchScreen</key>
<dict/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -0,0 +1,77 @@
import Foundation
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Prepare the database with test fixtures if requested
if CommandLine.arguments.contains("-fixedTestData") {
try appDatabase.createPlayersForUITests()
} else {
// Otherwise, populate the database if it is empty, for better
// demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
}
return appDatabase
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
//
// Typical reasons for an error here include:
// * The parent directory cannot be created, or disallows writing.
// * The database is not accessible, due to permissions or data protection when the device is locked.
// * The device is out of space.
// * The database could not be migrated to its latest schema version.
// Check the error message to determine what the actual problem was.
fatalError("Unresolved error \(error)")
}
}
/// Creates an empty database for SwiftUI previews
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
/// Creates a database full of random players for SwiftUI previews
static func random() -> AppDatabase {
let appDatabase = empty()
try! appDatabase.createRandomPlayersIfEmpty()
return appDatabase
}
}
@@ -0,0 +1,105 @@
import GRDB
/// The Player struct.
///
/// Identifiable conformance supports SwiftUI list animations, and type-safe
/// GRDB primary key methods.
/// Equatable conformance supports tests.
struct Player: Identifiable, Equatable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
/// Use nil for players that are not inserted yet in the database.
var id: Int64?
var name: String
var score: Int
}
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
/// Creates a new player with empty name and zero score
static func new() -> Player {
Player(id: nil, name: "", score: 0)
}
/// Creates a new player with random name and random score
static func makeRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
/// Returns a random name
static func randomName() -> String {
names.randomElement()!
}
/// Returns a random score
static func randomScore() -> Int {
10 * Int.random(in: 0...100)
}
}
// MARK: - Persistence
/// Make Player a Codable Record.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
// MARK: - Player Database Requests
/// Define some player requests used by the application.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
// Sort by name in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -0,0 +1,55 @@
import Combine
import GRDB
import GRDBQuery
/// A player request can be used with the `@Query` property wrapper in order to
/// feed a view with a list of players.
///
/// For example:
///
/// struct MyView: View {
/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player]
///
/// var body: some View {
/// List(players) { player in ... )
/// }
/// }
struct PlayerRequest: Queryable {
enum Ordering {
case byScore
case byName
}
/// The ordering used by the player request.
var ordering: Ordering
// MARK: - Queryable Implementation
static var defaultValue: [Player] { [] }
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
// Build the publisher from the general-purpose read-only access
// granted by `appDatabase.reader`.
// Some apps will prefer to call a dedicated method of `appDatabase`.
ValueObservation
.tracking(fetchValue(_:))
.publisher(
in: appDatabase.reader,
// The `.immediate` scheduling feeds the view right on
// subscription, and avoids an undesired animation when the
// application starts.
scheduling: .immediate)
.eraseToAnyPublisher()
}
// This method is not required by Queryable, but it makes it easier
// to test PlayerRequest.
func fetchValue(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore:
return try Player.all().orderedByScore().fetchAll(db)
case .byName:
return try Player.all().orderedByName().fetchAll(db)
}
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,116 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "icon_20pt@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "icon_20pt@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"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_60pt@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"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"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt@2x.png",
"scale" : "2x"
},
{
"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" : {
"version" : 1,
"author" : "xcode"
}
}
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: 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: 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.5 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,12 @@
{
"images" : [
{
"filename" : "LaunchIcon.pdf",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchIcon" translatesAutoresizingMaskIntoConstraints="NO" id="Sgi-te-PKu">
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
</imageView>
</subviews>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerY" secondItem="6Tk-OE-BBY" secondAttribute="centerY" id="KT7-xd-gV4"/>
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerX" secondItem="6Tk-OE-BBY" secondAttribute="centerX" id="feL-Vs-SeN"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchIcon" width="167" height="237"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>%lld Players</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@VARIABLE@</string>
<key>VARIABLE</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>zero</key>
<string>No Player</string>
<key>one</key>
<string>1 Player</string>
<key>other</key>
<string>%lld Players</string>
</dict>
</dict>
<key>%lld points</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@VARIABLE@</string>
<key>VARIABLE</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>zero</key>
<string>0 point</string>
<key>one</key>
<string>1 point</string>
<key>other</key>
<string>%lld points</string>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,154 @@
import GRDBQuery
import SwiftUI
/// The main application view
struct AppView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
/// The `players` property is automatically updated when the database changes
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
/// We'll need to leave edit mode in several occasions.
@State private var editMode = EditMode.inactive
/// Tracks the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
// If you want to define the query on initialization, you will prefer:
//
// @Query<PlayerRequest> private var players: [Player]
//
// init(initialOrdering: PlayerRequest.Ordering) {
// _players = Query(PlayerRequest(ordering: initialOrdering))
// }
var body: some View {
NavigationView {
PlayerList(players: players)
.navigationBarTitle(Text("\(players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: ToggleOrderingButton(
ordering: $players.ordering,
willChange: {
// onChange(of: $players.wrappedValue.ordering)
// is not able to leave the editing mode during
// the animation of the list content.
// Workaround: stop editing before the ordering
// is changed, and the list content is updated.
stopEditing()
}))
.toolbar { toolbarContent }
.onChange(of: players) { players in
if players.isEmpty {
stopEditing()
}
}
.environment(\.editMode, $editMode)
}
}
private var toolbarContent: some ToolbarContent {
ToolbarItemGroup(placement: .bottomBar) {
Button {
// Don't stopEditing() here because this is
// performed `onChange(of: players)`
Task {
try? await appDatabase.deleteAllPlayers()
}
} label: {
Image(systemName: "trash").imageScale(.large)
}
Spacer()
Button {
stopEditing()
Task {
try? await appDatabase.refreshPlayers()
}
} label: {
Image(systemName: "arrow.clockwise").imageScale(.large)
}
Spacer()
Button {
stopEditing()
// Perform 50 refreshes in parallel
Task {
try? await withThrowingTaskGroup(of: Void.self) { group in
for _ in 0..<50 {
_ = group.addTaskUnlessCancelled {
try await appDatabase.refreshPlayers()
}
}
try await group.waitForAll()
}
}
} label: {
Image(systemName: "tornado").imageScale(.large)
}
}
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button {
stopEditing()
newPlayerIsPresented = true
} label: {
Image(systemName: "plus")
}
.accessibility(label: Text("New Player"))
.sheet(isPresented: $newPlayerIsPresented) {
PlayerCreationView()
}
}
private func stopEditing() {
withAnimation {
editMode = .inactive
}
}
}
private struct ToggleOrderingButton: View {
@Binding var ordering: PlayerRequest.Ordering
let willChange: () -> Void
var body: some View {
switch ordering {
case .byName:
Button {
willChange()
ordering = .byScore
} label: {
Label("Name", systemImage: "arrowtriangle.up.fill").labelStyle(.titleAndIcon)
}
case .byScore:
Button {
willChange()
ordering = .byName
} label: {
Label("Score", systemImage: "arrowtriangle.down.fill").labelStyle(.titleAndIcon)
}
}
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview the default, empty database
AppView()
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
}
}
}
@@ -0,0 +1,50 @@
import SwiftUI
/// The view that creates a new player.
struct PlayerCreationView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.dismiss) private var dismiss
@State private var form = PlayerForm(name: "", score: "")
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerFormView(form: $form)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(role: .cancel) {
dismiss()
} label: {
Text("Cancel")
},
trailing: Button {
Task { await save() }
} label: {
Text("Save")
})
}
}
private func save() async {
do {
var player = Player(id: nil, name: "", score: 0)
form.apply(to: &player)
try await appDatabase.savePlayer(&player)
dismiss()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
}
@@ -0,0 +1,40 @@
import SwiftUI
/// The view that edits an existing player.
struct PlayerEditionView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.isPresented) private var isPresented
private let player: Player
@State private var form: PlayerForm
init(player: Player) {
self.player = player
self.form = PlayerForm(player)
}
var body: some View {
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
// Save when back button is pressed
if !isPresented {
Task {
var savedPlayer = player
form.apply(to: &savedPlayer)
// Ignore error because I don't know how to cancel the
// back button and present the error
try? await appDatabase.savePlayer(&savedPlayer)
}
}
}
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
}
@@ -0,0 +1,47 @@
import SwiftUI
/// The Player editing form, embedded in both
/// `PlayerCreationView` and `PlayerEditionView`.
struct PlayerFormView: View {
@Binding var form: PlayerForm
var body: some View {
List {
TextField("Name", text: $form.name)
.accessibility(label: Text("Player Name"))
TextField("Score", text: $form.score).keyboardType(.numberPad)
.accessibility(label: Text("Player Score"))
}
.listStyle(InsetGroupedListStyle())
}
}
struct PlayerForm {
var name: String
var score: String
}
extension PlayerForm {
init(_ player: Player) {
self.name = player.name
self.score = "\(player.score)"
}
func apply(to player: inout Player) {
player.name = name
player.score = Int(score) ?? 0
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
}
}
@@ -0,0 +1,59 @@
import SwiftUI
struct PlayerList: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
/// The players in the list
var players: [Player]
var body: some View {
List {
ForEach(players) { player in
NavigationLink(destination: editionView(for: player)) {
PlayerRow(player: player)
// Don't animate player update
.animation(nil, value: player)
}
}
.onDelete { offsets in
let playerIds = offsets.compactMap { players[$0].id }
Task {
try? await appDatabase.deletePlayers(ids: playerIds)
}
}
}
// Animate list updates
.animation(.default, value: players)
.listStyle(.plain)
}
/// The view that edits a player in the list.
private func editionView(for player: Player) -> some View {
PlayerEditionView(player: player).navigationBarTitle(player.name)
}
}
private struct PlayerRow: View {
var player: Player
var body: some View {
HStack {
Text(player.name)
Spacer()
Text("\(player.score) points").foregroundColor(.gray)
}
}
}
struct PlayerList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
}
}
@@ -0,0 +1,144 @@
import XCTest
import GRDB
@testable import GRDBAsyncDemo
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
// Then the player table exists, with id, name & score columns
try dbQueue.read { db in
try XCTAssert(db.tableExists("player"))
let columns = try db.columns(in: "player")
let columnNames = Set(columns.map { $0.name })
XCTAssertEqual(columnNames, ["id", "name", "score"])
}
}
func test_savePlayer_inserts() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
var player = Player(id: nil, name: "Arthur", score: 100)
try await appDatabase.savePlayer(&player)
// Then the player exists in the database
let playerExists = try await dbQueue.read { [player] in try player.exists($0) }
XCTAssertTrue(playerExists)
}
func test_savePlayer_updates() async throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = try await dbQueue.write { db in
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
}
// When we modify and save the player
player.name = "Barbara"
player.score = 1000
try await appDatabase.savePlayer(&player)
// Then the player has been updated in the database
let fetchedPlayer = try await dbQueue.read { [player] db in
try XCTUnwrap(Player.fetchOne(db, key: player.id))
}
XCTAssertEqual(fetchedPlayer, player)
}
func test_deletePlayers() async throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
let playerIds: [Int64] = try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
_ = try Player(id: nil, name: "Barbara", score: 200).inserted(db)
_ = try Player(id: nil, name: "Craig", score: 150).inserted(db)
_ = try Player(id: nil, name: "David", score: 120).inserted(db)
return try Player.selectPrimaryKey().fetchAll(db)
}
// When we delete two players
let deletedId1 = playerIds[0]
let deletedId2 = playerIds[2]
try await appDatabase.deletePlayers(ids: [deletedId1, deletedId2])
// Then the deleted players no longer exist
try await dbQueue.read { db in
try XCTAssertFalse(Player.exists(db, id: deletedId1))
try XCTAssertFalse(Player.exists(db, id: deletedId2))
}
// Then the database still contains two players
let count = try await dbQueue.read { try Player.fetchCount($0) }
XCTAssertEqual(count, 2)
}
func test_deleteAllPlayers() async throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
_ = try Player(id: nil, name: "Barbara", score: 200).inserted(db)
_ = try Player(id: nil, name: "Craig", score: 150).inserted(db)
_ = try Player(id: nil, name: "David", score: 120).inserted(db)
}
// When we delete all players
try await appDatabase.deleteAllPlayers()
// Then the database does not contain any player
let count = try await dbQueue.read { try Player.fetchCount($0) }
XCTAssertEqual(count, 0)
}
func test_refreshPlayers_populates_an_empty_database() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
try await appDatabase.refreshPlayers()
// Then the database is not empty
let count = try await dbQueue.read { try Player.fetchCount($0) }
XCTAssert(count > 0)
}
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
try appDatabase.createRandomPlayersIfEmpty()
// Then the database is not empty
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
}
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we create random players
try appDatabase.createRandomPlayersIfEmpty()
// Then the database still only contains the original player
let players = try dbQueue.read(Player.fetchAll)
XCTAssertEqual(players, [player])
}
}
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -0,0 +1,43 @@
import XCTest
import GRDB
@testable import GRDBAsyncDemo
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
}
@@ -0,0 +1,108 @@
import XCTest
import GRDB
@testable import GRDBAsyncDemo
class PlayerTests: XCTestCase {
// MARK: - CRUD
// Test that our Player type properly talks to GRDB.
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// Then the player gets a non-nil id
XCTAssertNotNil(player.id)
}
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
var insertedPlayer = Player(id: nil, name: "Arthur", score: 100)
let fetchedPlayer: Player? = try dbQueue.write { db in
try insertedPlayer.insert(db)
return try Player.fetchOne(db, key: insertedPlayer.id)
}
// Then the fetched player is equal to the inserted player
XCTAssertEqual(insertedPlayer, fetchedPlayer)
}
// MARK: - Requests
// Test that requests defined on the Player type behave as expected.
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 150)
var player4 = Player(id: 4, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by score
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
// Then fetched players are ordered by score descending
XCTAssertEqual(players, [player2, player3, player4, player1])
}
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 200)
var player4 = Player(id: 4, name: "David", score: 200)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by score
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
// Then fetched players are ordered by score descending and by name
XCTAssertEqual(players, [player2, player3, player4, player1])
}
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
var player3 = Player(id: 3, name: "Craig", score: 150)
var player4 = Player(id: 4, name: "David", score: 120)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
try player3.insert(db)
try player4.insert(db)
}
// When we fetch players ordered by name
let players = try dbQueue.read(Player.all().orderedByName().fetchAll)
// Then fetched players are ordered by name
XCTAssertEqual(players, [player1, player2, player3, player4])
}
}
@@ -0,0 +1,51 @@
Async/Await + SwiftUI Demo Application
======================================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
**This demo application is an Async/Await + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md), and for Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
**Requirements**: iOS 15.0+ / Xcode 13.1+
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
The topics covered in this demo are:
- 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 SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
- [GRDBAsyncDemoApp.swift](GRDBAsyncDemo/GRDBAsyncDemoApp.swift)
`GRDBAsyncDemoApp` feeds the app views with a database, through the SwiftUI environment.
- [AppDatabase.swift](GRDBAsyncDemo/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema.
- [Persistence.swift](GRDBAsyncDemo/Persistence.swift)
This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews.
- [Player.swift](GRDBAsyncDemo/Player.swift)
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
- [PlayerRequest.swift](GRDBAsyncDemo/PlayerRequest.swift), [AppView.swift](GRDBAsyncDemo/Views/AppView.swift)
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
`PlayerRequest` feeds the `@Query` property wrapper (`@Query`, defined in [GRDBQuery](https://github.com/groue/GRDBQuery), allows SwiftUI views to display up-to-date database content).
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
- [GRDBAsyncDemoTests](GRDBAsyncDemoTests)
- Test the database schema
- Test the `Player` record and its requests
- Test the `PlayerRequest` methods that feed the list of players.
- Test the `AppDatabase` methods that let the app access the database.
Binary file not shown.

After

Width:  |  Height:  |  Size: 799 KiB

@@ -3,28 +3,29 @@
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
56519DC7274FC85600ED16D8 /* GRDBQuery in Frameworks */ = {isa = PBXBuildFile; productRef = 56519DC6274FC85600ED16D8 /* GRDBQuery */; };
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; };
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; };
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */; };
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */; };
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerForm.swift */; };
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* PlayerList.swift */; };
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */; };
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; };
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; };
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
56F8A1202735989D0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A11F2735989D0011ACBE /* GRDB */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -35,69 +36,6 @@
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
remoteInfo = GRDBCombineDemo;
};
567C3E342520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
567C3E362520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
567C3E382520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
567C3E402520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
remoteInfo = GRDBtvOS;
};
567C3E422520B7000011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
remoteInfo = GRDBtvOSTests;
};
567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -107,7 +45,6 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -119,23 +56,24 @@
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = "<group>"; };
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
567C3E592520B75C0011F6E9 /* PlayerForm.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = "<group>"; };
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
56F8A11C2735988F0011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -150,7 +88,8 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
567C3E4E2520B70E0011F6E9 /* GRDB.framework in Frameworks */,
56519DC7274FC85600ED16D8 /* GRDBQuery in Frameworks */,
56F8A1202735989D0011ACBE /* GRDB in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -162,6 +101,7 @@
children = (
56026C9C25B8A7D000D1DF3F /* Info.plist */,
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
56717251261B334D00423B6F /* PlayerRequestTests.swift */,
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
);
path = GRDBCombineDemoTests;
@@ -177,22 +117,14 @@
path = Resources;
sourceTree = "<group>";
};
56185BC225B8048B00B9C30F /* Support */ = {
isa = PBXGroup;
children = (
567C3E222520B6DF0011F6E9 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
567C3E0D2520B6DE0011F6E9 = {
isa = PBXGroup;
children = (
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
567C3E172520B6DE0011F6E9 /* Products */,
567C3E4D2520B70E0011F6E9 /* Frameworks */,
56F8A11C2735988F0011ACBE /* GRDB.swift */,
);
sourceTree = "<group>";
};
@@ -208,14 +140,14 @@
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = {
isa = PBXGroup;
children = (
567C3E222520B6DF0011F6E9 /* Info.plist */,
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
567C3E542520B75C0011F6E9 /* Persistence.swift */,
567C3E532520B75C0011F6E9 /* Player.swift */,
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
56185BC125B8047D00B9C30F /* Resources */,
56185BC225B8048B00B9C30F /* Support */,
567C3E552520B75C0011F6E9 /* ViewModels */,
567C3E582520B75C0011F6E9 /* Views */,
);
path = GRDBCombineDemo;
@@ -229,21 +161,6 @@
path = "Preview Content";
sourceTree = "<group>";
};
567C3E2A2520B7000011F6E9 /* Products */ = {
isa = PBXGroup;
children = (
567C3E352520B7000011F6E9 /* GRDB.framework */,
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */,
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */,
567C3E3B2520B7000011F6E9 /* GRDB.framework */,
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */,
567C3E3F2520B7000011F6E9 /* GRDB.framework */,
567C3E412520B7000011F6E9 /* GRDB.framework */,
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
567C3E4D2520B70E0011F6E9 /* Frameworks */ = {
isa = PBXGroup;
children = (
@@ -251,22 +168,14 @@
name = Frameworks;
sourceTree = "<group>";
};
567C3E552520B75C0011F6E9 /* ViewModels */ = {
isa = PBXGroup;
children = (
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */,
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */,
);
path = ViewModels;
sourceTree = "<group>";
};
567C3E582520B75C0011F6E9 /* Views */ = {
isa = PBXGroup;
children = (
567C3E592520B75C0011F6E9 /* PlayerForm.swift */,
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */,
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */,
567C3E5A2520B75C0011F6E9 /* AppView.swift */,
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */,
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */,
56717239261B23C800423B6F /* PlayerList.swift */,
);
path = Views;
sourceTree = "<group>";
@@ -304,9 +213,13 @@
buildRules = (
);
dependencies = (
567C3E522520B71C0011F6E9 /* PBXTargetDependency */,
56F8A11E273598960011ACBE /* PBXTargetDependency */,
);
name = GRDBCombineDemo;
packageProductDependencies = (
56F8A11F2735989D0011ACBE /* GRDB */,
56519DC6274FC85600ED16D8 /* GRDBQuery */,
);
productName = GRBCombineDemo;
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
productType = "com.apple.product-type.application";
@@ -317,7 +230,8 @@
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1230;
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 1250;
LastUpgradeCheck = 1200;
TargetAttributes = {
56026C9725B8A7D000D1DF3F = {
@@ -330,7 +244,7 @@
};
};
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
compatibilityVersion = "Xcode 9.3";
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
@@ -338,14 +252,11 @@
Base,
);
mainGroup = 567C3E0D2520B6DE0011F6E9;
packageReferences = (
56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */,
);
productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 567C3E2A2520B7000011F6E9 /* Products */;
ProjectRef = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
},
);
projectRoot = "";
targets = (
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
@@ -354,65 +265,6 @@
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
567C3E352520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E342520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E372520B7000011F6E9 /* GRDBOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
remoteRef = 567C3E362520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E392520B7000011F6E9 /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 567C3E382520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E3B2520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E3A2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E3D2520B7000011F6E9 /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 567C3E3C2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E3F2520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E3E2520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E412520B7000011F6E9 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 567C3E402520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567C3E432520B7000011F6E9 /* GRDBtvOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBtvOSTests.xctest;
remoteRef = 567C3E422520B7000011F6E9 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
56026C9625B8A7D000D1DF3F /* Resources */ = {
isa = PBXResourcesBuildPhase;
@@ -441,6 +293,7 @@
files = (
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -450,14 +303,14 @@
files = (
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */,
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */,
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
5671723A261B23C800423B6F /* PlayerList.swift in Sources */,
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */,
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */,
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */,
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */,
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */,
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */,
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -469,10 +322,9 @@
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
};
567C3E522520B71C0011F6E9 /* PBXTargetDependency */ = {
56F8A11E273598960011ACBE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
productRef = 56F8A11D273598960011ACBE /* GRDB */;
};
/* End PBXTargetDependency section */
@@ -502,7 +354,6 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -522,7 +373,6 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -587,7 +437,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -642,7 +492,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
@@ -659,10 +509,9 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -681,10 +530,9 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -727,6 +575,33 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/groue/GRDBQuery";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 0.6.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
56519DC6274FC85600ED16D8 /* GRDBQuery */ = {
isa = XCSwiftPackageProductDependency;
package = 56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */;
productName = GRDBQuery;
};
56F8A11D273598960011ACBE /* GRDB */ = {
isa = XCSwiftPackageProductDependency;
productName = GRDB;
};
56F8A11F2735989D0011ACBE /* GRDB */ = {
isa = XCSwiftPackageProductDependency;
productName = GRDB;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
}
@@ -2,6 +2,6 @@
<Workspace
version = "1.0">
<FileRef
location = "self:/Users/groue/Documents/git/groue/GRDB.swift/Documentation/DemoApps/GRBCombineDemo/GRDBCombineDemo.xcodeproj">
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "grdbquery",
"kind" : "remoteSourceControl",
"location" : "https://github.com/groue/GRDBQuery",
"state" : {
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
"version" : "0.6.0"
}
}
],
"version" : 2
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -29,7 +29,8 @@
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
@@ -60,6 +61,13 @@
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,13 +1,30 @@
import Combine
import Foundation
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// A database of players.
///
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
@@ -17,30 +34,76 @@ struct AppDatabase {
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
/// can use a fast in-memory `DatabaseQueue`.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
private let dbWriter: DatabaseWriter
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
.collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
@@ -55,11 +118,28 @@ struct AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please provide a name"
}
}
}
/// Saves (inserts or updates) a player. When the method returns, the
/// player id is not nil.
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
if player.name.isEmpty {
throw ValidationError.missingName
}
try dbWriter.write { db in
try player.save(db)
}
@@ -68,7 +148,7 @@ extension AppDatabase {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
_ = try Player.deleteAll(db, ids: ids)
}
}
@@ -82,14 +162,13 @@ extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
if try Player.all().isEmpty(db) {
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
var player = Player.newRandom()
try player.insert(db)
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
// Delete a random player
@@ -110,37 +189,47 @@ extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
if try Player.all().isEmpty(db) {
try createRandomPlayers(db)
}
}
}
private static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
Player(id: nil, name: "David", score: 4),
Player(id: nil, name: "Elena", score: 1),
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
_ = try player.inserted(db) // insert but ignore inserted id
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.insert(db)
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
}
}
// MARK: - Database Access: Reads
// This demo app does not provide any specific reading method, and instead
// gives an unrestricted read-only access to the rest of the application.
// In your app, you are free to choose another path, and define focused
// reading methods.
extension AppDatabase {
/// Returns a publisher that tracks changes in players ordered by name
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
/// Returns a publisher that tracks changes in players ordered by score
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
/// Provides a read-only access to the database
var reader: DatabaseReader {
dbWriter
}
}
@@ -1,12 +1,40 @@
import GRDBQuery
import SwiftUI
@main
struct GRDBCombineDemoApp: App {
let appDatabase = AppDatabase.shared
var body: some Scene {
WindowGroup {
PlayerList(viewModel: PlayerListViewModel(database: appDatabase))
AppView().environment(\.appDatabase, .shared)
}
}
}
// MARK: - Give SwiftUI access to the database
//
// Define a new environment key that grants access to an AppDatabase.
//
// The technique is documented at
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
private struct AppDatabaseKey: EnvironmentKey {
static var defaultValue: AppDatabase { .empty() }
}
extension EnvironmentValues {
var appDatabase: AppDatabase {
get { self[AppDatabaseKey.self] }
set { self[AppDatabaseKey.self] = newValue }
}
}
// In this demo app, views observe the database with the @Query property
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
// define a dedicated initializer for `appDatabase` access, so we comply:
extension Query where Request.DatabaseContext == AppDatabase {
/// Convenience initializer for requests that feed from `AppDatabase`.
init(_ request: Request) {
self.init(request, in: \.appDatabase)
}
}
@@ -1,3 +1,4 @@
import Foundation
import GRDB
extension AppDatabase {
@@ -6,16 +7,43 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Connect to a database on disk
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let url: URL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: url.path)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
// Prepare the database with test fixtures if requested
if CommandLine.arguments.contains("-fixedTestData") {
try appDatabase.createPlayersForUITests()
} else {
// Otherwise, populate the database if it is empty, for better
// demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
}
return appDatabase
} catch {
@@ -35,8 +63,8 @@ extension AppDatabase {
/// Creates an empty database for SwiftUI previews
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = DatabaseQueue()
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -2,7 +2,8 @@ import GRDB
/// The Player struct.
///
/// Identifiable conformance supports SwiftUI list animations.
/// Identifiable conformance supports SwiftUI list animations, and type-safe
/// GRDB primary key methods.
/// Equatable conformance supports tests.
struct Player: Identifiable, Equatable {
/// The player id.
@@ -31,7 +32,7 @@ extension Player {
}
/// Creates a new player with random name and random score
static func newRandom() -> Player {
static func makeRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
@@ -50,7 +51,7 @@ extension Player {
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
@@ -59,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -68,28 +69,37 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
// Sort by name in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score
/// A request of players ordered by score.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -0,0 +1,55 @@
import Combine
import GRDB
import GRDBQuery
/// A player request can be used with the `@Query` property wrapper in order to
/// feed a view with a list of players.
///
/// For example:
///
/// struct MyView: View {
/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player]
///
/// var body: some View {
/// List(players) { player in ... )
/// }
/// }
struct PlayerRequest: Queryable {
enum Ordering {
case byScore
case byName
}
/// The ordering used by the player request.
var ordering: Ordering
// MARK: - Queryable Implementation
static var defaultValue: [Player] { [] }
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
// Build the publisher from the general-purpose read-only access
// granted by `appDatabase.reader`.
// Some apps will prefer to call a dedicated method of `appDatabase`.
ValueObservation
.tracking(fetchValue(_:))
.publisher(
in: appDatabase.reader,
// The `.immediate` scheduling feeds the view right on
// subscription, and avoids an undesired animation when the
// application starts.
scheduling: .immediate)
.eraseToAnyPublisher()
}
// This method is not required by Queryable, but it makes it easier
// to test PlayerRequest.
func fetchValue(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore:
return try Player.all().orderedByScore().fetchAll(db)
case .byName:
return try Player.all().orderedByName().fetchAll(db)
}
}
}
@@ -1,67 +0,0 @@
import Combine
import Foundation
/// The view model that validates and saves an edited player into the database.
///
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditionView`.
final class PlayerFormViewModel: ObservableObject {
/// A validation error that prevents the player from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please give a name to this player."
}
}
}
@Published var name: String = ""
@Published var score: String = ""
private let database: AppDatabase
private var player: Player
init(database: AppDatabase, player: Player) {
self.database = database
self.player = player
updateViewFromPlayer()
}
// MARK: - Manage the Player Form
/// Validates and saves the player into the database.
func savePlayer() throws {
if name.isEmpty {
throw ValidationError.missingName
}
player.name = name
player.score = Int(score) ?? 0
try database.savePlayer(&player)
}
/// Resets form values to the original player values.
func reset() {
updateViewFromPlayer()
}
/// Edits a new player
func editNewPlayer() {
player = .new()
updateViewFromPlayer()
}
// MARK: - Private
private func updateViewFromPlayer() {
self.name = player.name
if player.score == 0 && player.id == nil {
// Avoid displaying "0" for a new player: it does not look good.
self.score = ""
} else {
self.score = "\(player.score)"
}
}
}
@@ -1,118 +0,0 @@
import Combine
import Foundation
/// The view model that feeds `PlayerList`, and performs list modifications
/// in the database.
final class PlayerListViewModel: ObservableObject {
enum Ordering {
case byScore
case byName
}
struct PlayerList {
var players: [Player]
var animatedChanges: Bool
}
/// The list ordering
@Published var ordering: Ordering = .byScore
/// The players in the list
@Published var playerList = PlayerList(players: [], animatedChanges: false)
/// The view model that edits a new player
let newPlayerViewModel: PlayerFormViewModel
private let database: AppDatabase
private var playersCancellable: AnyCancellable?
init(database: AppDatabase) {
self.database = database
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
playersCancellable = playersPublisher(in: database)
.scan(nil) { (previousList: PlayerList?, players: [Player]) in
if previousList == nil {
// Do not animate first view update
return PlayerList(players: players, animatedChanges: false)
} else {
return PlayerList(players: players, animatedChanges: true)
}
}
.compactMap { $0 }
.sink { [weak self] playerList in
self?.playerList = playerList
}
}
// MARK: - Players List Management
/// Deletes all players
func deleteAllPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.deleteAllPlayers()
}
func deletePlayers(atOffsets offsets: IndexSet) {
// Eventual error presentation is left as an exercise for the reader.
let playerIDs = offsets.compactMap { playerList.players[$0].id }
try! database.deletePlayers(ids: playerIDs)
}
/// Refreshes the list of players
func refreshPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.refreshPlayers()
}
/// Spawns many concurrent database updates, for demo purpose
func stressTest() {
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
// MARK: - Change Player Ordering
/// Toggles between the available orderings
func toggleOrdering() {
switch ordering {
case .byName:
ordering = .byScore
case .byScore:
ordering = .byName
}
}
// MARK: - Player Edition
/// Returns a view model suitable for editing a player.
func formViewModel(for player: Player) -> PlayerFormViewModel {
PlayerFormViewModel(database: database, player: player)
}
// MARK: - Private
/// Returns a publisher of the players in the list
private func playersPublisher(in database: AppDatabase) -> AnyPublisher<[Player], Never> {
// Players depend on the current ordering
$ordering.map { ordering -> AnyPublisher<[Player], Error> in
switch ordering {
case .byScore:
return database.playersOrderedByScorePublisher()
case .byName:
return database.playersOrderedByNamePublisher()
}
}
.map { playersPublisher in
// Turn database errors into an empty players list.
// Eventual error presentation is left as an exercise for the reader.
playersPublisher.catch { error in
Just<[Player]>([])
}
}
.switchToLatest()
.eraseToAnyPublisher()
}
}
@@ -0,0 +1,145 @@
import GRDBQuery
import SwiftUI
/// The main application view
struct AppView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
/// The `players` property is automatically updated when the database changes
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
/// We'll need to leave edit mode in several occasions.
@State private var editMode = EditMode.inactive
/// Tracks the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
// If you want to define the query on initialization, you will prefer:
//
// @Query<PlayerRequest> private var players: [Player]
//
// init(initialOrdering: PlayerRequest.Ordering) {
// _players = Query(PlayerRequest(ordering: initialOrdering))
// }
var body: some View {
NavigationView {
PlayerList(players: players)
.navigationBarTitle(Text("\(players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: ToggleOrderingButton(
ordering: $players.ordering,
willChange: {
// onChange(of: $players.wrappedValue.ordering)
// is not able to leave the editing mode during
// the animation of the list content.
// Workaround: stop editing before the ordering
// is changed, and the list content is updated.
stopEditing()
}))
.toolbar { toolbarContent }
.onChange(of: players) { players in
if players.isEmpty {
stopEditing()
}
}
.environment(\.editMode, $editMode)
}
}
private var toolbarContent: some ToolbarContent {
ToolbarItemGroup(placement: .bottomBar) {
Button {
// Don't stopEditing() here because this is
// performed `onChange(of: players)`
try! appDatabase.deleteAllPlayers()
} label: {
Image(systemName: "trash").imageScale(.large)
}
Spacer()
Button {
stopEditing()
try! appDatabase.refreshPlayers()
} label: {
Image(systemName: "arrow.clockwise").imageScale(.large)
}
Spacer()
Button {
stopEditing()
// Perform 50 refreshes in parallel
for _ in 0..<50 {
DispatchQueue.global().async {
try! AppDatabase.shared.refreshPlayers()
}
}
} label: {
Image(systemName: "tornado").imageScale(.large)
}
}
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button {
stopEditing()
newPlayerIsPresented = true
} label: {
Image(systemName: "plus")
}
.accessibility(label: Text("New Player"))
.sheet(isPresented: $newPlayerIsPresented) {
PlayerCreationView()
}
}
private func stopEditing() {
withAnimation {
editMode = .inactive
}
}
}
private struct ToggleOrderingButton: View {
@Binding var ordering: PlayerRequest.Ordering
let willChange: () -> Void
var body: some View {
switch ordering {
case .byName:
Button {
willChange()
ordering = .byScore
} label: {
Label("Name", systemImage: "arrowtriangle.up.fill").labelStyle(.titleAndIcon)
}
case .byScore:
Button {
willChange()
ordering = .byName
} label: {
Label("Score", systemImage: "arrowtriangle.down.fill").labelStyle(.titleAndIcon)
}
}
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview the default, empty database
AppView()
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
}
}
}
@@ -1,52 +0,0 @@
import SwiftUI
/// The Player creation sheet
struct PlayerCreationSheet: View {
/// Manages the player form
let viewModel: PlayerFormViewModel
/// Executed when user cancels or saves the new user.
let dismissAction: () -> Void
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerForm(viewModel: viewModel)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(
action: self.dismissAction,
label: { Text("Cancel") }),
trailing: Button(
action: self.save,
label: { Text("Save") }))
}
}
private func save() {
do {
try viewModel.savePlayer()
dismissAction()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .new())
return PlayerCreationSheet(
viewModel: viewModel,
dismissAction: { })
}
}
@@ -0,0 +1,50 @@
import SwiftUI
/// The view that creates a new player.
struct PlayerCreationView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.dismiss) private var dismiss
@State private var form = PlayerForm(name: "", score: "")
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerFormView(form: $form)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(role: .cancel) {
dismiss()
} label: {
Text("Cancel")
},
trailing: Button {
save()
} label: {
Text("Save")
})
}
}
private func save() {
do {
var player = Player(id: nil, name: "", score: 0)
form.apply(to: &player)
try appDatabase.savePlayer(&player)
dismiss()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
}
@@ -1,28 +1,37 @@
import SwiftUI
/// The Player edition view, designed to be the destination of
/// a NavigationLink.
/// The view that edits an existing player.
struct PlayerEditionView: View {
/// Manages the player form
let viewModel: PlayerFormViewModel
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.isPresented) private var isPresented
private let player: Player
@State private var form: PlayerForm
init(player: Player) {
self.player = player
self.form = PlayerForm(player)
}
var body: some View {
PlayerForm(viewModel: viewModel)
.onDisappear(perform: {
// Ignore validation errors
try? self.viewModel.savePlayer()
})
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
// Save when back button is pressed
if !isPresented {
var savedPlayer = player
form.apply(to: &savedPlayer)
// Ignore error because I don't know how to cancel the
// back button and present the error
try? appDatabase.savePlayer(&savedPlayer)
}
}
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return NavigationView {
PlayerEditionView(viewModel: viewModel)
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
@@ -1,39 +0,0 @@
import SwiftUI
/// The Player editing form, embedded in both
/// `PlayerCreationSheet` and `PlayerEditionView`.
struct PlayerForm: View {
/// Manages the player form
@ObservedObject var viewModel: PlayerFormViewModel
var body: some View {
List {
TextField("Name", text: $viewModel.name)
TextField("Score", text: $viewModel.score)
.keyboardType(.numberPad)
}
.listStyle(GroupedListStyle())
// Make sure the form is reset, in case a previous edition ended
// with a validation error.
//
// The bug we want to prevent is the following:
//
// 1. Launch the app
// 2. Tap a player
// 3. Erase the name so that validation fails
// 4. Hit the back button
// 5. Tap the same player
// 6. Bug: the form displays an empty name.
.onAppear(perform: viewModel.reset)
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return PlayerForm(viewModel: viewModel)
}
}
@@ -0,0 +1,47 @@
import SwiftUI
/// The Player editing form, embedded in both
/// `PlayerCreationView` and `PlayerEditionView`.
struct PlayerFormView: View {
@Binding var form: PlayerForm
var body: some View {
List {
TextField("Name", text: $form.name)
.accessibility(label: Text("Player Name"))
TextField("Score", text: $form.score).keyboardType(.numberPad)
.accessibility(label: Text("Player Score"))
}
.listStyle(InsetGroupedListStyle())
}
}
struct PlayerForm {
var name: String
var score: String
}
extension PlayerForm {
init(_ player: Player) {
self.name = player.name
self.score = "\(player.score)"
}
func apply(to player: inout Player) {
player.name = name
player.score = Int(score) ?? 0
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
}
}
@@ -1,117 +1,38 @@
import SwiftUI
/// The list of players
struct PlayerList: View {
/// Manages the list of players
@ObservedObject var viewModel: PlayerListViewModel
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
/// Controls the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
/// The players in the list
var players: [Player]
var body: some View {
NavigationView {
VStack {
playerList
toolbar
}
.navigationBarTitle(Text("\(viewModel.playerList.players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: toggleOrderingButton)
}
}
private var playerList: some View {
List {
ForEach(viewModel.playerList.players) { player in
NavigationLink(destination: self.editionView(for: player)) {
ForEach(players) { player in
NavigationLink(destination: editionView(for: player)) {
PlayerRow(player: player)
.animation(nil)
// Don't animate player update
.animation(nil, value: player)
}
}
.onDelete(perform: { offsets in
self.viewModel.deletePlayers(atOffsets: offsets)
})
}
.listStyle(PlainListStyle())
.animation(viewModel.playerList.animatedChanges ? .default : nil)
}
private var toolbar: some View {
HStack {
Button(
action: viewModel.deleteAllPlayers,
label: { Image(systemName: "trash").imageScale(.large) })
Spacer()
Button(
action: viewModel.refreshPlayers,
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
Spacer()
Button(
action: viewModel.stressTest,
label: { Image(systemName: "tornado").imageScale(.large) })
}
.padding()
}
/// The button that toggles between name/score ordering.
private var toggleOrderingButton: some View {
switch viewModel.ordering {
case .byName:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Name")
Image(systemName: "arrowtriangle.up.fill")
.imageScale(.small)
}
})
case .byScore:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Score")
Image(systemName: "arrowtriangle.down.fill")
.imageScale(.small)
}
})
.onDelete { offsets in
let playerIds = offsets.compactMap { players[$0].id }
try? appDatabase.deletePlayers(ids: playerIds)
}
}
// Animate list updates
.animation(.default, value: players)
.listStyle(.plain)
}
/// The view that edits a player in the list.
private func editionView(for player: Player) -> some View {
PlayerEditionView(
viewModel: viewModel.formViewModel(for: player))
.navigationBarTitle(player.name)
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button(
action: {
// Make sure we do not edit a previously created player.
self.viewModel.newPlayerViewModel.editNewPlayer()
self.newPlayerIsPresented = true
},
label: { Image(systemName: "plus").imageScale(.large) })
.sheet(
isPresented: $newPlayerIsPresented,
content: { self.newPlayerCreationSheet })
}
/// The player creation sheet.
private var newPlayerCreationSheet: some View {
PlayerCreationSheet(
viewModel: self.viewModel.newPlayerViewModel,
dismissAction: {
self.newPlayerIsPresented = false
})
PlayerEditionView(player: player).navigationBarTitle(player.name)
}
}
struct PlayerRow: View {
private struct PlayerRow: View {
var player: Player
var body: some View {
@@ -123,9 +44,14 @@ struct PlayerRow: View {
}
}
struct PlayerListView_Previews: PreviewProvider {
struct PlayerList_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerListViewModel(database: .random())
return PlayerList(viewModel: viewModel)
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
}
}
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -143,112 +143,4 @@ class AppDatabaseTests: XCTestCase {
let players = try dbQueue.read(Player.fetchAll)
XCTAssertEqual(players, [player])
}
func test_playersOrderedByNamePublisher_publishes_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.playersOrderedByNamePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
exp.fulfill()
}
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_playersOrderedByNamePublisher_publishes_right_on_subscripion() throws {
// Our SwiftUI views have no "waiting" state, and must be fed with
// players without any delay in order to avoid any rendering glitch.
// This test makes sure `playersOrderedByNamePublisher` publishes right
// on subscription.
// Given a players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we observe players
var players: [Player]?
_ = appDatabase.playersOrderedByNamePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
}
// Then the players are published right on subscription
XCTAssertNotNil(players)
}
func test_playersOrderedByScorePublisher_publishes_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.playersOrderedByScorePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
exp.fulfill()
}
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
func test_playersOrderedByScorePublisher_publishes_right_on_subscripion() throws {
// Our SwiftUI views have no "waiting" state, and must be fed with
// players without any delay in order to avoid any rendering glitch.
// This test makes sure `playersOrderedByScorePublisher` publishes right
// on subscription.
// Given a players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we observe players
var players: [Player]?
_ = appDatabase.playersOrderedByScorePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
}
// Then the players are published right on subscription
XCTAssertNotNil(players)
}
}
@@ -0,0 +1,43 @@
import XCTest
import GRDB
@testable import GRDBCombineDemo
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
}
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -3,27 +3,29 @@ Combine + SwiftUI Demo Application
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
**This demo application is a Combine + SwiftUI application, based on the MVVM design pattern.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md), and for Async/Await + SwiftUI, see [GRDBAsyncDemo](../GRDBAsyncDemo/README.md).
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
**Requirements**: iOS 15.0+ / Xcode 12+
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
The topics covered in this demo are:
- 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 SwiftUI List with [ValueObservation](../../../README.md#valueobservation) Combine publishers.
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift)
`GRDBCombineDemoApp` feeds the app views with a database.
`GRDBCombineDemoApp` feeds the app views with a database, through the SwiftUI environment.
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema.
- [Persistence.swift](GRDBCombineDemo/Persistence.swift)
@@ -31,18 +33,19 @@ The topics covered in this demo are:
- [Player.swift](GRDBCombineDemo/Player.swift)
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
- [PlayerList.swift](GRDBCombineDemo/Views/PlayerList.swift) and [PlayerListViewModel.swift](GRDBCombineDemo/ViewModels/PlayerListViewModel.swift)
- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift)
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditionView.swift](GRDBCombineDemo/Views/PlayerEditionView.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
`PlayerForm` is the SwiftUI view that displays a Player editing form. It is embedded in `PlayerEditionView` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
`PlayerRequest` feeds the `@Query` property wrapper (`@Query`, defined in [GRDBQuery](https://github.com/groue/GRDBQuery), allows SwiftUI views to display up-to-date database content).
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
- [GRDBCombineDemoTests](GRDBCombineDemoTests)
- Test the database schema
- Test the `Player` record and its requests
- Test the `PlayerRequest` methods that feed the list of players.
- Test the `AppDatabase` methods that let the app access the database.
@@ -15,7 +15,6 @@ 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 {
@@ -23,19 +22,25 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate {
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompleted()
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompleted()
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompleted()
urlSessionTask.setTaskCompletedWithSnapshot(false)
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompleted()
task.setTaskCompletedWithSnapshot(false)
}
}
}
@@ -3,20 +3,20 @@
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; };
56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */; };
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; };
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, ); }; };
567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* 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, ); }; };
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD01E926430002582E0 /* InterfaceController.swift */; };
568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; };
568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; };
@@ -40,6 +40,20 @@
remoteGlobalIDString = 56B036021E8D9EBE003B6DA4;
remoteInfo = GRDBDemoiOS;
};
5642252F29A2390800D714BF /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDB;
};
5642253329A2391900D714BF /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDB;
};
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
@@ -54,62 +68,6 @@
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;
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
@@ -127,15 +85,15 @@
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
568E5FDD1E926430002582E0 /* Embed App Extensions */ = {
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */,
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */,
);
name = "Embed App Extensions";
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
568E5FE11E926430002582E0 /* Embed Watch Content */ = {
@@ -155,7 +113,7 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */,
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -166,7 +124,7 @@
dstPath = "";
dstSubfolderSpec = 10;
files = (
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */,
567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -214,7 +172,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56606D24235593AB00185962 /* GRDB.framework in Frameworks */,
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -222,7 +180,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56606D202355938A00185962 /* GRDB.framework in Frameworks */,
567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -243,13 +201,7 @@
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 */,
56606D0C2355931F00185962 /* GRDBTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -309,13 +261,13 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036121E8D9EBE003B6DA4 /* Info.plist */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56185BBE25B8036100B9C30F /* Persistence.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56FE6F4E24A9112900711EDF /* Resources */,
56FE6F5124A9118000711EDF /* Support */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
);
path = GRDBDemoiOS;
@@ -340,14 +292,6 @@
path = ViewControllers;
sourceTree = "<group>";
};
56FE6F5124A9118000711EDF /* Support */ = {
isa = PBXGroup;
children = (
56B036121E8D9EBE003B6DA4 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -374,7 +318,7 @@
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
buildPhases = (
568E5FBD1E926430002582E0 /* Resources */,
568E5FDD1E926430002582E0 /* Embed App Extensions */,
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */,
);
buildRules = (
);
@@ -398,7 +342,7 @@
buildRules = (
);
dependencies = (
56606D23235593A300185962 /* PBXTargetDependency */,
5642253429A2391900D714BF /* PBXTargetDependency */,
);
name = "GRDBDemoWatchOS Extension";
productName = "GRDBDemoWatchOS Extension";
@@ -418,7 +362,7 @@
buildRules = (
);
dependencies = (
56606D1E2355937900185962 /* PBXTargetDependency */,
5642253029A2390800D714BF /* PBXTargetDependency */,
568E5FD81E926430002582E0 /* PBXTargetDependency */,
);
name = GRDBDemoiOS;
@@ -433,7 +377,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1200;
LastUpgradeCheck = 1400;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56185BEF25B80B8900B9C30F = {
@@ -462,7 +406,7 @@
};
};
buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */;
compatibilityVersion = "Xcode 3.2";
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
@@ -496,55 +440,13 @@
remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */ = {
56606D0C2355931F00185962 /* GRDBTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
path = GRDBTests.xctest;
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 56606D112355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D142355931F00185962 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 56606D132355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D162355931F00185962 /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 56606D152355931F00185962 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56606D182355931F00185962 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
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 */
/* Begin PBXResourcesBuildPhase section */
@@ -625,15 +527,15 @@
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
};
56606D1E2355937900185962 /* PBXTargetDependency */ = {
5642253029A2390800D714BF /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 56606D1D2355937900185962 /* PBXContainerItemProxy */;
name = GRDB;
targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */;
};
56606D23235593A300185962 /* PBXTargetDependency */ = {
5642253429A2391900D714BF /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBWatchOS;
targetProxy = 56606D22235593A300185962 /* PBXContainerItemProxy */;
name = GRDB;
targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */;
};
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
@@ -686,8 +588,11 @@
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests;
@@ -709,8 +614,11 @@
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -727,7 +635,11 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
@@ -743,7 +655,11 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
@@ -837,14 +753,14 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
WATCHOS_DEPLOYMENT_TARGET = 8.0;
};
name = Debug;
};
@@ -893,13 +809,14 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
WATCHOS_DEPLOYMENT_TARGET = 8.0;
};
name = Release;
};
@@ -911,7 +828,10 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
@@ -925,7 +845,10 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1200"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1230"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -29,7 +29,8 @@
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
@@ -60,6 +61,13 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,12 +1,29 @@
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// `AppDatabase` lets the application access the database.
///
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
@@ -16,30 +33,76 @@ final class AppDatabase {
/// Application can use a `DatabasePool`, and tests can use a fast
/// in-memory `DatabaseQueue`.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
private let dbWriter: DatabaseWriter
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
.collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
@@ -54,10 +117,11 @@ final class AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// Saves (inserts or updates) a player. When the method returns, the
/// player id is not nil.
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbWriter.write { db in
try player.save(db)
@@ -67,7 +131,7 @@ extension AppDatabase {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
_ = try Player.deleteAll(db, ids: ids)
}
}
@@ -81,14 +145,13 @@ extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
if try Player.all().isEmpty(db) {
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
var player = Player.newRandom()
try player.insert(db)
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
// Delete a random player
@@ -109,7 +172,7 @@ extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
if try Player.all().isEmpty(db) {
try createRandomPlayers(db)
}
}
@@ -118,54 +181,20 @@ extension AppDatabase {
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.insert(db)
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
}
}
// MARK: - Database Access: Reads
// This demo app does not provide any specific reading method, and instead
// gives an unrestricted read-only access to the rest of the application.
// In your app, you are free to choose another path, and define focused
// reading methods.
extension AppDatabase {
/// Tracks changes in the number of players
func observePlayerCount(
onError: @escaping (Error) -> Void,
onChange: @escaping (Int) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.fetchCount)
.start(
in: dbWriter,
onError: onError,
onChange: onChange)
}
/// Tracks changes in players ordered by name
func observePlayersOrderedByName(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.start(
in: dbWriter,
onError: onError,
onChange: onChange)
}
/// Tracks changes in players ordered by score
func observePlayersOrderedByScore(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.start(
in: dbWriter,
onError: onError,
onChange: onChange)
/// Provides a read-only access to the database
var reader: DatabaseReader {
dbWriter
}
}
@@ -1,17 +1,32 @@
import Foundation
import GRDB
extension AppDatabase {
/// The shared `PlayerDatabase`
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Connect to a database on disk
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let url: URL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: url.path)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
@@ -2,8 +2,9 @@ import GRDB
/// The Player struct.
///
/// Identifiable conformance supports type-safe GRDB primary key methods.
/// Hashable conformance supports table view updates
struct Player: Hashable {
struct Player: Identifiable, Hashable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
@@ -30,7 +31,7 @@ extension Player {
}
/// Creates a new player with random name and random score
static func newRandom() -> Player {
static func makeRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
@@ -49,7 +50,7 @@ extension Player {
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
@@ -58,8 +59,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
@@ -67,28 +68,37 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
// Sort by name in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score
/// A request of players ordered by score.
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="19455" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19454"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -17,14 +18,14 @@
<tableViewSection headerTitle="Name" id="Nzq-eO-jT3">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
<rect key="frame" x="20" y="55.5" width="374" height="44"/>
<rect key="frame" x="20" y="32" width="374" height="40.5"/>
<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="374" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="374" height="40.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="20" y="11" width="334" height="22"/>
<rect key="frame" x="20" y="11" width="334" height="18.5"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
<connections>
@@ -36,7 +37,8 @@
<constraints>
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" id="9cK-nj-70V"/>
<constraint firstAttribute="trailingMargin" secondItem="m5m-Zs-j0z" secondAttribute="trailing" id="JsE-8v-XAS"/>
<constraint firstItem="m5m-Zs-j0z" firstAttribute="centerY" secondItem="iyM-TJ-JB4" secondAttribute="centerY" id="psG-tW-QrM"/>
<constraint firstAttribute="bottomMargin" secondItem="m5m-Zs-j0z" secondAttribute="bottom" id="KbI-Yl-Las"/>
<constraint firstItem="m5m-Zs-j0z" firstAttribute="top" secondItem="iyM-TJ-JB4" secondAttribute="topMargin" id="v2S-en-21g"/>
</constraints>
</tableViewCellContentView>
</tableViewCell>
@@ -45,14 +47,14 @@
<tableViewSection headerTitle="Score" id="Urb-uF-sj1">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
<rect key="frame" x="20" y="155" width="374" height="44"/>
<rect key="frame" x="20" y="122" width="374" height="40.5"/>
<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="374" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="374" height="40.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="0" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="20" y="11" width="334" height="22"/>
<rect key="frame" x="20" y="11" width="334" height="18.5"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
<connections>
@@ -61,9 +63,10 @@
</textField>
</subviews>
<constraints>
<constraint firstAttribute="bottomMargin" secondItem="rZ9-Fa-cyr" secondAttribute="bottom" id="3Ya-Po-TQ3"/>
<constraint firstAttribute="trailingMargin" secondItem="rZ9-Fa-cyr" secondAttribute="trailing" id="Gso-FU-Ct1"/>
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="centerY" secondItem="ccO-0O-u72" secondAttribute="centerY" id="UqA-ea-emb"/>
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" id="WrY-St-72v"/>
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="top" secondItem="ccO-0O-u72" secondAttribute="topMargin" id="mmE-f2-e9r"/>
</constraints>
</tableViewCellContentView>
</tableViewCell>
@@ -90,10 +93,10 @@
</navigationItem>
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
<connections>
<outlet property="cancelBarButtonItem" destination="VIN-Hi-Twt" id="dET-mF-ZXe"/>
<outlet property="commitBarButtonItem" destination="2um-u5-BhV" id="Jym-us-zdP"/>
<outlet property="cancelButtonItem" destination="VIN-Hi-Twt" id="dET-mF-ZXe"/>
<outlet property="nameCell" destination="2gb-gB-918" id="ch2-MB-uRm"/>
<outlet property="nameTextField" destination="m5m-Zs-j0z" id="A6a-pw-q8s"/>
<outlet property="saveButtonItem" destination="2um-u5-BhV" id="Jym-us-zdP"/>
<outlet property="scoreCell" destination="vp3-Ft-Gth" id="b8A-42-8Dw"/>
<outlet property="scoreTextField" destination="rZ9-Fa-cyr" id="4kw-gV-uih"/>
</connections>
@@ -112,7 +115,7 @@
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
<segue destination="iNr-Oe-muq" kind="relationship" relationship="rootViewController" id="e5b-3U-9Vz"/>
<segue destination="iNr-Oe-muq" kind="relationship" relationship="rootViewController" destinationCreationSelector="makePlayerCreationViewController:" id="e5b-3U-9Vz"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="kNr-vk-I5l" userLabel="First Responder" sceneMemberID="firstResponder"/>
@@ -123,8 +126,8 @@
<scene sceneID="N1X-4j-Re4">
<objects>
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<navigationBar key="navigationBar" contentMode="scaleToFill" largeTitles="YES" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="44" width="414" height="96"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -142,32 +145,32 @@
<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="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<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="414" height="43.5"/>
<rect key="frame" x="0.0" y="44.5" width="414" 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="383" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="384.5" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<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="20" y="12" width="33.5" height="20.5"/>
<rect key="frame" x="20" y="14" width="28.5" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<nil key="highlightedColor"/>
</label>
<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="331" y="12" width="44" height="20.5"/>
<rect key="frame" x="339" y="14" width="37.5" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<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"/>
<color key="textColor" systemColor="secondaryLabelColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</tableViewCellContentView>
<connections>
<segue destination="iNr-Oe-muq" kind="show" identifier="Edit" id="Lgu-Yd-HSy"/>
<segue destination="iNr-Oe-muq" kind="show" identifier="" destinationCreationSelector="makePlayerEditionViewController:" id="Lgu-Yd-HSy"/>
</connections>
</tableViewCell>
</prototypes>
@@ -182,7 +185,7 @@
<navigationItem key="navigationItem" title="Hall Of Fame" id="QIv-M6-kT1">
<barButtonItem key="leftBarButtonItem" systemItem="add" id="2bK-Fl-55Q">
<connections>
<segue destination="ein-Sr-i8w" kind="presentation" identifier="New" id="ehP-ZN-Nt4"/>
<segue destination="ein-Sr-i8w" kind="presentation" identifier="" id="ehP-ZN-Nt4"/>
</connections>
</barButtonItem>
</navigationItem>
@@ -199,4 +202,12 @@
<inferredMetricsTieBreakers>
<segue reference="Lgu-Yd-HSy"/>
</inferredMetricsTieBreakers>
<resources>
<systemColor name="secondaryLabelColor">
<color red="0.23529411764705882" green="0.23529411764705882" blue="0.2627450980392157" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
</systemColor>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
@@ -1,39 +1,42 @@
import UIKit
class PlayerEditionViewController: UITableViewController {
enum Presentation {
/// Modal presentation: edition ends with the "Commit" unwind segue.
case modal
enum Mode {
/// Edition ends with the "Commit" unwind segue.
case creation
/// Push presentation: edition ends when user hits the back button.
case push
/// Edition ends when user hits the back button.
case edition
}
/// The edited player
var player: Player! {
didSet {
configureForm()
}
}
private(set) var player: Player
/// The presentation mode
var presentation: Presentation! {
didSet {
configureNavigationItem()
}
}
let mode: Mode
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var commitBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var cancelButtonItem: UIBarButtonItem!
@IBOutlet private weak var saveButtonItem: UIBarButtonItem!
@IBOutlet private weak var nameCell: UITableViewCell!
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var scoreCell: UITableViewCell!
@IBOutlet private weak var scoreTextField: UITextField!
init?(_ coder: NSCoder, mode: Mode, player: Player) {
self.mode = mode
self.player = player
super.init(coder: coder)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureForm()
configureNavigationItem()
configureForm()
}
}
@@ -55,24 +58,22 @@ extension PlayerEditionViewController {
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if case .push = presentation, parent == nil {
if mode == .edition, parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
}
private func configureNavigationItem() {
guard isViewLoaded else { return }
if let presentation = presentation {
switch presentation {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
switch mode {
case .creation:
navigationItem.title = "New Player"
navigationItem.leftBarButtonItem = cancelButtonItem
navigationItem.rightBarButtonItem = saveButtonItem
case .edition:
navigationItem.title = player.name
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
}
}
@@ -104,14 +105,10 @@ extension PlayerEditionViewController: UITextFieldDelegate {
@IBAction func textFieldDidChange(_ textField: UITextField) {
// User has edited the player: prevent interactive dismissal
if case .modal = presentation {
isModalInPresentation = true
}
isModalInPresentation = true
}
private func configureForm() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
@@ -122,9 +119,7 @@ extension PlayerEditionViewController: UITextFieldDelegate {
}
private func saveChanges() {
guard var player = self.player else {
return
}
var player = self.player
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
try! AppDatabase.shared.savePlayer(&player)
@@ -10,13 +10,11 @@ class PlayerListViewController: UITableViewController {
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var dataSource: PlayerDataSource!
private var animatesPlayersChange = false // Don't animate first update
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
configureDataSourceContent()
observePlayers()
}
}
@@ -25,7 +23,7 @@ class PlayerListViewController: UITableViewController {
configureToolbar()
configureNavigationItem()
configureDataSource()
configureDataSourceContent()
observePlayers()
}
override func viewWillAppear(_ animated: Bool) {
@@ -35,21 +33,31 @@ class PlayerListViewController: UITableViewController {
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(image: UIImage(systemName: "tornado"), style: .plain, target: self, action: #selector(stressTest)),
UIBarButtonItem(systemItem: .trash, primaryAction: UIAction { [unowned self] _ in
setEditing(false, animated: true)
try! AppDatabase.shared.deleteAllPlayers()
}),
UIBarButtonItem(systemItem: .flexibleSpace),
UIBarButtonItem(systemItem: .refresh, primaryAction: UIAction { [unowned self] _ in
setEditing(false, animated: true)
try! AppDatabase.shared.refreshPlayers()
}),
UIBarButtonItem(systemItem: .flexibleSpace),
UIBarButtonItem(image: UIImage(systemName: "tornado"), primaryAction: UIAction { [unowned self] _ in
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! AppDatabase.shared.refreshPlayers()
}
}
}),
]
}
private func configureNavigationItem() {
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "Players", style: .plain,
target: nil, action: nil)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Players")
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
@@ -57,29 +65,20 @@ class PlayerListViewController: UITableViewController {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
primaryAction: UIAction { [unowned self] _ in
setEditing(false, animated: true)
playerOrdering = .byName
})
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
primaryAction: UIAction { [unowned self] _ in
setEditing(false, animated: true)
playerOrdering = .byScore
})
}
}
private func configureTitle() {
playerCountCancellable = AppDatabase.shared.observePlayerCount(
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 configureDataSource() {
dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
@@ -95,37 +94,60 @@ class PlayerListViewController: UITableViewController {
tableView.dataSource = dataSource
}
private func configureDataSourceContent() {
switch playerOrdering {
case .byName:
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateDataSourceContent(with: players)
})
case .byScore:
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateDataSourceContent(with: players)
})
private func configureTitle(from players: [Player]) {
switch players.count {
case 0:
navigationItem.title = "No Player"
case 1:
navigationItem.title = "1 Player"
case let count:
navigationItem.title = "\(count) Players"
}
}
private func updateDataSourceContent(with players: [Player]) {
private func configureDataSource(from players: [Player]) {
var snapshot = NSDiffableDataSourceSnapshot<Int, Player>()
snapshot.appendSections([0])
snapshot.appendItems(players, toSection: 0)
if animatesPlayersChange {
dataSource.apply(snapshot, animatingDifferences: true, completion: nil)
} else {
// Future updates will be animated
animatesPlayersChange = true
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
// Remember selection
let selectedPlayerId = tableView.indexPathForSelectedRow.flatMap {
dataSource.itemIdentifier(for: $0)?.id
}
// Avoid a UIKit warning; don't animate when popping from edition
let animated = view.window != nil
dataSource.apply(snapshot, animatingDifferences: animated, completion: {
// Restore selection
if let index = players.firstIndex(where: { $0.id == selectedPlayerId }) {
self.tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
}
})
}
private func observePlayers() {
let request: QueryInterfaceRequest<Player>
switch playerOrdering {
case .byName:
request = Player.all().orderedByName()
case .byScore:
request = Player.all().orderedByScore()
}
playersCancellable = ValueObservation
.tracking(request.fetchAll(_:))
.start(
in: AppDatabase.shared.reader,
// Immediate scheduling feeds the data source right on subscription,
// and avoids an undesired animation when the application starts.
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self else { return }
self.configureTitle(from: players)
self.configureDataSource(from: players)
})
}
}
@@ -133,26 +155,16 @@ class PlayerListViewController: UITableViewController {
// MARK: - Navigation
extension PlayerListViewController {
@IBSegueAction func makePlayerEditionViewController(_ coder: NSCoder) -> PlayerEditionViewController? {
guard let indexPath = tableView.indexPathForSelectedRow,
let player = dataSource.itemIdentifier(for: indexPath)
else { return nil }
return PlayerEditionViewController(coder, mode: .edition, player: player)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
guard let controller = segue.destination as? PlayerEditionViewController,
let indexPath = tableView.indexPathForSelectedRow,
let player = dataSource.itemIdentifier(for: indexPath)
else { return }
controller.title = player.name
controller.player = player
controller.presentation = .push
}
else if segue.identifier == "New" {
guard let navigationController = segue.destination as? UINavigationController,
let controller = navigationController.viewControllers.first as? PlayerEditionViewController
else { return }
setEditing(false, animated: true)
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
controller.presentation = .modal
}
@IBSegueAction func makePlayerCreationViewController(_ coder: NSCoder) -> PlayerEditionViewController? {
let player = Player(id: nil, name: "", score: 0)
return PlayerEditionViewController(coder, mode: .creation, player: player)
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
@@ -180,37 +192,3 @@ private class PlayerDataSource: UITableViewDiffableDataSource<Int, Player> {
}
}
}
// MARK: - Actions
extension PlayerListViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
playerOrdering = .byScore
}
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! AppDatabase.shared.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! AppDatabase.shared.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! AppDatabase.shared.refreshPlayers()
}
}
}
}
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -143,92 +143,4 @@ class AppDatabaseTests: XCTestCase {
let players = try dbQueue.read(Player.fetchAll)
XCTAssertEqual(players, [player])
}
func test_observePlayerCount() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we observe the player count and wait for the first value
let exp = expectation(description: "Player count")
var count: Int?
let cancellable = appDatabase.observePlayerCount(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
count = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then that first value is one
XCTAssertEqual(count, 1)
}
func test_observePlayersOrderedByName() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.observePlayersOrderedByName(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
players = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_observePlayersOrderedByScore() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
players = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
}
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
Loaded 100 of 640 files, more files were not shown because too many files have changed in this diff. Show more