Compare commits

...
Author SHA1 Message Date
Gwendal Roué b44628b9cd Add missing SendableMetatype requirements 2025-07-25 07:27:28 +02:00
Gwendal Roué 8ba1bc9a96 Merge branch 'development' 2025-07-23 13:27:07 +02:00
Gwendal Roué c4e39285a0 v7.6.1 2025-07-23 13:27:01 +02:00
Gwendal Roué 1622b72b62 Merge pull request #1797 from groue/dev/cancellation-fix
Fix race condition regarding Task cancellation
2025-07-23 13:24:52 +02:00
Gwendal Roué 215128390d Fix race condition: prevent cancellation from cancelling other database accesses after database accesses has completed
Before this change, cancelling a database access could cancel *another* database access 😱
2025-07-23 12:01:58 +02:00
Gwendal Roué c5283a0bd9 Warn against the incompatibility between custom SQLite builds and SPM
Addresses https://github.com/groue/GRDB.swift/issues/1709#issuecomment-3100503200
2025-07-22 07:47:41 +02:00
Gwendal Roué fb68849bfb Merge branch 'development' 2025-07-20 18:11:22 +02:00
Gwendal Roué c2bddde88a v7.6.0 2025-07-20 17:21:28 +02:00
Gwendal Roué b4a21d63b2 Merge pull request #1796 from groue/dev/public-RowDecodingError
Throwing row accessors
2025-07-20 17:13:49 +02:00
Gwendal Roué 6ca38eda3b Give TableAliasBase a location in DocC 2025-07-20 14:38:15 +02:00
Gwendal Roué d76922fe1a Document throwing accessors for records and record collections 2025-07-20 14:38:15 +02:00
Gwendal Roué a46f3b69e9 Document throwing row accessors 2025-07-20 14:38:15 +02:00
Gwendal Roué b572982e34 Document RowDecodingError 2025-07-20 13:11:42 +02:00
Gwendal Roué 5a8b025ee8 TODO: test throwing row accessors of record collections and sets 2025-07-20 13:00:12 +02:00
Gwendal Roué 9a1914a813 Test throwing record row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué 4a92263c5e Test throwing column row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué f72d0cecb2 Document throwing row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué 24e0f5ddeb Make throwing row accessors public 2025-07-20 13:00:12 +02:00
Gwendal Roué 2b1b56ea47 Make RowDecodingError public 2025-07-20 13:00:12 +02:00
Gwendal Roué ad704c58e5 Hide implementation of RowDecodingError
Turn the enum into a struct so that it can be made public without exposing internal details
2025-07-20 13:00:12 +02:00
Gwendal Roué 3f928bcf9c Merge pull request #1794 from groue/dev/actor-access
Access task locals from asynchronous database accesses
2025-07-19 17:15:25 +02:00
Gwendal Roué c91c183354 Async database accesses are no longer escaping and no longer need to capture self 2025-07-19 16:42:17 +02:00
Gwendal Roué c666393e63 AppDatabase can be a struct, so let it be a struct 2025-07-19 16:42:17 +02:00
Gwendal Roué d242421862 Async methods accept a non-escaping closure 2025-07-19 16:42:17 +02:00
Gwendal Roué 7a1e65b142 Remove late cancellation checks
I'm slowly changing my mind about this.
2025-07-19 15:27:08 +02:00
Gwendal Roué fb4578a7d6 Delete unused code 2025-07-19 15:26:46 +02:00
Gwendal Roué 6069e6d683 DatabasePool.barrierWriteWithoutTransaction can access task locals 2025-07-19 15:26:44 +02:00
Gwendal Roué a703da9b27 Async version of Pool.barrier { ... } 2025-07-19 14:25:50 +02:00
Gwendal Roué 684266b7b8 DispatchQueueActor supports barriers in concurrent DispatchQueue 2025-07-19 14:25:50 +02:00
Gwendal Roué b24fb76610 Failing test for task locals with DatabaseWriter (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué cbbd0cb945 Add asserts about expected ends of transaction 2025-07-19 14:25:50 +02:00
Gwendal Roué dd4227303a DatabasePool unsafeRead can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 69b786dc9e Allow COMMIT from a cancelled read-only access. 2025-07-19 14:25:50 +02:00
Gwendal Roué 9dd8b2cef7 Add failing test for task locals access from unsafeRead (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué c5ac6cdaa6 DatabaseSnapshotPool reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué e154a652dc Don't check for reentrancy from async Pool.read
One can't call an async function from a database access anywau
2025-07-19 14:25:50 +02:00
Gwendal Roué 41d4f23a83 DatabasePool reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 27b7400979 Async version of Pool.get() 2025-07-19 14:25:50 +02:00
Gwendal Roué e6847886db Extract DispatchQueueActor
We'll probably need it in order to access pool elements with support for task locals
2025-07-19 14:25:50 +02:00
Gwendal Roué c064515247 DatabaseQueue and DatabaseSnapshot reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 96236a3d44 Turn Database.cancel into a sendable closure 2025-07-19 14:25:50 +02:00
Gwendal Roué 01cd49b4ec Failing test for task locals (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué 9db14cb893 Merge pull request #1776 from Jason-Abbott/development
Add custom build instruction for hardened runtime
2025-06-11 09:22:36 +02:00
Jason Abbott b26f60eae0 Add custom build instruction for hardened runtime 2025-06-10 18:45:29 -06:00
Gwendal Roué 79a41dcbbb Merge pull request #1773 from Jason-Abbott/development 2025-06-01 10:24:09 +02:00
Jason Abbott c7d50486ad Merge branch 'groue:development' into development 2025-05-30 12:05:03 -06:00
Jason Abbott 93292d88f4 Make DatabasePreUpdateEvent.Kind Sendable, matching DatabaseEvent.Kind, and also duplicate comments from DatabaseEvent.Kind while here 2025-05-30 12:02:23 -06:00
Gwendal Roué be22e0a2d0 Merge pull request #1768 from groue/dev/throwing-closures
All closures that accept DatabaseComponents can throw
2025-05-12 20:58:47 +02:00
Gwendal Roué d1a2cb0948 All closures that accept DatabaseComponents can throw 2025-05-12 20:33:18 +02:00
Gwendal Roué a5a1be26b4 Merge branch 'development' 2025-05-11 14:25:02 +02:00
Gwendal Roué b84d1eaeef v7.5.0 2025-05-11 14:23:56 +02:00
Gwendal Roué e7a35dde06 Extend Usage section 2025-05-11 14:23:04 +02:00
Gwendal Roué c2e6c86934 Warn against the independent observation of each element in a list. 2025-05-11 13:32:50 +02:00
Gwendal Roué 7c2cbfe814 Merge pull request #1759 from groue/dev/expression-builder
Build request with closures
2025-05-11 13:28:01 +02:00
Gwendal Roué 034b241e71 Rename ColumnsProvider to DatabaseComponents 2025-05-11 13:10:19 +02:00
Gwendal Roué 814146c40d DocC 2025-05-11 11:56:21 +02:00
Gwendal Roué fedcdef65e Fix typo 2025-05-11 11:21:48 +02:00
Gwendal Roué 2316fb3831 Prefer key paths when possible 2025-05-11 11:12:19 +02:00
Gwendal Roué 98e2812089 Convenience api for updating a single column 2025-05-11 10:58:09 +02:00
Gwendal Roué 8f6f1aa264 TODO 2025-05-11 10:57:28 +02:00
Gwendal Roué 96d04716c2 Update more documentation with the closure syntax 2025-05-11 10:57:20 +02:00
Gwendal Roué 004968517e Update more documentation with the closure syntax 2025-05-10 17:43:22 +02:00
Gwendal Roué f635aea2f2 Update more documentation with the closure syntax 2025-05-10 16:38:02 +02:00
Gwendal Roué 5c9b772e65 Test CommonTableExpression aliases on Swift 6.1 2025-05-10 16:37:44 +02:00
Gwendal Roué d6ff3b14d4 DocC 2025-05-10 15:34:10 +02:00
Gwendal Roué fac0c22ecb Documentation for generic TableAlias 2025-05-10 14:52:48 +02:00
Gwendal Roué 5461caff04 Tests for generic TableAlias 2025-05-10 14:52:48 +02:00
Gwendal Roué 6cc3116ff4 TableAlias is generic 2025-05-10 14:52:48 +02:00
Gwendal Roué 55edcff97f Extract TableAlias 2025-05-10 09:40:16 +02:00
Gwendal Roué 430141344d Update more documentation with the closure syntax 2025-05-10 09:36:14 +02:00
Gwendal Roué 0567f69e66 Update AssociationBasics.md with the closure syntax 2025-05-10 09:36:14 +02:00
Gwendal Roué be2fb76d77 DocC 2025-05-10 09:36:14 +02:00
Gwendal Roué 503fb09270 Test that aggregate can be expressed with key-paths in Swift 6.1 2025-05-10 09:36:14 +02:00
Gwendal Roué ec6042e9c7 Update Tour.playground with closure syntax 2025-05-10 09:36:14 +02:00
Gwendal Roué 190ccda727 Rename deleteAndFetchStatement(_:select:) for consistency 2025-05-10 09:36:14 +02:00
Gwendal Roué af1adff71d More closure syntax for requests in README 2025-05-10 09:36:14 +02:00
Gwendal Roué 43e103d5f8 Recommend GRDB7 for CocoaPods 2025-05-10 09:36:14 +02:00
Gwendal Roué 7b2e9d838a Swift 6.1 compiler: test key-path requests. 2025-05-10 09:36:14 +02:00
Gwendal Roué 6b0faede2a Use closure syntax for insertAndFetch 2025-05-10 09:36:14 +02:00
Gwendal Roué ed402d5de6 Use closure syntax for batch updates 2025-05-10 09:36:14 +02:00
Gwendal Roué db5c4cc458 Use closure syntax for requests in README 2025-05-10 09:36:14 +02:00
Gwendal Roué 352f77f225 Stop recommending String enums for Columns.
We now recommend:

    enum Columns {
        static let id = Column("id")
        static let title = Column("title")
        static let latitude = Column("latitude")
        static let longitude = Column("longitude")
    }

Instead of the previous recommendation:

    enum Columns: String, ColumnExpression {
        case id, title, latitude, longitude
    }

This is because SE-0438 does not support Metatype Keypaths for enums. A request like `Place.order(\.title)` does not compile with a String enum.
2025-05-10 09:36:14 +02:00
Gwendal Roué ed98ac30e0 DocC 2025-05-10 09:36:14 +02:00
Gwendal Roué 35fa28ab90 QueryInterfaceRequest.select(_:as:) with ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué a89bd88340 Prefer key paths over closures, except in tests
Don't use key paths in tests because they are Swift 6.1+ only
2025-05-10 09:36:14 +02:00
Gwendal Roué b01f6da3cf Remove TODO 2025-05-10 09:36:14 +02:00
Gwendal Roué e7fdd65072 deleteAndFetchStatement(_,selection:) with ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué ff15f30a3b select(_, as:) with ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué f69ca1a573 Build aggregates from ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué e8b143e2ee Demo app uses ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué 5e9b965bee Test requests built from ColumnsProvider 2025-05-10 09:36:13 +02:00
Gwendal Roué ce238b6643 Build requests from ColumnsProvider 2025-05-10 09:36:13 +02:00
Gwendal Roué 787393db18 Fix Swiftlint warning 2025-05-10 09:36:13 +02:00
Gwendal Roué 8774497f31 Modernize QueryInterfaceRequestTests with an inner Columns type
so that we can use the new SQLExpressionBuilder
2025-05-10 09:36:13 +02:00
Gwendal Roué 94e90e7e6c Columns and ColumnsProvider associated types of TableRecord 2025-05-10 09:36:13 +02:00
Gwendal Roué 9064717b8a Merge pull request #1764 from groue/dev/fts-pattern-initializers
Make it possible to create a raw FTS5Pattern without any database connection
2025-05-08 13:07:27 +02:00
Gwendal Roué 00f462292b Documentation 2025-05-08 12:50:19 +02:00
Gwendal Roué 5a0622e5b8 Tests for FTS5Pattern.init(rawPattern:allowedColumns:) 2025-05-08 12:48:24 +02:00
Gwendal Roué 596db46407 Make FTS5Pattern.init(rawPattern:allowedColumns:) public
Fix #1763
2025-05-08 12:47:21 +02:00
Gwendal Roué 0aaa2a4f37 Adjust wording about Linux 2025-04-26 17:31:40 +02:00
Gwendal Roué 04e73c26c4 v7.4.1 2025-03-28 08:17:58 +01:00
Gwendal Roué a71c1d6e80 Removed unnecessary TODO warning 2025-03-28 08:15:54 +01:00
Gwendal Roué 52b7b7bd26 Merge branch 'development' 2025-03-22 14:57:59 +01:00
Gwendal Roué 9a9d2e9993 v7.4.0 2025-03-22 14:16:44 +01:00
Gwendal Roué 1ce8e38bea Merge pull request #1747 from groue/dev/issue-1746
Transaction observers are not impacted by Task Cancellation
2025-03-22 13:43:07 +01:00
Gwendal Roué 67b34dc57c TransactionObserver can access the database, even if the transaction was completed in a cancelled task.
Fix https://github.com/groue/GRDB.swift/discussions/1746
2025-03-22 12:13:42 +01:00
Gwendal Roué 515bd78d28 Failing test for https://github.com/groue/GRDB.swift/discussions/1746 2025-03-22 12:12:12 +01:00
Gwendal Roué f2aa6b386f Improve the documentation for table recreation 2025-03-15 12:06:31 +01:00
Gwendal Roué 71e09a38d4 Document that migrations that rename foreign key columns should use immediate foreign key checks
Fix #1740
2025-03-15 12:06:14 +01:00
Gwendal Roué d800a79d5d Merge pull request #1745 from groue/dev/multi-argument-max
Add the MIN and MAX multi-argument SQL functions to the query interface
2025-03-15 11:32:20 +01:00
Gwendal Roué 4065ff58e8 Add the min and max multi-argument functions 2025-03-15 10:02:24 +01:00
Gwendal Roué 18eab53f74 Document aggregate functions 2025-03-15 09:51:32 +01:00
Gwendal Roué 6eba24d169 Merge branch 'development' 2025-02-23 19:53:59 +01:00
Gwendal Roué bd3ac9ef75 v7.3.0 2025-02-23 18:44:22 +01:00
Gwendal Roué 392137c357 XCTestExpectation is Sendable starting Xcode 16.3 beta 2025-02-23 18:43:45 +01:00
Gwendal Roué b48a56ae03 Revert "Merge pull request #1732 from groue/dev/sending-closures"
This reverts commit bbd1eab402, reversing
changes made to 9b09c5342e.
2025-02-23 18:43:45 +01:00
Gwendal Roué bbd1eab402 Merge pull request #1732 from groue/dev/sending-closures
Async database accesses no longer require Sendable closures.
2025-02-23 15:33:54 +01:00
Gwendal Roué 53c9d12d29 Async database access no longer require Sendable closures. 2025-02-23 15:16:36 +01:00
Gwendal Roué 9b09c5342e Merge pull request #1731 from groue/dev/virtual-table-options
Support for temporary virtual tables
2025-02-23 13:59:48 +01:00
Gwendal Roué aed22fe0bc Support for temporary virtual tables. 2025-02-23 13:45:46 +01:00
Gwendal Roué eec220b652 Merge pull request #1730 from groue/dev/issue-1728
Undeprecate Date coding strategies based on DateFormatter
2025-02-23 11:13:02 +01:00
Gwendal Roué 79a782038e Undeprecate Date coding strategies based on DateFormatter
https://github.com/swiftlang/swift/issues/78635#issuecomment-2676324549
> DateFormatter is indeed thread safe and its conformance to Sendable is correct
2025-02-23 11:12:24 +01:00
Gwendal Roué 618e72d153 Merge pull request #1729 from groue/dev/issue-1728
Deprecate Date coding strategies based on DateFormatter
2025-02-22 14:29:08 +01:00
Gwendal Roué 824100990f Deprecate Date coding strategies based on DateFormatter
Fix #1728
2025-02-22 13:45:42 +01:00
Gwendal Roué c7205b172f Merge branch 'development' 2025-02-12 08:49:02 +01:00
Gwendal Roué 49d14e6b66 v7.2.0 2025-02-12 08:48:52 +01:00
Gwendal Roué 54ed7ec611 Merge pull request #1719 from groue/dev/selectID
Select ids with selectID()
2025-02-12 08:46:40 +01:00
Gwendal Roué 68e17351ff CI: iPhone 15 Pro simulator is no longer available 2025-02-12 08:31:34 +01:00
Gwendal Roué 494e697e94 Warn against selectID() when the ID type is an optional. 2025-02-12 08:25:27 +01:00
Gwendal Roué 87b236dfe0 selectID
This reverts 7ffc332327

At the time, selectID was replaced with selectPrimaryKey(as:) because:

> 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??.

This problem is reintroduced, but we now recommend against optional ids in https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices. And record with optional ids can use selectPrimaryKey(as:).
2025-02-11 20:47:49 +01:00
Gwendal Roué ea6d8e0123 Merge branch 'development' 2025-02-05 15:34:18 +01:00
Gwendal Roué 073209f1dc v7.1.0 2025-02-05 15:34:09 +01:00
Gwendal Roué 430530f5f1 CHANGELOG 2025-02-05 14:08:28 +01:00
Gwendal Roué a716915280 Merge pull request #1717 from groue/dev/RxGRDB
Allow RxGRDB to compile without warning
2025-02-05 13:58:25 +01:00
Gwendal Roué ef36727d9a 🎵 Whatever Lola wants, Lola gets
Address https://github.com/RxSwiftCommunity/RxGRDB/issues/72

Based on https://github.com/swiftlang/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md#preconcurrency-attribute-on-nominal-declarations

See also https://www.massicotte.org/preconcurrency#working-with-swift-5

"Whatever Lola wants, Lola gets" because the Swift language is a blind and cruel mistress.
2025-02-05 13:38:19 +01:00
Gwendal Roué 78b2796f46 CHANGELOG 2025-02-05 08:00:29 +01:00
Gwendal Roué 3535a42c53 Merge pull request #1716 from groue/dev/issue-1715
Fix: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled.
2025-02-04 20:51:58 +01:00
Gwendal Roué 5a4d9b5cb9 Let PRAGMA QUERY_ONLY statements run from a cancelled database access
Fix #1715
2025-02-04 19:35:39 +01:00
Gwendal Roué a64b09d121 Failing test for #1715 2025-02-04 19:35:39 +01:00
Gwendal Roué 287c4be82d Merge pull request #1713 from groue/dev/sqliteLibVersionNumber
Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber`
2025-02-01 12:59:42 +01:00
Gwendal Roué 32c9ba24ba Replace sqlite3_libversion_number() with Database.sqliteLibVersionNumber
and remove SQLite imports that are no longer necessary.
2025-02-01 12:19:11 +01:00
Gwendal Roué 0401d449bb Database.sqliteLibVersionNumber 2025-02-01 12:01:41 +01:00
Gwendal Roué 4de97e6903 Merge branch 'development' 2025-01-26 16:30:56 +01:00
Gwendal Roué 676636bae4 7.0.0 2025-01-26 16:30:06 +01:00
Gwendal Roué 8e7cbf098f Fix Realm integration 2025-01-26 16:29:51 +01:00
Gwendal Roué 7250d759fe Fix generatePerformanceReport.rb script 2025-01-26 16:29:51 +01:00
Gwendal Roué fe7b9955b1 Upgrade performance tests dependencies 2025-01-26 16:29:51 +01:00
Gwendal Roué 6df8e2bd34 Fix casing of swiftpackageindex.com urls 2025-01-26 15:31:12 +01:00
Gwendal Roué 81cd33b71c CHANGELOG 2025-01-26 15:26:01 +01:00
Gwendal Roué 2e2c0eaec1 Merge pull request #1699 from groue/dev/jsonb
Support for JSONB expressions
2025-01-26 15:22:25 +01:00
Gwendal Roué ed17710694 Add tests of JSON_GROUP_ARRAY output, from both JSON and JSONB input 2025-01-26 14:44:27 +01:00
Gwendal Roué 0f68d8b684 JSON_VALID options 2025-01-26 14:21:35 +01:00
Gwendal Roué 367f8f7e37 Add missing imports for C SQLite functions 2025-01-26 14:21:35 +01:00
Gwendal Roué 831e79ee82 JSONB functions and tests 2025-01-26 14:21:35 +01:00
Gwendal Roué 8b3f9c0936 Prefer JSONB when building JSON 2025-01-26 14:21:35 +01:00
Gwendal Roué 950db13d46 Declare JSONB functions behavior 2025-01-26 14:21:35 +01:00
Gwendal Roué 0e664cf22e Not only pluralization can be a problem 2025-01-23 08:10:36 +01:00
Gwendal Roué 1e5602ca9d Merge pull request #1703 from groue/dev/inflections-fixes
Fix pluralization of Bias, Focus, Gas, and Lens
2025-01-22 21:29:31 +01:00
Gwendal Roué 8147811ab4 Mention Bias, Focus, Gas, and Lens in the GRDB 7 Migration Guide 2025-01-22 21:02:09 +01:00
Gwendal Roué 4c9b0eb90e Fix failing tests for inflections 2025-01-22 20:41:55 +01:00
Gwendal Roué b63d75da21 Failing tests for inflections
- bias/biases
- focus/focuses
- gas/gases
- lens/lenses
2025-01-22 20:41:39 +01:00
Gwendal Roué 5a3db29e21 Remove link to X account 2025-01-21 13:14:03 +01:00
Gwendal Roué fa0985eb01 Documentation: add @retroactive to Tagged extensions 2025-01-21 08:03:46 +01:00
Gwendal Roué 495e76bb1a Fix performance tests for SQLite.swift 2025-01-20 08:51:01 +01:00
Gwendal Roué bbf39353b5 Merge branch 'development' 2025-01-19 18:20:47 +01:00
Gwendal Roué 442b8b0589 7.0.0-beta.7 2025-01-19 17:30:17 +01:00
Gwendal Roué 2c85bc2cfc CHANGELOG 2025-01-19 16:57:34 +01:00
Gwendal Roué 3f56bc8199 Merge pull request #1700 from groue/dev/all-columns-excluding
Select all columns from a table, but a few ones
2025-01-19 16:50:48 +01:00
Gwendal Roué 37ea21eb96 Test AllColumnsExcluding and Table 2025-01-19 16:26:59 +01:00
Gwendal Roué 96c9eb5699 Enhance documentation of generated columns 2025-01-19 16:26:59 +01:00
Gwendal Roué 33103bb373 AllColumnsExcluding tests 2025-01-19 16:26:59 +01:00
Gwendal Roué 6b23181337 Use .allColumns and .rowID instead of AllColumns() and Column.rowID 2025-01-19 16:26:59 +01:00
Gwendal Roué c5366f4a01 AllColumnsExcluding documentation 2025-01-19 16:26:59 +01:00
Gwendal Roué a642ac51aa AllColumnsExcluding 2025-01-19 16:26:59 +01:00
Gwendal Roué d03208b33a Remove unused code 2025-01-19 16:26:59 +01:00
Gwendal Roué a4132a00db Clarify code that aims at fixing #1357 2025-01-19 16:26:59 +01:00
Gwendal Roué 61c7fdf81b Github CI: use tvOS 18.1 2025-01-19 16:26:29 +01:00
Gwendal Roué ec40855466 Merge pull request #1697 from kevinlg/fix-typo-in-docs
Fix typo in Readme.md
2025-01-09 07:23:43 +01:00
Kevin LE GOFF 1cca3686f5 Fix typo in Readme.md 2025-01-09 00:01:48 +02:00
Gwendal Roué 1e354ba79c Delete the rationale for Sendable records
... because the reality is that I just don't know how to relax this requirement.

See:

- https://www.youtube.com/watch?v=JmrnE7HUaDE
- https://forums.swift.org/t/swiftserverconf-feedback-on-leveraging-structured-concurrency-in-your-applications/75176
2025-01-02 17:07:55 +01:00
Gwendal Roué 0ea5471b56 Merge pull request #1696 from groue/dev/sqlite-3.47.2
Bump custom SQLite to 3.47.2
2025-01-02 12:57:50 +01:00
Gwendal Roué b2e808b9e4 Bump custom SQLite to 3.47.2 2025-01-02 12:28:14 +01:00
Gwendal Roué ac0c085a4a Merge pull request #1695 from JasonnnW3000/master
Update LICENSE, fix copyright license year
2025-01-01 12:25:30 +01:00
JasonnnW3000 9f9f0d37dd Update LICENSE, fix license year
Signed-off-by: JasonnnW3000 <sufssl04@gmail.com>
2024-12-31 23:58:47 -05:00
Gwendal Roué 898e7b6abe Merge pull request #1662 from compnerd/c
Core: import `ucrt` on Windows for `strcmp`
2024-11-13 16:11:39 +01:00
Gwendal Roué 0fb599812f Merge pull request #1661 from compnerd/extensions
Foundation: elide extensions on Windows to match Linux
2024-11-13 16:11:10 +01:00
Saleem Abdulrasool 77a4d17940 Core: import ucrt on Windows for strcmp
This uses the deprecated `strcmp` interface on Windows, which requires
the C library to be imported. Add the missing import to allow building
on Windows.
2024-11-12 11:12:27 -08:00
Saleem Abdulrasool c865a847fd Foundation: elide extensions on Windows to match Linux
Similar to Linux, elide some extensions on Windows. This is required to
build this module on Windows.
2024-11-12 11:10:07 -08:00
Gwendal Roué 832bc1aa74 Merge pull request #1660 from nylki/patch-1
docs: fixes typos "FST"->"FTS"
2024-11-11 11:50:35 +01:00
Tom Brewe 910ca2d0ce docs: fixes typos "FST"->"FTS" 2024-11-01 20:16:44 +01:00
Gwendal Roué 3ecb5c5455 Remove compiler warning in demo app 2024-10-22 08:18:38 +02:00
Gwendal Roué 84d25dfc9d Merge branch 'development' 2024-10-13 18:54:36 +02:00
Gwendal Roué 5664c5a829 7.0.0-beta.6 2024-10-13 18:54:10 +02:00
Gwendal Roué 334a63aa4a Update links to database schema documentation 2024-10-13 17:58:57 +02:00
Gwendal Roué 7e506f6488 Merge pull request #1654 from groue/dev/SQLite-3.46.1
Bump custom SQLite builds to 3.46.1
2024-10-13 17:52:53 +02:00
Gwendal Roué 5341f139e5 Update the Swift badge 2024-10-13 13:55:18 +02:00
Gwendal Roué 917b7ecc90 Bump custom SQLite to 3.46.1 2024-10-13 12:50:56 +02:00
Gwendal Roué c396fc20be Merge branch 'development' 2024-10-13 12:18:03 +02:00
Gwendal Roué 73083c4f1b 7.0.0-beta.5 2024-10-13 12:17:37 +02:00
Gwendal Roué 2c12f0a5e6 Merge pull request #1652 from groue/dev/schema-doc
Enhance the database schema documentation
2024-10-13 11:33:25 +02:00
Gwendal Roué c97f633022 More documentation of database schema methods 2024-10-13 11:28:14 +02:00
Gwendal Roué 4315030af5 More tests for object existence checks 2024-10-13 11:12:27 +02:00
Gwendal Roué 13b6c9d36b Split database schema documentation into several files, and restore the overview of database schema features
Fixes #1623
2024-10-13 10:54:13 +02:00
Gwendal Roué 8aaeb253d2 Merge pull request #1653 from Jnosh/schema-changes-readonly
Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections
2024-10-13 10:49:53 +02:00
Janosch Hildebrand a741fb38f0 Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections 2024-10-12 18:36:15 +02:00
Gwendal Roué 2c49a69f43 Raise a fatal error when the users filters a database view by primary key
Fixes #1648
2024-10-12 15:41:36 +02:00
Gwendal Roué d6b50b2c54 Merge branch 'development' 2024-10-12 14:04:05 +02:00
Gwendal Roué ad983f7971 7.0.0-beta.4 2024-10-12 14:03:56 +02:00
Gwendal Roué 7cd075bbdc Merge pull request #1651 from groue/dev/hasSchemaChanges
Allow applications to handle DatabaseMigrator schema changes.
2024-10-12 14:01:01 +02:00
Gwendal Roué 0aa8498620 DatabaseMigrator.hasSchemaChanges 2024-10-12 12:40:36 +02:00
Gwendal Roué bccf312af6 Merge branch 'development' 2024-10-06 18:49:34 +02:00
Gwendal Roué 5b4a86b5f7 7.0.0-beta.3 2024-10-06 18:42:03 +02:00
Gwendal Roué 68d12916e6 Fix Swiftlint warning 2024-10-06 18:36:43 +02:00
Gwendal Roué 6a4f454464 Merge pull request #1649 from bok-/master
Add `DatabaseValueConvertible` tip for JSON columns
2024-10-06 18:30:23 +02:00
Gwendal Roué a9fa2871aa Document the requirements 2024-10-06 18:19:11 +02:00
Rob Amos 8c5396898a Add DatabaseValueConvertible tip 2024-10-06 23:18:13 +11:00
Gwendal Roué dd14710c86 Fix typo 2024-10-06 13:55:29 +02:00
Gwendal Roué 97c0c72702 Merge pull request #1645 from philmitchell/coalesce
Add coalesce free function and Row method
2024-10-06 13:55:02 +02:00
Gwendal Roué a17d72e04c Make the top-level coalesce function work with collections of size zero and one. 2024-10-06 12:53:22 +02:00
Gwendal Roué 761b00f9bc Test Row.coalesce with collections of size zero and one. 2024-10-06 12:45:38 +02:00
Gwendal Roué ac3278a38b Test top-level function coalesce like other top-level functions 2024-10-06 12:42:33 +02:00
Gwendal Roué 06c3ab0d16 Test Row.coalesce on all variants of Row 2024-10-06 12:42:10 +02:00
Gwendal Roué f38619ada8 Restore alphabetical order of SQL functions 2024-10-06 12:42:10 +02:00
Gwendal Roué 8cac458efc Use "real" column names in examples.
Also, remove "essential".
2024-10-06 12:42:10 +02:00
Gwendal Roué a13c1bec29 Add coalesce in DocC 2024-10-06 12:19:49 +02:00
Gwendal Roué c6781f46d2 Prefer Collection over Array
This allows the user to call those methods with an Array, or any other collection at hand (including lazy ones)

This change makes `return coalesce(columns.lazy.map { $0.name })` iterate lazily. Before this commit, `map` was returning a non-lazy Array.
2024-10-06 12:19:49 +02:00
Gwendal Roué fd04831586 Merge pull request #1644 from tayloraswift/enable-linux-build
use #if directives to conditionally `@preconcurrency import `the `Dispatch` module to enable building the package on linux
2024-10-06 11:45:59 +02:00
Phil Mitchell d7754fa79c Add coalesce free function and Row method 2024-09-30 13:10:59 +10:00
Dianna 5f2185a118 use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux 2024-09-29 21:44:34 +00:00
Gwendal Roué dc03b8a29e Update links to GRDB7 documentation 2024-09-29 20:29:51 +02:00
Gwendal Roué a0c1de55c4 Enhance PlayerListModelTests 2024-09-29 17:10:05 +02:00
Gwendal Roué d1f5a37520 Enhance the demo app tests
Based on https://forums.swift.org/t/testing-closure-based-asynchronous-apis/73705/36
2024-09-29 15:46:18 +02:00
Gwendal Roué ed5f8c11ab 7.0.0-beta.2 2024-09-29 15:17:41 +02:00
Gwendal Roué afda0d1e7c Merge pull request #1643 from finestructure/patch-1
Update .spi.yml
2024-09-29 15:12:38 +02:00
Sven A. Schmidt 18c7f51a4e Update .spi.yml 2024-09-29 15:10:03 +02:00
Gwendal Roué a6b15684c3 Improve migration notes for ValueObservation 2024-09-29 13:27:07 +02:00
Gwendal Roué 9bdde6bc6f More links in GRDBDemo README 2024-09-29 13:04:36 +02:00
Gwendal Roué db9ef1bb27 Emphasize Swift concurrency recommendations in the migration guide 2024-09-29 12:12:57 +02:00
Gwendal Roué 2958020c69 De-emphasize the Record class in the migration guide 2024-09-29 12:10:26 +02:00
Gwendal Roué 895436a2a1 Mention companion libraries in the GRDB 7 migration guide 2024-09-29 12:07:34 +02:00
196 changed files with 14423 additions and 3991 deletions

No files matched your search

+2 -2
View File
@@ -46,11 +46,11 @@ jobs:
name: "macOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=iPhone 15 Pro"
destination: "OS=18.1,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.0,name=Apple TV"
destination: "OS=18.1,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
+1
View File
@@ -2,3 +2,4 @@ version: 1
builder:
configs:
- documentation_targets: [GRDB]
swift_version: 6.0
+146 -30
View File
@@ -7,7 +7,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.0.0` Betas - [7.0.0-beta](#700-beta)
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
- `7.5.x` Releases - [7.5.0](#750)
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
- `7.3.x` Releases - [7.3.0](#730)
- `7.2.x` Releases - [7.2.0](#720)
- `7.1.x` Releases - [7.1.0](#710)
- `7.0.x` Releases - [7.0.0](#700)
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
#### 6.x Releases
@@ -131,6 +138,115 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.6.1
Released July 23, 2025
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
## 7.6.0
Released July 20, 2025
- **New**: All closures that accept DatabaseComponents can throw by [@groue](https://github.com/groue) in [#1768](https://github.com/groue/GRDB.swift/pull/1768)
- **New**: Add Sendable conformance to DatabasePreUpdateEvent.Kind, matching DatabaseEvent.Kind by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1773](https://github.com/groue/GRDB.swift/pull/1773)
- **New**: Add custom build instruction for hardened runtime by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1776](https://github.com/groue/GRDB.swift/pull/1776)
- **New**: Access task locals from asynchronous database accesses by [@groue](https://github.com/groue) in [#1794](https://github.com/groue/GRDB.swift/pull/1794)
- **New**: Throwing row accessors by [@groue](https://github.com/groue) in [#1796](https://github.com/groue/GRDB.swift/pull/1796)
## 7.5.0
Released May 11, 2025
- **New**: Make it possible to create a raw FTS5Pattern without any database connection by [@groue](https://github.com/groue) in [#1764](https://github.com/groue/GRDB.swift/pull/1764)
- **New**: Build request with closures by [@groue](https://github.com/groue) in [#1759](https://github.com/groue/GRDB.swift/pull/1759)
## 7.4.1
Released March 28, 2025
- Removed a compiler warning
## 7.4.0
Released March 22, 2025
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
## 7.3.0
Released February 23, 2025
- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731)
- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730))
## 7.2.0
Released February 12, 2025
- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719)
## 7.1.0
Released February 5, 2025
- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713)
- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716)
- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717)
## 7.0.0
Released January 26, 2025
- **New**: Support for JSONB expressions by [@groue](https://github.com/groue) in [#1699](https://github.com/groue/GRDB.swift/pull/1699)
- **Breaking Change**: Fix inflections of Bias, Focus, Gas, and Lens by [@groue](https://github.com/groue) in [#1703](https://github.com/groue/GRDB.swift/pull/1703)
## 7.0.0-beta.7
Released January 19, 2025
- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700)
- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697)
- **New**: Bump custom SQLite to 3.47.2 by [@groue](https://github.com/groue) in [#1696](https://github.com/groue/GRDB.swift/pull/1696)
- **Fixed**: Update LICENSE, fix copyright license year by [@JasonnnW3000](https://github.com/JasonnnW3000) in [#1695](https://github.com/groue/GRDB.swift/pull/1695)
- **Fixed**: Core: import `ucrt` on Windows for `strcmp` by [@compnerd](https://github.com/compnerd) in [#1662](https://github.com/groue/GRDB.swift/pull/1662)
- **Fixed**: Foundation: elide extensions on Windows to match Linux by [@compnerd](https://github.com/compnerd) in [#1661](https://github.com/groue/GRDB.swift/pull/1661)
- **Fixed**: Docs: fixes typos "FST"->"FTS" by [@nylki](https://github.com/nylki) in [#1660](https://github.com/groue/GRDB.swift/pull/1660)
## 7.0.0-beta.6
Released October 13, 2024
- **New**: Bump custom SQLite builds to 3.46.1 by [@groue](https://github.com/groue) in [#1654](https://github.com/groue/GRDB.swift/pull/1654)
## 7.0.0-beta.5
Released October 13, 2024
- **Fixed**: Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections by [@Jnosh](https://github.com/Jnosh) in [#1653](https://github.com/groue/GRDB.swift/pull/1653)
- **Documentation Update**: Enhance the database schema documentation by [@groue](https://github.com/groue) in [#1652](https://github.com/groue/GRDB.swift/pull/1652)
## 7.0.0-beta.4
Released October 12, 2024
- **New**: Allow applications to handle DatabaseMigrator schema changes by [@groue](https://github.com/groue) in [#1651](https://github.com/groue/GRDB.swift/pull/1651)
## 7.0.0-beta.3
Released October 6, 2024
- **Fix**: use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux by [@tayloraswift](https://github.com/tayloraswift) in [#1644](https://github.com/groue/GRDB.swift/pull/1644)
- **New**: Add coalesce free function and Row method by [@philmitchell](https://github.com/philmitchell) in [#1645](https://github.com/groue/GRDB.swift/pull/1645)
- **Documentation Update**: Add `DatabaseValueConvertible` tip for JSON columns by [@bok-](https://github.com/bok-) in [#1649](https://github.com/groue/GRDB.swift/pull/1649)
## 7.0.0-beta.2
Released September 29, 2024
- **Fix**: Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643)
## 7.0.0-beta
Released September 29, 2024
@@ -139,11 +255,11 @@ Released September 29, 2024
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
- **Breaking Change**: Bump requirements by [@groue](https://github.com/groue) in [#1598](https://github.com/groue/GRDB.swift/pull/1598) and [#1634](https://github.com/groue/GRDB.swift/pull/1634)
- **Breaking Change**: Bump requirements by [@groue](https://github.com/groue) in [#1598](https://github.com/groue/GRDB.swift/pull/1598) and [#1634](https://github.com/groue/GRDB.swift/pull/1634)
- **Breaking Change**: Enhance ergonomics of record methods that insert/save/upsert and fetch by [@groue](https://github.com/groue) in [#1599](https://github.com/groue/GRDB.swift/pull/1599)
- **Breaking Change**: Rename the CSQLite module to GRDBSQLite, and stop exporting the C SQLite functions by [@groue](https://github.com/groue) in [#1600](https://github.com/groue/GRDB.swift/pull/1600)
- **Breaking Change**: Perform all writes with immediate transactions by default by [@groue](https://github.com/groue) in [#1602](https://github.com/groue/GRDB.swift/pull/1602)
@@ -198,8 +314,8 @@ Released July 11, 2024
Released April 21, 2024
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
## 6.26.0
@@ -224,7 +340,7 @@ Released February 25, 2024
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
@@ -251,7 +367,7 @@ Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
@@ -287,8 +403,8 @@ Released October 4, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compa
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
@@ -312,14 +428,14 @@ Released July 9, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasoneassociation)
## 6.15.1
@@ -336,7 +452,7 @@ Released June 2, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
## 6.14.0
@@ -371,7 +487,7 @@ Released April 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
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 [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
@@ -398,8 +514,8 @@ Released March 14, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
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:))
- [`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
@@ -408,9 +524,9 @@ Released March 12, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
- **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)
- [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
@@ -418,7 +534,7 @@ Released February 24, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/com
- **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.
- **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
@@ -429,7 +545,7 @@ Released February 19, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/com
- **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.
- **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
@@ -459,11 +575,11 @@ Released November 28, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/com
- **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**: 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
+1 -1
View File
@@ -1,4 +1,4 @@
Sharing a Database in an App Group Container
============================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing).
+134 -118
View File
@@ -58,15 +58,26 @@ GRDB Associations
Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book:
```swift
struct Author {
struct Author: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: Int64
var name: String
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
}
}
struct Book {
struct Book: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: Int64
var authorId: Int64?
var title: String
enum Columns {
static let id = Column(CodingKeys.id)
static let authorId = Column(CodingKeys.authorId)
static let title = Column(CodingKeys.title)
}
}
```
@@ -75,7 +86,7 @@ Now, suppose we wanted to load all books from an existing author. We'd need to d
```swift
let author: Author = ...
let books = try Book
.filter(Column("authorId") == author.id)
.filter { $0.authorId == author.id }
.fetchAll(db)
```
@@ -121,7 +132,7 @@ let books = try author.books.fetchAll(db)
As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*:
```swift
struct BookInfo: FetchableRecord, Decodable {
struct BookInfo: Decodable, FetchableRecord {
let book: Book
let author: Author?
}
@@ -130,7 +141,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. 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 ...`.
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
@@ -728,9 +739,15 @@ Your help is needed. You have to instruct GRDB which foreign key to use:
```swift
struct Book: TableRecord {
// Table columns
enum Columns {
static let authorId = Column("authorId")
static let translatorId = Column("translatorId")
}
// Define foreign keys
static let authorForeignKey = ForeignKey(["authorId"])
static let translatorForeignKey = ForeignKey(["translatorId"])
static let authorForeignKey = ForeignKey([Columns.authorId])
static let translatorForeignKey = ForeignKey([Columns.translatorId])
// Use foreign keys to define associations:
static let author = belongsTo(Person.self, using: authorForeignKey)
@@ -747,24 +764,11 @@ struct Person: TableRecord {
}
```
Foreign keys can also be defined from query interface columns:
```swift
struct Book: TableRecord {
enum Columns: String, ColumnExpression {
case id, title, authorId, translatorId
}
static let authorForeignKey = ForeignKey([Columns.authorId])
static let translatorForeignKey = ForeignKey([Columns.translatorId])
}
```
When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key:
```swift
struct Book: TableRecord {
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])
static let authorForeignKey = ForeignKey([Columns.authorId], to: [Person.Columns.id])
static let author = belongsTo(Person.self, using: authorForeignKey)
}
```
@@ -836,8 +840,8 @@ Requests for associated records can be filtered and ordered like all [query inte
```swift
let novels = try author
.books
.filter(Column("kind") == BookKind.novel)
.order(Column("publishDate").desc)
.filter { $0.kind == BookKind.novel }
.order(\.publishDate.desc)
.fetchAll(db) // [Book]
```
@@ -921,7 +925,7 @@ struct BookInfo: Decodable, FetchableRecord {
var author: PartialAuthor
}
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.including(required: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -935,7 +939,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("country")))
.annotated(withRequired: Book.author.select(\.country)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -982,7 +986,7 @@ struct BookInfo: Decodable, FetchableRecord {
var author: PartialAuthor?
}
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.including(optional: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -996,7 +1000,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("country")))
.annotated(withOptional: Book.author.select(\.country))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1064,7 +1068,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
var books: [PartialBook]
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.including(all: Author.books.select { [$0.title, $0.year] })
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
@@ -1079,7 +1083,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
}
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.select(\.title)
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
@@ -1093,7 +1097,7 @@ For example, fetch books along with the name and country of their author:
// 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")))
let request = Book.annotated(withRequired: Book.author.select { [$0.name, $0.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".
@@ -1108,7 +1112,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String // A column of the required associated record
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1122,7 +1126,7 @@ struct BookInfo: Decodable, FetchableRecord {
var authorName: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
.annotated(withRequired: Book.author.select { $0.name.forKey("authorName") })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1135,7 +1139,7 @@ For example, fetch books along with the name and country of their eventual autho
// 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")))
let request = Book.annotated(withOptional: Book.author.select { [$0.name, $0.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".
@@ -1150,7 +1154,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String? // A column of the optional associated record
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1164,7 +1168,7 @@ struct BookInfo: Decodable, FetchableRecord {
var authorName: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
.annotated(withOptional: Book.author.select { $0.name.forKey("authorName") })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1178,7 +1182,7 @@ For example, fetch books by French authors:
// FROM book
// JOIN author ON author.id = book.authorId
// AND author.country = 'France'
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
let request = Book.joining(required: Book.author.filter { $0.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".
@@ -1188,7 +1192,7 @@ To fetch results from such a request, you do not need to define a dedicated reco
```swift
// Fetch all books by French authors
let books = try Book
.joining(required: Book.author.filter(Column("country") == "France"))
.joining(required: Book.author.filter { $0.country == "France" })
.fetchAll(db)
```
@@ -1239,7 +1243,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.including(required: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1254,9 +1258,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.annotated(withRequired: Book.author.select {
[$0.name.forKey("authorName"), $0.country]
})
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1286,7 +1290,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.including(optional: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1301,9 +1305,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.annotated(withOptional: Book.author.select {
[$0.name.forKey("authorName"), $0.country]
})
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1333,7 +1337,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.including(all: Author.books.select { [$0.title, $0.year] })
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
@@ -1346,7 +1350,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.select(\.title)
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
@@ -1460,7 +1464,7 @@ The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys
// FROM book
// JOIN person ON person.id = book.authorId
// AND person.countryCode = 'FR'
let frenchAuthor = Book.author.filter(Column("countryCode") == "FR")
let frenchAuthor = Book.author.filter { $0.countryCode == "FR" }
let request = Book.joining(required: frenchAuthor)
// This request feeds the Book record:
@@ -1474,10 +1478,10 @@ The one below fetches all authors along with their novels and poems:
```swift
let request = Author
.including(all: Author.book
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.forKey("novels"))
.including(all: Author.book
.filter(Column("kind") == "poems")
.filter { $0.kind == "poems" }
.forKey("poems"))
// This request can feed the following record:
@@ -1508,7 +1512,7 @@ The `order()` method, that you already know for [sorting simple requests](../REA
// FROM book
// JOIN person ON person.id = book.authorId
// ORDER BY person.name
let sortedAuthor = Book.author.order(Column("name"))
let sortedAuthor = Book.author.order(\.name)
let request = Book.including(required: sortedAuthor)
```
@@ -1519,10 +1523,10 @@ When you sort both the base record and the associated record, the request is sor
// FROM book
// JOIN person ON person.id = book.authorId
// ORDER BY book.publishDate DESC, person.name
let sortedAuthor = Book.author.order(Column("name"))
let sortedAuthor = Book.author.order(\.name)
let request = Book
.including(required: sortedAuthor)
.order(Column("publishDate").desc)
.order(\.publishDate.desc)
```
**There are more sorting options:**
@@ -1559,7 +1563,7 @@ The `Team.players` association is ordered by position, so that all team players
```swift
extension Team {
static let players = hasMany(Player.self).order(Column("position"))
static let players = hasMany(Player.self).order(\.position)
var players: QueryInterfaceRequest<Player> {
request(for: Team.players)
@@ -1591,7 +1595,7 @@ Again, the `Team.players` association is ordered by position, so that all team p
```swift
extension Team {
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
static let playerRoles = hasMany(PlayerRole.self).order(\.position)
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
@@ -1623,9 +1627,9 @@ let teamInfos = try Team
// Custom ordering
let team: Team = ...
let players = try team.players.order(Column("name")).fetchAll(db)
let players = try team.players.order(\.name).fetchAll(db)
let teamInfos = try Team
.including(all: Team.players.order(Column("name")))
.including(all: Team.players.order(\.name))
.asRequest(of: TeamInfo.self)
.fetchAll(db)
```
@@ -1651,7 +1655,7 @@ To specify the selection in a specific request, use the `select` method:
// SELECT book.*, author.id, author.name
// FROM book
// JOIN author ON author.id = book.authorId
let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
let restrictedAuthor = Book.author.select { [$0.id, $0.name] }
let request = Book.including(required: restrictedAuthor)
```
@@ -1673,7 +1677,7 @@ Associations support more refinements:
}
let distinctBookKinds = Author.books
.select(Column("kind"))
.select(\.kind)
.distinct()
.forKey("bookKinds")
@@ -1699,10 +1703,8 @@ Associations support more refinements:
}
let bookKindInfos = Author.books
.select(
Column("kind"),
max(Column("year")).forKey("maxYear"))
.group(Column("kind"))
.select { [$0.kind, max($0.year).forKey("maxYear")] }
.group(\.kind)
.forKey("bookKindInfos")
let authorInfos: [AuthorInfo] = try Author
@@ -1772,7 +1774,7 @@ Let's first see a wrong way to do it:
// WHERE book.publishDate >= book.deathDate
let request = Book
.joining(required: Book.author)
.filter(Column("publishDate") >= Column("deathDate"))
.filter { $0.publishDate >= $0.deathDate }
```
When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate".
@@ -1782,21 +1784,35 @@ That is because the "deathDate" column has been used for filtering books, when i
To fix this error, we need a **table alias**:
```swift
let authorAlias = TableAlias()
let authorAlias = TableAlias<Author>()
```
We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed:
```swift
// SELECT book.*
// FROM book
// JOIN person ON person.id = book.authorId
// WHERE book.publishDate >= person.deathDate
// Swift 6.1
//
// > SELECT book.*
// > FROM book
// > JOIN person ON person.id = book.authorId
// > WHERE book.publishDate >= person.deathDate
let request = Book
.joining(required: Book.author.aliased(authorAlias))
.filter(Column("publishDate") >= authorAlias[Column("deathDate")])
.filter { $0.publishDate >= authorAlias.deathDate }
// Swift 6.0
//
// > SELECT book.*
// > FROM book
// > JOIN person ON person.id = book.authorId
// > WHERE book.publishDate >= person.deathDate
let request = Book
.joining(required: Book.author.aliased(authorAlias))
.filter { $0.publishDate >= authorAlias[Author.Columns.deathDate] }
```
Note that Swift 6.1 is required for the short syntac `alias.column`. From now on, we will only give examples in Swift 6.1.
**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first:
```swift
@@ -1806,7 +1822,7 @@ let request = Book
// ORDER BY person.name, book.publishDate
let request = Book
.joining(required: Book.author.aliased(authorAlias))
.order(authorAlias[Column("name")], Column("publishDate"))
.order { [authorAlias.name, $0.publishDate] }
```
**Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it:
@@ -1817,8 +1833,8 @@ let request = Book
// JOIN person a ON a.id = b.authorId
// AND a.countryCode = 'FR'
// WHERE b.publishDate >= a.deathDate
let bookAlias = TableAlias(name: "b")
let authorAlias = TableAlias(name: "a")
let bookAlias = TableAlias<Book>(name: "b")
let authorAlias = TableAlias<Person>(name: "a")
let request = Book.aliased(bookAlias)
.joining(required: Book.author.aliased(authorAlias)
.filter(sql: "a.countryCode = ?", arguments: ["FR"]))
@@ -1838,11 +1854,11 @@ let request = Book.aliased(bookAlias)
>
> ```swift
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
> let authorAlias = TableAlias()
> let authorAlias = TableAlias<Author>()
> let request = Author
> .aliased(authorAlias)
> .including(all: Author.books
> .filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
> .filter { $0.publishDate >= authorAlias.deathDate })
> ```
@@ -1904,7 +1920,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
extension DerivableRequest<Author> {
/// Filters authors by country
func filter(country: String) -> Self {
filter(Column("country") == country)
filter { $0.country == country }
}
}
@@ -1917,12 +1933,13 @@ extension DerivableRequest<Book> {
/// Order books by author name and then book title
func orderedByAuthorNameAndYear() -> Self {
let authorAlias = TableAlias()
let authorAlias = TableAlias<Author>()
return self
.joining(optional: Book.author.aliased(authorAlias))
.order(
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
Column("year"))
.order { [
authorAlias.name.collating(.localizedCaseInsensitiveCompare),
$0.year,
] }
}
}
```
@@ -2063,7 +2080,7 @@ Keys can also be customized with the `forKey` method:
```swift
extension Author {
static let novels = books
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.forKey("novels")
}
Author.including(all: Author.novels) // association key "novels"
@@ -2169,26 +2186,25 @@ struct BookInfo: FetchableRecord {
init(row: Row) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
coverImage = row["coverImage"]
author = try row.decode(forKey: "author")
country = try row.decodeIfPresent(forKey: "country")
coverImage = try row.decodeIfPresent(forKey: "coverImage")
}
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
```
You are already familiar with row subscripts to decode [database values](../README.md#column-values):
When you extract a record from a row, GRDB looks up the tree of **association keys**:
```swift
let name: String = row["name"]
let author = try row.decode(Author.self, forKey: "author")
```
When you extract a record instead of a value from a row, GRDB looks up the tree of **association keys**. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil:
If the key is not found, or only associated with columns that are all NULL, an optional record is decoded as nil:
```swift
let author: Author = row["author"]
let country: Country? = row["country"]
let country = try row.decodeIfPresent(Country.self, forKey: "country")
```
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
@@ -2204,7 +2220,7 @@ struct AuthorInfo: FetchableRecord {
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
books = try row.decode(forKey: "books")
}
}
@@ -2288,7 +2304,7 @@ let author: Author = ...
let bookCount = try author.books.fetchCount(db) // Int
// The year of the most recent book by this author
let request = author.books.select(max(yearColumn))
let request = author.books.select { max($0.year) }
let maxBookYear = try Int.fetchOne(db, request) // Int?
```
@@ -2359,7 +2375,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
// GROUP BY author.id
let request = Author.annotated(with:
Author.books.count,
Author.books.max(Column("year")))
Author.books.max(\.year))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
@@ -2376,13 +2392,13 @@ The default name is built from the aggregating method, the **[association key](#
| Method | Association Key | Aggregated Column | Aggregate name |
| ------ | --------------- | ----------------- | -------------- |
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
| `Author.books.count`. | `books` | - | `bookCount` |
| `Author.books.min(Column("year"))` | `books` | `year` | `minBookYear` |
| `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` ¹ |
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
| `Author.books.count`. | `books` | - | `bookCount` |
| `Author.books.min(\.year)` | `books` | `year` | `minBookYear` |
| `Author.books.max(\.year)` | `books` | `year` | `maxBookYear` |
| `Author.books.average(\.price)` | `books` | `price` | `averageBookPrice` |
| `Author.books.sum(\.awards)` | `books` | `awards` | `bookAwardsSum` |
| `Author.books.total((\.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.
@@ -2511,7 +2527,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
</details>
```swift
let request = Author.having(Author.books.max(Column("year")) >= 2010)
let request = Author.having(Author.books.max(\.year) >= 2010)
```
- Authors who wrote at least one book of kind "novel":
@@ -2530,7 +2546,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
</details>
```swift
let novels = Author.books.filter(Column("kind") == "novel")
let novels = Author.books.filter { $0.kind == "novel" }
let request = Author.having(novels.isEmpty == false)
```
@@ -2616,7 +2632,7 @@ Aggregates can be modified and combined with Swift operators:
</details>
```swift
let request = Author.having(Author.books.max(Column("year")) >= 2010)
let request = Author.having(Author.books.max(\.year) >= 2010)
```
- Arithmetic operators `+`, `-`, `*`, `/`
@@ -2656,7 +2672,7 @@ Aggregates can be modified and combined with Swift operators:
</details>
```swift
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
let request = Team.annotated(with: Team.players.min(\.score) ?? 0)
```
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
@@ -2674,7 +2690,7 @@ Aggregates can be modified and combined with Swift operators:
</details>
```swift
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
let request = Team.annotated(with: abs(Team.players.max(\.score)))
```
### Isolation of Multiple Aggregates
@@ -2711,8 +2727,8 @@ In the example below, we use compute two aggregates from the same association `A
}
let request = Author.annotated(with:
Author.books.min(Column("year")), // association key "books"
Author.books.max(Column("year"))) // association key "books"
Author.books.min(\.year), // association key "books"
Author.books.max(\.year)) // association key "books"
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
@@ -2782,11 +2798,11 @@ But in the following example, we use the same association `Author.books` twice,
}
let novelCount = Author.books
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.forKey("novels") // association key "novels"
.count
let theatrePlayCount = Author.books
.filter(Column("kind") == "theatrePlay")
.filter { $0.kind == "theatrePlay" }
.forKey("theatrePlays") // association key "theatrePlays"
.count
let request = Author.annotated(with: novelCount, theatrePlayCount)
@@ -2813,11 +2829,11 @@ But in the following example, we use the same association `Author.books` twice,
```swift
// WRONG: not counting distinct sets of associated books
let novelCount = Author.books // association key "books"
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.count
.forKey("novelCount")
let theatrePlayCount = Author.books // association key "books"
.filter(Column("kind") == "theatrePlay")
.filter { $0.kind == "theatrePlay" }
.count
.forKey("theatrePlayCount")
let request = Author.annotated(with: novelCount, theatrePlayCount)
@@ -2847,11 +2863,11 @@ Those methods are defined on extensions to the `DerivableRequest` protocol:
```swift
extension DerivableRequest<Author> {
func filter(country: String) -> Self {
filter(Column("country") == country)
filter { $0.country == country }
}
func orderedByName() -> Self {
order(Column("name").collating(.localizedCaseInsensitiveCompare))
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
}
}
@@ -2882,11 +2898,11 @@ See [Recommended Practices for Designing Record Types] for more information.
```swift
// NOT IMPLEMENTED: loading all authors along with their posthumous books
let authorAlias = TableAlias()
let authorAlias = TableAlias<Author>()
let request = Author
.aliased(authorAlias)
.including(all: Author.books
.filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
.filter { $0.publishDate >= authorAlias.deathDate })
```
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**:
@@ -2963,7 +2979,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[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
@@ -2998,16 +3014,16 @@ 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]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
[Row Adapters]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter
[query interface requests]: ../README.md#requests
[TableRecord]: ../README.md#tablerecord-protocol
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices
[regular aggregating methods]: ../README.md#fetching-aggregated-values
[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]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[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
+12 -12
View File
@@ -226,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()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
- 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 [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
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:
@@ -332,7 +332,7 @@ let hallOfFamePublisher = ValueObservation
// 2nd request
let bestPlayers = try Player
.order(Column("score").desc)
.order(\.score.desc)
.limit(10)
.fetchAll(db)
@@ -358,7 +358,7 @@ let totalPlayerCountPublisher = ValueObservation
// OK
let bestPlayerPublisher = ValueObservation
.tracking(Player
.order(Column("score").desc)
.order(\.score.desc)
.limit(10)
.fetchAll)
.publisher(in: dbQueue)
@@ -382,23 +382,23 @@ let cancellable = hallOfFamePublisher.sink(
[Usage]: #usage
[Asynchronous Database Access]: #asynchronous-database-access
[Combine]: https://developer.apple.com/documentation/combine
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[Database Changes Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
[Database Observation]: #database-observation
[Combine and Data Consistency]: #combine-and-data-consistency
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
[SQLite]: http://sqlite.org
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
[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:)
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
[configured]: ../README.md#databasepool-configuration
[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
[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
+16 -10
View File
@@ -31,7 +31,7 @@ The CTE request can be provided as a [query interface request]:
// WITH playerName AS (SELECT name FROM player) ...
let playerNameCTE = CommonTableExpression(
named: "playerName",
request: Player.select(Column("name")))
request: Player.select(\.name))
```
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
@@ -123,7 +123,7 @@ And we can then filter the `player` table with a subquery:
// WHERE name = (SELECT * FROM playerName)
let request = Player
.with(playerNameCTE)
.filter(Column("name") == playerNameCTE.all())
.filter { $0.name == playerNameCTE.all() }
```
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
@@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele
// UPDATE player SET name = (SELECT * FROM playerName)
try Player
.with(playerNameCTE)
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
.updateAll(db) { $0.name.set(to: playerNameCTE.all()) }
// WITH playerName AS (SELECT 'O''Brien')
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
try Player
.with(playerNameCTE)
.filter(Column("name") == playerNameCTE.all())
.filter { $0.name == playerNameCTE.all() }
.deleteAll(db)
```
@@ -281,9 +281,15 @@ struct Chat: Codable, FetchableRecord, PersistableRecord {
}
struct Message: Codable, FetchableRecord, PersistableRecord {
var chatID: Int64
var chatId: Int64
var date: Date
...
enum Columns {
static let chatId = Column("chatId")
static let date = Column("date")
...
}
}
```
@@ -315,8 +321,8 @@ We start by defining the CTE request, which loads the latest messages of all cha
```swift
// SELECT *, MAX(date) FROM message GROUP BY chatID
let latestMessageRequest = Message
.annotated(with: max(Column("date")))
.group(Column("chatID"))
.annotated { max($0.date) }
.group(\.chatId)
```
We can now define the CTE for the latest messages:
@@ -324,7 +330,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(
let latestMessageCTE = CommonTableExpression<Message>(
named: "latestMessage",
request: latestMessageRequest)
```
@@ -337,9 +343,9 @@ The association from a chat to its latest message follows:
let latestMessage = Chat.association(
to: latestMessageCTE,
on: { chat, latestMessage in
chat[Column("id")] == latestMessage[Column("chatID")]
chat.id == latestMessage.chatId
})
.order(Column("date").desc)
.order(\.date.desc)
```
The final request can now be defined:
+1 -1
View File
@@ -1,4 +1,4 @@
:twisted_rightwards_arrows: Concurrency
=======================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
+35 -29
View File
@@ -3,56 +3,58 @@ 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.44.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.47.2](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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
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.
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB git repository, checkout the latest tagged version:
```sh
cd [GRDB directory]
git checkout [latest tag]
git submodule update --init SQLiteCustom/src
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
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).
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.
4. Create four files in the `GRDBCustomSQLite` folder:
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is one space between -D and the option name.
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
```c
// As many #define as there are custom SQLite compilation options
#define SQLITE_ENABLE_SNAPSHOT
#define SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
```sh
# License: MIT License
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
@@ -61,52 +63,52 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
# PROJECT PATHS
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
#######################################################
# The path to the folder containing GRDBCustom.xcodeproj:
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
# The path to your custom "SQLiteLib-USER.xcconfig":
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
# The path to your custom "GRDBCustomSQLite-USER.h":
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
#######################################################
#
#######################################################
if [ ! -d "$GRDB_SOURCE_PATH" ];
then
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
exit 1
fi
SyncFileChanges () {
SOURCE=$1
DESTINATIONPATH=$2
DESTINATIONFILENAME=$3
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
if [ ! -f "$SOURCE" ];
then
echo "error: Source file missing: $SOURCE"
exit 1
fi
rsync -a "$SOURCE" "$DESTINATION"
}
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
echo "Finished syncing"
```
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
@@ -116,17 +118,21 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
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**:
```sh
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
```
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
Select your application target in the "Provide build settings from" menu.
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
(The build error without this exception is "Library not loaded ... different Team IDs")
Now you can use GRDB with your custom SQLite build:
```swift
@@ -12,10 +12,10 @@ import os.log
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
final class AppDatabase: Sendable {
struct AppDatabase: Sendable {
/// Access to the database.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
/// Creates a `AppDatabase`, and makes sure the database schema
@@ -30,19 +30,19 @@ final class AppDatabase: Sendable {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
/// 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#The-eraseDatabaseOnSchemaChange-Option>
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations#The-eraseDatabaseOnSchemaChange-Option>
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("v1") { db in
// Create a table
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
// 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()
@@ -67,20 +67,17 @@ extension AppDatabase {
/// Returns a database configuration suited for `AppDatabase`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
/// - parameter config: A base configuration.
static func makeConfiguration(_ config: Configuration = Configuration()) -> Configuration {
// var config = config
//
// Add custom SQL functions or collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
//
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/trace(options:_:)>
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
// config.prepareDatabase { db in
// let dbName = db.description
@@ -96,7 +93,7 @@ extension AppDatabase {
// #if DEBUG
// // Protect sensitive information by enabling verbose debugging in
// // DEBUG builds only.
// // See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
// // See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/publicstatementarguments>
// config.publicStatementArguments = true
// #endif
@@ -133,7 +130,7 @@ extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() async throws {
try await dbWriter.write { [self] db in
try await dbWriter.write { db in
if try Player.all().isEmpty(db) {
// When database is empty, insert new random players
try createRandomPlayers(db)
@@ -64,45 +64,3 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
id = inserted.rowID
}
}
// Convenience access to player columns in this file
private typealias Columns = Player.Columns
// 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(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(
Columns.score.desc,
Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -8,7 +8,7 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
// <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
@@ -47,7 +47,7 @@ extension AppDatabase {
/// 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
// See https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -41,9 +41,16 @@ import GRDB
let observation = ValueObservation.tracking { [ordering] db in
switch ordering {
case .byName:
try Player.all().orderedByName().fetchAll(db)
try Player
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
.fetchAll(db)
case .byScore:
try Player.all().orderedByScore().fetchAll(db)
try Player
.order { [
$0.score.desc,
$0.name.collating(.localizedCaseInsensitiveCompare),
] }
.fetchAll(db)
}
}
@@ -6,41 +6,36 @@ struct PlayerListModelTests {
// MARK: - PlayerListModel.observePlayers tests
@Test(.timeLimit(.minutes(1)))
@MainActor func observation_started_after_player_creation() async throws {
// Given a PlayerListModel on a database that contains a player
@MainActor func observation_grabs_current_database_state() async throws {
// Given a PlayerListModel on a database that contains one player
let appDatabase = try makeEmptyTestDatabase()
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
let model = PlayerListModel(appDatabase: appDatabase)
// When we start observing the database
// When the model starts observing the database
model.observePlayers()
// Then the model eventually fetches the player.
// We poll because we do not know when the model will update its players.
await pollUntil {
model.players.isEmpty == false
}
#expect(model.players == [player])
// Then the model eventually has one player.
try await pollUntil { model.players.count == 1 }
}
@Test(.timeLimit(.minutes(1)))
@MainActor func observation_started_before_player_creation() async throws {
// Given a PlayerListModel that observes a empty database
@MainActor func observation_grabs_database_changes() async throws {
// Given a PlayerListModel that has one player
let appDatabase = try makeEmptyTestDatabase()
var player1 = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player1)
let model = PlayerListModel(appDatabase: appDatabase)
model.observePlayers()
try await pollUntil { model.players.count == 1 }
// When we insert a player
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
// When we insert a second player
var player2 = Player(name: "Barbara", score: 800)
try appDatabase.savePlayer(&player2)
// Then the model eventually fetches the player.
// We poll because we do not know when the model will update its players.
await pollUntil {
model.players.isEmpty == false
}
#expect(model.players == [player])
// Then the model eventually has two players.
try await pollUntil { model.players.count == 2 }
}
@Test
@@ -68,14 +63,14 @@ struct PlayerListModelTests {
}
/// Convenience method that loops until a condition is met.
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async {
await confirmation { confirmation in
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async throws {
try await confirmation { confirmation in
while true {
if await condition() {
confirmation()
return
} else {
await Task.yield()
try await Task.sleep(for: .seconds(0.01))
}
}
}
+14 -4
View File
@@ -11,8 +11,8 @@ 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](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 track database changes and animate a SwiftUI List with [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:**
@@ -23,7 +23,9 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBDemo/Database/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, and provides methods that read and write.
`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, and provides methods that read and write.
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
- [Persistence.swift](GRDBDemo/Database/Persistence.swift)
@@ -33,4 +35,12 @@ The topics covered in this demo are:
`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).
- [GRDBDemoTests](GRDBDemoTests)
- [PlayerListModel.swift](GRDBDemo/Views/PlayerListModel.swift)
`PlayerListModel` is an `@Observable` object that observes the database, displays always fresh values on screen, and performs actions.
`PlayerListModel` is [tested](GRDBDemoTests/PlayerListModelTests.swift).
- [PlayersNavigationView.swift](GRDBDemo/Views/PlayersNavigationView.swift)
`PlayersNavigationView` is the main navigation view of the application. It instantiates a `PlayerListModel` from the `AppDatabase` stored in the SwiftUI environment.
+2 -2
View File
@@ -3,7 +3,7 @@ FTS5 Tokenizers
**[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.**
GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
- Have "fi" match the ligature "&#xfb01;" (U+FB01)
- Have "first" match "1st"
@@ -95,7 +95,7 @@ let documents = try Document.matching(pattern).fetchAll(db)
## FTS5Tokenizer
**FST5Tokenizer** is the protocol for all FTS5 tokenizers.
**FTS5Tokenizer** is the protocol for all FTS5 tokenizers.
It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers.
+1 -1
View File
@@ -2,4 +2,4 @@
FetchedRecordsController has been removed in GRDB 5.
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
+8 -8
View File
@@ -82,7 +82,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
- See [FTS3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
@@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
**FTS3 and FTS4 full-text tables store and index textual content.**
Create tables with the `create(virtualTable:using:)` method:
Create tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts3(content)
@@ -301,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface):
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
```
@@ -326,7 +326,7 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
Create FTS5 tables with the `create(virtualTable:using:)` method:
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts5(content)
@@ -550,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface):
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
```
@@ -689,7 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
**You can define [record](../README.md#records) types around the full-text virtual tables.**
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) for more information.
## Unicode Full-Text Gotchas
+4 -4
View File
@@ -501,10 +501,10 @@ let publisher = observation
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()
[removeDuplicates]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()
[Custom SQL functions]: ../README.md#custom-sql-functions
[Batch updates]: ../README.md#update-requests
[SQL Interpolation]: SQLInterpolation.md
@@ -512,4 +512,4 @@ let publisher = observation
[SQLRequest]: ../README.md#custom-requests
[QueryInterfaceRequest]: ../README.md#requests
[Combine publishers]: Combine.md
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[Database Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
+1 -1
View File
@@ -195,7 +195,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
To help you update your applications with persistence callbacks, let's look at two examples.
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
Next, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
+141 -47
View File
@@ -4,24 +4,33 @@ Migrating From GRDB 6 to GRDB 7
**This guide helps you upgrade your applications from GRDB 6 to GRDB 7.**
- [Preparing the Migration to GRDB 7](#preparing-the-migration-to-grdb-7)
- [Recommendations Regarding Swift Concurrency](#recommendations-regarding-swift-concurrency)
- [New requirements](#new-requirements)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
- [Companion Libraries](#companion-libraries)
- [Column Coding Strategies](#column-coding-strategies)
- [Cancellable Async Database Accesses](#cancellable-async-database-accesses)
- [Default Transaction Kind](#default-transaction-kind)
- [Associations to record types named Bias, Focus, Gas, and Lens](#associations-to-record-types-named-bias-focus-gas-and-lens)
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
- [Recommendations Regarding Swift Concurrency](#recommendations-regarding-swift-concurrency)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
- [Other Changes](#other-changes)
## Preparing the Migration to GRDB 7
Before upgrading, ensure you are using the [latest GRDB 6 release](https://github.com/groue/GRDB.swift/tags) and address any deprecation warnings. Once this is done, proceed with upgrading to GRDB 7. Due to breaking changes, your application may no longer compile. Follow the fix-it suggestions for simple syntax updates, and review the specific modifications described below.
## Recommendations Regarding Swift Concurrency
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
Depending of the language mode and level of concurrency checkings used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
## New requirements
GRDB requirements have been bumped:
- **Swift Compiler 6+** (was Swift 5.7+). Both Swift 5 and Swift 6 language modes are supported. For more information, see the [Migrating to Swift 6] Apple guide.
- **Swift Compiler 6+** (was Swift 5.7+).
- **Xcode 16.0+** (was Xcode 14.0+)
- **iOS 13+** (was iOS 11+)
- **macOS 10.15+** (was macOS 10.13+)
@@ -29,41 +38,12 @@ GRDB requirements have been bumped:
- **watchOS 7.0+** (was watchOS 4+)
- **SQLite 3.20.0+** (was SQLite 3.19.3+)
## The Record Base Class is Discouraged
## Companion Libraries
The usage of the [Record] base class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
Companion libraries have been updated for GRDB 7:
It is not recommended to define any new type that subclass `Record`.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
For example:
```swift
// GRDB 6
class Player: Record {
var id: UUID
var name: String
var score: Int
override class var databaseTableName: String { "player" }
init(id: UUID, name: String, score: Int) { ... }
required init(row: Row) throws { ... }
override func encode(to container: inout PersistenceContainer) throws { ...}
}
// GRDB 7
struct Player: Codable {
var id: UUID
var name: String
var score: Int
}
extension Player: FetchableRecord, PersistableRecord { }
```
Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non-Sendable record types in GRDB.
- [GRDBQuery releases](https://github.com/groue/GRDBQuery/releases) (SwiftUI)
- [GRDBSnapshotTesting releases](https://github.com/groue/GRDBSnapshotTesting/releases) (Snapshot Testing)
## Column Coding Strategies
@@ -117,6 +97,53 @@ try await task.value
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
## Associations to record types named Bias, Focus, Gas, and Lens
GRDB 7 has fixed its singularization and pluralization rules for database tables named "bias", "focus", "gas", and "lens".
If your application defines associations to those tables, you can now rely on proper inflections (pluralization and singularization).
With GRDB 7, you can remove custom association keys:
```swift
struct Camera: TableRecord {
// GRDB 6: fix incorrect GRDB inflection
static let lenses = hasMany(Lens.self).forKey("lenses")
// GRDB 7
static let lenses = hasMany(Lens.self)
}
```
If your application was not specifying custom association keys in order to fix the wrong inflections, then it may define types that will no longer decode their properties as intended:
```swift
// Works in GRDB 6, breaks in GRDB 7
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lens: [Lens] // <- incorrect pluralization
}
let results = Camera
.including(all: Camera.lenses)
.asRequest(of: CameraWithLenses.self)
.fetchAll(db)
```
There are two possible solutions. One is to rename properties, the other is to keep on using the wrong inflection (it's your call):
```swift
// GRDB 7, alternative 1
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lenses: [Lens] // <- fixed pluralization
}
// GRDB 7, alternative 2
struct Camera: TableRecord {
// Use "lens" instead of "lenses" for GRDB 6 compatibility.
static let lenses = hasMany(Lens.self).forKey("lens")
}
```
## Default Transaction Kind
Some applications specify a default transaction kind, which was previously recommended in the [Sharing a Database] guide:
@@ -131,6 +158,46 @@ In GRDB 7, `Configuration` no longer has a `defaultTransactionKind` property, be
You can still specify a transaction kind explicitly when necessary. See [Transaction Kinds] for details.
## ValueObservation and the Main Actor
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
```swift
// GRDB 7
@MainActor func startObservation() {
let observation = ValueObservation.tracking { ... }
let cancellable = observation.start(in: dbQueue) { error in
// This closure is MainActor-isolated.
} onChange: { value in
// This closure is MainActor-isolated.
print("Fresh value", value)
}
}
```
You can opt-out of the main actor with a specific scheduler such as `.async(onQueue:)`:
```swift
func startObservation() {
let observation = ValueObservation.tracking { ... }
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main))
{ error in
// Called on the specified dispatch queue.
} onChange: { value in
// Called on the specified dispatch queue.
print("Fresh value", value)
}
}
```
## Access to SQLite C functions
In GRDB 6, the underlying C SQLite library is implicitly available:
@@ -164,25 +231,52 @@ In GRDB 7, you may need an additional import, depending on how GRDB is integrate
- In other cases, no additional import is needed.
## Recommendations Regarding Swift Concurrency
## The Record Base Class is Discouraged
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
Depending of the language mode and level of concurrency checkings used by your application (see [Migrating to Swift 6]), you may see warnings or errors. We address those issues, and provide general guidance, in [Swift Concurrency and GRDB].
It is not recommended to define any new type that subclass `Record`.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
For example:
```swift
// GRDB 6
class Player: Record {
var id: UUID
var name: String
var score: Int
override class var databaseTableName: String { "player" }
init(id: UUID, name: String, score: Int) { ... }
required init(row: Row) throws { ... }
override func encode(to container: inout PersistenceContainer) throws { ...}
}
// GRDB 7
struct Player: Codable {
var id: UUID
var name: String
var score: Int
}
extension Player: FetchableRecord, PersistableRecord { }
```
Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non-Sendable record types in GRDB.
## Other Changes
- `ValueObservation` must be started from the Main Actor by default. Use an explicit `async(onQueue: .main)` scheduling in order to remove this constraint.
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/record
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record
@@ -1,4 +1,4 @@
Good Practices for Designing Record Types
=========================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
+1 -1
View File
@@ -1,3 +1,3 @@
# Migrations
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations).
@@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in
CREATE TABLE place (
id INTEGER PRIMARY KEY,
title TEXT,
favorite BOOLEAN NOT NULL,
isFavorite BOOLEAN NOT NULL,
latitude DOUBLE NOT NULL,
longitude DOUBLE NOT NULL
)
""")
try db.execute(sql: """
INSERT INTO place (title, favorite, latitude, longitude)
INSERT INTO place (title, isFavorite, latitude, longitude)
VALUES (?, ?, ?, ?)
""", arguments: ["Paris", true, 48.85341, 2.3488])
let parisId = db.lastInsertedRowID
@@ -52,11 +52,11 @@ try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
while let row = try rows.next() {
let title: String = row["title"]
let favorite: Bool = row["favorite"]
let isFavorite: Bool = row["isFavorite"]
let coordinate = CLLocationCoordinate2D(
latitude: row["latitude"],
longitude: row["longitude"])
print("Fetched", title, favorite, coordinate)
print("Fetched", title, isFavorite, coordinate)
}
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
@@ -69,35 +69,43 @@ try! dbQueue.inDatabase { db in
struct Place {
var id: Int64?
var title: String?
var favorite: Bool
var isFavorite: Bool
var coordinate: CLLocationCoordinate2D
}
// Adopt FetchableRecord
extension Place : FetchableRecord {
init(row: Row) {
id = row["id"]
title = row["title"]
favorite = row["favorite"]
id = row[Columns.id]
title = row[Columns.title]
isFavorite = row[Columns.isFavorite]
coordinate = CLLocationCoordinate2DMake(
row["latitude"],
row["longitude"])
row[Columns.latitude],
row[Columns.longitude])
}
}
// Adopt TableRecord
extension Place : TableRecord {
static let databaseTableName = "place"
enum Columns {
static let id = Column("id")
static let title = Column("title")
static let isFavorite = Column("isFavorite")
static let latitude = Column("latitude")
static let longitude = Column("longitude")
}
}
// Adopt MutablePersistableRecord
extension Place : MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) throws {
container["id"] = id
container["title"] = title
container["favorite"] = favorite
container["latitude"] = coordinate.latitude
container["longitude"] = coordinate.longitude
container[Columns.id] = id
container[Columns.title] = title
container[Columns.isFavorite] = isFavorite
container[Columns.latitude] = coordinate.latitude
container[Columns.longitude] = coordinate.longitude
}
mutating func didInsert(_ inserted: InsertionSuccess) {
@@ -109,13 +117,13 @@ try dbQueue.inDatabase { db in
var berlin = Place(
id: nil,
title: "Berlin",
favorite: false,
isFavorite: false,
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
try berlin.insert(db)
berlin.id // some value
berlin.favorite = true
berlin.isFavorite = true
try berlin.update(db)
// Fetch from SQL
@@ -124,13 +132,10 @@ try dbQueue.inDatabase { db in
//: Avoid SQL with the query interface:
let title = Column("title")
let favorite = Column("favorite")
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
let paris = try Place.fetchOne(db, key: 1) // Place?
let favoritePlaces = try Place // [Place]
.filter(favorite == true)
.order(title)
.filter { $0.isFavorite == true }
.order { $0.title }
.fetchAll(db)
}
+14 -13
View File
@@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties:
ValueObservation.tracking { db in
try Player.fetchOne(db, id: 1)
// or
try Player.filter(Column("id") == 1).fetchOne(db)
try Player.filter { $0.id == 1 }.fetchOne(db)
}
// Non-optimized observations
@@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties:
// Nicer SQL
// SELECT * FROM player WHERE id = 1
try Player.fetchOne(db, id: 1)
try Player.filter(Column("id") == 1).fetchOne(db)
try Player.filter { $0.id == 1 }.fetchOne(db)
// Less nice SQL
// SELECT * FROM player WHERE id = 1 LIMIT 1
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
### FetchRequest
@@ -261,7 +261,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
// ~~~~~~~~~~
Player.filter(Column("name") == "O'Brien")
Player.filter { $0.name == "O'Brien" }
```
### QueryInterfaceRequest
@@ -346,8 +346,9 @@ Functions and methods that build an SQL expression should return an SQLExpressio
```swift
// SELECT * FROM player WHERE LENGTH(name) > 0
let expression = length(Column("name")) > 0 // SQLExpression
Player.filter(expression)
Player.filter {
length($0.name) > 0 // SQLExpression
}
```
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
@@ -358,7 +359,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression {
}
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
```
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
@@ -368,7 +369,7 @@ This technique, based on [SQL Interpolation], is composable and works well even
// JOIN team ON team.id = player.teamId
// WHERE DATE(player.createdAt) = '2020-01-23'
let request = Player
.filter(date(Column("createdAt")) == "2020-01-23")
.filter { date($0.createdAt) == "2020-01-23" }
.including(required: Player.team)
```
@@ -497,7 +498,7 @@ protocol SQLSelectable {
SQLSelectable feeds the `select()` method of the query interface:
```swift
Player.select(AllColumns())
Player.select(.allColumns)
Player.select(Column("name"), Column("score"))
```
@@ -505,7 +506,7 @@ All [SQLSpecificExpressible] values are selectable. Other selectable values are:
```swift
// SELECT * FROM player
Player.select(AllColumns())
Player.select(.allColumns)
// SELECT MAX(score) AS maxScore FROM player
Player.select(max(Column("score")).forKey("maxScore"))
@@ -583,7 +584,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres
// SELECT * FROM player
// WHERE score >= (SELECT AVG(score) FROM player)
let averageScore = Player.select(average(Column("score")))
Player.filter(Column("score") >= averageScore)
Player.filter { $0.score >= averageScore }
```
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
@@ -607,8 +608,8 @@ myRequest(Player.select(...).filter(...))
[association aggregates]: AssociationsBasics.md#association-aggregates
[Column]: #column
[ColumnExpression]: #columnexpression
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionconvertible
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[DatabaseValue]: #databasevalue
[DatabaseValueConvertible]: #databasevalueconvertible
[DerivableRequest]: #derivablerequest
+2 -2
View File
@@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression {
SQL("DATE(\(expression))").sqlExpression
}
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
```
@@ -365,7 +365,7 @@ Let's extend Player with database methods.
This chapter lists all kinds of supported interpolations.
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table) instances:
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/table) instances:
```swift
struct Player: TableRecord { ... }
+1 -1
View File
@@ -1,4 +1,4 @@
Sharing a Database
==================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing).
+1 -1
View File
@@ -1,4 +1,4 @@
Single-Row Tables
=================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables).
+10 -10
View File
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
### Allow database records to cross threads
@@ -149,16 +149,16 @@ Next, you choose the dispatch queue on which notifications happen (generally the
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information.
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for further information.
### Non-blocking database reads
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
[Database pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
### Strong and clear multi-threading guarantees
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
For detailed information about GRDB concurrency, check the [Concurrency Guide].
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
### Never pay for using raw SQL
@@ -207,13 +207,13 @@ try player.updateChanges {
// SELECT * FROM player ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
.order(\.score.desc)
.limit(10)
.fetchAll(db)
// SELECT MAX(score) FROM player
let maximumScore: Int? = try Player
.select(max(scoreColumn))
.select { max($0.score) }
.asRequestOf(Int.self)
.fetchOne(db)
@@ -285,12 +285,12 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB]
Happy GRDB! :gift:
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[Concurrency Guide]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency
[Core Data]: https://developer.apple.com/documentation/coredata
[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[DatabasePool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
[Diesel]: http://diesel.rs
[FCModel]: https://github.com/marcoarment/FCModel
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
[Fluent]: https://github.com/vapor/fluent
[FMDB]: https://github.com/ccgus/fmdb
[GRDB]: https://github.com/groue/GRDB.swift
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.0.0-beta'
s.version = '7.6.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+9 -1
View File
@@ -68,6 +68,7 @@
562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A432DCF3A19007676E4 /* TableAlias.swift */; };
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; };
@@ -272,6 +273,7 @@
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */; };
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
@@ -487,6 +489,7 @@
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
56231A432DCF3A19007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -767,6 +770,7 @@
56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = "<group>"; };
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = "<group>"; };
56AACAA722ACED7100A40F2A /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
@@ -1284,6 +1288,7 @@
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
56231A432DCF3A19007676E4 /* TableAlias.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -1592,13 +1597,13 @@
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
@@ -1608,6 +1613,7 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -2168,6 +2174,7 @@
buildActionMask = 2147483647;
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */,
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
56158780288D875E00A67323 /* Optional.swift in Sources */,
@@ -2176,6 +2183,7 @@
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */,
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */,
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
+5 -2
View File
@@ -7,6 +7,9 @@ import SQLCipher
import SQLite3
#endif
#if !canImport(Darwin)
@preconcurrency
#endif
import Dispatch
import Foundation
@@ -141,7 +144,7 @@ public struct Configuration: Sendable {
/// do {
/// // The sensitive information to protect
/// let email = "..."
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
/// } catch {
/// // By default, sensitive information is NOT printed
/// // when an error occurs:
@@ -170,7 +173,7 @@ public struct Configuration: Sendable {
/// do {
/// // The sensitive information to protect
/// let email = "..."
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
/// } catch {
/// // Sensitive information is printed in DEBUG builds:
/// print(error)
+138 -21
View File
@@ -96,7 +96,15 @@ extension Database {
// MARK: - Database Schema
/// Returns the current schema version.
/// Returns the current schema version (`PRAGMA schema_version`).
///
/// For example:
///
/// ```swift
/// let version = try dbQueue.read { db in
/// try db.schemaVersion()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
public func schemaVersion() throws -> Int32 {
@@ -234,8 +242,19 @@ extension Database {
/// Returns whether a table exists
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.tableExists("player") { ... }
/// if try db.tableExists("player", in: "main") { ... }
/// if try db.tableExists("player", in: "temp") { ... }
/// if try db.tableExists("player", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
@@ -278,8 +297,19 @@ extension Database {
/// Returns whether a view exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.viewExists("player") { ... }
/// if try db.viewExists("player", in: "main") { ... }
/// if try db.viewExists("player", in: "temp") { ... }
/// if try db.viewExists("player", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
@@ -296,8 +326,19 @@ extension Database {
/// Returns whether a trigger exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.triggerExists("on_player_update") { ... }
/// if try db.triggerExists("on_player_update", in: "main") { ... }
/// if try db.triggerExists("on_player_update", in: "temp") { ... }
/// if try db.triggerExists("on_player_update", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
@@ -340,6 +381,15 @@ extension Database {
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let primaryKey = try db.primaryKey("player")
/// print(primaryKey.columns)
/// }
/// ```
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
@@ -359,6 +409,36 @@ extension Database {
throw DatabaseError.noSuchTable(tableName)
}
/// Returns the name of the single-column primary key.
///
/// A fatal error is raised if the primary key has several columns, or
/// if `tableName` is the name of a database view.
func filteringPrimaryKeyColumn(_ tableName: String) throws -> String {
do {
let primaryKey = try primaryKey(tableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Filtering by primary key requires a single-column primary key in the table '\(tableName)'")
return primaryKey.columns[0]
} catch let error as DatabaseError {
// Maybe the user tries to filter a view by primary key,
// as in <https://github.com/groue/GRDB.swift/issues/1648>.
// In this case, raise a fatalError because this is a
// programmer error which is very likely to be detected
// during development.
if case .SQLITE_ERROR = error.resultCode,
(try? viewExists(tableName)) == true
{
fatalError("""
Filtering by primary key is not available on the database view '\(tableName)'. \
Use `filter(Column("...") == value)` instead.
""")
} else {
throw error
}
}
}
/// Returns nil if table does not exist
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
SchedulingWatchdog.preconditionValidQueue(self)
@@ -499,14 +579,26 @@ extension Database {
/// The indexes on table named `tableName`.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let indexes = db.indexes(in: "player")
/// for index in indexes {
/// print(index.columns)
/// }
/// }
/// ```
///
/// Only indexes on columns are returned. Indexes on expressions are
/// not returned.
///
/// SQLite does not define any index for INTEGER PRIMARY KEY columns: this
/// method does not return any index that represents the primary key.
/// SQLite does not define any index for INTEGER PRIMARY KEY columns:
/// this method does not return any index that represents the
/// primary key.
///
/// If you want to know if a set of columns uniquely identifies a row, because
/// the columns contain the primary key or a unique index, use
/// If you want to know if a set of columns uniquely identifies a row,
/// because the columns contain the primary key or a unique index, use
/// ``table(_:hasUniqueKey:)``.
///
/// When `schemaName` is not specified, known schemas are iterated in
@@ -587,16 +679,19 @@ extension Database {
/// For example:
///
/// ```swift
/// // One table with one primary key (id), and a unique index (a, b):
/// //
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
/// // > CREATE UNIQUE INDEX i ON t(a, b);
/// try db.table("t", hasUniqueKey: ["id"]) // true
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
/// try db.table("t", hasUniqueKey: ["c"]) // false
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
/// try dbQueue.read { db in
/// // One table with one primary key (id)
/// // and a unique index (a, b):
/// //
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
/// // > CREATE UNIQUE INDEX i ON t(a, b);
/// try db.table("t", hasUniqueKey: ["id"]) // true
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
/// try db.table("t", hasUniqueKey: ["c"]) // false
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
/// }
/// ```
public func table(
_ tableName: String,
@@ -610,6 +705,17 @@ extension Database {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let foreignKeys = try db.foreignKeys(in: "player")
/// for foreignKey in foreignKeys {
/// print(foreignKey.destinationTable)
/// }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
@@ -831,6 +937,17 @@ extension Database {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let columns = try db.columns(in: "player")
/// for column in columns {
/// print(column.name)
/// }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist,or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
+3 -5
View File
@@ -494,11 +494,9 @@ extension Database {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
if suspensionMutex.load().isCancelled {
// The only error that a user sees when a Task is cancelled
// is CancellationError.
throw CancellationError()
}
// The only error that a user sees when a Task is cancelled
// is CancellationError.
try suspensionMutex.load().checkCancellation()
default:
break
}
+88 -17
View File
@@ -121,6 +121,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``clearSchemaCache()``
/// - ``logError``
/// - ``releaseMemory()``
/// - ``sqliteLibVersionNumber``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
@@ -302,6 +303,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// An integer equal to [`SQLITE_VERSION_NUMBER`](https://www.sqlite.org/c3ref/c_source_id.html).
///
/// This property returns the result of `sqlite3_libversion_number()`.
///
/// ```swift
/// // Prints, for example, "3048000"
/// print(Database.sqliteLibVersionNumber)
/// ```
@inline(__always)
@inlinable
public static var sqliteLibVersionNumber: CInt {
sqlite3_libversion_number()
}
/// Whether the database region selected by statement execution is
/// recorded into `selectedRegion` by `track(_:)`.
///
@@ -325,10 +341,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// If true, the database access has been cancelled.
var isCancelled: Bool
/// If true, the database throws an error when it is cancelled.
var interruptsWhenCancelled: Bool
func checkCancellation() throws {
if isCancelled, interruptsWhenCancelled {
throw CancellationError()
}
}
}
/// Support for `checkForSuspensionViolation(from:)`
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
let suspensionMutex = Mutex(Suspension(
isSuspended: false,
isCancelled: false,
interruptsWhenCancelled: true))
// MARK: - Transaction Date
@@ -1121,7 +1149,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// See <https://www.sqlite.org/c3ref/interrupt.html>
func interrupt() {
sqlite3_interrupt(sqliteConnection)
if let sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
// MARK: - Database Suspension
@@ -1195,22 +1225,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Cancels the current database access. All statements but ROLLBACK
/// will throw `CancellationError`, until `uncancel()` is called.
///
/// This method can be called from any thread.
func cancel() {
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
/// Returns a closure that cancels the current database access.
/// Most statements will throw `CancellationError`, until `uncancel()`
/// is called.
var cancel: @Sendable () -> Void {
// Workaround the fact that SQLiteConnection is not Sendable.
struct Connection: @unchecked Sendable {
var sqliteConnection: SQLiteConnection?
}
let connection = Connection(sqliteConnection: sqliteConnection)
return { [suspensionMutex, connection] in
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
}
suspension.isCancelled = true
return suspension.interruptsWhenCancelled
}
suspension.isCancelled = true
return true
}
if needsInterrupt {
interrupt()
if needsInterrupt {
if let sqliteConnection = connection.sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
}
}
@@ -1221,6 +1260,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Within the given closure, Task cancellation does not interrupt
/// database accesses.
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
let previous = suspensionMutex.withLock {
let previous = $0.interruptsWhenCancelled
$0.interruptsWhenCancelled = false
return previous
}
defer {
suspensionMutex.withLock {
$0.interruptsWhenCancelled = previous
}
}
return try value()
}
/// Support for `checkForSuspensionViolation(from:)`
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
@@ -1272,6 +1329,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
// Commits when read-only are just like rollbacks above.
if statement.transactionEffect == .commitTransaction && isReadOnly {
return
}
// Suspension should not prevent adjusting the read-only mode.
// See <https://github.com/groue/GRDB.swift/issues/1715>.
if statement.isQueryOnlyPragma {
return
}
// How should we interrupt the statement?
enum Interrupt {
case abort // Rollback and throw SQLITE_ABORT
@@ -1281,7 +1349,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
// Check for cancellation first, so that the only error that
// a user sees when a Task is cancelled is CancellationError.
if suspension.isCancelled {
if suspension.isCancelled, suspension.interruptsWhenCancelled {
return .cancel
}
@@ -2058,6 +2126,9 @@ extension Database {
/// That's the reason why it is recommended to store JSON as text.
public static let jsonText = ColumnType(rawValue: "TEXT")
/// The `BLOB` column type, suitable for JSONB columns.
public static let jsonb = ColumnType(rawValue: "BLOB")
/// The `INTEGER` column type.
public static let integer = ColumnType(rawValue: "INTEGER")
+9 -2
View File
@@ -173,13 +173,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// }
/// return int * int
/// }
///
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// let dbQueue = try DatabaseQueue()
/// try dbQueue.read { db in
/// db.add(function: square)
///
/// // SELECT square(score) FROM player
/// let squaredScores = let Player
/// .select(square(Column("score")), as: Int.self)
/// .select({ square($0.score) }, as: Int.self)
/// .fetchAll(db)
/// }
/// ```
@@ -457,7 +464,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate {
public protocol DatabaseAggregate: SendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+47 -68
View File
@@ -352,40 +352,24 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
releaseReader(.reuse)
}
do {
let result = try dbAccess.inDatabase(db) {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -403,7 +387,9 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
do {
@@ -436,35 +422,16 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(.reuse)
}
do {
let result = try dbAccess.inDatabase(db) {
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
return try await readerPool.get { reader in
try await reader.execute { db in
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -584,7 +551,9 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
try? db.commit() // Ignore commit error
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
do {
@@ -802,7 +771,7 @@ extension DatabasePool: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -818,22 +787,32 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
asyncBarrierWriteWithoutTransaction { dbResult in
do {
try dbAccess.checkCancellation()
let db = try dbResult.get()
let result = try dbAccess.inDatabase(db) {
try updates(db)
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// Pool.barrier does not support async calls (yet?).
// So we perform cancellation checks just as in
// the async version of SerializedDatabase.execute().
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await readerPool.barrier {
try Task.checkCancellation()
return try writer.sync { db in
defer {
cancelMutex.store(nil)
db.uncancel()
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try updates(db)
}
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
+8 -6
View File
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -248,8 +248,9 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -272,7 +273,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
@@ -296,8 +297,9 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore error because we can not notify it.
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -385,7 +387,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -396,7 +398,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
+6 -6
View File
@@ -22,14 +22,14 @@ import Dispatch
/// ### Reading from the Database
///
/// - ``read(_:)-3806d``
/// - ``read(_:)-4d1da``
/// - ``read(_:)-5mfwu``
/// - ``readPublisher(receiveOn:value:)``
/// - ``asyncRead(_:)``
///
/// ### Unsafe Methods
///
/// - ``unsafeRead(_:)-5i7tf``
/// - ``unsafeRead(_:)-5gsav``
/// - ``unsafeRead(_:)-90w0p``
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
@@ -215,7 +215,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
@@ -319,7 +319,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -652,7 +652,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -669,7 +669,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
+3 -2
View File
@@ -83,6 +83,7 @@ extension DatabaseRegionObservation {
/// - parameter onChange: The closure to execute when a transaction has
/// modified the observed region.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
public func start(
in writer: any DatabaseWriter,
onError: @escaping @Sendable (Error) -> Void,
@@ -200,7 +201,7 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -211,7 +212,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & SendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+4 -2
View File
@@ -113,7 +113,9 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
}
@@ -152,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
@@ -173,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
+14 -25
View File
@@ -294,36 +294,25 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(self.poolCompletion(db))
}
do {
let result = try dbAccess.inDatabase(db) {
try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
let (reader, releaseReader) = try await readerPool.get()
var readerCompletion: PoolCompletion?
defer {
// readerCompletion might be null in cancelled database accesses
releaseReader(readerCompletion ?? .reuse)
}
let (result, completion) = try await reader.execute { db in
let result = Result { try value(db) }
let completion = poolCompletion(db)
return (result, completion)
}
readerCompletion = completion
return try result.get()
}
public func asyncRead(
@@ -353,7 +342,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
+65 -16
View File
@@ -541,13 +541,20 @@ extension DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -584,13 +591,20 @@ extension DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -623,13 +637,20 @@ extension DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -657,13 +678,20 @@ extension DatabaseValueConvertible where Self: Hashable {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -696,13 +724,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -736,13 +771,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -772,13 +814,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -808,8 +857,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
+10 -10
View File
@@ -22,18 +22,18 @@ import Dispatch
/// ### Writing into the Database
///
/// - ``write(_:)-76inz``
/// - ``write(_:)-3db50``
/// - ``write(_:)-4gnqx``
/// - ``writePublisher(receiveOn:updates:)``
/// - ``writePublisher(receiveOn:updates:thenRead:)``
/// - ``writeWithoutTransaction(_:)-4qh1w``
/// - ``writeWithoutTransaction(_:)-67mri``
/// - ``writeWithoutTransaction(_:)-18zhj``
/// - ``asyncWrite(_:completion:)``
/// - ``asyncWriteWithoutTransaction(_:)``
///
/// ### Exclusive Access to the Database
///
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
///
/// ### Reading from the Latest Committed Database State
@@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -640,7 +640,7 @@ extension DatabaseWriter {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
public func write<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writeWithoutTransaction { db in
var result: T?
@@ -885,7 +885,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -902,7 +902,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
@@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@@ -947,7 +947,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
+45
View File
@@ -0,0 +1,45 @@
import Dispatch
/// An actor that runs in a DispatchQueue.
///
/// Inspired by <https://forums.swift.org/t/using-dispatchqueue-as-actors-serial-executor-under-linux/75260/3>
actor DispatchQueueActor {
private let executor: DispatchQueueExecutor
/// - precondition: the queue is serial, or flags contains `.barrier`.
init(queue: DispatchQueue, flags: DispatchWorkItemFlags = []) {
self.executor = DispatchQueueExecutor(queue: queue, flags: flags)
}
nonisolated var unownedExecutor: UnownedSerialExecutor {
executor.asUnownedSerialExecutor()
}
func execute<T>(_ work: () throws -> T) rethrows -> T {
try work()
}
}
private final class DispatchQueueExecutor: SerialExecutor {
private let queue: DispatchQueue
private let flags: DispatchWorkItemFlags
init(queue: DispatchQueue, flags: DispatchWorkItemFlags) {
self.queue = queue
self.flags = flags
}
func enqueue(_ job: UnownedJob) {
queue.async(flags: flags) {
job.runSynchronously(on: self.asUnownedSerialExecutor())
}
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
}
func checkIsolated() {
dispatchPrecondition(condition: .onQueue(queue))
}
}
+434 -116
View File
@@ -52,6 +52,8 @@ import Foundation
/// - ``subscript(_:)-9c1fw``
/// - ``subscript(_:)-3jhwm``
/// - ``subscript(_:)-7krrg``
/// - ``decode(_:atIndex:)-33ykh``
/// - ``decode(_:atIndex:)-3btwn``
/// - ``withUnsafeData(atIndex:_:)``
/// - ``dataNoCopy(atIndex:)``
///
@@ -60,6 +62,9 @@ import Foundation
/// - ``subscript(_:)-3tp8o``
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``coalesce(_:)-359k7``
/// - ``decode(_:forColumn:)-4i1o4``
/// - ``decode(_:forColumn:)-4rhs4``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
@@ -68,6 +73,9 @@ import Foundation
/// - ``subscript(_:)-9txgm``
/// - ``subscript(_:)-2esg7``
/// - ``subscript(_:)-wl9a``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-1ljuo``
/// - ``decode(_:forColumn:)-47qeg``
/// - ``withUnsafeData(at:_:)``
/// - ``dataNoCopy(_:)``
///
@@ -82,6 +90,10 @@ import Foundation
/// - ``subscript(_:)-8god3``
/// - ``subscript(_:)-jwnx``
/// - ``subscript(_:)-6ge6t``
/// - ``decode(_:forKey:)-9bbd3``
/// - ``decode(_:forKey:)-2w6lc``
/// - ``decode(_:forKey:)-2soc2``
/// - ``decodeIfPresent(_:forKey:)``
/// - ``PrefetchedRowsView``
/// - ``ScopesTreeView``
/// - ``ScopesView``
@@ -117,6 +129,10 @@ import Foundation
///
/// - ``RowAdapter``
///
/// ### Errors
///
/// - ``RowDecodingError``
///
/// ### Supporting Types
///
/// - ``RowCursor``
@@ -450,7 +466,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
try! decode(Value.self, forColumn: columnName)
}
/// Returns the value at given column, converted to the requested type.
@@ -487,7 +503,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
try! decode(Value.self, forColumn: columnName)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
@@ -531,7 +547,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
try! decode(Value.self, forKey: column.name)
try! decode(Value.self, forColumn: column)
}
/// Returns the value at given column, converted to the requested type.
@@ -571,7 +587,7 @@ extension Row {
-> Value
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
try! decode(Value.self, forKey: column.name)
try! decode(Value.self, forColumn: column)
}
/// Calls the given closure with the `Data` at given index.
@@ -671,6 +687,53 @@ extension Row {
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
dataNoCopy(named: column.name)
}
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
///
/// For example:
///
/// ```swift
/// let name: String? = row.coalesce(["nickname", "name"])
/// ```
///
/// Prefer `coalesce` to nil-coalescing row values, which does not
/// return the expected value:
///
/// ```swift
/// // INCORRECT
/// let name: String? = row["nickname"] ?? row["name"]
/// ```
public func coalesce<T: DatabaseValueConvertible>(
_ columns: some Collection<String>
) -> T? {
for column in columns {
if let value = self[column] as T? {
return value
}
}
return nil
}
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
///
/// For example:
///
/// ```swift
/// let name: String? = row.coalesce([Column("nickname"), Column("name")])
/// ```
///
/// Prefer `coalesce` to nil-coalescing row values, which does not
/// return the expected value:
///
/// ```swift
/// // INCORRECT
/// let name: String? = row[Column("nickname")] ?? row[Column("name")]
/// ```
public func coalesce<T: DatabaseValueConvertible>(
_ columns: some Collection<any ColumnExpression>
) -> T? {
return coalesce(columns.lazy.map { $0.name })
}
}
extension Row {
@@ -690,12 +753,13 @@ extension Row {
// MARK: - Extracting Records
/// The record associated to the given scope.
/// Returns the record associated to the given key.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
@@ -720,26 +784,28 @@ extension Row {
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author = bookRow["author"]
/// let country: Country = bookRow["country"]
/// let book = try Book(row: row)
/// let author: Author = row["author"]
/// let country: Country = row["country"]
/// ```
///
/// See also: ``scopesTree``
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
try! decode(Record.self, forKey: scope)
}
/// The eventual record associated to the given scope.
/// Returns the eventual record associated to the given key.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
@@ -760,25 +826,26 @@ extension Row {
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// // Fetch a book, with its eventual author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author? = bookRow["author"]
/// let country: Country? = bookRow["country"]
/// let book = try Book(row: row)
/// let author: Author? = row["author"]
/// let country: Country? = row["country"]
/// ```
///
/// See also: ``scopesTree``
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
try! decodeIfPresent(Record.self, forKey: scope)
}
/// A collection of prefetched records associated to the given
/// Returns a collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
@@ -794,10 +861,10 @@ extension Row {
/// struct Book: TableRecord, FetchableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: [Book] = author["books"]
/// let author = try Author(row: row)
/// let books: [Book] = row["books"]
/// ```
///
/// See also: ``prefetchedRows``
@@ -812,7 +879,8 @@ extension Row {
try! decode(Records.self, forKey: key)
}
/// A set prefetched records associated to the given association key.
/// Returns the set of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
@@ -827,10 +895,10 @@ extension Row {
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: Set<Book> = author["books"]
/// let author = try Author(row: row)
/// let books: Set<Book> = row["books"]
/// ```
///
/// See also: ``prefetchedRows``
@@ -886,7 +954,8 @@ extension Row {
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopesTree``.
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
public var scopes: ScopesView {
impl.scopes(prefetchedRows: prefetchedRows)
}
@@ -1016,10 +1085,28 @@ extension Row {
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score = try row.decode(Int.self, atIndex: 0) // 42
/// let score: Int = try row.decode(atIndex: 0) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
/// let name: String = try row.decode(atIndex: 0) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = try row.decode(atIndex: 0) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible>(
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
@@ -1033,13 +1120,37 @@ extension Row {
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: "score") // 42
/// let score: Int = try row.decode(forColumn: "score") // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
/// let name: String = try row.decode(forColumn: "name") // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: "name") // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: "missing") // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible>(
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
forColumn columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
@@ -1051,6 +1162,47 @@ extension Row {
}
return try Value.decode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forColumn column: some ColumnExpression)
throws -> Value
{
try decode(type, forColumn: column.name)
}
}
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
@@ -1065,11 +1217,29 @@ extension Row {
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score = try row.decode(Int.self, atIndex: 0) // 42
/// let score: Int = try row.decode(atIndex: 0) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
/// let name: String = try row.decode(atIndex: 0) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = try row.decode(atIndex: 0) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inline(__always)
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
@@ -1087,13 +1257,37 @@ extension Row {
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: "score") // 42
/// let score: Int = try row.decode(forColumn: "score") // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
/// let name: String = try row.decode(forColumn: "name") // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: "name") // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: "missing") // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
forColumn columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
@@ -1106,6 +1300,51 @@ extension Row {
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forColumn column: some ColumnExpression)
throws -> Value
{
try decode(type, forColumn: column.name)
}
// Support for fast decoding in scoped rows
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
@@ -1138,37 +1377,51 @@ extension Row {
// MARK: - Throwing Record Decoding Methods
extension Row {
/// Returns the eventual record associated with the given scope.
/// Returns the eventual record associated to the given key.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// The result is nil if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// let author: Author? = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
/// struct Country: TableRecord, FetchableRecord { }
///
/// Associated records stored in nested associations are available, too:
/// // Fetch a book, with its eventual author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
/// let book = try Book(row: row)
/// let author: Author? = try row.decode(forKey: "author")
/// let country: Country? = try row.decode(forKey: "country")
/// ```
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// let country: Country? = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// Nil is returned if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decodeIfPresent<Record: FetchableRecord>(
/// - parameter type: The decoded type.
/// - parameter scope: A scope identifier.
/// - throws: Any error that happens during the decoding.
public func decodeIfPresent<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record?
@@ -1179,37 +1432,48 @@ extension Row {
return try Record(row: scopedRow)
}
/// Returns the record associated with the given scope.
/// Returns the record associated to the given key.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// For example:
///
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// let author: Author = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
/// struct Country: TableRecord, FetchableRecord { }
///
/// Associated records stored in nested associations are available, too:
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
/// let book = try Book(row: row)
/// let author: Author = try row.decode(forKey: "author")
/// let country: Country = try row.decode(forKey: "country")
/// ```
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// let country: Country = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// A fatal error is raised if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decode<Record: FetchableRecord>(
/// - parameter type: The decoded type.
/// - parameter scope: A scope identifier.
/// - throws: Any error that happens during the decoding.
public func decode<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record
@@ -1251,20 +1515,34 @@ extension Row {
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
extension Row {
/// Returns the records encoded in the given prefetched rows.
/// Returns a collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
/// struct Book: TableRecord, FetchableRecord { }
///
/// let books: [Book] = row["books"]
/// print(books[0].title)
/// // Prints "Moby-Dick"
func decode<Collection>(
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: row)
/// let books: [Book] = try row.decode(forKey: "books")
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter type: The type of the decoded collection.
/// - parameter key: An association key.
/// - throws: Any error that happens during the decoding.
public func decode<Collection>(
_ type: Collection.Type = Collection.self,
forKey key: String)
throws -> Collection
@@ -1272,6 +1550,7 @@ extension Row {
Collection: RangeReplaceableCollection,
Collection.Element: FetchableRecord
{
// TODO: test independently
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
@@ -1302,24 +1581,39 @@ extension Row {
return collection
}
/// Returns the set of records encoded in the given prefetched rows.
/// Returns the set of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let books: Set<Book> = row["books"]
/// print(books.first!.title)
/// // Prints "Moby-Dick"
func decode<Record: FetchableRecord & Hashable>(
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: row)
/// let books: Set<Book> = try row.decode(forKey: "books")
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter type: The type of the decoded set.
/// - parameter key: An association key.
/// - throws: Any error that happens during the decoding.
public func decode<Record: FetchableRecord & Hashable>(
_ type: Set<Record>.Type = Set<Record>.self,
forKey key: String)
throws -> Set<Record>
{
// TODO: test independently
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
@@ -1686,11 +1980,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
@@ -1735,11 +2035,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
@@ -1767,11 +2073,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
@@ -1803,11 +2115,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
+32 -16
View File
@@ -23,9 +23,21 @@ enum RowKey: Hashable, Sendable {
case prefetchKey(String)
}
/// A decoding error
@usableFromInline
enum RowDecodingError: Error {
/// A decoding error thrown when decoding a database row.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// // RowDecodingError: could not decode String from database value NULL.
/// let name = try row.decode(String.self, forColumn: "name")
/// ```
public struct RowDecodingError: Error {
enum Impl {
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
}
@usableFromInline
struct Context: CustomDebugStringConvertible, Sendable {
/// A description of what went wrong, for debugging purposes.
@@ -55,17 +67,19 @@ enum RowDecodingError: Error {
}
}
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
var impl: Impl
var context: Context {
switch self {
switch impl {
case .keyNotFound(_, let context),
.valueMismatch(_, let context):
return context
}
}
static func valueMismatch(_ type: Any.Type, _ context: Context) -> Self {
self.init(impl: .valueMismatch(type, context))
}
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
static func valueMismatch(
@@ -74,11 +88,10 @@ enum RowDecodingError: Error {
databaseValue: DatabaseValue)
-> Self
{
valueMismatch(
type,
RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
"""))
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
""")
return self.init(impl: .valueMismatch(type, context))
}
/// Convenience method that builds the
@@ -115,11 +128,15 @@ enum RowDecodingError: Error {
/// error message.
@usableFromInline
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
keyNotFound(
self.init(impl: .keyNotFound(
.columnName(columnName),
RowDecodingError.Context(decodingContext: context, debugDescription: """
column not found: \(String(reflecting: columnName))
"""))
""")))
}
static func keyNotFound(_ rowKey: RowKey, _ context: Context) -> Self {
self.init(impl: .keyNotFound(rowKey, context))
}
}
@@ -167,8 +184,7 @@ struct RowDecodingContext {
}
extension RowDecodingError: CustomStringConvertible {
@usableFromInline
var description: String {
public var description: String {
let context = self.context
let row = context.row
var chunks: [String] = []
+2 -2
View File
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
fileprivate func qualified(with alias: TableAliasBase) -> Element {
switch self {
case .sql:
// A raw SQL string can't be qualified with a table alias,
@@ -192,7 +192,7 @@ public struct SQL: Sendable {
try elements.map { try $0.sql(context) }.joined()
}
func qualified(with alias: TableAlias) -> SQL {
func qualified(with alias: TableAliasBase) -> SQL {
SQL(elements: elements.map { $0.qualified(with: alias) })
}
}
+3
View File
@@ -1,3 +1,6 @@
#if !canImport(Darwin)
@preconcurrency
#endif
import Dispatch
/// SchedulingWatchdog makes sure that databases connections are used on correct
+18 -116
View File
@@ -5,6 +5,9 @@ final class SerializedDatabase {
/// The database connection
private let db: Database
/// The actor that performs asynchronous accesses
private let actor: DispatchQueueActor
/// The database configuration
var configuration: Configuration { db.configuration }
@@ -55,6 +58,8 @@ final class SerializedDatabase {
} else {
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
}
self.actor = DispatchQueueActor(queue: queue)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
do {
@@ -245,20 +250,22 @@ final class SerializedDatabase {
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @escaping @Sendable (Database) throws -> T
_ block: @Sendable (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
self.async { db in
do {
let result = try dbAccess.inDatabase(db) {
try block(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try await actor.execute {
defer {
cancelMutex.store(nil)
db.uncancel()
preconditionNoUnsafeTransactionLeft(db)
}
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try block(db)
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
@@ -305,108 +312,3 @@ final class SerializedDatabase {
// It happens the job of SerializedDatabase is precisely to provide thread-safe
// access to `Database`.
extension SerializedDatabase: @unchecked Sendable { }
// MARK: - Task Cancellation Support
enum DatabaseAccessCancellationState: @unchecked Sendable {
// @unchecked Sendable because database is only accessed from its
// dispatch queue.
case notConnected
case connected(Database)
case cancelled
case expired
}
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
/// Supports Task cancellation in async database accesses.
///
/// Usage:
///
/// ```swift
/// let dbAccess = CancellableDatabaseAccess()
/// return try dbAccess.withCancellableContinuation { continuation in
/// asyncDatabaseAccess { db in
/// do {
/// let result = try dbAccess.inDatabase(db) {
/// // Perform database operations
/// }
/// continuation.resume(returning: result)
/// } catch {
/// continuation.resume(throwing: error)
/// }
/// }
/// }
/// ```
extension CancellableDatabaseAccess: DatabaseCancellable {
convenience init() {
self.init(.notConnected)
}
func cancel() {
withLock { state in
switch state {
case let .connected(db):
db.cancel()
state = .cancelled
case .notConnected:
state = .cancelled
case .cancelled, .expired:
break
}
}
}
func withCancellableContinuation<Value>(
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
) async throws -> Value {
try await withTaskCancellationHandler {
try checkCancellation()
return try await withUnsafeThrowingContinuation { continuation in
fn(continuation)
}
} onCancel: {
cancel()
}
}
func checkCancellation() throws {
try withLock { state in
if case .cancelled = state {
throw CancellationError()
}
}
}
/// Wraps a full database access with cancellation support. When this
/// method returns, the database is NOT cancelled.
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
try withLock { state in
switch state {
case .connected, .expired:
fatalError("Can't use a CancellableDatabaseAccess twice")
case .notConnected:
state = .connected(db)
case .cancelled:
throw CancellationError()
}
}
return try throwingFirstError {
try work()
} finally: {
let cancelled = withLock { state in
if case .cancelled = state {
db.uncancel()
return true
} else {
state = .expired
return false
}
}
if cancelled {
throw CancellationError()
}
}
}
}
+4
View File
@@ -92,6 +92,9 @@ public final class Statement {
/// The effects on the database (reported by `sqlite3_set_authorizer`).
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
private(set) var isQueryOnlyPragma = false
/// A boolean value indicating if the prepared statement makes no direct
/// changes to the content of the database file.
///
@@ -160,6 +163,7 @@ public final class Statement {
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.authorizerEventKinds = authorizer.databaseEventKinds
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
}
deinit {
+11
View File
@@ -13,6 +13,8 @@ import string_h
import Glibc
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
import Darwin
#elseif os(Windows)
import ucrt
#endif
/// `StatementAuthorizer` provides information about compiled database
@@ -39,6 +41,9 @@ final class StatementAuthorizer {
/// savepoint statement.
var transactionEffect: Statement.TransactionEffect?
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
var isQueryOnlyPragma = false
private var isDropStatement = false
init(_ database: Database) {
@@ -65,6 +70,7 @@ final class StatementAuthorizer {
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionEffect = nil
isQueryOnlyPragma = false
isDropStatement = false
}
@@ -190,6 +196,11 @@ final class StatementAuthorizer {
}
return SQLITE_OK
case SQLITE_PRAGMA:
if let cString1 {
isQueryOnlyPragma = sqlite3_stricmp(cString1, "query_only") == 0
}
return SQLITE_OK
default:
return SQLITE_OK
}
+72 -16
View File
@@ -563,13 +563,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -608,13 +615,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -647,13 +661,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -681,13 +702,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -720,13 +748,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -760,13 +795,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -796,13 +838,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -827,13 +876,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
+1 -1
View File
@@ -1,4 +1,4 @@
#if !os(Linux)
#if !os(Linux) && !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
#if !os(Linux)
#if !os(Linux) && !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
+1 -1
View File
@@ -9,7 +9,7 @@ import SQLite3
import Foundation
#if !os(Linux)
#if !os(Linux) && !os(Windows)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
@@ -650,8 +650,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/capitalized``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.capitalized)
/// let request = Player.select { $0.name.capitalized }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let capitalize =
@@ -672,8 +671,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/lowercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.lowercased)
/// let request = Player.select { $0.name.lowercased }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let lowercase =
@@ -694,8 +692,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/uppercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.uppercased)
/// let request = Player.select { $0.name.uppercased }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let uppercase =
@@ -716,8 +713,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/localizedCapitalized``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let request = Player.select { $0.name.localizedCapitalized }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let localizedCapitalize =
@@ -739,8 +735,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/localizedLowercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedLowercase)
/// let request = Player.select { $0.name.localizedLowercase }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let localizedLowercase =
@@ -761,8 +756,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/localizedUppercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedUppercase)
/// let request = Player.select { $0.name.localizedUppercase }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let localizedUppercase =
+21 -12
View File
@@ -549,8 +549,12 @@ class DatabaseObservationBroker {
savepointStack.clear()
if !database.isReadOnly {
for observation in transactionObservations {
observation.databaseDidCommit(database)
// Observers must be able to access the database, even if the
// task that has performed the commit is cancelled.
database.ignoringCancellation {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
}
}
@@ -613,8 +617,13 @@ class DatabaseObservationBroker {
if notifyTransactionObservers {
assert(!database.isReadOnly, "Read-only transactions are not notified")
for observation in transactionObservations {
observation.databaseDidRollback(database)
// Observers must be able to access the database, even if the
// task that has performed the commit is cancelled.
database.ignoringCancellation {
for observation in transactionObservations {
observation.databaseDidRollback(database)
}
}
}
databaseDidEndTransaction()
@@ -1243,16 +1252,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
public struct DatabasePreUpdateEvent {
/// An event kind
public enum Kind: CInt {
/// SQLITE_INSERT
case insert = 18
/// An event kind.
public enum Kind: CInt, Sendable {
/// An insertion event
case insert = 18 // SQLITE_INSERT
/// SQLITE_DELETE
case delete = 9
/// A deletion event
case delete = 9 // SQLITE_DELETE
/// SQLITE_UPDATE
case update = 23
/// An update event
case update = 23 // SQLITE_UPDATE
}
/// The event kind
+1 -1
View File
@@ -97,7 +97,7 @@ try dbQueue.write { db in
}
```
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
+9 -398
View File
@@ -6,7 +6,7 @@ Define or query the database schema.
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example:
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed in <doc:DatabaseSchemaModifications>. For example:
```swift
try db.create(table: "player") { t in
@@ -16,408 +16,19 @@ try db.create(table: "player") { t in
}
```
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
## Database Schema Recommendations
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
### Table names should be English, singular, and camelCased
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// table columns and constraints
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "players") { t in
// table columns and constraints
}
```
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
```swift
extension Player: TableRecord {
// Required because table name is not 'player'
static let databaseTableName = "players"
}
extension PostalAddress: TableRecord {
// Required because table name is not 'postalAddress'
static let databaseTableName = "postal_address"
}
extension Award: TableRecord {
// Required because table name is not 'award'
static let databaseTableName = "Auszeichnung"
}
```
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
```swift
extension Player: TableRecord {
// Explicit association key because the table name is not 'postalAddress'
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
// Explicit association key because the table name is not 'award'
static let awards = hasMany(Award.self, key: "awards")
}
```
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
### Column names should be camelCased
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("fullName", .text).notNull()
t.column("score", .integer).notNull()
t.column("creationDate", .datetime).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("full_name", .text).notNull()
t.column("score", .integer).notNull()
t.column("creation_date", .datetime).notNull()
}
```
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
```swift
struct Player: Decodable, FetchableRecord {
var id: Int64
var fullName: String
var score: Int
var creationDate: Date
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id, fullName = "full_name", score, creationDate = "creation_date"
}
}
```
### Tables should have explicit primary keys
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// Auto-incremented primary key
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "team") { t in
// Single-column primary key
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.belongsTo("player")
t.belongsTo("team")
}
t.column("role", .text).notNull()
}
```
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
See <doc:SingleRowTables> when you need to define a table that contains a single row.
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
```swift
// A table without any explicit primary key
try db.create(table: "player") { t in
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
// The record type for the 'player' table'
struct Player: Codable {
// Uniquely identifies a player.
var rowid: Int64?
var name: String
var score: Int
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
}
// Update id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
rowid = inserted.rowID
}
}
try dbQueue.read { db in
// SELECT *, rowid FROM player WHERE rowid = 1
if let player = try Player.fetchOne(db, id: 1) {
// DELETE FROM player WHERE rowid = 1
let deleted = try player.delete(db)
print(deleted) // true
}
}
```
### Single-column primary keys should be named 'id'
This helps record types play well with the standard `Identifiable` protocol.
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.primaryKey("uuid", .text)
t.column("name", .text).notNull()
}
```
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
```swift
// Custom coding keys
struct Player: Codable, Identifiable {
var id: String
var name: String
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id = "uuid", name
}
}
// Extra property
struct Player: Identifiable {
var uuid: String
var name: String
// Required because the primary key column is not 'id'
var id: String { uuid }
}
```
### Unique keys should be supported by unique indexes
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
}
// One single player at any given position in a team
try db.create(
indexOn: "player",
columns: ["teamId", "position"],
options: .unique)
```
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
>
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
>
> ```swift
> // Unique constraint on player(name) can not be dropped.
> try db.create(table: "player") { t in
> t.column("name", .text).unique()
> }
>
> // Unique index on team(name) can be dropped.
> try db.create(table: "team") { t in
> t.column("name", .text)
> }
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
> ```
>
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
```swift
try dbQueue.write { db in
// Fatal error: table player has no unique index on columns ...
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
try Player.deleteOne(db, key: ["name": "Arthur"])
// Use instead:
let player = try Player
.filter(Column("teamId") == 42 && Column("position") == 1)
.fetchOne(db)
try Player
.filter(Column("name") == "Arthur")
.deleteAll(db)
}
```
### Relations between tables should be supported by foreign keys
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
```swift
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("color", .text).notNull()
}
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.belongsTo("team").notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// No foreign key
t.column("teamId", .integer).notNull()
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
extension Player: TableRecord {
static let team = belongsTo(Team.self)
}
extension Team: TableRecord {
static let players = hasMany(Player.self)
}
```
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
```swift
extension Player: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let teamForeignKey = ForeignKey(["teamId"])
static let team = belongsTo(Team.self,
using: teamForeignKey)
}
extension Team: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let players = hasMany(Player.self,
using: Player.teamForeignKey)
}
```
Most applications modify the database schema as new versions ship: it is recommended to wrap all schema changes in <doc:Migrations>.
## Topics
### Database Tables
### Define the database schema
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
- ``Database/rename(table:to:)``
- ``Database/ColumnType``
- ``Database/ConflictResolution``
- ``Database/ForeignKeyAction``
- ``TableAlteration``
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- <doc:DatabaseSchemaModifications>
- <doc:DatabaseSchemaRecommendations>
### Database Views
### Introspect the database schema
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
- <doc:DatabaseSchemaIntrospection>
### Database Indexes
### Check the database schema
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### Querying the Database Schema
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
- ``Database/primaryKey(_:in:)``
- ``Database/schemaVersion()``
- ``Database/table(_:hasUniqueKey:)``
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
- ``PrimaryKeyInfo``
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:in:)``
- ``ForeignKeyViolation``
### Sunsetted Methods
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
- <doc:DatabaseSchemaIntegrityChecks>
@@ -0,0 +1,13 @@
# Integrity Checks
Perform integrity checks of the database content
## Topics
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:in:)``
- ``ForeignKeyViolation``
@@ -0,0 +1,35 @@
# Database Schema Introspection
Get information about schema objects such as tables, columns, indexes, foreign keys, etc.
## Topics
### Querying the Schema Version
- ``Database/schemaVersion()``
### Existence Checks
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
### Table Structure
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/primaryKey(_:in:)``
- ``Database/table(_:hasUniqueKey:)``
### Reserved Tables
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
### Supporting Types
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
- ``PrimaryKeyInfo``
@@ -0,0 +1,293 @@
# Modifying the Database Schema
How to modify the database schema
## Overview
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
## Create Tables
The ``Database/create(table:options:body:)`` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search](https://github.com/groue/GRDB.swift/blob/master/Documentation/FullTextSearch.md), or use raw SQL.
```swift
// CREATE TABLE place (
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// title TEXT,
// favorite BOOLEAN NOT NULL DEFAULT 0,
// latitude DOUBLE NOT NULL,
// longitude DOUBLE NOT NULL
// )
try db.create(table: "place") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text)
t.column("favorite", .boolean).notNull().defaults(to: false)
t.column("longitude", .double).notNull()
t.column("latitude", .double).notNull()
}
```
**Configure table creation**
```swift
// CREATE TABLE player ( ... )
try db.create(table: "player") { t in ... }
// CREATE TEMPORARY TABLE player IF NOT EXISTS (
try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
```
Reference: ``TableOptions``
**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `json`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
```swift
// CREATE TABLE player (
// score,
// name TEXT,
// creationDate DATETIME,
// address TEXT,
try db.create(table: "player") { t in
t.column("score")
t.column("name", .text)
t.column("creationDate", .datetime)
t.column("address", .json)
```
Reference: ``TableDefinition/column(_:_:)``
Define **not null** columns, and set **default values**:
```swift
// email TEXT NOT NULL,
t.column("email", .text).notNull()
// name TEXT NOT NULL DEFAULT 'Anonymous',
t.column("name", .text).notNull().defaults(to: "Anonymous")
```
Reference: ``ColumnDefinition``
**Define primary, unique, or foreign keys**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise):
```swift
// id INTEGER PRIMARY KEY AUTOINCREMENT,
t.autoIncrementedPrimaryKey("id")
// uuid TEXT PRIMARY KEY NOT NULL,
t.primaryKey("uuid", .text)
// teamName TEXT NOT NULL,
// position INTEGER NOT NULL,
// PRIMARY KEY (teamName, position),
t.primaryKey {
t.column("teamName", .text)
t.column("position", .integer)
}
// email TEXT UNIQUE,
t.column("email", .text).unique()
// teamId TEXT REFERENCES team(id) ON DELETE CASCADE,
// countryCode TEXT REFERENCES country(code) NOT NULL,
t.belongsTo("team", onDelete: .cascade)
t.belongsTo("country").notNull()
```
Reference: ``TableDefinition``, ``ColumnDefinition/unique(onConflict:)``
**Create an index** on a column
```swift
t.column("score", .integer).indexed()
```
Reference: ``ColumnDefinition``
For extra index options, see <doc:DatabaseSchemaModifications#Create-Indexes> below.
**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL expression.
```swift
// name TEXT CHECK (LENGTH(name) > 0)
// score INTEGER CHECK (score > 0)
t.column("name", .text).check { length($0) > 0 }
t.column("score", .integer).check(sql: "score > 0")
```
Reference: ``ColumnDefinition``
Columns can also be defined with a raw sql String, or an [SQL literal](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md#sql-literal) in which you can safely embed raw values without any risk of syntax errors or SQL injection:
```swift
t.column(sql: "name TEXT")
let defaultName: String = ...
t.column(literal: "name TEXT DEFAULT \(defaultName)")
```
Reference: ``TableDefinition``
Other **table constraints** can involve several columns:
```swift
// PRIMARY KEY (a, b),
t.primaryKey(["a", "b"])
// UNIQUE (a, b) ON CONFLICT REPLACE,
t.uniqueKey(["a", "b"], onConflict: .replace)
// FOREIGN KEY (a, b) REFERENCES parents(c, d),
t.foreignKey(["a", "b"], references: "parents")
// CHECK (a + b < 10),
t.check(Column("a") + Column("b") < 10)
// CHECK (a + b < 10)
t.check(sql: "a + b < 10")
// Raw SQL constraints
t.constraint(sql: "CHECK (a + b < 10)")
t.constraint(literal: "CHECK (a + b < \(10))")
```
Reference: ``TableDefinition``
**Generated columns**:
```swift
t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
}
```
Reference: ``ColumnDefinition``
## Modify Tables
SQLite lets you modify existing tables:
```swift
// ALTER TABLE referer RENAME TO referrer
try db.rename(table: "referer", to: "referrer")
// ALTER TABLE player ADD COLUMN hasBonus BOOLEAN
// ALTER TABLE player RENAME COLUMN url TO homeURL
// ALTER TABLE player DROP COLUMN score
try db.alter(table: "player") { t in
t.add(column: "hasBonus", .boolean)
t.rename(column: "url", to: "homeURL")
t.drop(column: "score")
}
```
Reference: ``TableAlteration``
> Note: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> for more information.
## Drop Tables
Drop tables with the ``Database/drop(table:)`` method:
```swift
try db.drop(table: "obsolete")
```
## Create Indexes
Create an index on a column:
```swift
try db.create(table: "player") { t in
t.column("email", .text).unique()
t.column("score", .integer).indexed()
}
```
Create indexes on an existing table:
```swift
// CREATE INDEX index_player_on_email ON player(email)
try db.create(indexOn: "player", columns: ["email"])
// CREATE UNIQUE INDEX index_player_on_email ON player(email)
try db.create(indexOn: "player", columns: ["email"], options: .unique)
```
Create indexes with a specific collation:
```swift
// CREATE INDEX index_player_on_email ON player(email COLLATE NOCASE)
try db.create(
index: "index_player_on_email",
on: "player",
expressions: [Column("email").collating(.nocase)])
```
Create indexes on expressions:
```swift
// CREATE INDEX index_player_on_total_score ON player(score+bonus)
try db.create(
index: "index_player_on_total_score",
on: "player",
expressions: [Column("score") + Column("bonus")])
// CREATE INDEX index_player_on_country ON player(address ->> 'country')
try db.create(
index: "index_player_on_country",
on: "player",
expressions: [
JSONColumn("address")["country"],
])
```
Unique constraints and unique indexes are somewhat different: don't miss the tip in <doc:DatabaseSchemaRecommendations/Unique-keys-should-be-supported-by-unique-indexes> below.
## Topics
### Database Tables
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:options:using:)``
- ``Database/create(virtualTable:options:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
- ``Database/rename(table:to:)``
- ``Database/ColumnType``
- ``Database/ConflictResolution``
- ``Database/ForeignKeyAction``
- ``TableAlteration``
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- ``VirtualTableOptions``
### Database Views
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### Sunsetted Methods
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
@@ -0,0 +1,334 @@
# Database Schema Recommendations
Recommendations for an ideal integration of the database schema with GRDB
## Overview
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
## Table names should be English, singular, and camelCased
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// table columns and constraints
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "players") { t in
// table columns and constraints
}
```
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
```swift
extension Player: TableRecord {
// Required because table name is not 'player'
static let databaseTableName = "players"
}
extension PostalAddress: TableRecord {
// Required because table name is not 'postalAddress'
static let databaseTableName = "postal_address"
}
extension Award: TableRecord {
// Required because table name is not 'award'
static let databaseTableName = "Auszeichnung"
}
```
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
```swift
extension Player: TableRecord {
// Explicit association key because the table name is not 'postalAddress'
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
// Explicit association key because the table name is not 'award'
static let awards = hasMany(Award.self, key: "awards")
}
```
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
## Column names should be camelCased
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("fullName", .text).notNull()
t.column("score", .integer).notNull()
t.column("creationDate", .datetime).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("full_name", .text).notNull()
t.column("score", .integer).notNull()
t.column("creation_date", .datetime).notNull()
}
```
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
```swift
struct Player: Decodable, FetchableRecord {
var id: Int64
var fullName: String
var score: Int
var creationDate: Date
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id, fullName = "full_name", score, creationDate = "creation_date"
}
}
```
## Tables should have explicit primary keys
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// Auto-incremented primary key
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "team") { t in
// Single-column primary key
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.belongsTo("player")
t.belongsTo("team")
}
t.column("role", .text).notNull()
}
```
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
See <doc:SingleRowTables> when you need to define a table that contains a single row.
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
```swift
// A table without any explicit primary key
try db.create(table: "player") { t in
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
// The record type for the 'player' table'
struct Player: Codable {
// Uniquely identifies a player.
var rowid: Int64?
var name: String
var score: Int
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[.allColumns, .rowID]
}
// Update id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
rowid = inserted.rowID
}
}
try dbQueue.read { db in
// SELECT *, rowid FROM player WHERE rowid = 1
if let player = try Player.fetchOne(db, id: 1) {
// DELETE FROM player WHERE rowid = 1
let deleted = try player.delete(db)
print(deleted) // true
}
}
```
## Single-column primary keys should be named 'id'
This helps record types play well with the standard `Identifiable` protocol.
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.primaryKey("uuid", .text)
t.column("name", .text).notNull()
}
```
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
```swift
// Custom coding keys
struct Player: Codable, Identifiable {
var id: String
var name: String
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id = "uuid", name
}
}
// Extra property
struct Player: Identifiable {
var uuid: String
var name: String
// Required because the primary key column is not 'id'
var id: String { uuid }
}
```
## Unique keys should be supported by unique indexes
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
}
// One single player at any given position in a team
try db.create(
indexOn: "player",
columns: ["teamId", "position"],
options: .unique)
```
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
>
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
>
> ```swift
> // Unique constraint on player(name) can not be dropped.
> try db.create(table: "player") { t in
> t.column("name", .text).unique()
> }
>
> // Unique index on team(name) can be dropped.
> try db.create(table: "team") { t in
> t.column("name", .text)
> }
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
> ```
>
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
```swift
try dbQueue.write { db in
// Fatal error: table player has no unique index on columns ...
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
try Player.deleteOne(db, key: ["name": "Arthur"])
// Use instead:
let player = try Player
.filter { $0.teamId == 42 && $0.position == 1 }
.fetchOne(db)
try Player
.filter { $0.name == "Arthur" }
.deleteAll(db)
}
```
## Relations between tables should be supported by foreign keys
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
```swift
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("color", .text).notNull()
}
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.belongsTo("team").notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// No foreign key
t.column("teamId", .integer).notNull()
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
extension Player: TableRecord {
static let team = belongsTo(Team.self)
}
extension Team: TableRecord {
static let players = hasMany(Player.self)
}
```
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
```swift
extension Player: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let teamForeignKey = ForeignKey(["teamId"])
static let team = belongsTo(Team.self,
using: teamForeignKey)
}
extension Team: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let players = hasMany(Player.self,
using: Player.teamForeignKey)
}
```
@@ -59,7 +59,7 @@ You can feed `DatabaseRegionObservation` with any type that conforms to the ``Da
```swift
// Observe the score column of the 'player' table
let observation = DatabaseRegionObservation(
tracking: Player.select(Column("score")))
tracking: Player.select(\.score))
// Observe the 'score' column of the 'player' table
let observation = DatabaseRegionObservation(
@@ -107,10 +107,10 @@ import GRDB
import Tagged
// Add database support to Tagged values
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: StatementBinding where RawValue: StatementBinding { }
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
extension Tagged: @retroactive SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: @retroactive StatementBinding where RawValue: StatementBinding { }
extension Tagged: @retroactive StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: @retroactive DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
```
This makes it possible to use `Tagged` values in all the expected places:
@@ -103,9 +103,9 @@ By default, `ValueObservation` notifies the initial value, as well as eventual c
```swift
// The default scheduling
let cancellable = observation.start(in: dbQueue) { error in
// Called asynchronously on the main actor
// This closure is MainActor-isolated.
} onChange: { value in
// Called asynchronously on the main actor
// This closure is MainActor-isolated.
print("Fresh value", value)
}
```
@@ -214,7 +214,7 @@ Consider a scenario where you'd like to get a specific Player's row, but only wh
let observation = ValueObservation.tracking(
// Define the tracked database region
// (the score column of the player with id 1)
region: Player.select(Column("score")).filter(id: 1),
region: Player.select(\.score).filter(id: 1),
// Define what to fetch upon such change to the tracked region
// (the player with id 1)
fetch: { db in try Player.fetchOne(db, id: 1) }
@@ -263,6 +263,10 @@ You can filter out undesired duplicate notifications with the ``removeDuplicates
When needed, you can help GRDB optimize observations and reduce database contention:
> Important: **Keep your number of observations bounded.**
>
> In particular, do not observe independently all elements in a list. Instead, observe the whole list in a single observation.
> Tip: Stop observations when possible.
>
> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`.
+31 -4
View File
@@ -27,8 +27,8 @@ try db.create(table: "player") { t in
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
>
> ```swift
> // CREATE INDEX "player_on_country"
> // ON "player"("address" ->> 'country')
> // CREATE INDEX player_on_country
> // ON player(address ->> 'country')
> try db.create(
> index: "player_on_country",
> on: "player",
@@ -36,10 +36,16 @@ try db.create(table: "player") { t in
> JSONColumn("address")["country"],
> ])
>
> struct Player: FetchableRecord, TableRecord {
> enum Columns {
> static let address = JSONColumn("address")
> }
> }
>
> // SELECT * FROM player
> // WHERE "address" ->> 'country' = 'DE'
> // WHERE address ->> 'country' = 'DE'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .filter { $0.address["country"] == "DE" }
> .fetchAll(db)
> ```
@@ -98,6 +104,27 @@ extension Team: FetchableRecord, PersistableRecord {
}
```
> Tip: Conform your `Codable` property to `DatabaseValueConvertible` if you want to be able to filter on specific values of it:
>
> ```swift
> struct Address: Codable { ... }
> extension Address: DatabaseValueConvertible {}
>
> struct Player: FetchableRecord, TableRecord {
> enum Columns {
> static let address = JSONColumn("address")
> }
> }
>
> // SELECT * FROM player
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
> let players = try Player
> .filter { $0.address == Address(...) }
> .fetchAll(db)
> ```
>
> Take care that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`.
## Manipulate JSON values at the database level
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
+47 -7
View File
@@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in
}
```
#### How to Rename a Foreign Key
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
```swift
// IMPORTANT: rename foreign keys with immediate foreign key checks.
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
try db.rename(table: "team", to: "guild")
try db.alter(table: "player") { t in
// Rename a foreign key
t.rename(column: "teamId", to: "guildId")
}
}
```
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
#### How to Recreate a Database Table
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
For example:
@@ -113,19 +133,39 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
The detailed sequence of operations for recreating a database table from a migration is:
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
```swift
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
```
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
4. Drop the old table X: `DROP TABLE X`.
```swift
try db.create(table: "new_X") { t in ... }
```
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
3. Transfer content from `X` into `new_X` using a statement like:
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
```swift
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
```
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
4. Drop the old table `X`:
```swift
try db.drop(table: "X")
```
5. Change the name of `new_X` to `X` using:
```swift
try db.rename(table: "new_X", to: "X")
```
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
>
@@ -39,7 +39,7 @@ migrator.registerMigration("createLibrary") { db in
try migrator.migrate(dbQueue)
```
1. Our database tables follow the <doc:DatabaseSchema#Database-Schema-Recommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
1. Our database tables follow the <doc:DatabaseSchemaRecommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
@@ -214,7 +214,7 @@ extension Book.Kind: DatabaseValueConvertible { }
// Fetch all novels
let novels = try dbQueue.read { db in
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db)
}
```
@@ -297,7 +297,7 @@ Once we have record types that are able to read and write in the database, we'd
### Columns
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration, with the name `Columns`, nested inside the record type. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
```swift
// HOW TO define columns for a Codable record
@@ -310,13 +310,15 @@ extension Author {
}
```
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
For non-Codable record types, declare columns with their names:
```swift
// HOW TO define columns for a non-Codable record
extension Author {
enum Columns: String, ColumnExpression {
case id, name, countryCode
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let countryCode = Column("countryCode")
}
}
```
@@ -328,12 +330,12 @@ try dbQueue.read { db in
// Fetch all authors, ordered by name,
// in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
.fetchAll(db)
// Count French authors
let frenchAuthorCount: Int = try Author.all()
.filter(Author.Columns.countryCode == "FR")
.filter { $0.countryCode == "FR" }
.fetchCount(db)
}
```
@@ -349,13 +351,12 @@ Define those methods in extensions of the ``DerivableRequest`` protocol, as belo
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
}
/// Filters authors from a country
func filter(countryCode: String) -> Self {
filter(Author.Columns.countryCode == countryCode)
filter { $0.countryCode == countryCode }
}
}
@@ -363,13 +364,12 @@ extension DerivableRequest<Author> {
extension DerivableRequest<Book> {
/// Order books by title, in a localized case-insensitive fashion
func orderByTitle() -> Self {
let title = Book.Columns.title
return order(title.collating(.localizedCaseInsensitiveCompare))
order { $0.title.collating(.localizedCaseInsensitiveCompare) }
}
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
filter { $0.kind == kind }
}
}
```
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
// Selects authors' name
func selectName() -> QueryInterfaceRequest<String> {
select(\.name)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
// The names of Japanese authors
let names: Set<String> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.selectName()
.fetchSet(db)
```
+1 -1
View File
@@ -332,7 +332,7 @@ The full implementation of `TimestampedRecord` follows:
```swift
/// A record type that tracks its creation and modification dates. See
/// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps>
/// <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps>
protocol TimestampedRecord: MutablePersistableRecord {
var creationDate: Date? { get set }
var modificationDate: Date? { get set }
+69 -92
View File
@@ -39,11 +39,79 @@ All safety guarantees of Swift 6 are enforced during database accesses. They are
The following sections describe, with more details, how GRDB interacts with Swift Concurrency.
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Shorthand-Closure-Notation>
- <doc:SwiftConcurrency#Non-Sendable-Configuration-of-Record-Types>
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Choosing-between-Synchronous-and-Asynchronous-Database-Accesses>
### Shorthand Closure Notation
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
```swift
// Standard closure:
let count = try await writer.read { db in
try Player.fetchCount(db)
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
- **Using Xcode**
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
- **In a SwiftPM package manifest**
Enable the `InferSendableFromCaptures` upcoming feature:
```swift
.target(
name: "MyTarget",
swiftSettings: [
.enableUpcomingFeature("InferSendableFromCaptures")
]
)
```
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
### Non-Sendable Configuration of Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
```swift
extension Player: FetchableRecord, PersistableRecord {
// ❌ Static property 'databaseSelection' is not concurrency-safe
// because non-'Sendable' type '[any SQLSelectable]'
// may have shared mutable state
static let databaseSelection: [any SQLSelectable] = [
Columns.id, Columns.name, Columns.score
]
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let score = Column("score")
}
}
```
**To fix this error**, replace the stored property with a computed property:
```swift
extension Player: FetchableRecord, PersistableRecord {
static var databaseSelection: [any SQLSelectable] {
[Columns.id, Columns.name, Columns.score]
}
}
```
### Non-Sendable Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
@@ -128,97 +196,6 @@ You do not need to perform this refactoring right away: you can compile your app
Yes. Classes that can not be modified, made of constant `let` properties, are Sendable. Those immutable classes will not make it easy to modify the database, though.
#### FAQ: Why this Sendable requirement?
**GRDB needs new features in the Swift language and the SDKs in order to deal with non-Sendable types.**
[SE-0430: `sending` parameter and result values](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0430-transferring-parameters-and-results.md) looks like the language feature we need, but:
- `DispatchQueue.async` does not accept a `sending` closure. GRDB needs this in order to accept non-Sendable records to be sent to the database, as below:
```swift
let nonSendableRecord: Player
try await writer.write { db in
try nonSendableRecord.insert(db)
}
```
Please [file a feedback](http://feedbackassistant.apple.com) for requesting this DispatchQueue improvement. The more the merrier. I personally filed FB15270949.
- Database access methods taint the values they fetch. In the code below, the rules of [SE-0414: Region based Isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md) have the compiler refuse that the fetched player is sent back to the caller:
```swift
let player = try await writer.read { db in
try Player.fetchOne(db, id: 42)
}
```
Strictly speaking, the compiler diagnostic is correct: one could copy the non-Sendable `db` argument into the fetched `Player` instance, making it unsuitable for later use. In practice, nobody does that. Copying `db` is a programmer error, and GRDB promptly raises a fatal error whenever a `db` copy would be improperly used. But there is no way to tell the compiler about this practice.
For all those reasons, GRDB has to require values that are asynchronously written and read from the database to be `Sendable`.
### Shorthand Closure Notation
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
```swift
// Standard closure:
let count = try await writer.read { db in
try Player.fetchCount(db)
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
- **Using Xcode**
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
- **In a SwiftPM package manifest**
Enable the `InferSendableFromCaptures` upcoming feature:
```swift
.target(
name: "MyTarget",
swiftSettings: [
.enableUpcomingFeature("InferSendableFromCaptures")
]
)
```
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
### Non-Sendable Configuration of Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
```swift
extension Player: FetchableRecord, MutablePersistableRecord {
// ❌ Static property 'databaseSelection' is not concurrency-safe
// because non-'Sendable' type '[any SQLSelectable]'
// may have shared mutable state
static let databaseSelection: [any SQLSelectable] = [
Column("id"), Column("name"), Column("score")
]
}
```
**To fix this error**, replace the stored property with a computed property:
```swift
extension Player: FetchableRecord, MutablePersistableRecord {
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name"), Column("score")]
}
}
```
### Choosing between Synchronous and Asynchronous Database Accesses
GRDB connections provide two versions of `read` and `write`, one that is synchronous, and one that is asynchronous. It might not be clear how to choose one or the other.
+1 -1
View File
@@ -326,7 +326,7 @@ extension Database {
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
if Database.sqliteLibVersionNumber >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
+3 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS3 full-text engine.
///
/// To create FTS3 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts3(content)
@@ -63,7 +63,7 @@ public struct FTS3 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
/// Returns an array of tokens found in the string argument.
@@ -143,7 +143,7 @@ extension FTS3: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
+2 -2
View File
@@ -106,13 +106,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
}
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
+13 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS4 full-text engine.
///
/// To create FTS4 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts4(content)
@@ -31,7 +31,7 @@ public struct FTS4 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
}
@@ -102,6 +102,16 @@ extension FTS4: VirtualTableModule {
case .synchronized(let contentTable):
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts4(content="t", b, c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS4 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -149,7 +159,7 @@ extension FTS4: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
+15 -5
View File
@@ -13,7 +13,7 @@ import Foundation
/// The virtual table module for the FTS5 full-text engine.
///
/// To create FTS5 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
@@ -85,7 +85,7 @@ public struct FTS5 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
@@ -143,7 +143,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
FTS5TableDefinition(configuration: configuration)
}
@@ -219,7 +219,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
@@ -227,6 +227,16 @@ extension FTS5: VirtualTableModule {
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts5(content="t",content_rowid="a",b,c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS5 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -274,7 +284,7 @@ extension FTS5: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
+21 -2
View File
@@ -7,8 +7,9 @@
///
/// ### Creating Raw FTS5 Patterns
///
/// - ``init(rawPattern:allowedColumns:)``
/// - ``Database/makeFTS5Pattern(rawPattern:forTable:)``
///
///
/// ### Creating FTS5 Patterns from User Input
///
/// - ``init(matchingAllPrefixesIn:)``
@@ -123,7 +124,25 @@ public struct FTS5Pattern: Sendable {
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
}
init(rawPattern: String, allowedColumns: [String] = []) throws {
/// Creates a pattern from a raw pattern string.
///
/// The pattern syntax is documented at <https://www.sqlite.org/fts5.html#full_text_query_syntax>
///
/// For example:
///
/// ```swift
/// // OK
/// let pattern = try FTS5Pattern(rawPattern: "and")
///
/// // Throws an error: malformed MATCH expression: [AND]
/// let pattern = try FTS5Pattern(rawPattern: "AND")
/// ```
///
/// If the pattern tests for specific columns, you must pass those
/// columns in the `allowedColumns` parameter.
///
/// - throws: A ``DatabaseError`` if the pattern has an invalid syntax.
public init(rawPattern: String, allowedColumns: [String] = []) throws {
// Correctness above all: use SQLite to validate the pattern.
//
// Invalid patterns have SQLite return an error on the first
+4 -4
View File
@@ -112,14 +112,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("separators")
components.append(separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("tokenchars")
components.append(tokenCharacters.sorted().map { String($0) }.joined())
}
@@ -197,14 +197,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("separators")
components.append(separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("tokenchars")
components.append(tokenCharacters.sorted().map { String($0) }.joined())
}
+3
View File
@@ -1,4 +1,5 @@
// Fixits for changes introduced by GRDB 7.0.0
// swiftlint:disable all
extension Configuration {
@available(*, unavailable, message: "The default transaction kind is now automatically managed.")
@@ -15,3 +16,5 @@ extension DatabasePool {
@available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.")
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
}
// swiftlint:enable all
+7 -5
View File
@@ -28,7 +28,7 @@
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn!
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn
/// }
/// }
///
@@ -43,7 +43,7 @@
/// // Fetch all country codes
/// // SELECT DISTINCT address ->> 'countryCode' FROM player
/// let countryCodes: [String] = try Player
/// .select(Player.Columns.address["countryCode"], as: String.self)
/// .select({ $0.address["countryCode"] }, as: String.self)
/// .distinct()
/// .fetchAll(db)
/// }
@@ -59,8 +59,10 @@
/// > extension Player: FetchableRecord, PersistableRecord {
/// > // That's another valid way to define columns.
/// > // But we don't have any JSONColumn this time.
/// > enum Columns: String, ColumnExpression {
/// > case id, name, address
/// > enum Columns {
/// > static let id = Column("id")
/// > static let name = Column("name")
/// > static let address = Column("address")
/// > }
/// > }
/// >
@@ -68,7 +70,7 @@
/// > // Fetch all country codes
/// > // SELECT DISTINCT address ->> 'countryCode' FROM player
/// > let countryCodes: [String] = try Player
/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self)
/// > .select({ $0.address.asJSON["countryCode"] }, as: String.self)
/// > .distinct()
/// > .fetchAll(db)
/// > }
+60 -24
View File
@@ -135,12 +135,16 @@ extension SQLSpecificExpressible {
/// For example:
///
/// ```swift
/// let info = Column("info").asJSON
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = Column("info")
/// }
/// }
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .select({ $0.info.asJSON["firstName"] }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -157,18 +161,22 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .select({ $0.info["firstName"] }, as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .select({ $0.info["address"] }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -185,18 +193,22 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
/// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self)
/// .fetchOne(db)
///
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
/// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -212,12 +224,16 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
/// // → '["Arthur","Miller"]'
/// let nameComponents = try Player
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
/// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -235,18 +251,22 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT info -> 'firstName' FROM player
/// // → '"Arthur"'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
/// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self)
/// .fetchOne(db)
///
/// // SELECT info -> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
/// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -265,18 +285,22 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .select({ $0.info["firstName"] }, as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .select({ $0.info["address"] }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -294,18 +318,22 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
/// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self)
/// .fetchOne(db)
///
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
/// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -322,12 +350,16 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
/// // → '["Arthur","Miller"]'
/// let nameComponents = try Player
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
/// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self)
/// .fetchOne(db)
/// ```
///
@@ -346,18 +378,22 @@ extension SQLJSONExpressible {
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
/// struct Player: TableRecord {
/// enum Columns {
/// static let info = JSONColumn("info")
/// }
/// }
///
/// // SELECT info -> 'firstName' FROM player
/// // → '"Arthur"'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
/// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self)
/// .fetchOne(db)
///
/// // SELECT info -> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
/// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self)
/// .fetchOne(db)
/// ```
///
+410 -21
View File
@@ -1,4 +1,6 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// MARK: - JSON
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
@@ -339,8 +341,19 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
///
/// - parameter value: The tested value.
/// - parameter options: See eventual second argument of the
/// `JSON_VALID` function. See <https://www.sqlite.org/json1.html#the_json_valid_function>.
public static func jsonIsValid(
_ value: some SQLExpressible,
options: JSONValidationOptions? = nil
) -> SQLExpression {
if let options {
.function("JSON_VALID", [value.sqlExpression, options.rawValue.sqlExpression])
} else {
.function("JSON_VALID", [value.sqlExpression])
}
}
/// The `JSON_QUOTE` SQL function.
@@ -365,14 +378,21 @@ extension Database {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
/// Player.select(Database.jsonGroupArray(Column("name")))
/// Player.select { Database.jsonGroupArray($0.name) }
///
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
/// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) }
///
/// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player
/// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name")))
/// Player.select { Database.jsonGroupArray($0.name, orderBy: $0.name) }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@@ -394,16 +414,27 @@ extension Database {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score")))
/// Player.select {
/// Database.jsonGroupObject(
/// key: $0.name,
/// value: $0.score)
/// }
///
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score"),
/// filter: Column("score") > 0))
/// Player.select {
/// Database.jsonGroupObject(
/// key: $0.name,
/// value: $0.score,
/// filter: $0.score > 0)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@@ -419,7 +450,347 @@ extension Database {
isJSONValue: true)
}
}
// MARK: - JSONB
extension Database {
public struct JSONValidationOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static let json = JSONValidationOptions(rawValue: 1)
public static let json5 = JSONValidationOptions(rawValue: 2)
public static let probablyJSONB = JSONValidationOptions(rawValue: 4)
public static let jsonb = JSONValidationOptions(rawValue: 8)
}
/// Validates and returns a binary JSONB representation of the provided
/// JSON, with the `JSONB` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB(' { "a": [ "test" ] } ') → '{"a":["test"]}'
/// Database.jsonb(#" { "a": [ "test" ] } "#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
public static func jsonb(_ value: some SQLExpressible) -> SQLExpression {
.function("JSONB", [value.sqlExpression])
}
/// Creates a binary JSONB array with the `JSONB_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
/// Database.jsonbArray(1...4)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonbArray(
_ values: some Collection<some SQLExpressible>
) -> SQLExpression {
.function("JSONB_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// Creates a binary JSONB array with the `JSONB_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
/// Database.jsonbArray([1, 2, "3", 4])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonbArray(
_ values: some Collection<any SQLExpressible>
) -> SQLExpression {
.function("JSONB_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// The `JSONB_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_EXTRACT('{"a":123}', '$.a') → 123
/// Database.jsonbExtract(#"{"a":123}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSONB_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
/// The `JSONB_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
/// Database.jsonbExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbExtract(
_ value: some SQLExpressible,
atPaths paths: some Collection<some SQLExpressible>
) -> SQLExpression {
.function("JSONB_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSONB_INSERT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
/// Database.jsonbInsert("[1,2,3,4]", ["$[#]": value: 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbInsert(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_INSERT", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSONB_REPLACE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbReplace(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_REPLACE", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSONB_SET` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbSet(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_SET", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// Creates a binary JSONB object with the `JSONB_OBJECT` SQL function.
/// Pass key/value pairs with a Swift collection such as a `Dictionary`.
///
/// For example:
///
/// ```swift
/// // JSONB_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
/// Database.jsonbObject([
/// "c": #"{"e":5}"#,
/// ])
///
/// // JSONB_OBJECT('c', JSONB_OBJECT('e', 5)) → '{"c":{"e":5}}'
/// Database.jsonbObject([
/// "c": Database.jsonbObject(["e": 5])),
/// ])
///
/// // JSONB_OBJECT('c', JSONB('{"e":5}')) → '{"c":{"e":5}}'
/// Database.jsonbObject([
/// "c": Database.jsonb(#"{"e":5}"#),
/// ])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
public static func jsonbObject(
_ elements: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_OBJECT", elements.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSONB_PATCH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
/// Database.jsonbPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
public static func jsonbPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
-> SQLExpression
{
.function("JSONB_PATCH", [value.sqlExpression, patch.sqlExpression])
}
/// The `JSONB_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
/// Database.jsonbRemove("[0,1,2,3,4]", atPath: "$[2]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSONB_REMOVE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSONB_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
/// Database.jsonbRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbRemove(
_ value: some SQLExpressible,
atPaths paths: some Collection<some SQLExpressible>
) -> SQLExpression {
.function("JSONB_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSONB_GROUP_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT JSONB_GROUP_ARRAY(name) FROM player
/// Player.select { Database.jsonbGroupArray($0.name) }
///
/// // SELECT JSONB_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
/// Player.select { Database.jsonbGroupArray($0.name, filter: $0.score > 0) }
///
/// // SELECT JSONB_GROUP_ARRAY(name ORDER BY name) FROM player
/// Player.select { Database.jsonbGroupArray($0.name, orderBy: $0.name) }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonbGroupArray(
_ value: some SQLExpressible,
orderBy ordering: (any SQLOrderingTerm)? = nil,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction(
"JSONB_GROUP_ARRAY",
[value.sqlExpression.jsonBuilderExpression],
ordering: ordering?.sqlOrdering,
filter: filter?.sqlExpression,
isJSONValue: true)
}
/// The `JSONB_GROUP_OBJECT` SQL function.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT JSONB_GROUP_OBJECT(name, score) FROM player
/// Player.select {
/// Database.jsonbGroupObject(
/// key: $0.name,
/// value: $0.score)
/// }
///
/// // SELECT JSONB_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
/// Player.select {
/// Database.jsonbGroupObject(
/// key: $0.name,
/// value: $0.score,
/// filter: $0.score > 0)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonbGroupObject(
key: some SQLExpressible,
value: some SQLExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"JSONB_GROUP_OBJECT",
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
filter: filter?.sqlExpression,
isJSONValue: true)
}
}
#else
// MARK: - JSON
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
@@ -790,11 +1161,18 @@ extension Database {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
/// Player.select(Database.jsonGroupArray(Column("name")))
/// Player.select { Database.jsonGroupArray($0.name) }
///
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
/// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@@ -815,16 +1193,27 @@ extension Database {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score")))
/// Player.select {
/// Database.jsonGroupObject(
/// key: $0.name,
/// value: $0.score)
/// }
///
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score"),
/// filter: Column("score") > 0))
/// Player.select {
/// Database.jsonGroupObject(
/// key: $0.name,
/// value: $0.score,
/// filter: $0.score > 0)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
+97 -61
View File
@@ -40,6 +40,10 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
///
/// ### Detecting Schema Changes
///
/// - ``hasSchemaChanges(_:)``
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks: Sendable {
@@ -102,6 +106,8 @@ public struct DatabaseMigrator: Sendable {
/// migrator.eraseDatabaseOnSchemaChange = true
/// #endif
/// ```
///
/// See also ``hasSchemaChanges(_:)``.
public var eraseDatabaseOnSchemaChange = false
private var defersForeignKeyChecks = true
private var _migrations: [Migration] = []
@@ -279,6 +285,96 @@ public struct DatabaseMigrator: Sendable {
}
}
// MARK: - Detecting Schema Changes
/// Returns a boolean value indicating whether the migrator detects a
/// change in the definition of migrations.
///
/// The result is true if one of those conditions is met:
///
/// - A migration has been removed, or renamed.
/// - There exists any difference in the `sqlite_master` table, which
/// contains the SQL used to create database tables, indexes,
/// triggers, and views.
///
/// This method supports the ``eraseDatabaseOnSchemaChange`` option.
/// When `eraseDatabaseOnSchemaChange` does not exactly fit your
/// needs, you can implement it manually as below:
///
/// ```swift
/// #if DEBUG
/// // Speed up development by nuking the database when migrations change
/// if dbQueue.read(migrator.hasSchemaChanges) {
/// try dbQueue.erase()
/// // Perform other needed logic
/// }
/// #endif
/// try migrator.migrate(dbQueue)
/// ```
///
public func hasSchemaChanges(_ db: Database) throws -> Bool {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
return true
}
if let lastAppliedIdentifier = _migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
//
// Let's migrate a temporary database up to the same
// level, and compare the database schemas. If they
// differ, we'll return true
let tmpSchema = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = db.configuration
tmpConfig.readonly = false // We need write access
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.writeTargetQueue = nil // Avoid deadlocks
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
// Create the temporary database on disk, just in
// case migrations would involve a lot of data.
//
// SQLite supports temporary on-disk databases, but
// those are not guaranteed to accept the
// preparation functions provided by the user.
//
// See https://github.com/groue/GRDB.swift/issues/931
// for an issue created by such databases.
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
return try tmpDatabase.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema(.main)
}
}()
// Only compare user objects
func isUserObject(_ object: SchemaObject) -> Bool {
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
}
let tmpUserSchema = tmpSchema.filter(isUserObject)
let userSchema = try db.schema(.main).filter(isUserObject)
if userSchema != tmpUserSchema {
return true
}
}
return false
}
// MARK: - Querying Migrations
/// The list of registered migration identifiers, in the same order as they
@@ -409,69 +505,9 @@ public struct DatabaseMigrator: Sendable {
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
needsErase = true
return .commit
}
if let lastAppliedIdentifier = _migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
//
// Let's migrate a temporary database up to the same
// level, and compare the database schemas. If they
// differ, we'll erase the database.
let tmpSchema = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = db.configuration
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.writeTargetQueue = nil // Avoid deadlocks
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
// Create the temporary database on disk, just in
// case migrations would involve a lot of data.
//
// SQLite supports temporary on-disk databases, but
// those are not guaranteed to accept the
// preparation functions provided by the user.
//
// See https://github.com/groue/GRDB.swift/issues/931
// for an issue created by such databases.
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
return try tmpDatabase.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema(.main)
}
}()
// Only compare user objects
func isUserObject(_ object: SchemaObject) -> Bool {
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
}
let tmpUserSchema = tmpSchema.filter(isUserObject)
let userSchema = try db.schema(.main).filter(isUserObject)
if userSchema != tmpUserSchema {
needsErase = true
return .commit
}
}
needsErase = try hasSchemaChanges(db)
return .commit
}
if needsErase {
try db.erase()
}
@@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest {
}
let alias = TableAlias()
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
return self.aliased(alias).filter(matchExpression)
return self._aliased(alias).filter(matchExpression)
}
}
@@ -22,7 +22,7 @@ extension TableRequest where Self: FilteredRequest {
}
let alias = TableAlias()
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
return self.aliased(alias).filter(matchExpression)
return self._aliased(alias).filter(matchExpression)
}
}
+7 -15
View File
@@ -25,9 +25,14 @@
///
/// ```swift
/// struct Book: TableRecord {
/// enum Columns {
/// static let authorId = Column("authorId")
/// static let translatorId = Column("translatorId")
/// }
///
/// // Define foreign keys
/// static let authorForeignKey = ForeignKey(["authorId"]))
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
///
/// // Use foreign keys to define associations:
/// static let author = belongsTo(
@@ -41,19 +46,6 @@
/// }
/// ```
///
/// Foreign keys can also be defined from query interface columns:
///
/// ```swift
/// struct Book: TableRecord {
/// enum Columns: String, ColumnExpression {
/// case id, title, authorId, translatorId
/// }
///
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
/// }
/// ```
///
/// When the destination table does not define any primary key, you need to
/// provide the destination columns:
///
@@ -164,7 +164,7 @@ extension Association {
// TableRequest conformance
extension Association {
public func aliased(_ alias: TableAlias) -> Self {
public func _aliased(_ alias: TableAliasBase) -> Self {
withDestinationRelation { relation in
relation = relation.aliased(alias)
}
@@ -305,15 +305,25 @@ extension AssociationToOne {
///
/// ### Building Association Aggregates
///
/// - ``average(_:)``
/// - ``average(_:)-1ehdb``
/// - ``count``
/// - ``isEmpty``
/// - ``max(_:)``
/// - ``min(_:)``
/// - ``sum(_:)``
/// - ``total(_:)``
/// - ``max(_:)-a32j``
/// - ``min(_:)-41jp8``
/// - ``sum(_:)-47yg7``
/// - ``total(_:)-6dd9d``
///
/// - ``AssociationAggregate``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above.
///
/// - ``average(_:)-4bbk9``
/// - ``max(_:)-4g5ut``
/// - ``min(_:)-6al4w``
/// - ``sum(_:)-6ge96``
/// - ``total(_:)-56v8i``
public protocol AssociationToMany: Association { }
extension AssociationToMany {
@@ -136,6 +136,56 @@ extension AssociationToMany {
}
}
/// Returns the average of the given expression in associated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// struct Team: FetchableRecord, TableRecord {
/// static let players = Team.hasMany(Player.self)
/// }
///
/// try dbQueue.read { db in
/// // Fetch all teams whose average player score is greater than 1000
/// let averageScore = Team.players.average(\.score)
/// let teams: [Team] = try Team
/// .having(averageScore >= 1000)
/// .fetchAll(db)
/// }
/// ```
///
/// When the input expression is a ``ColumnExpression``, the returned
/// association aggregate is named `"average[Key][Column]"`, where `key` is
/// the association key. For example:
///
/// ```swift
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var averagePlayerScore: Double
/// }
///
/// try dbQueue.read { db in
/// let averageScore = Team.players.average(\.score)
/// let infos: [TeamInfo] = try Team
/// .annotated(with: averageScore)
/// .asRequest(of: TeamInfo.self)
/// .fetchAll(db)
/// }
/// ```
public func average(
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
try average(expression(RowDecoder.databaseComponents))
}
/// Returns the maximum value of the given expression in associated records.
///
/// For example:
@@ -183,6 +233,56 @@ extension AssociationToMany {
}
}
/// Returns the maximum value of the given expression in associated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// struct Team: FetchableRecord, TableRecord {
/// static let players = Team.hasMany(Player.self)
/// }
///
/// try dbQueue.read { db in
/// // Fetch all teams whose maximum player score is greater than 1000
/// let maxScore = Team.players.max(\.score)
/// let teams: [Team] = try Team
/// .having(maxScore >= 1000)
/// .fetchAll(db)
/// }
/// ```
///
/// When the input expression is a ``ColumnExpression``, the returned
/// association aggregate is named `"maximum[Key][Column]"`, where `key` is
/// the association key. For example:
///
/// ```swift
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var maximumPlayerScore: Double
/// }
///
/// try dbQueue.read { db in
/// let maxScore = Team.players.max(\.score)
/// let infos: [TeamInfo] = try Team
/// .annotated(with: maxScore)
/// .asRequest(of: TeamInfo.self)
/// .fetchAll(db)
/// }
/// ```
public func max(
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
try max(expression(RowDecoder.databaseComponents))
}
/// Returns the minimum value of the given expression in associated records.
///
/// For example:
@@ -230,10 +330,61 @@ extension AssociationToMany {
}
}
/// Returns the minimum value of the given expression in associated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// struct Team: FetchableRecord, TableRecord {
/// static let players = Team.hasMany(Player.self)
/// }
///
/// try dbQueue.read { db in
/// // Fetch all teams whose minimum player score is less than 1000
/// let minScore = Team.players.min(\.score)
/// let teams: [Team] = try Team
/// .having(minScore < 1000)
/// .fetchAll(db)
/// }
/// ```
///
/// When the input expression is a ``ColumnExpression``, the returned
/// association aggregate is named `"minimum[Key][Column]"`, where `key` is
/// the association key. For example:
///
/// ```swift
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var minimumPlayerScore: Double
/// }
///
/// try dbQueue.read { db in
/// let minScore = Team.players.min(\.score)
/// let infos: [TeamInfo] = try Team
/// .annotated(with: minScore)
/// .asRequest(of: TeamInfo.self)
/// .fetchAll(db)
/// }
/// ```
public func min(
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
try min(expression(RowDecoder.databaseComponents))
}
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `SUM` SQL function. See also ``total(_:)``
/// and <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
/// This aggregate invokes the `SUM` SQL function.
/// See also ``AssociationToMany/total(_:)-56v8i`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
///
@@ -282,8 +433,63 @@ extension AssociationToMany {
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `TOTAL` SQL function. See also ``sum(_:)``
/// and <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
/// This aggregate invokes the `SUM` SQL function.
/// See also ``AssociationToMany/total(_:)-6dd9d`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// struct Team: FetchableRecord, TableRecord {
/// static let players = Team.hasMany(Player.self)
/// }
///
/// try dbQueue.read { db in
/// // Fetch all teams whose sum of player scores is greater than 1000
/// let scoreSum = Team.players.sum(\.score)
/// let teams: [Team] = try Team
/// .having(scoreSum >= 1000)
/// .fetchAll(db)
/// }
/// ```
///
/// When the input expression is a ``ColumnExpression``, the returned
/// association aggregate is named `"[key][Column]Sum"`, where `key` is the
/// association key. For example:
///
/// ```swift
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerScoreSum: Double
/// }
///
/// try dbQueue.read { db in
/// let scoreSum = Team.players.sum(\.score)
/// let infos: [TeamInfo] = try Team
/// .annotated(with: scoreSum)
/// .asRequest(of: TeamInfo.self)
/// .fetchAll(db)
/// }
/// ```
public func sum(
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
try sum(expression(RowDecoder.databaseComponents))
}
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `TOTAL` SQL function.
/// See also ``AssociationToMany/sum(_:)-6ge96`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
///
@@ -331,6 +537,64 @@ extension AssociationToMany {
return aggregate
}
}
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `TOTAL` SQL function.
/// See also ``AssociationToMany/sum(_:)-47yg7`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// struct Team: FetchableRecord, TableRecord {
/// static let players = Team.hasMany(Player.self)
/// }
///
/// try dbQueue.read { db in
/// // Fetch all teams whose sum of player scores is greater than 1000
/// let totalScore = Team.players.total(\.score)
/// let teams: [Team] = try Team
/// .having(totalScore >= 1000)
/// .fetchAll(db)
/// }
/// ```
///
/// When the input expression is a ``ColumnExpression``, the returned
/// association aggregate is named `"[key][Column]Sum"`, where `key` is the
/// association key. For example:
///
/// ```swift
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerScoreSum: Double
/// }
///
/// try dbQueue.read { db in
/// let totalScore = Team.players.total(\.score)
/// let infos: [TeamInfo] = try Team
/// .annotated(with: totalScore)
/// .asRequest(of: TeamInfo.self)
/// .fetchAll(db)
/// }
/// ```
public func total(
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
try total(expression(RowDecoder.databaseComponents))
}
}
extension AssociationToMany where RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
}
/// A value aggregated from a population of associated records.
@@ -385,12 +385,18 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible
)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: cte.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a common table expression that you can join
@@ -421,13 +427,18 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Destination.Type,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
JoinAssociation(
to: Destination.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a table record that you can join
@@ -458,12 +469,17 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Table<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: destination.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a table that you can join
@@ -23,15 +23,20 @@
/// ``Table`` instance. For example:
///
/// ```swift
/// struct Player: TableRecord, FetchableRecord, DecodableRecord { }
/// struct Player: TableRecord, FetchableRecord, DecodableRecord {
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// // WHERE name = 'O''Reilly'
/// // ORDER BY score DESC
/// let request = Player
/// .filter(Column("name") == "O'Reilly")
/// .order(Column("score").desc)
/// .filter { $0.name == "O'Reilly" }
/// .order(\.score.desc)
/// let players: [Player] = try request.fetchAll(db)
/// }
/// ```
@@ -52,10 +57,10 @@
/// ### Changing The Type of Fetched Results
///
/// - ``asRequest(of:)``
/// - ``select(_:as:)-282xc``
/// - ``select(_:as:)-3o8qw``
/// - ``select(_:as:)-4cj9h``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
///
/// ### Batch Delete
@@ -65,17 +70,31 @@
/// - ``deleteAndFetchCursor(_:)``
/// - ``deleteAndFetchAll(_:)``
/// - ``deleteAndFetchSet(_:)``
/// - ``deleteAndFetchStatement(_:selection:)``
/// - ``deleteAndFetchStatement(_:select:)``
///
/// ### Batch Update
///
/// - ``updateAll(_:onConflict:assignment:)``
/// - ``updateAll(_:onConflict:assignments:)``
/// - ``updateAndFetchCursor(_:onConflict:assignments:)``
/// - ``updateAndFetchAll(_:onConflict:assignments:)``
/// - ``updateAndFetchSet(_:onConflict:assignments:)``
/// - ``updateAndFetchStatement(_:onConflict:assignments:select:)``
/// - ``ColumnAssignment``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above.
///
/// - ``deleteAndFetchStatement(_:selection:)``
/// - ``select(_:as:)-282xc``
/// - ``select(_:as:)-3o8qw``
/// - ``updateAll(_:onConflict:_:)-9r4v``
/// - ``updateAll(_:onConflict:_:)-49qg8``
/// - ``updateAndFetchCursor(_:onConflict:_:)``
/// - ``updateAndFetchAll(_:onConflict:_:)``
/// - ``updateAndFetchSet(_:onConflict:_:)``
/// - ``updateAndFetchStatement(_:onConflict:_:selection:)``
/// - ``ColumnAssignment``
public struct QueryInterfaceRequest<RowDecoder> {
var relation: SQLRelation
}
@@ -186,6 +205,37 @@ extension QueryInterfaceRequest: SelectionRequest {
select(selection, as: type)
}
/// Defines the result columns, and defines the type of decoded rows.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let id = Column("id")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT id FROM player
/// let request = Player.all().select(\.id, as: Int.self)
/// let scores = try request.fetchSet(db) // Set<Int>
///
/// // SELECT MAX(score) FROM player
/// let request = Player.all().select({ max($0.score) }, as: Int.self)
/// let maxScore = try request.fetchOne(db) // Int?
/// ```
///
/// Any previous selection is discarded.
public func select<T>(
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
as type: T.Type = T.self
) rethrows -> QueryInterfaceRequest<T>
where RowDecoder: TableRecord
{
try select(selection).asRequest(of: T.self)
}
/// Defines the result columns with an SQL string, and defines the type of
/// decoded rows.
///
@@ -237,7 +287,7 @@ extension QueryInterfaceRequest: SelectionRequest {
select(sqlLiteral, as: type)
}
/// Selects the primary key.
/// Returns a request that selects the primary key.
///
/// All primary keys are supported:
///
@@ -281,6 +331,46 @@ extension QueryInterfaceRequest: SelectionRequest {
.asRequest(of: PrimaryKey.self)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// // SELECT id FROM player WHERE ...
/// let request = try Player.filter(...).selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try Player.filter(...)
/// .selectID()
/// .fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try Player.filter(...)
/// .selectPrimaryKey(as: Int64.self)
/// .fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable & SendableMetatype
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
@@ -320,15 +410,27 @@ extension QueryInterfaceRequest: OrderedRequest {
/// Creates a request that reverses applied orderings.
///
/// // SELECT * FROM player ORDER BY name DESC
/// var request = Player.all().order(Column("name"))
/// request = request.reversed()
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player ORDER BY name DESC
/// var request = Player.all().order(\.name)
/// request = request.reversed()
/// ```
///
/// If no ordering was applied, the returned request is identical.
///
/// // SELECT * FROM player
/// var request = Player.all()
/// request = request.reversed()
/// ```swift
/// // SELECT * FROM player
/// var request = Player.all()
/// request = request.reversed()
/// ```
public func reversed() -> Self {
with {
$0.relation = $0.relation.reversed()
@@ -337,9 +439,18 @@ extension QueryInterfaceRequest: OrderedRequest {
/// Creates a request without any ordering.
///
/// // SELECT * FROM player
/// var request = Player.all().order(Column("name"))
/// request = request.unordered()
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player
/// let request = Player.all()
/// .order(\.name)
/// .unordered()
/// ```
public func unordered() -> Self {
with {
$0.relation = $0.relation.unordered()
@@ -414,7 +525,7 @@ extension QueryInterfaceRequest: TableRequest {
relation.source.tableName
}
public func aliased(_ alias: TableAlias) -> Self {
public func _aliased(_ alias: TableAliasBase) -> Self {
with {
$0.relation = $0.relation.aliased(alias)
}
@@ -462,9 +573,15 @@ extension QueryInterfaceRequest {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.read { db in
/// let maxScore: Int? = try Player
/// .select(max(scoreColumn))
/// .select { max($0.score) }
/// .asRequest(of: Int.self) // <--
/// .fetchOne(db)
/// }
@@ -474,6 +591,10 @@ extension QueryInterfaceRequest {
}
}
extension QueryInterfaceRequest where RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
}
// MARK: - Check Existence
extension QueryInterfaceRequest {
@@ -482,9 +603,15 @@ extension QueryInterfaceRequest {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// try dbQueue.read { db in
/// let arthurIsMissing = try Player
/// .filter(Column("name") == "Arthur")
/// .filter { $0.name == "Arthur" }
/// .isEmpty(db)
/// }
/// ```
@@ -545,6 +672,43 @@ extension QueryInterfaceRequest {
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // Delete all players and return their names
/// // DELETE FROM player RETURNING name
/// let request = Player.all()
/// let statement = try request.deleteAndFetchStatement(db, selection: \.name)
/// let deletedNames = try String.fetchSet(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `select` is not empty.
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
}
/// Returns a cursor over the records deleted by a
/// `DELETE RETURNING` statement.
///
@@ -692,6 +856,44 @@ extension QueryInterfaceRequest {
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // Delete all players and return their names
/// // DELETE FROM player RETURNING name
/// let request = Player.all()
/// let statement = try request.deleteAndFetchStatement(db, selection: \.name)
/// let deletedNames = try String.fetchSet(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `select` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
}
/// Returns a cursor over the records deleted by a
/// `DELETE RETURNING` statement.
///
@@ -830,6 +1032,75 @@ extension QueryInterfaceRequest {
}
}
/// Updates matching rows, and returns the number of updated rows.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// let request = Player.all()
/// try request.updateAll(db) { $0.score.set(to: 0) }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignment: A closure that returns an assignment.
/// - returns: The number of updated rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)])
}
/// Updates matching rows, and returns the number of updated rows.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// let request = Player.all()
/// try request.updateAll(db) { $0.score.set(to: 0) }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: The number of updated rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Updates matching rows, and returns the number of updated rows.
///
/// For example:
@@ -898,6 +1169,57 @@ extension QueryInterfaceRequest {
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score)
/// }
/// }
///
/// // Fetch all updated scores
/// // UPDATE player SET score = score + 10 RETURNING score
/// let request = Player.all()
/// let statement = try request.updateAndFetchStatement(db) {
/// $0.score += 10
/// } select: {
/// [$0.score]
/// }
/// let updatedScores = try Int.fetchAll(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments (must not be empty).
/// - parameter selection: A closure that returns the returned columns
/// (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The results of `select` and `assignments` results
/// are not empty.
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
db,
onConflict: conflictResolution,
assignments(RowDecoder.databaseComponents),
selection: select(RowDecoder.databaseComponents))
}
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
@@ -946,6 +1268,48 @@ extension QueryInterfaceRequest {
return updateStatement
}
/// Returns a cursor over the records updated by an
/// `UPDATE RETURNING` statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] }
/// while let player = try players.next() {
/// print("Player \(player) was updated")
/// }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: A cursor over the updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Returns a cursor over the records updated by an
/// `UPDATE RETURNING` statement.
///
@@ -986,6 +1350,45 @@ extension QueryInterfaceRequest {
return try RowDecoder.fetchCursor(statement)
}
/// Execute an `UPDATE RETURNING` statement and returns the array of
/// updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: An array of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Execute an `UPDATE RETURNING` statement and returns the array of
/// updated records.
///
@@ -1018,6 +1421,45 @@ extension QueryInterfaceRequest {
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
/// Execute an `UPDATE RETURNING` statement and returns the set of
/// updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10]) }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: A set of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Execute an `UPDATE RETURNING` statement and returns the set of
/// updated records.
///
@@ -1050,6 +1492,58 @@ extension QueryInterfaceRequest {
try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
#else
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score)
/// }
/// }
///
/// // Fetch all updated scores
/// // UPDATE player SET score = score + 10 RETURNING score
/// let request = Player.all()
/// let statement = try request.updateAndFetchStatement(db) {
/// $0.score += 10
/// } select: {
/// [$0.score]
/// }
/// let updatedScores = try Int.fetchAll(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments (must not be empty).
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The results of `select` and `assignments` results
/// are not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
db,
onConflict: conflictResolution,
assignments(RowDecoder.databaseComponents),
selection: select(RowDecoder.databaseComponents))
}
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
@@ -1099,6 +1593,49 @@ extension QueryInterfaceRequest {
return updateStatement
}
/// Returns a cursor over the records updated by an
/// `UPDATE RETURNING` statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] }
/// while let player = try players.next() {
/// print("Player \(player) was updated")
/// }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: A cursor over the updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Returns a cursor over the records updated by an
/// `UPDATE RETURNING` statement.
///
@@ -1140,6 +1677,46 @@ extension QueryInterfaceRequest {
return try RowDecoder.fetchCursor(statement)
}
/// Execute an `UPDATE RETURNING` statement and returns the array of
/// updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: An array of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Execute an `UPDATE RETURNING` statement and returns the array of
/// updated records.
///
@@ -1173,6 +1750,46 @@ extension QueryInterfaceRequest {
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
/// Execute an `UPDATE RETURNING` statement and returns the set of
/// updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10]) }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: A set of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Execute an `UPDATE RETURNING` statement and returns the set of
/// updated records.
///
@@ -1216,10 +1833,17 @@ extension QueryInterfaceRequest {
/// such as ``ColumnExpression/set(to:)`` or `+=`:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// let assignment = Column("score").set(to: 0)
/// try Player.updateAll(db, assignment)
/// try Player.updateAll(db) {
/// $0.score.set(to: 0)
/// }
/// }
/// ```
public struct ColumnAssignment {
@@ -1261,9 +1885,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.updateAll(db, Column("score").set(to: 0))
/// try Player.updateAll(db) { $0.set(to: 0) }
/// }
/// ```
public func set(to value: (any SQLExpressible)?) -> ColumnAssignment {
@@ -1289,9 +1919,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score + 1
/// try Player.updateAll(db, Column("score") += 1)
/// try Player.updateAll(db) { $0.score += 1 }
/// }
/// ```
public static func += (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1310,9 +1946,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score - 1
/// try Player.updateAll(db, Column("score") -= 1)
/// try Player.updateAll(db) { $0.score -= 1 }
/// }
/// ```
public static func -= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1331,9 +1973,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score * 2
/// try Player.updateAll(db, Column("score") *= 2)
/// try Player.updateAll(db) { $0.score *= 2 }
/// }
/// ```
public static func *= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1352,9 +2000,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score / 2
/// try Player.updateAll(db, Column("score") /= 2)
/// try Player.updateAll(db) { $0.score /= 2 }
/// }
/// ```
public static func /= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1373,9 +2027,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let mask = Column("mask")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score & 2
/// try Player.updateAll(db, Column("mask") &= 2)
/// // UPDATE player SET mask = mask & 2
/// try Player.updateAll(db) { $0.mask &= 2 }
/// }
/// ```
public static func &= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1394,9 +2054,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let mask = Column("mask")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score | 2
/// try Player.updateAll(db, Column("mask") |= 2)
/// // UPDATE player SET mask = mask | 2
/// try Player.updateAll(db) { $0.mask |= 2 }
/// }
/// ```
public static func |= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1415,9 +2081,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let mask = Column("mask")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score << 2
/// try Player.updateAll(db, Column("mask") <<= 2)
/// // UPDATE player SET mask = mask << 2
/// try Player.updateAll(db) { $0.mask <<= 2 }
/// }
/// ```
public static func <<= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -1436,9 +2108,15 @@ extension ColumnExpression {
/// Usage:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let mask = Column("mask")
/// }
/// }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = score >> 2
/// try Player.updateAll(db, Column("mask") >>= 2)
/// // UPDATE player SET mask = mask >> 2
/// try Player.updateAll(db) { $0.mask >>= 2 }
/// }
/// ```
public static func >>= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
@@ -22,14 +22,23 @@ public protocol TypedRequest<RowDecoder> {
///
/// ### The SELECT Clause
///
/// - ``annotated(with:)-4qcem``
/// - ``annotated(with:)-6ehs4``
/// - ``annotated(with:)-9wodv``
/// - ``annotated(with:)-69r3``
/// - ``annotatedWhenConnected(with:)``
/// - ``select(_:)-30yzl``
/// - ``select(_:)-7e2y5``
/// - ``select(_:)-270ge``
/// - ``select(_:)-4jw13``
/// - ``select(literal:)``
/// - ``select(sql:arguments:)``
/// - ``selectWhenConnected(_:)``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above.
///
/// - ``annotated(with:)-4qcem``
/// - ``annotated(with:)-6ehs4``
/// - ``select(_:)-30yzl``
/// - ``select(_:)-7e2y5``
public protocol SelectionRequest {
/// Defines the result columns.
///
@@ -209,6 +218,122 @@ extension SelectionRequest {
}
}
extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
/// Defines the result column.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let id = Column("id")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT score FROM player
/// let request = Player.all().select(\.score)
/// ```
///
/// Any previous selection is replaced:
///
/// ```swift
/// // SELECT score FROM player
/// let request = Player.all()
/// .select(\.id)
/// .select(\.score)
/// ```
public func select(
_ selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> Self {
try select(selection(Self.RowDecoder.databaseComponents))
}
/// Defines the result columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let id = Column("id")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT id, score FROM player
/// let request = Player.all().select { [$0.id, $0.score] }
/// ```
///
/// Any previous selection is replaced:
///
/// ```swift
/// // SELECT score FROM player
/// let request = Player.all()
/// .select { [$0.id] }
/// .select { [$0.score] }
/// ```
public func select(
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> Self {
try select(selection(Self.RowDecoder.databaseComponents))
}
/// Appends a result column to the selected columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let bonus = Column("bonus")
/// }
/// }
///
/// // SELECT *, score + bonus AS totalScore FROM player
/// let request = Player.all().annotated {
/// ($0.score + $0.bonus).forKey("totalScore")
/// }
/// ```
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
public func annotated(
with selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> Self {
try annotated(with: selection(Self.RowDecoder.databaseComponents))
}
/// Appends result columns to the selected columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let bonus = Column("bonus")
/// }
/// }
///
/// // SELECT *, score + bonus AS totalScore FROM player
/// let request = Player.all().annotated {
/// [($0.score + $0.bonus).forKey("totalScore")]
/// }
/// ```
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
public func annotated(
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> Self {
try annotated(with: selection(Self.RowDecoder.databaseComponents))
}
}
// MARK: - FilteredRequest
/// A request that can filter database rows.
@@ -221,11 +346,17 @@ extension SelectionRequest {
/// ### The WHERE and JOIN ON Clauses
///
/// - ``all()``
/// - ``filter(_:)``
/// - ``filter(_:)-7j0nw``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
/// - ``filterWhenConnected(_:)``
/// - ``none()``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above.
///
/// - ``filter(_:)-48a4t``
public protocol FilteredRequest {
/// Filters the fetched rows with a boolean SQL expression.
///
@@ -310,6 +441,34 @@ extension FilteredRequest {
}
}
extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
// prevent the `Player.filter { 42 }` misuse.
// See https://github.com/groue/GRDB.swift/pull/864
/// Filters the fetched rows with a boolean SQL expression.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = Player.all().filter { $0.name == name }
/// ```
public func filter(
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
) rethrows -> Self {
try filter(predicate(Self.RowDecoder.databaseComponents))
}
}
// MARK: - TableRequest
/// A request that feeds from a database table
@@ -322,7 +481,7 @@ extension FilteredRequest {
///
/// ### Instance Methods
///
/// - ``aliased(_:)``
/// - ``aliased(_:)-3k5h4``
/// - ``TableAlias``
///
/// ### The WHERE Clause
@@ -343,11 +502,23 @@ extension FilteredRequest {
/// ### The ORDER BY Clause
///
/// - ``orderByPrimaryKey()``
///
/// ### Legacy APIs
///
/// It is recommended to prefer record aliases over anonymous aliases.
///
/// - ``aliased(_:)-772vb``
public protocol TableRequest {
/// The name of the database table
var databaseTableName: String { get }
/// Returns a request that can be referred to with the provided alias.
func _aliased(_ alias: TableAliasBase) -> Self
}
extension TableRequest where Self: TypedRequest {
/// Returns a request that can be referred to with the provided
/// anonymous alias.
///
/// Use this method when you need to refer to this request from
/// another request.
@@ -402,7 +573,77 @@ public protocol TableRequest {
/// .filter(sql: "b.publishDate >= a.deathDate")
/// .fetchAll(db)
/// ```
func aliased(_ alias: TableAlias) -> Self
public func aliased(_ alias: TableAlias<Void>) -> Self {
self._aliased(alias)
}
/// Returns a request that can be referred to with the provided
/// record alias.
///
/// Use this method when you need to refer to this request from
/// another request.
///
/// The first example fetches posthumous books:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// enum Columns {
/// static let deathDate = Column("deathDate")
/// }
/// }
///
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// enum Columns {
/// static let publishDate = Column("publishDate")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // WHERE book.publishDate >= author.deathDate
/// let authorAlias = TableAlias<Author>()
/// let posthumousBooks = try Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .filter { $0.publishDate >= authorAlias.deathDate }
/// .fetchAll(db)
/// ```
///
/// The second example sorts books by author name first, and then by title:
///
/// ```swift
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name, book.title
/// let authorAlias = TableAlias<Author>()
/// let books = try Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order { [authorAlias.name, $0.title] }
/// .fetchAll(db)
/// ```
///
/// The third example uses named ``TableAlias`` so that SQL snippets can
/// refer to SQL tables with those names:
///
/// ```swift
/// // SELECT b.*
/// // FROM book b
/// // JOIN author a ON a.id = b.authorId
/// // AND a.countryCode = 'FR'
/// // WHERE b.publishDate >= a.deathDate
/// let bookAlias = TableAlias<Book>(name: "b")
/// let authorAlias = TableAlias<Author>(name: "a")
/// let posthumousFrenchBooks = try Book.aliased(bookAlias)
/// .joining(required: Book.author.aliased(authorAlias)
/// .filter(sql: "a.countryCode = ?", arguments: ["FR"]))
/// .filter(sql: "b.publishDate >= a.deathDate")
/// .fetchAll(db)
/// ```
public func aliased(_ alias: TableAlias<RowDecoder>) -> Self {
self._aliased(alias)
}
}
extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
@@ -458,11 +699,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
return filterWhenConnected(keys: { [databaseTableName] db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = primaryKey.columns[0]
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
let strategy = recordType.databaseDataEncodingStrategy(for: column)
let expressions = try datas.map { try strategy.encode($0).sqlExpression }
return expressions
@@ -475,11 +712,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
return filterWhenConnected(keys: { [databaseTableName] db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = primaryKey.columns[0]
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
let strategy = recordType.databaseDateEncodingStrategy(for: column)
let expressions = dates.map { strategy.encode($0).sqlExpression }
return expressions
@@ -492,11 +725,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
return filterWhenConnected(keys: { [databaseTableName] db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = primaryKey.columns[0]
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
let strategy = recordType.databaseUUIDEncodingStrategy(for: column)
let expressions = uuids.map { strategy.encode($0).sqlExpression }
return expressions
@@ -524,12 +753,8 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// Don't bother removing NULLs. We'd lose CPU cycles, and this does not
// change the SQLite results anyway.
let expressions = try keys(db)
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
return SQLCollection.array(expressions).contains(Column(primaryKey.columns[0]).sqlExpression)
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
return SQLCollection.array(expressions).contains(Column(column).sqlExpression)
}
}
@@ -739,18 +964,26 @@ extension TableRequest where Self: AggregatingRequest {
///
/// ### The GROUP BY Clause
///
/// - ``group(_:)-edak``
/// - ``group(_:)-4216o``
/// - ``group(_:)-5soxm``
/// - ``group(_:)-32exm``
/// - ``group(literal:)``
/// - ``group(sql:arguments:)``
/// - ``groupWhenConnected(_:)``
///
/// ### The HAVING Clause
///
/// - ``having(_:)``
/// - ``having(_:)-27hlo``
/// - ``having(literal:)``
/// - ``having(sql:arguments:)``
/// - ``havingWhenConnected(_:)``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above.
///
/// - ``group(_:)-edak``
/// - ``group(_:)-4216o``
/// - ``having(_:)-2ssg9``
public protocol AggregatingRequest {
/// Returns an aggregate request grouped on the given SQL expressions.
///
@@ -941,6 +1174,71 @@ extension AggregatingRequest {
}
}
extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
/// Returns an aggregate request grouped on the given SQL expression.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let teamId = Column("teamId")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// let request = Player
/// .select { [$0.teamId, max($0.score)] }
/// .group(\.teamId)
/// ```
///
/// Any previous grouping is discarded.
public func group(
_ expression: (DatabaseComponents) throws -> any SQLExpressible
) rethrows -> Self {
try group(expression(Self.RowDecoder.databaseComponents))
}
/// Returns an aggregate request grouped on the given SQL expressions.
public func group(
_ expressions: (DatabaseComponents) throws -> [any SQLExpressible]
) rethrows -> Self {
try group(expressions(Self.RowDecoder.databaseComponents))
}
/// Filters the aggregated groups with a boolean SQL expression.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let teamId = Column("teamId")
/// static let score = Column("score")
/// }
/// }
///
/// // SELECT teamId, MAX(score)
/// // FROM player
/// // GROUP BY teamId
/// // HAVING MAX(score) > 1000
/// let request = Player
/// .select { [$0.teamId, max($0.score)] }
/// .group(\.teamId)
/// .having { max($0.score) > 1000 }
/// ```
public func having(
_ predicate: (DatabaseComponents) throws -> any SQLExpressible
) rethrows -> Self {
try having(predicate(Self.RowDecoder.databaseComponents))
}
}
// MARK: - OrderedRequest
/// A request that can sort database rows.
@@ -949,14 +1247,21 @@ extension AggregatingRequest {
///
/// ### The ORDER BY Clause
///
/// - ``order(_:)-63rzl``
/// - ``order(_:)-6co0m``
/// - ``order(_:)-5q7wj``
/// - ``order(_:)-711zj``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderWhenConnected(_:)``
/// - ``reversed()``
/// - ``unordered()``
/// - ``withStableOrder()``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above.
///
/// - ``order(_:)-63rzl``
/// - ``order(_:)-6co0m``
public protocol OrderedRequest {
/// Sorts the fetched rows according to the given SQL ordering terms.
///
@@ -994,9 +1299,15 @@ public protocol OrderedRequest {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player ORDER BY name DESC
/// let request = Player.all()
/// .order(Column("name"))
/// .order(\.name)
/// .reversed()
/// ```
///
@@ -1010,12 +1321,16 @@ public protocol OrderedRequest {
/// Returns a request without any ordering.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player
/// let request = Player.all()
/// .order(Column("name"))
/// .order(\.name)
/// .unordered()
/// ```
func unordered() -> Self
@@ -1108,6 +1423,74 @@ extension OrderedRequest {
}
}
extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
/// Sorts the fetched rows according to the given SQL ordering term.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player ORDER BY name
/// let request = Player.all().order(\.name)
///
/// // SELECT * FROM player ORDER BY score DESC
/// let request = Player.all().order(\.score.desc)
/// ```
///
/// Any previous ordering is discarded:
///
/// ```swift
/// // SELECT * FROM player ORDER BY name
/// let request = Player.all()
/// .order(\.score.desc)
/// .order(\.name)
/// ```
public func order(
_ ordering: (DatabaseComponents) throws -> any SQLOrderingTerm
) rethrows -> Self {
try order(ordering(Self.RowDecoder.databaseComponents))
}
/// Sorts the fetched rows according to the given SQL ordering terms.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.all()
/// .order { [$0.score.desc, $0.name] }
/// ```
///
/// Any previous ordering is discarded:
///
/// ```swift
/// // SELECT * FROM player ORDER BY name
/// let request = Player.all()
/// .order { [$0.score.desc] }
/// .order { [$0.name] }
/// ```
public func order(
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
) rethrows -> Self {
try order(orderings(Self.RowDecoder.databaseComponents))
}
}
// MARK: - JoinableRequest
/// A request that can join and prefetch associations.
@@ -1250,12 +1633,17 @@ extension JoinableRequest {
/// For example, we can fetch only books whose author is French:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
/// struct Book: TableRecord, FetchableRecord, Decodable {
/// struct Author: TableRecord {
/// enum Columns {
/// static let countryCode = Column("countryCode")
/// }
/// }
///
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR")
/// let frenchAuthors = Book.author.filter { $0.countryCode == "FR" }
/// let bookInfos = try Book.all()
/// .joining(required: frenchAuthors)
/// .fetchAll(db)
@@ -1272,9 +1660,19 @@ extension JoinableRequest where Self: SelectionRequest {
/// For example:
///
/// ```swift
/// struct Team: TableRecord {
/// enum Columns {
/// static let countryCode = Column("countryCode")
/// }
/// }
///
/// struct Player: Decodable, TableRecord, FetchableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.color
/// // FROM player LEFT JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let teamColor = Player.team.select(\.color)
/// let request = Player.all().annotated(withOptional: teamColor)
/// ```
///
@@ -1300,9 +1698,9 @@ extension JoinableRequest where Self: SelectionRequest {
/// ``JoinableRequest/joining(optional:)``:
///
/// ```swift
/// let teamAlias = TableAlias()
/// let teamAlias = TableAlias<Team>()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .annotated(with: teamAlias.color)
/// .joining(optional: Player.team.aliased(teamAlias))
/// ```
public func annotated<A: Association>(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
@@ -1324,9 +1722,19 @@ extension JoinableRequest where Self: SelectionRequest {
/// For example:
///
/// ```swift
/// struct Team: TableRecord {
/// enum Columns {
/// static let color = Column("color")
/// }
/// }
///
/// struct Player: Decodable, FetchableRecord, TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.color
/// // FROM player JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let teamColor = Player.team.select(\.color)
/// let request = Player.all().annotated(withRequired: teamColor)
/// ```
///
@@ -1352,9 +1760,9 @@ extension JoinableRequest where Self: SelectionRequest {
/// ``JoinableRequest/joining(required:)``:
///
/// ```swift
/// let teamAlias = TableAlias()
/// let teamAlias = TableAlias<Team>()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .annotated(with: teamAlias.color])
/// .joining(required: Player.team.aliased(teamAlias))
/// ```
public func annotated<A: Association>(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder {
@@ -1383,7 +1791,7 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### Instance Methods
///
/// - ``TableRequest/aliased(_:)``
/// - ``TableRequest/aliased(_:)-3k5h4``
/// - ``TableAlias``
///
/// ### The WITH Clause
@@ -1392,12 +1800,12 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The SELECT Clause
///
/// - ``SelectionRequest/annotated(with:)-4qcem``
/// - ``SelectionRequest/annotated(with:)-6ehs4``
/// - ``SelectionRequest/annotated(with:)-9wodv``
/// - ``SelectionRequest/annotated(with:)-69r3``
/// - ``SelectionRequest/annotatedWhenConnected(with:)``
/// - ``distinct()``
/// - ``SelectionRequest/select(_:)-30yzl``
/// - ``SelectionRequest/select(_:)-7e2y5``
/// - ``SelectionRequest/select(_:)-270ge``
/// - ``SelectionRequest/select(_:)-4jw13``
/// - ``SelectionRequest/select(literal:)``
/// - ``SelectionRequest/select(sql:arguments:)``
/// - ``SelectionRequest/selectWhenConnected(_:)``
@@ -1405,7 +1813,7 @@ extension JoinableRequest where Self: SelectionRequest {
/// ### The WHERE Clause
///
/// - ``FilteredRequest/all()``
/// - ``FilteredRequest/filter(_:)``
/// - ``FilteredRequest/filter(_:)-7j0nw``
/// - ``TableRequest/filter(id:)``
/// - ``TableRequest/filter(ids:)``
/// - ``TableRequest/filter(key:)-1p9sq``
@@ -1421,21 +1829,21 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The GROUP BY and HAVING Clauses
///
/// - ``AggregatingRequest/group(_:)-edak``
/// - ``AggregatingRequest/group(_:)-4216o``
/// - ``AggregatingRequest/group(_:)-5soxm``
/// - ``AggregatingRequest/group(_:)-32exm``
/// - ``AggregatingRequest/group(literal:)``
/// - ``AggregatingRequest/group(sql:arguments:)``
/// - ``TableRequest/groupByPrimaryKey()``
/// - ``AggregatingRequest/groupWhenConnected(_:)``
/// - ``AggregatingRequest/having(_:)``
/// - ``AggregatingRequest/having(_:)-27hlo``
/// - ``AggregatingRequest/having(literal:)``
/// - ``AggregatingRequest/having(sql:arguments:)``
/// - ``AggregatingRequest/havingWhenConnected(_:)``
///
/// ### The ORDER BY Clause
///
/// - ``OrderedRequest/order(_:)-63rzl``
/// - ``OrderedRequest/order(_:)-6co0m``
/// - ``OrderedRequest/order(_:)-5q7wj``
/// - ``OrderedRequest/order(_:)-711zj``
/// - ``OrderedRequest/order(literal:)``
/// - ``OrderedRequest/order(sql:arguments:)``
/// - ``OrderedRequest/orderWhenConnected(_:)``
@@ -1466,6 +1874,23 @@ extension JoinableRequest where Self: SelectionRequest {
/// - ``SelectionRequest``
/// - ``TableRequest``
/// - ``TypedRequest``
///
/// ### Legacy APIs
///
/// It is recommended to prefer the closure-based apis defined above, as
/// well as record aliases over anonymous aliases.
///
/// - ``TableRequest/aliased(_:)-772vb``
/// - ``SelectionRequest/annotated(with:)-4qcem``
/// - ``SelectionRequest/annotated(with:)-6ehs4``
/// - ``FilteredRequest/filter(_:)-48a4t``
/// - ``AggregatingRequest/group(_:)-edak``
/// - ``AggregatingRequest/group(_:)-4216o``
/// - ``AggregatingRequest/having(_:)-2ssg9``
/// - ``OrderedRequest/order(_:)-63rzl``
/// - ``OrderedRequest/order(_:)-6co0m``
/// - ``SelectionRequest/select(_:)-30yzl``
/// - ``SelectionRequest/select(_:)-7e2y5``
public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
JoinableRequest, OrderedRequest,
SelectionRequest, TableRequest
@@ -1475,11 +1900,17 @@ public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredReques
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT DISTINCT * FROM player
/// let request = Player.all().distinct()
///
/// // SELECT DISTINCT name FROM player
/// let request = Player.select(Column("name")).distinct()
/// let request = Player.select(\.name).distinct()
/// ```
func distinct() -> Self
@@ -1492,18 +1923,31 @@ public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredReques
/// latest message:
///
/// ```swift
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
/// struct Chat: TableRecord {
/// enum Columns {
/// static let id = Column("id")
/// }
/// }
///
/// let latestMessageCTE = CommonTableExpression(
/// struct Message: TableRecord {
/// enum Columns {
/// static let date = Column("date")
/// static let chatId = Column("chatId")
/// }
/// }
///
/// let latestMessageRequest = Message
/// .annotated { max($0.date) }
/// .group(\.chatId)
///
/// let latestMessageCTE = CommonTableExpression<Message>(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessageAssociation = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// chat.id == latestMessage.chatId
/// })
///
/// // WITH latestMessage AS
+44 -11
View File
@@ -39,9 +39,18 @@ extension ColumnExpression {
/// SQL generated by the query interface.
///
/// For example, see how `Column("total").detached` makes it possible to
/// sort this query, when a raw `Column("total")` could not:
/// sort this query:
///
/// ```swift
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
///
/// enum Columns {
/// static let score = Column("score")
/// static let bonus = Column("bonus")
/// }
/// }
///
/// // SELECT player.*,
/// // (player.score + player.bonus) AS total,
/// // team.*
@@ -50,9 +59,9 @@ extension ColumnExpression {
/// // ORDER BY total, player.name
/// // ~~~~~
/// let request = Player
/// .annotated(with: (Column("score") + Column("bonus")).forKey("total"))
/// .annotated { ($0.score + $0.bonus).forKey("total") }
/// .including(required: Player.team)
/// .order(Column("total").detached, Column("name"))
/// .order { [Column("total").detached, $0.name] }
/// ```
public var detached: SQLExpression {
SQL(sql: name.quotedDatabaseIdentifier).sqlExpression
@@ -61,6 +70,13 @@ extension ColumnExpression {
extension ColumnExpression where Self == Column {
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// // SELECT rowid FROM player
/// let rowids = try Player.select(.rowID).fetchSet(db)
/// ```
public static var rowID: Self { Column.rowID }
}
@@ -69,14 +85,29 @@ extension ColumnExpression where Self == Column {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// struct Player: FetchableRecord, TableRecord {
/// var score: Int
///
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// let maximumScore = try dbQueue.read { db in
/// // SELECT MAX(score) FROM player
/// try dbQueue.read { db in
/// // DELETE FROM player WHERE score = 0
/// try Player
/// .select(max(Column("score")), as: Int.self)
/// .filter { $0.score == 0 }
/// .deleteAll(db)
///
/// // SELECT * FROM player ORDER BY score DESC LIMIT 10
/// let bestPlayers = try Player
/// .order(\.score)
/// .limit(10)
/// .fetchAll(db)
///
/// // SELECT MAX(score) FROM player
/// let maximumScore = try Player
/// .select({ max($0.score) }, as: Int.self)
/// .fetchOne(db)
/// }
/// ```
@@ -116,11 +147,13 @@ extension Column: ColumnExpression { }
/// Support for column enums:
///
/// struct Player {
/// enum Columns: String, ColumnExpression {
/// case id, name, score
/// }
/// ```swift
/// struct Player {
/// enum Columns: String, ColumnExpression {
/// case id, name, score
/// }
/// }
/// ```
extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String {
public var name: String { rawValue }
}
+1 -1
View File
@@ -39,7 +39,7 @@ struct SQLCollection {
extension SQLCollection {
/// Returns a qualified collection.
func qualified(with alias: TableAlias) -> SQLCollection {
func qualified(with alias: TableAliasBase) -> SQLCollection {
switch impl {
case .subquery,
.table:
+115 -41
View File
@@ -29,8 +29,14 @@
/// SQL("DATE(\(value))").sqlExpression
/// }
///
/// struct Player: TableRecord {
/// enum Columns {
/// static let createdAt = Column("createdAt")
/// }
/// }
///
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
/// let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
/// let request = Player.filter { date($0.createdAt) == "2020-01-23" }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html>
@@ -68,7 +74,7 @@ public struct SQLExpression: Sendable {
///
/// player.id
/// player.name
case qualifiedColumn(String, TableAlias)
case qualifiedColumn(String, TableAliasBase)
/// A database value.
///
@@ -151,7 +157,7 @@ public struct SQLExpression: Sendable {
/// A table full-text match.
///
/// <table> MATCH <pattern>
indirect case tableMatch(TableAlias, SQLExpression)
indirect case tableMatch(TableAliasBase, SQLExpression)
/// A logical `NOT` operator.
///
@@ -199,7 +205,7 @@ public struct SQLExpression: Sendable {
/// player.id
/// document.rowid
/// country.code
case qualifiedFastPrimaryKey(TableAlias)
case qualifiedFastPrimaryKey(TableAliasBase)
/// An expression that is true iff the row exists:
///
@@ -207,10 +213,10 @@ public struct SQLExpression: Sendable {
/// - For tables WITHOUT ROWID, it is true iff any primary key column is not null.
/// - For views, it is true iff any column is not null.
/// - For CTEs, it is not implemented yet.
case qualifiedExists(TableAlias, isNegated: Bool)
case qualifiedExists(TableAliasBase, isNegated: Bool)
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Impl {
func qualified(with alias: TableAliasBase) -> Impl {
switch self {
case .databaseValue,
.qualifiedColumn,
@@ -316,12 +322,17 @@ public struct SQLExpression: Sendable {
/// Use it with the `joined(operator:)` method. For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let bonus = Column("bonus")
/// }
/// }
///
/// // SELECT score + bonus + 1000 FROM player
/// let values = [
/// scoreColumn,
/// bonusColumn,
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// let request = Player.select {
/// [$0.score, $0.bonus, 1000.databaseValue].joined(operator: .add)
/// }
/// ```
public struct AssociativeBinaryOperator: Hashable, Sendable {
/// The SQL operator
@@ -637,7 +648,7 @@ extension SQLExpression {
///
/// player.id
/// player.name
static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self {
static func qualifiedColumn(_ name: String, _ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedColumn(name, alias))
}
@@ -860,7 +871,7 @@ extension SQLExpression {
/// A table full-text match.
///
/// <table> MATCH <pattern>
static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self {
static func tableMatch(_ alias: TableAliasBase, _ expression: SQLExpression) -> Self {
self.init(impl: .tableMatch(alias, expression))
}
@@ -954,6 +965,17 @@ extension SQLExpression {
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"JSONB",
"JSONB_ARRAY",
"JSONB_EXTRACT",
"JSONB_GROUP_ARRAY",
"JSONB_GROUP_OBJECT",
"JSONB_INSERT",
"JSONB_OBJECT",
"JSONB_PATCH",
"JSONB_REMOVE",
"JSONB_REPLACE",
"JSONB_SET",
"LENGTH",
"LIKE",
"LIKELIHOOD",
@@ -1005,6 +1027,16 @@ extension SQLExpression {
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"JSONB",
"JSONB_ARRAY",
"JSONB_GROUP_ARRAY",
"JSONB_GROUP_OBJECT",
"JSONB_INSERT",
"JSONB_OBJECT",
"JSONB_PATCH",
"JSONB_REMOVE",
"JSONB_REPLACE",
"JSONB_SET",
]
/// The `COUNT(*)` expression.
@@ -1127,7 +1159,7 @@ extension SQLExpression {
/// player.id
/// document.rowid
/// country.code
static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self {
static func qualifiedFastPrimaryKey(_ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedFastPrimaryKey(alias))
}
@@ -1137,7 +1169,7 @@ extension SQLExpression {
/// - For tables WITHOUT ROWID, it is true iff any primary key column is not null.
/// - For views, it is true iff any column is not null.
/// - For CTEs, it is not implemented yet.
static func qualifiedExists(_ alias: TableAlias) -> Self {
static func qualifiedExists(_ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedExists(alias, isNegated: false))
}
}
@@ -1146,7 +1178,7 @@ extension SQLExpression {
extension SQLExpression {
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Self {
func qualified(with alias: TableAliasBase) -> Self {
.init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation)
}
@@ -1191,7 +1223,7 @@ extension SQLExpression {
/// - parameter acceptsBijection: If true, expressions that define a
/// bijection on a column return this column. For example: `-score`
/// returns `score`.
func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? {
func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? {
switch impl {
case let .qualifiedColumn(name, a):
if alias == a {
@@ -1478,7 +1510,7 @@ extension SQLExpression {
///
/// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1
/// try Player.filter(Column("name") == "Arthur").fetchOne(db)
func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set<String> {
func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set<String> {
switch impl {
case let .rowValue(expressions):
assert(!expressions.isEmpty)
@@ -1546,7 +1578,7 @@ extension SQLExpression {
/// let request = Player.filter(keys: [1, 2, 3])
/// let regionObservation = DatabaseRegionObservation(tracking: request)
/// let valueObservation = ValueObservation.tracking(request.fetchAll)
func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set<Int64>? {
switch impl {
case let .databaseValue(dbValue):
if dbValue.isNull || dbValue == false.databaseValue {
@@ -1953,7 +1985,7 @@ struct SQLSimpleFunctionInvocation {
isPure && arguments.allSatisfy(\.isConstantInRequest)
}
func qualified(with alias: TableAlias) -> Self {
func qualified(with alias: TableAliasBase) -> Self {
SQLSimpleFunctionInvocation(
name: name,
arguments: arguments.map { $0.qualified(with: alias) },
@@ -1961,7 +1993,7 @@ struct SQLSimpleFunctionInvocation {
isJSONValue: isJSONValue)
}
func column(_ db: Database, for alias: TableAlias) throws -> String? {
func column(_ db: Database, for alias: TableAliasBase) throws -> String? {
let name = name.uppercased()
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
return try arguments[0].column(db, for: alias, acceptsBijection: true)
@@ -1997,7 +2029,7 @@ struct SQLAggregateFunctionInvocation {
/// A false value does not provide any information.
var isJSONValue: Bool
func qualified(with alias: TableAlias) -> Self {
func qualified(with alias: TableAliasBase) -> Self {
SQLAggregateFunctionInvocation(
name: name,
arguments: arguments.map { $0.qualified(with: alias) },
@@ -2099,8 +2131,9 @@ extension SQLExpression {
case .jsonValue:
if isJSONValue {
return self
} else if Database.sqliteLibVersionNumber >= 3045000 {
return .function("JSONB", [self])
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
@@ -2116,8 +2149,9 @@ extension SQLExpression {
case .jsonValue:
if isJSONValue {
return self
} else if Database.sqliteLibVersionNumber >= 3045000 {
return .function("JSONB", [self])
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
@@ -2136,7 +2170,14 @@ public protocol SQLExpressible {
}
extension SQLExpressible where Self == Column {
/// The hidden rowID column
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// // SELECT rowid FROM player
/// let rowids = try Player.select(.rowID).fetchSet(db)
/// ```
public static var rowID: Self { Column.rowID }
}
@@ -2168,6 +2209,7 @@ extension SQLExpressible where Self == Column {
/// - ``average(_:filter:)``
/// - ``capitalized``
/// - ``cast(_:as:)-1dmu3``
/// - ``coalesce(_:)``
/// - ``count(_:)``
/// - ``count(distinct:)``
/// - ``dateTime(_:_:)``
@@ -2178,8 +2220,10 @@ extension SQLExpressible where Self == Column {
/// - ``localizedLowercased``
/// - ``localizedUppercased``
/// - ``lowercased``
/// - ``min(_:_:_:)``
/// - ``min(_:)``
/// - ``min(_:filter:)``
/// - ``max(_:_:_:)``
/// - ``max(_:)``
/// - ``max(_:filter:)``
/// - ``sum(_:)``
@@ -2248,15 +2292,21 @@ extension Sequence where Element: SQLSpecificExpressible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let isRegistered = Column("isRegistered")
/// static let score = Column("score")
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player
/// // WHERE (registered
/// // WHERE (isRegistered
/// // AND (score >= 1000)
/// // AND (name IS NOT NULL))
/// let conditions = [
/// Column("registered"),
/// Column("score") >= 1000,
/// Column("name") != nil]
/// Player.filter(conditions.joined(operator: .and))
/// Player.filter {
/// [$0.isRegistered, $0.score >= 1000, $0.name != nil].joined(operator: .and)
/// }
/// ```
///
/// When the sequence is empty, `joined(operator:)` returns the neutral
@@ -2279,15 +2329,21 @@ extension Sequence where Element == any SQLSpecificExpressible {
/// For example:
///
/// ```
/// struct Player: TableRecord {
/// enum Columns {
/// static let isRegistered = Column("isRegistered")
/// static let score = Column("score")
/// static let name = Column("name")
/// }
/// }
///
/// // SELECT * FROM player
/// // WHERE (registered
/// // WHERE (isRegistered
/// // AND (score >= 1000)
/// // AND (name IS NOT NULL))
/// let conditions = [
/// Column("registered"),
/// Column("score") >= 1000,
/// Column("name") != nil]
/// Player.filter(conditions.joined(operator: .and))
/// Player.filter {
/// [$0.isRegistered, $0.score >= 1000, $0.name != nil].joined(operator: .and)
/// }
/// ```
///
/// When the sequence is empty, `joined(operator:)` returns the neutral
@@ -2350,9 +2406,17 @@ extension SQLSpecificExpressible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let bonus = Column("bonus")
/// }
/// }
///
/// // SELECT (score + bonus) AS totalScore FROM player
/// let totalScore = (Column("score") * Column("bonus")).forKey("totalScore")
/// let request = Player.select(totalScore)
/// let request = Player.select {
/// ($0.score * $0.bonus).forKey("totalScore")
/// }
/// ```
///
/// If you need to refer to the aliased column in another part of a request,
@@ -2363,7 +2427,9 @@ extension SQLSpecificExpressible {
/// // FROM player
/// // ORDER BY totalScore
/// let request = Player
/// .select(totalScore)
/// .select {
/// ($0.score * $0.bonus).forKey("totalScore")
/// }
/// .order(Column("totalScore").detached)
/// ```
public func forKey(_ key: String) -> SQLSelection {
@@ -2387,9 +2453,17 @@ extension SQLSpecificExpressible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let email = Column("email")
/// }
/// }
///
/// // SELECT * FROM player
/// // WHERE email = 'contact@example.com' COLLATE NOCASE
/// Player.filter(Column("email").collating(.nocase) == "contact@example.com")
/// Player.filter {
/// $0.email.collating(.nocase) == "contact@example.com"
/// }
/// ```
public func collating(_ collation: Database.CollationName) -> SQLExpression {
.collated(sqlExpression, collation)
+73 -15
View File
@@ -11,7 +11,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `AVG` SQL function.
/// The `AVG` SQL aggregate function.
///
/// For example:
///
@@ -26,7 +26,7 @@ public func average(
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `AVG` SQL function.
/// The `AVG` SQL aggregate function.
///
/// For example:
///
@@ -44,7 +44,7 @@ public func average(
filter: filter.sqlExpression)
}
/// The `AVG` SQL function.
/// The `AVG` SQL aggregate function.
///
/// For example:
///
@@ -71,6 +71,32 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat
.cast(expression.sqlExpression, as: storageClass)
}
/// The `COALESCE` SQL function.
///
/// For example:
///
/// ```swift
/// // COALESCE(value1, value2, ...)
/// coalesce([Column("value1"), Column("value2"), ...])
/// ```
///
/// Unlike the SQL function, `coalesce` accepts any number of arguments.
/// When `values` is empty, the result is `NULL`. When `values` contains a
/// single value, the result is this value. `COALESCE` is used from
/// two values upwards.
public func coalesce(_ values: some Collection<any SQLSpecificExpressible>) -> SQLExpression {
// SQLite COALESCE wants at least two arguments.
// There is no reason to apply the same limitation.
guard let value = values.first else {
return .null
}
if values.count > 1 {
return .function("COALESCE", values.map { $0.sqlExpression })
} else {
return value.sqlExpression
}
}
/// The `COUNT` SQL function.
///
/// For example:
@@ -121,8 +147,24 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("LENGTH", [value.sqlExpression])
}
/// The `MAX` SQL multi-argument function.
///
/// For example:
///
/// ```swift
/// // MAX(score, 1000)
/// max(Column("score"), 1000)
/// ```
public func max(
_ value1: any SQLSpecificExpressible,
_ value2: any SQLExpressible,
_ values: any SQLExpressible...
) -> SQLExpression {
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -137,7 +179,7 @@ public func max(
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -153,7 +195,7 @@ public func max(
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -166,8 +208,24 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
/// The `MIN` SQL multi-argument function.
///
/// For example:
///
/// ```swift
/// // MIN(score, 1000)
/// min(Column("score"), 1000)
/// ```
public func min(
_ value1: any SQLSpecificExpressible,
_ value2: any SQLExpressible,
_ values: any SQLExpressible...
) -> SQLExpression {
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -182,7 +240,7 @@ public func min(
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -198,7 +256,7 @@ public func min(
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -212,7 +270,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -236,7 +294,7 @@ public func sum(
filter: filter?.sqlExpression)
}
#else
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -258,7 +316,7 @@ public func sum(
filter: filter.sqlExpression)
}
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -276,7 +334,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
@@ -300,7 +358,7 @@ public func total(
filter: filter?.sqlExpression)
}
#else
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
@@ -322,7 +380,7 @@ public func total(
filter: filter.sqlExpression)
}
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
+1 -1
View File
@@ -86,7 +86,7 @@ extension SQLOrdering {
}
extension SQLOrdering {
func qualified(with alias: TableAlias) -> SQLOrdering {
func qualified(with alias: TableAliasBase) -> SQLOrdering {
switch impl {
case .expression(let expression):
return .expression(expression.qualified(with: alias))
+10 -10
View File
@@ -331,7 +331,7 @@ extension SQLRelation: Refinable {
}
}
func aliased(_ alias: TableAlias) -> Self {
func aliased(_ alias: TableAliasBase) -> Self {
with {
$0.source = $0.source.aliased(alias)
}
@@ -636,7 +636,7 @@ extension SQLRelation {
}
// <https://github.com/groue/GRDB.swift/issues/1357>
guard selection.allSatisfy(\.isTriviallyCountable) else {
if selection.contains(where: \.requiresTrivialCount) {
return try fetchTrivialCount(db)
}
@@ -674,9 +674,9 @@ struct SQLLimit {
struct SQLSource: Sendable {
var tableName: String
var alias: TableAlias?
var alias: TableAliasBase?
func aliased(_ alias: TableAlias) -> SQLSource {
func aliased(_ alias: TableAliasBase) -> SQLSource {
if let sourceAlias = self.alias {
alias.becomeProxy(of: sourceAlias)
return self
@@ -705,7 +705,7 @@ extension SQLRelation {
}
}
func qualified(with alias: TableAlias) -> Element {
func qualified(with alias: TableAliasBase) -> Element {
switch self {
case .terms(let terms):
return .terms(terms.map { $0.map { $0.qualified(with: alias) } })
@@ -752,7 +752,7 @@ extension SQLRelation {
isReversed: !isReversed)
}
func qualified(with alias: TableAlias) -> Ordering {
func qualified(with alias: TableAliasBase) -> Ordering {
Ordering(
elements: elements.map { $0.qualified(with: alias) },
isReversed: isReversed)
@@ -814,7 +814,7 @@ enum SQLAssociationCondition: Sendable {
/// player[Column("id")] == bonus[Column("playerID")]
/// })
/// Player.with(bonus).joining(required: association)
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
case expression(@Sendable (_ left: TableAliasBase, _ right: TableAliasBase) -> SQLExpression?)
/// The condition that does not constrain the two associated tables
/// in any way.
@@ -831,8 +831,8 @@ enum SQLAssociationCondition: Sendable {
func joinExpression(
_ db: Database,
leftAlias: TableAlias,
rightAlias: TableAlias)
leftAlias: TableAliasBase,
rightAlias: TableAliasBase)
throws -> SQLExpression?
{
switch self {
@@ -999,7 +999,7 @@ extension JoinMapping {
/// JOIN operator.
/// - parameter rightAlias: A TableAlias for the table on the right of the
/// JOIN operator.
func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression {
func joinExpression(leftAlias: TableAliasBase, rightAlias: TableAliasBase) -> SQLExpression {
map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and)
}
}
+217 -48
View File
@@ -24,8 +24,14 @@ public struct SQLSelection: Sendable {
case allColumns
/// All columns, qualified: `player.*`
case qualifiedAllColumns(TableAlias)
case qualifiedAllColumns(TableAliasBase)
/// All columns but the specified ones
case allColumnsExcluding(Set<CaseInsensitiveIdentifier>)
/// All columns but the specified ones, qualified.
case qualifiedAllColumnsExcluding(TableAliasBase, Set<CaseInsensitiveIdentifier>)
/// An expression
case expression(SQLExpression)
@@ -41,11 +47,24 @@ public struct SQLSelection: Sendable {
/// All columns: `*`
static let allColumns = SQLSelection(impl: .allColumns)
/// All columns but the specified ones.
static func allColumnsExcluding(_ excludedColumns: Set<CaseInsensitiveIdentifier>) -> Self {
SQLSelection(impl: .allColumnsExcluding(excludedColumns))
}
/// All columns, qualified: `player.*`
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
static func qualifiedAllColumns(_ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedAllColumns(alias))
}
/// All columns but the specified ones, qualified.
static func qualifiedAllColumnsExcluding(
_ alias: TableAliasBase,
_ excludedColumns: Set<CaseInsensitiveIdentifier>
) -> Self {
self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns))
}
/// An expression
static func expression(_ expression: SQLExpression) -> Self {
self.init(impl: .expression(expression))
@@ -70,13 +89,16 @@ extension SQLSelection {
/// Returns nil when the number of columns is unknown.
func columnCount(_ context: SQLGenerationContext) throws -> Int? {
switch impl {
case .allColumns:
case .allColumns, .allColumnsExcluding:
// Likely a GRDB bug: we can't count the number of columns in an
// unqualified table.
return nil
case let .qualifiedAllColumns(alias):
return try context.columnCount(in: alias.tableName)
return try context.columnCount(in: alias.tableName, excluding: [])
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
return try context.columnCount(in: alias.tableName, excluding: excludedColumns)
case .expression,
.aliasedExpression:
@@ -104,7 +126,28 @@ extension SQLSelection {
// SELECT COUNT(*) FROM tableName ...
return .all
case .qualifiedAllColumns:
case .allColumnsExcluding:
// SELECT DISTINCT a, b, c FROM tableName ...
if distinct {
// TODO: if the selection were qualified, and if we had a
// database connection, we could detect the case where there
// remains only one column, and we could perform a
// SELECT COUNT(DISTINCT remainingColumn) FROM tableName
//
// Since most people will not use `.allColumns(excluding:)`
// when they want to select only one column, I guess that
// this optimization has little chance to be needed.
//
// Can't count
return nil
}
// SELECT a, b, c FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
return .all
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return nil
case let .expression(expression),
@@ -126,41 +169,6 @@ extension SQLSelection {
}
}
/// Returns the SQL that feeds the argument of the `COUNT` function.
///
/// For example:
///
/// COUNT(*)
/// COUNT(id)
/// ^---- countedSQL
///
/// - parameter context: An SQL generation context which accepts
/// statement arguments.
func countedSQL(_ context: SQLGenerationContext) throws -> String {
switch impl {
case .allColumns:
return "*"
case let .qualifiedAllColumns(alias):
if context.qualifier(for: alias) != nil {
// SELECT COUNT(t.*) is invalid SQL
fatalError("Not implemented, or invalid query")
}
return "*"
case let .expression(expression),
let .aliasedExpression(expression, _):
return try expression.sql(context)
case .literal:
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several literal expressions instead. \
See SQL.sqlExpression.
""")
}
}
/// Returns the SQL that feeds the selection of a `SELECT` statement.
///
/// For example:
@@ -179,11 +187,38 @@ extension SQLSelection {
case .allColumns:
return "*"
case .allColumnsExcluding:
// Likely a GRDB bug: we don't know the table name so we can't
// load remaining columns. This selection should have been
// turned into a `.qualifiedAllColumnsExcluding`.
fatalError("Not implemented, or invalid query")
case let .qualifiedAllColumns(alias):
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
let columnsNames = try context.columnNames(in: alias.tableName)
let remainingColumnsNames = if excludedColumns.isEmpty {
columnsNames
} else {
columnsNames.filter {
!excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0))
}
}
if columnsNames.count == remainingColumnsNames.count {
// We're not excluding anything
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
} else {
return try remainingColumnsNames
.map { try SQLExpression.column($0).qualified(with: alias).sql(context) }
.joined(separator: ", ")
}
case let .expression(expression):
return try expression.sql(context)
@@ -226,14 +261,17 @@ extension SQLSelection {
}
/// Returns a qualified selection
func qualified(with alias: TableAlias) -> SQLSelection {
func qualified(with alias: TableAliasBase) -> SQLSelection {
switch impl {
case .qualifiedAllColumns:
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return self
case .allColumns:
return .qualifiedAllColumns(alias)
case let .allColumnsExcluding(excludedColumns):
return .qualifiedAllColumnsExcluding(alias, excludedColumns)
case let .expression(expression):
return .expression(expression.qualified(with: alias))
@@ -245,15 +283,27 @@ extension SQLSelection {
}
}
/// Returns whether this selection MUST be counted with a "trivial"
/// count: `SELECT COUNT(*) FROM (SELECT ...)`.
///
/// Supports SQLRelation.fetchCount.
///
/// See <https://github.com/groue/GRDB.swift/issues/1357>
var isTriviallyCountable: Bool {
var requiresTrivialCount: Bool {
switch impl {
case .aliasedExpression, .literal:
return false
case .allColumns, .qualifiedAllColumns, .expression:
// Trivial count is required.
//
// For example, the WHERE clause here requires the aliased
// column to be preserved in the counting request:
// SELECT *, column AS alt FROM player WHERE alt
return true
case .allColumns, .qualifiedAllColumns:
return false
case .allColumnsExcluding, .qualifiedAllColumnsExcluding:
return false
case .expression:
return false
}
}
}
@@ -297,15 +347,41 @@ enum SQLCount {
///
/// ## Topics
///
/// ### Standard Selections
///
/// - ``rowID``
/// - ``allColumns``
/// - ``allColumns(excluding:)-3sg4w``
/// - ``allColumns(excluding:)-3blq4``
///
/// ### Supporting Types
///
/// - ``AllColumns``
/// - ``AllColumnsExcluding``
/// - ``SQLSelection``
public protocol SQLSelectable {
/// Returns an SQL selection.
var sqlSelection: SQLSelection { get }
}
extension SQLSelectable where Self == Column {
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public static var rowID: Self { Column.rowID }
}
extension SQLSelection: SQLSelectable {
// Not a real deprecation, just a usage warning
@available(*, deprecated, message: "Already SQLSelection")
@@ -319,10 +395,14 @@ extension SQLSelection: SQLSelectable {
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let players = try Player.select(AllColumns()).fetchAll(db)
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public struct AllColumns: Sendable {
/// The `*` selection.
@@ -334,3 +414,92 @@ extension AllColumns: SQLSelectable {
.allColumns
}
}
extension SQLSelectable where Self == AllColumns {
/// All columns of the requested table.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public static var allColumns: AllColumns { AllColumns() }
}
// MARK: - AllColumnsExcluding
/// `AllColumnsExcluding` selects all columns in a database table, but the
/// ones you specify.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public struct AllColumnsExcluding: Sendable {
var excludedColumns: Set<CaseInsensitiveIdentifier>
public init(_ excludedColumns: some Collection<String>) {
self.excludedColumns = Set(excludedColumns.lazy.map {
CaseInsensitiveIdentifier(rawValue: $0)
})
}
}
extension AllColumnsExcluding: SQLSelectable {
public var sqlSelection: SQLSelection {
.allColumnsExcluding(excludedColumns)
}
}
extension SQLSelectable where Self == AllColumnsExcluding {
/// All columns of the requested table, excluding the provided columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public static func allColumns(excluding excludedColumns: some Collection<String>) -> Self {
AllColumnsExcluding(excludedColumns)
}
/// All columns of the requested table, excluding the provided columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: [Column("generatedColumn")])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public static func allColumns(excluding excludedColumns: some Collection<any ColumnExpression>) -> Self {
AllColumnsExcluding(excludedColumns.map(\.name))
}
}
+136 -6
View File
@@ -48,6 +48,8 @@
///
/// ### Updating Rows
///
/// - ``updateAll(_:onConflict:assignment:)``
/// - ``updateAll(_:onConflict:assignments:)``
/// - ``updateAll(_:onConflict:_:)-4w9b``
/// - ``updateAll(_:onConflict:_:)-4cvap``
///
@@ -56,7 +58,8 @@
/// `Table` provide convenience access to most ``DerivableRequest`` and
/// ``QueryInterfaceRequest`` methods.
///
/// - ``aliased(_:)``
/// - ``aliased(_:)-3135k``
/// - ``aliased(_:)-5dkyd``
/// - ``all()``
/// - ``annotated(with:)-6i101``
/// - ``annotated(with:)-6x399``
@@ -94,6 +97,7 @@
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
@@ -424,6 +428,40 @@ extension Table {
all().selectPrimaryKey(as: type)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// let table = Table<Player>("player")
///
/// // SELECT id FROM player
/// let request = try table.selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// let table = Table<Player>("player")
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try table.selectID().fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable & SendableMetatype
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// table columns.
///
@@ -705,11 +743,23 @@ extension Table {
all().limit(limit, offset: offset)
}
/// Returns a request that can be referred to with the provided alias.
/// Returns a request that can be referred to with the provided
/// anonymous alias.
///
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
/// See ``TableRequest/aliased(_:)`` for more information.
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<RowDecoder> {
///
/// See ``TableRequest/aliased(_:)-772vb`` for more information.
public func aliased(_ alias: TableAlias<Void>) -> QueryInterfaceRequest<RowDecoder> {
all().aliased(alias)
}
/// Returns a request that can be referred to with the provided
/// record alias.
///
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
///
/// See ``TableRequest/aliased(_:)-3k5h4`` for more information.
public func aliased(_ alias: TableAlias<RowDecoder>) -> QueryInterfaceRequest<RowDecoder> {
all().aliased(alias)
}
@@ -1295,12 +1345,17 @@ extension Table {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: cte.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a common table expression.
@@ -1849,6 +1904,77 @@ extension Table {
// MARK: - Batch Update
extension Table {
/// Updates all rows, and returns the number of updated rows.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// let playerTable = Table<Player>("player")
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try playerTable.updateAll(db) { $0.score.set(to: 0) }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignment: A closure that returns an assignments.
/// - returns: The number of updated rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)])
}
/// Updates all rows, and returns the number of updated rows.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// let playerTable = Table<Player>("player")
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try playerTable.updateAll(db) { $0.score.set(to: 0) }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: The number of updated rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Updates all rows, and returns the number of updated rows.
///
/// For example:
@@ -1905,3 +2031,7 @@ extension Table {
try updateAll(db, onConflict: conflictResolution, assignments)
}
}
extension Table where RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
}
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more