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
178 changed files with 12931 additions and 3271 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
+112 -29
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.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.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,82 @@ 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
@@ -172,7 +255,7 @@ 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/v7.0.0-beta.6/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.
@@ -231,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
@@ -257,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
@@ -284,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
@@ -320,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
@@ -345,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
@@ -369,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
@@ -404,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
@@ -431,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
@@ -441,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
@@ -451,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
@@ -462,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
@@ -492,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).
+34 -28
View File
@@ -5,54 +5,56 @@ By default, GRDB uses the version of SQLite that ships with the target operating
**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()
@@ -77,7 +77,7 @@ extension AppDatabase {
// }
//
// 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
@@ -93,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
@@ -130,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)
}
}
+3 -3
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,7 @@ 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).
+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.
+7 -7
View File
@@ -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:
+55 -7
View File
@@ -10,6 +10,7 @@ Migrating From GRDB 6 to GRDB 7
- [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)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
@@ -96,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:
@@ -114,7 +162,7 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
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.
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:
@@ -221,14 +269,14 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
## Other Changes
- `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/v7.0.0-beta.6/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/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.6'
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 */,
+2 -2
View File
@@ -144,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:
@@ -173,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)
+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))
}
}
+386 -117
View File
@@ -52,6 +52,8 @@ import Foundation
/// - ``subscript(_:)-9c1fw``
/// - ``subscript(_:)-3jhwm``
/// - ``subscript(_:)-7krrg``
/// - ``decode(_:atIndex:)-33ykh``
/// - ``decode(_:atIndex:)-3btwn``
/// - ``withUnsafeData(atIndex:_:)``
/// - ``dataNoCopy(atIndex:)``
///
@@ -61,7 +63,8 @@ import Foundation
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``coalesce(_:)-359k7``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-4i1o4``
/// - ``decode(_:forColumn:)-4rhs4``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
@@ -70,6 +73,9 @@ import Foundation
/// - ``subscript(_:)-9txgm``
/// - ``subscript(_:)-2esg7``
/// - ``subscript(_:)-wl9a``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-1ljuo``
/// - ``decode(_:forColumn:)-47qeg``
/// - ``withUnsafeData(at:_:)``
/// - ``dataNoCopy(_:)``
///
@@ -84,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``
@@ -119,6 +129,10 @@ import Foundation
///
/// - ``RowAdapter``
///
/// ### Errors
///
/// - ``RowDecodingError``
///
/// ### Supporting Types
///
/// - ``RowCursor``
@@ -452,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.
@@ -489,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
@@ -533,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.
@@ -573,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.
@@ -739,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.
@@ -769,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.
@@ -809,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:)``
@@ -843,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``
@@ -861,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.
@@ -876,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``
@@ -935,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)
}
@@ -1065,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
@@ -1082,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 {
@@ -1100,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
@@ -1114,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
@@ -1136,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 {
@@ -1155,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>(
@@ -1187,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?
@@ -1228,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
@@ -1300,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
@@ -1321,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 {
@@ -1351,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 {
@@ -1735,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> = """
@@ -1784,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> = """
@@ -1816,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> = """
@@ -1852,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) })
}
}
+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 {
+9
View File
@@ -41,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) {
@@ -67,6 +70,7 @@ final class StatementAuthorizer {
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionEffect = nil
isQueryOnlyPragma = false
isDropStatement = false
}
@@ -192,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> = """
@@ -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.
@@ -252,8 +252,8 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/create(virtualTable:options:using:)``
- ``Database/create(virtualTable:options:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
@@ -265,6 +265,7 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- ``VirtualTableOptions``
### Database Views
@@ -288,3 +289,5 @@ Those are legacy interfaces that are preserved for backwards compatibility. Thei
- ``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:_:)``
@@ -151,7 +151,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
[.allColumns, .rowID]
}
// Update id upon successful insertion
@@ -262,11 +262,11 @@ try dbQueue.write { db in
// Use instead:
let player = try Player
.filter(Column("teamId") == 42 && Column("position") == 1)
.filter { $0.teamId == 42 && $0.position == 1 }
.fetchOne(db)
try Player
.filter(Column("name") == "Arthur")
.filter { $0.name == "Arthur" }
.deleteAll(db)
}
```
@@ -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:
@@ -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`.
+14 -2
View File
@@ -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'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .filter { $0.address["country"] == "DE" }
> .fetchAll(db)
> ```
@@ -104,10 +110,16 @@ extension Team: FetchableRecord, PersistableRecord {
> 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(JSONColumn("address") == Address(...))
> .filter { $0.address == Address(...) }
> .fetchAll(db)
> ```
>
+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.
>
@@ -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 }
+8 -2
View File
@@ -91,8 +91,14 @@ extension Player: FetchableRecord, PersistableRecord {
// because non-'Sendable' type '[any SQLSelectable]'
// may have shared mutable state
static let databaseSelection: [any SQLSelectable] = [
Column("id"), Column("name"), Column("score")
Columns.id, Columns.name, Columns.score
]
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let score = Column("score")
}
}
```
@@ -101,7 +107,7 @@ extension Player: FetchableRecord, PersistableRecord {
```swift
extension Player: FetchableRecord, PersistableRecord {
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name"), Column("score")]
[Columns.id, Columns.name, Columns.score]
}
}
```
+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())
}
+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>
@@ -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 {
@@ -723,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.
///
@@ -925,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.
@@ -933,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.
///
@@ -978,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()
/// ```
///
@@ -994,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
@@ -1092,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.
@@ -1234,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)
@@ -1256,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)
/// ```
///
@@ -1284,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 {
@@ -1308,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)
/// ```
///
@@ -1336,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 {
@@ -1367,7 +1791,7 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### Instance Methods
///
/// - ``TableRequest/aliased(_:)``
/// - ``TableRequest/aliased(_:)-3k5h4``
/// - ``TableAlias``
///
/// ### The WITH Clause
@@ -1376,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(_:)``
@@ -1389,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``
@@ -1405,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(_:)``
@@ -1450,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
@@ -1459,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
@@ -1476,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:
+114 -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 }
}
@@ -2179,8 +2220,10 @@ extension SQLExpressible where Self == Column {
/// - ``localizedLowercased``
/// - ``localizedUppercased``
/// - ``lowercased``
/// - ``min(_:_:_:)``
/// - ``min(_:)``
/// - ``min(_:filter:)``
/// - ``max(_:_:_:)``
/// - ``max(_:)``
/// - ``max(_:filter:)``
/// - ``sum(_:)``
@@ -2249,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
@@ -2280,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
@@ -2351,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,
@@ -2364,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 {
@@ -2388,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)
+47 -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:
///
@@ -147,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:
///
@@ -163,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:
///
@@ -179,7 +195,7 @@ public func max(
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MAX` SQL function.
/// The `MAX` SQL aggregate function.
///
/// For example:
///
@@ -192,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:
///
@@ -208,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:
///
@@ -224,7 +256,7 @@ public func min(
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MIN` SQL function.
/// The `MIN` SQL aggregate function.
///
/// For example:
///
@@ -238,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:
///
@@ -262,7 +294,7 @@ public func sum(
filter: filter?.sqlExpression)
}
#else
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -284,7 +316,7 @@ public func sum(
filter: filter.sqlExpression)
}
/// The `SUM` SQL function.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
@@ -302,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:
///
@@ -326,7 +358,7 @@ public func total(
filter: filter?.sqlExpression)
}
#else
/// The `TOTAL` SQL function.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
@@ -348,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
}
@@ -37,8 +37,8 @@ final class SQLGenerationContext {
}
}
private let resolvedNames: [TableAlias: String]
private let ownAliases: Set<TableAlias>
private let resolvedNames: [TableAliasBase: String]
private let ownAliases: Set<TableAliasBase>
private let ownCTEs: [String: SQLCTE]
/// Creates a generation context.
@@ -50,7 +50,7 @@ final class SQLGenerationContext {
init(
_ db: Database,
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
aliases: [TableAlias] = [],
aliases: [TableAliasBase] = [],
ctes: OrderedDictionary<String, SQLCTE> = [:])
{
self.parent = .none(db: db, argumentsSink: argumentsSink)
@@ -66,7 +66,7 @@ final class SQLGenerationContext {
/// - parameter ctes: An dictionary of available CTEs.
private init(
parent: SQLGenerationContext,
aliases: [TableAlias],
aliases: [TableAliasBase],
ctes: OrderedDictionary<String, SQLCTE>)
{
self.parent = .context(parent)
@@ -77,7 +77,7 @@ final class SQLGenerationContext {
/// Returns a generation context suitable for subqueries.
func subqueryContext(
aliases: [TableAlias] = [],
aliases: [TableAliasBase] = [],
ctes: OrderedDictionary<String, SQLCTE> = [:]) -> SQLGenerationContext
{
SQLGenerationContext(parent: self, aliases: aliases, ctes: ctes)
@@ -118,7 +118,7 @@ final class SQLGenerationContext {
///
/// WHERE column == 1
/// SELECT *
func qualifier(for alias: TableAlias) -> String? {
func qualifier(for alias: TableAliasBase) -> String? {
if alias.hasUserName {
return alias.identityName
}
@@ -132,7 +132,7 @@ final class SQLGenerationContext {
}
/// WHERE <resolvedName> MATCH pattern
func resolvedName(for alias: TableAlias) -> String {
func resolvedName(for alias: TableAliasBase) -> String {
if let name = resolvedNames[alias] {
return name
}
@@ -145,7 +145,7 @@ final class SQLGenerationContext {
}
/// FROM tableName <alias>
func aliasName(for alias: TableAlias) -> String? {
func aliasName(for alias: TableAliasBase) -> String? {
let resolvedName = self.resolvedName(for: alias)
if resolvedName != alias.tableName {
return resolvedName
@@ -153,15 +153,50 @@ final class SQLGenerationContext {
return nil
}
func columnCount(in tableName: String) throws -> Int {
/// Return the number of columns in the table or CTE identified
/// by `tableName`.
///
/// - parameter tableName: The table name.
/// - parameter excludedColumns: The eventual set of excluded columns.
func columnCount(
in tableName: String,
excluding excludedColumns: Set<CaseInsensitiveIdentifier>
) throws -> Int {
if let cte = ownCTEs[tableName.lowercased()] {
return try cte.columnCount(db)
if excludedColumns.isEmpty {
return try cte.columnCount(db)
} else {
fatalError("Not implemented: counting CTE columns with excluded columns")
}
}
switch parent {
case let .context(context):
return try context.columnCount(in: tableName)
return try context.columnCount(in: tableName, excluding: excludedColumns)
case let .none(db: db, argumentsSink: _):
return try db.columns(in: tableName).count
if excludedColumns.isEmpty {
return try db.columns(in: tableName).count
} else {
return try db
.columns(in: tableName)
.filter { !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0.name)) }
.count
}
}
}
/// Return the names of the columns in the table or CTE identified
/// by `tableName`.
///
/// - parameter tableName: The table name.
func columnNames(in tableName: String) throws -> [String] {
if ownCTEs[tableName.lowercased()] != nil {
fatalError("Not implemented: extracing CTE column names")
}
switch parent {
case let .context(context):
return try context.columnNames(in: tableName)
case let .none(db: db, argumentsSink: _):
return try db.columns(in: tableName).map(\.name)
}
}
}
@@ -209,318 +244,9 @@ class StatementArgumentsSink {
}
}
// MARK: - TableAlias
/// A TableAlias identifies a table in a request.
///
/// See ``TableRequest/aliased(_:)`` for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public class TableAlias: @unchecked Sendable {
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
// TODO: GRDB7 Make TableAlias really Sendable
private enum Impl {
/// A TableAlias is undefined when it is created by the GRDB user:
///
/// let alias = TableAlias()
/// let alias = TableAlias(name: "custom")
case undefined(userName: String?)
/// A TableAlias is a table when explicitly specified:
///
/// let alias = TableAlias(tableName: "player")
///
/// Or when it qualifies a request that wasn't qualified yet (in which
/// case it turns from undefined to a table):
///
/// // SELECT custom.* FROM player custom
/// let alias = TableAlias(name: "custom")
/// let request = Player.all().aliased(alias)
case table(tableName: String, userName: String?)
/// A TableAlias can be a proxy for another table alias. Two different
/// instances for the same table identifier:
///
/// // Pointless example: make alias2 a proxy for alias1
/// let alias1 = TableAlias()
/// let alias2 = TableAlias()
/// Player.all()
/// .aliased(alias1)
/// .aliased(alias2)
///
/// Proxies are useful because queries get implicit aliases as soon
/// as they are joined with associations. In the example below,
/// customAlias becomes a proxy for the request's implicit alias, which
/// gets a custom name. This allows implicit and user aliases to merge
/// into a single "table identifier" that matches the user's expectations:
///
/// // SELECT custom.*, team.*
/// // FROM player custom
/// // JOIN team ON taem.id = custom.teamId
/// // WHERE custom.name = 'Arthur'
/// let customAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team)
/// .filter(sql: "custom.name = 'Arthur'")
/// .aliased(customAlias)
case proxy(TableAlias)
}
private var impl: Impl
/// Resolve all proxies
private var root: TableAlias {
if case .proxy(let base) = impl {
return base.root
} else {
return self
}
}
// exposed to SQLGenerationContext
fileprivate var identityName: String {
userName ?? tableName
}
// exposed to SQLGenerationContext
fileprivate var hasUserName: Bool {
userName != nil
}
var tableName: String {
switch impl {
case .undefined:
// Likely a GRDB bug
fatalError("Undefined alias has no table name")
case .table(tableName: let tableName, userName: _):
return tableName
case .proxy(let base):
return base.tableName
}
}
private var userName: String? {
switch impl {
case .undefined(let userName):
return userName
case .table(tableName: _, userName: let userName):
return userName
case .proxy(let base):
return base.userName
}
}
/// Creates a TableAlias.
///
/// When the alias is given a name, this name is guaranteed to be used as
/// the table alias in the SQL query:
///
/// ```swift
/// // SELECT p.* FROM player p
/// let alias = TableAlias(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
public init(name: String? = nil) {
self.impl = .undefined(userName: name)
}
init(tableName: String, userName: String? = nil) {
self.impl = .table(tableName: tableName, userName: userName)
}
func becomeProxy(of base: TableAlias) {
if self === base {
return
}
switch impl {
case let .undefined(userName):
if let userName {
// rename
assert(base.userName == nil || base.userName == userName)
base.setUserName(userName)
}
self.impl = .proxy(base)
case let .table(tableName: tableName, userName: userName):
assert(tableName == base.tableName)
if let userName {
// rename
assert(base.userName == nil || base.userName == userName)
base.setUserName(userName)
}
self.impl = .proxy(base)
case let .proxy(selfBase):
selfBase.becomeProxy(of: base)
}
}
/// Returns nil if aliases can't be merged (conflict in tables, aliases...)
func merged(with other: TableAlias) -> TableAlias? {
if self === other {
return self
}
let root = self.root
let otherRoot = other.root
switch (root.impl, otherRoot.impl) {
case let (.table(tableName: tableName, userName: userName),
.table(tableName: otherTableName, userName: otherUserName)):
guard tableName == otherTableName else {
// can't merge
return nil
}
if let userName, let otherUserName, userName != otherUserName {
// can't merge
return nil
}
root.becomeProxy(of: otherRoot)
return otherRoot
default:
// can't merge
return nil
}
}
private func setUserName(_ userName: String) {
switch impl {
case .undefined:
self.impl = .undefined(userName: userName)
case .table(tableName: let tableName, userName: _):
self.impl = .table(tableName: tableName, userName: userName)
case .proxy(let base):
base.setUserName(userName)
}
}
func setTableName(_ tableName: String) {
switch impl {
case .undefined(let userName):
self.impl = .table(tableName: tableName, userName: userName)
case .table(tableName: let initialTableName, userName: _):
// It is a programmer error to reuse the same TableAlias for
// multiple tables.
//
// // Don't do that
// let alias = TableAlias()
// let books = Book.aliased(alias)...
// let authors = Author.aliased(alias)...
GRDBPrecondition(
tableName.lowercased() == initialTableName.lowercased(),
"A TableAlias most not be used to refer to multiple tables")
case .proxy(let base):
base.setTableName(tableName)
}
}
/// Returns a result column that refers to the aliased table.
public subscript(_ selectable: some SQLSelectable) -> SQLSelection {
// TODO: test
selectable.sqlSelection.qualified(with: self)
}
/// Returns an SQL expression that refers to the aliased table.
///
/// For example, let's sort 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()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias[Column("name")], Column("title"))
/// ```
public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression {
expression.sqlExpression.qualified(with: self)
}
public subscript(_ expression: some SQLJSONExpressible &
SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm)
-> AnySQLJSONExpressible
{
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
}
/// Returns an SQL ordering term that refers to the aliased table.
///
/// For example, let's sort 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 ASC, book.title ASC
/// let authorAlias = TableAlias()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias[Column("name").asc], Column("title").asc)
/// ```
public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering {
ordering.sqlOrdering.qualified(with: self)
}
/// Returns an SQL column that refers to the aliased table.
///
/// For example, let's sort 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()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias["name"], Column("title"))
/// ```
public subscript(_ column: String) -> SQLExpression {
.qualifiedColumn(column, self)
}
/// A boolean SQL expression indicating whether this alias refers to some
/// rows, or not.
///
/// In the example below, we only fetch books that are not associated to
/// any author:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord { }
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try dbQueue.read { db in
/// let authorAlias = TableAlias()
/// let request = Book
/// .joining(optional: Book.author.aliased(authorAlias))
/// .filter(!authorAlias.exists)
/// let books = try request.fetchAll(db)
/// }
/// ```
public var exists: SQLExpression {
SQLExpression.qualifiedExists(self)
}
}
extension TableAlias: Equatable {
public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool {
ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root)
}
}
extension TableAlias: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
}
}
extension [TableAlias] {
extension [TableAliasBase] {
/// Resolve ambiguities in aliases' names.
fileprivate var resolvedNames: [TableAlias: String] {
fileprivate var resolvedNames: [TableAliasBase: String] {
// It is a programmer error to reuse the same TableAlias for
// multiple tables.
//
@@ -536,7 +262,7 @@ extension [TableAlias] {
}
var uniqueLowercaseNames: Set<String> = []
var ambiguousGroups: [[TableAlias]] = []
var ambiguousGroups: [[TableAliasBase]] = []
for (lowercaseName, group) in groups {
if group.count > 1 {
@@ -550,7 +276,7 @@ extension [TableAlias] {
}
}
var resolvedNames: [TableAlias: String] = [:]
var resolvedNames: [TableAliasBase: String] = [:]
for group in ambiguousGroups {
var index = 1
for alias in group {
@@ -235,7 +235,11 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: relation.source.tableName)
case .unique:
return try makeTrivialDeleteStatement(db, selection: selection)
@@ -264,7 +268,11 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: tableName)
}
/// Returns an `UPDATE` statement, with `RETURNING` clause if `selection`
@@ -323,7 +331,11 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: relation.source.tableName)
case .unique:
return try makeTrivialUpdateStatement(
@@ -380,7 +392,11 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: tableName)
}
// Support for the RETURNING clause
@@ -388,7 +404,8 @@ struct SQLQueryGenerator: Refinable {
_ db: Database,
sql: String,
arguments: StatementArguments,
returning selection: [any SQLSelectable])
returning selection: [any SQLSelectable],
from tableName: String)
throws -> Statement
{
if selection.isEmpty {
@@ -396,12 +413,17 @@ struct SQLQueryGenerator: Refinable {
statement.arguments = arguments
return statement
} else {
let context = SQLGenerationContext(db)
// Generate the RETURNING clause by turning selection into SQL.
// Make sure the selection is qualified with a table alias, so
// that selectables such as `.allColumns(excluding:)` can query
// the database about the database table.
let alias = TableAlias(tableName: tableName)
let context = SQLGenerationContext(db, aliases: [alias])
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.sql(context) }
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.makeStatement(sql: sql)
@@ -551,7 +573,7 @@ struct SQLQueryGenerator: Refinable {
/// LIMIT ... -- limit
private struct SQLQualifiedRelation: Sendable {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
var allAliases: [TableAliasBase] {
joins.reduce(into: [source.alias].compactMap { $0 }) {
$0.append(contentsOf: $1.value.relation.allAliases)
}
@@ -717,7 +739,7 @@ extension SQLQualifiedRelation: Refinable { }
/// A "qualified" source, where all tables are identified with a table alias.
private struct SQLQualifiedSource {
var tableName: String
var alias: TableAlias
var alias: TableAliasBase
init(_ source: SQLSource) {
self.tableName = source.tableName
@@ -766,13 +788,13 @@ private struct SQLQualifiedJoin: Refinable {
self.relation = SQLQualifiedRelation(child.relation)
}
func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String {
func sql(_ context: SQLGenerationContext, leftAlias: TableAliasBase) throws -> String {
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
}
private func sql(
_ context: SQLGenerationContext,
leftAlias: TableAlias,
leftAlias: TableAliasBase,
allowingInnerJoin allowsInnerJoin: Bool)
throws -> String
{
@@ -0,0 +1,443 @@
/// `TableAliasBase` is the base class of `TableAlias`.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#table-aliases> for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public class TableAliasBase: @unchecked Sendable {
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
// TODO: Make TableAlias really Sendable
private enum Impl {
/// A TableAlias is undefined when it is created by the GRDB user:
///
/// let alias = TableAlias()
/// let alias = TableAlias(name: "custom")
case undefined(userName: String?)
/// A TableAlias is a table when explicitly specified:
///
/// let alias = TableAlias(tableName: "player")
///
/// Or when it qualifies a request that wasn't qualified yet (in which
/// case it turns from undefined to a table):
///
/// // SELECT custom.* FROM player custom
/// let alias = TableAlias(name: "custom")
/// let request = Player.all().aliased(alias)
case table(tableName: String, userName: String?)
/// A TableAlias can be a proxy for another table alias. Two different
/// instances for the same table identifier:
///
/// // Pointless example: make alias2 a proxy for alias1
/// let alias1 = TableAlias()
/// let alias2 = TableAlias()
/// Player.all()
/// .aliased(alias1)
/// .aliased(alias2)
///
/// Proxies are useful because queries get implicit aliases as soon
/// as they are joined with associations. In the example below,
/// customAlias becomes a proxy for the request's implicit alias, which
/// gets a custom name. This allows implicit and user aliases to merge
/// into a single "table identifier" that matches the user's expectations:
///
/// // SELECT custom.*, team.*
/// // FROM player custom
/// // JOIN team ON taem.id = custom.teamId
/// // WHERE custom.name = 'Arthur'
/// let customAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team)
/// .filter(sql: "custom.name = 'Arthur'")
/// .aliased(customAlias)
case proxy(TableAliasBase)
}
private var impl: Impl
/// Resolve all proxies
private var root: TableAliasBase {
if case .proxy(let base) = impl {
return base.root
} else {
return self
}
}
// exposed to SQLGenerationContext
var identityName: String {
userName ?? tableName
}
// exposed to SQLGenerationContext
var hasUserName: Bool {
userName != nil
}
var tableName: String {
switch impl {
case .undefined:
// Likely a GRDB bug
fatalError("Undefined alias has no table name")
case .table(tableName: let tableName, userName: _):
return tableName
case .proxy(let base):
return base.tableName
}
}
private var userName: String? {
switch impl {
case .undefined(let userName):
return userName
case .table(tableName: _, userName: let userName):
return userName
case .proxy(let base):
return base.userName
}
}
/// Creates a TableAlias.
///
/// When the alias is given a name, this name is guaranteed to be used as
/// the table alias in the SQL query:
///
/// ```swift
/// // SELECT p.* FROM player p
/// let alias = TableAlias(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
init(name: String? = nil) {
self.impl = .undefined(userName: name)
}
init(tableName: String, userName: String? = nil) {
self.impl = .table(tableName: tableName, userName: userName)
}
func becomeProxy(of base: TableAliasBase) {
if self === base {
return
}
switch impl {
case let .undefined(userName):
if let userName {
// rename
assert(base.userName == nil || base.userName == userName)
base.setUserName(userName)
}
self.impl = .proxy(base)
case let .table(tableName: tableName, userName: userName):
assert(tableName == base.tableName)
if let userName {
// rename
assert(base.userName == nil || base.userName == userName)
base.setUserName(userName)
}
self.impl = .proxy(base)
case let .proxy(selfBase):
selfBase.becomeProxy(of: base)
}
}
/// Returns nil if aliases can't be merged (conflict in tables, aliases...)
func merged(with other: TableAliasBase) -> TableAliasBase? {
if self === other {
return self
}
let root = self.root
let otherRoot = other.root
switch (root.impl, otherRoot.impl) {
case let (.table(tableName: tableName, userName: userName),
.table(tableName: otherTableName, userName: otherUserName)):
guard tableName == otherTableName else {
// can't merge
return nil
}
if let userName, let otherUserName, userName != otherUserName {
// can't merge
return nil
}
root.becomeProxy(of: otherRoot)
return otherRoot
default:
// can't merge
return nil
}
}
private func setUserName(_ userName: String) {
switch impl {
case .undefined:
self.impl = .undefined(userName: userName)
case .table(tableName: let tableName, userName: _):
self.impl = .table(tableName: tableName, userName: userName)
case .proxy(let base):
base.setUserName(userName)
}
}
func setTableName(_ tableName: String) {
switch impl {
case .undefined(let userName):
self.impl = .table(tableName: tableName, userName: userName)
case .table(tableName: let initialTableName, userName: _):
// It is a programmer error to reuse the same TableAlias for
// multiple tables.
//
// // Don't do that
// let alias = TableAlias()
// let books = Book.aliased(alias)...
// let authors = Author.aliased(alias)...
GRDBPrecondition(
tableName.lowercased() == initialTableName.lowercased(),
"A TableAlias most not be used to refer to multiple tables")
case .proxy(let base):
base.setTableName(tableName)
}
}
}
extension TableAliasBase: Equatable {
public static func == (lhs: TableAliasBase, rhs: TableAliasBase) -> Bool {
ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root)
}
}
extension TableAliasBase: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
}
}
extension TableAliasBase {
/// Returns a result column that refers to the aliased table.
public subscript(_ selectable: some SQLSelectable) -> SQLSelection {
// TODO: test
selectable.sqlSelection.qualified(with: self)
}
/// Returns an SQL expression that refers to the aliased table.
///
/// For example, let's sort books by author name first, and then by title:
///
/// ```swift
/// struct Author: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
///
/// enum Columns {
/// static let title = Column("title")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name, book.title
/// let authorAlias = TableAlias<Author>()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order { [authorAlias.name, $0.title] }
/// ```
public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression {
expression.sqlExpression.qualified(with: self)
}
public subscript(_ expression: some SQLJSONExpressible &
SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm)
-> AnySQLJSONExpressible
{
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
}
public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering {
ordering.sqlOrdering.qualified(with: self)
}
/// Returns an SQL column that refers to the aliased table.
///
/// For example, let's sort 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()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias["name"], Column("title"))
/// ```
public subscript(_ column: String) -> SQLExpression {
.qualifiedColumn(column, self)
}
}
// MARK: - TableAlias
/// A TableAlias identifies a table in a request.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#table-aliases> for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// ## Topics
///
/// ## Supporting Types
///
/// - ``TableAliasBase``
@dynamicMemberLookup
public final class TableAlias<RowDecoder>: TableAliasBase, @unchecked Sendable {
init(tableName: String, userName: String? = nil)
where RowDecoder == Void
{
super.init(tableName: tableName, userName: userName)
}
init(root: TableAliasBase) {
super.init()
becomeProxy(of: root)
}
/// Creates an anonymous TableAlias.
///
/// When the alias is given a name, this name is guaranteed to be used as
/// the table alias in the SQL query:
///
/// ```swift
/// // SELECT p.* FROM player p
/// let alias = TableAlias(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
///
/// Anonymous aliases do not provide convenience access to table
/// columns, unlike record aliases. See ``TableAlias`` for
/// more information.
public init(name: String? = nil)
where RowDecoder == Void
{
super.init(name: name)
}
/// Creates a TableAlias for the specified record type.
///
/// When the alias is given a name, this name is guaranteed to be used as
/// the table alias in the SQL query:
///
/// ```swift
/// // SELECT p.* FROM player p
/// let alias = TableAlias<Player>(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
public init(
name: String? = nil,
for record: RowDecoder.Type = RowDecoder.self
) {
super.init(name: name)
}
}
extension TableAlias {
/// A boolean SQL expression indicating whether this alias refers to some
/// rows, or not.
///
/// In the example below, we only fetch books that are not associated to
/// any author:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord { }
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try dbQueue.read { db in
/// let authorAlias = TableAlias<Author>()
/// let request = Book
/// .joining(optional: Book.author.aliased(authorAlias))
/// .filter(!authorAlias.exists)
/// let books = try request.fetchAll(db)
/// }
/// ```
public var exists: SQLExpression {
SQLExpression.qualifiedExists(self)
}
}
extension TableAlias where RowDecoder: TableRecord {
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
/// Returns a result column that refers to the aliased table.
public subscript<T>(
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
) -> SQLSelection
where T: SQLSelectable
{
self[RowDecoder.databaseComponents[keyPath: keyPath]]
}
/// Returns an SQL expression that refers to the aliased table.
///
/// For example, let's sort books by author name first, and then by title:
///
/// ```swift
/// struct Author: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
///
/// enum Columns {
/// static let title = Column("title")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name, book.title
/// let authorAlias = TableAlias<Author>()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order { [authorAlias.name, $0.title] }
/// ```
public subscript<T>(
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
) -> SQLExpression
where T: SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm
{
self[RowDecoder.databaseComponents[keyPath: keyPath]]
}
public subscript<T>(
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
) -> AnySQLJSONExpressible
where T: SQLJSONExpressible &
SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm
{
self[RowDecoder.databaseComponents[keyPath: keyPath]]
}
public subscript<T>(
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
) -> SQLOrdering
where T: SQLOrderingTerm {
self[RowDecoder.databaseComponents[keyPath: keyPath]]
}
}
@@ -67,7 +67,12 @@ extension SQLInterpolation {
/// let player: Player = ...
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) {
let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName)
// Make sure we provide the tableName, so that we can interpolate
// the columns of a type whose `databaseSelection` contains an
// instance of `AllColumnsExcluding`.
let alias = TableAlias(
tableName: recordType.databaseTableName,
userName: tableAlias ?? recordType.databaseTableName)
elements.append(contentsOf: recordType.databaseSelection
.map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) }
.joined(separator: CollectionOfOne(.sql(", "))))
@@ -79,7 +84,7 @@ extension SQLInterpolation {
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// SELECT \(.allColumns) FROM player
/// """
public mutating func appendInterpolation(_ selection: some SQLSelectable) {
elements.append(.selection(selection.sqlSelection))
@@ -89,7 +94,7 @@ extension SQLInterpolation {
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// SELECT \(.allColumns) FROM player
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) {
@@ -194,7 +199,7 @@ extension SQLInterpolation {
/// Appends the request SQL (not wrapped inside parentheses).
///
/// let subquery = Player.select(max(Column("score")))
/// let subquery = Player.select { max($0.score) }
/// // or
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
///
@@ -370,6 +370,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -409,6 +435,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -447,6 +499,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -487,6 +565,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -339,7 +339,7 @@ extension Database {
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(
/// view: "hero",
/// as: Player.filter(Column("isHero") == true))
/// as: Player.filter(\.isHero))
/// ```
///
/// When creating views in <doc:Migrations>, it is not recommended to
@@ -125,6 +125,28 @@ public final class TableAlteration {
/// }
/// ```
///
/// Take care, when you rename **foreign keys** in <doc:Migrations>,
/// to run the migration with the ``DatabaseMigrator/ForeignKeyChecks/immediate``
/// foreign key checks, in order to avoid integrity failures:
///
/// ```swift
/// // RECOMMENDED: 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
/// t.rename(column: "teamId", to: "guildId")
/// }
/// }
///
/// // NOT RECOMMENDED: rename foreign keys with disabled foreign keys.
/// migrator.registerMigration("Guilds") { db in
/// try db.rename(table: "team", to: "guild")
/// try db.alter(table: "player") { t in
/// t.rename(column: "teamId", to: "guildId")
/// }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the old name of the column.
@@ -1,7 +1,7 @@
/// The protocol for SQLite virtual table modules.
///
/// The protocol can define a DSL for the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` `Database` method:
/// ``Database/create(virtualTable:options:using:_:)`` `Database` method:
///
/// ```swift
/// let module = ...
@@ -20,7 +20,7 @@
/// - ``VirtualTableConfiguration``
public protocol VirtualTableModule {
/// The type of the argument in the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
/// ``Database/create(virtualTable:options:using:_:)`` closure.
///
/// For example:
///
@@ -35,7 +35,7 @@ public protocol VirtualTableModule {
var moduleName: String { get }
/// Returns a table definition that is passed as the argument in the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
/// ``Database/create(virtualTable:options:using:_:)`` closure.
///
/// For example:
///
@@ -54,10 +54,29 @@ public protocol VirtualTableModule {
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
}
// TODO: Question the existence of this API. VirtualTableConfiguration was
// never able to be used by user-defined VirtualTableModule types, because
// `ifNotExists` has never been public.
public struct VirtualTableConfiguration {
/// If true, existing objects must not be replaced, or generate any error
/// (even if they do not match the objects that would be created otherwise.)
var ifNotExists: Bool
/// If true, new objects must be created in the temp schema.
var temporary: Bool
}
/// Virtual table creation options.
public struct VirtualTableOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the table if it does not already exist.
public static let ifNotExists = VirtualTableOptions(rawValue: 1 << 0)
/// Creates a temporary table.
public static let temporary = VirtualTableOptions(rawValue: 1 << 1)
}
extension Database {
@@ -77,18 +96,24 @@ extension Database {
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - options: Table creation options.
/// - module: The name of an SQLite virtual table module.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
public func create(
virtualTable name: String,
options: VirtualTableOptions = [],
using module: String
) throws {
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
if options.contains(.temporary) {
chunks.append("temp.\(name.quotedDatabaseIdentifier)")
} else {
chunks.append(name.quotedDatabaseIdentifier)
}
chunks.append("USING")
chunks.append(module)
let sql = chunks.joined(separator: " ")
@@ -114,21 +139,21 @@ extension Database {
///
/// - parameters:
/// - tableName: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - options: Table creation options.
/// - module: a virtual module.
/// - body: An optional closure that defines the virtual table.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
options: VirtualTableOptions = [],
using module: Module,
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
throws
{
// Define virtual table
let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists)
let configuration = VirtualTableConfiguration(
ifNotExists: options.contains(.ifNotExists),
temporary: options.contains(.temporary))
let definition = module.makeTableDefinition(configuration: configuration)
if let body {
try body(definition)
@@ -137,10 +162,14 @@ extension Database {
// Create virtual table
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(tableName.quotedDatabaseIdentifier)
if options.contains(.temporary) {
chunks.append("temp.\(tableName.quotedDatabaseIdentifier)")
} else {
chunks.append(tableName.quotedDatabaseIdentifier)
}
chunks.append("USING")
let arguments = try module.moduleArguments(for: definition, in: self)
if arguments.isEmpty {
@@ -156,4 +185,78 @@ extension Database {
return .commit
}
}
/// Creates a virtual database table.
///
/// For example:
///
/// ```swift
/// // CREATE VIRTUAL TABLE vocabulary USING spellfix1
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(virtualTable:options:using:)`` instead.
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: The name of an SQLite virtual table module.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
try create(
virtualTable: name,
options: ifNotExists ? .ifNotExists : [],
using: module)
}
/// Creates a virtual database table.
///
/// The type of the argument of the `body` function depends on the type of
/// the `module` argument: refer to this module's documentation.
///
/// You can use this method to create full-text virtual tables:
///
/// ```swift
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.column("title")
/// t.column("author")
/// t.column("body")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(virtualTable:options:using:_:)`` instead.
///
/// - parameters:
/// - tableName: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: a virtual module.
/// - body: An optional closure that defines the virtual table.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
using module: Module,
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
throws
{
try create(
virtualTable: tableName,
options: ifNotExists ? .ifNotExists : [],
using: module,
body)
}
}
@@ -308,18 +308,31 @@ extension TableRecord {
/// 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
@@ -339,12 +352,17 @@ extension TableRecord {
/// - returns: An association to the common table expression.
public static func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<Self>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<Self, 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.
@@ -700,12 +718,17 @@ extension TableRecord {
/// For example, we can fetch only books whose author is French:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
/// struct Author: TableRecord, FetchableRecord, Decodable {
/// enum Columns {
/// static let countryCode = Column("countryCode")
/// }
/// }
///
/// struct Book: TableRecord, FetchableRecord, Decodable {
/// 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
/// .joining(required: frenchAuthors)
/// .fetchAll(db)
@@ -726,9 +749,19 @@ extension TableRecord {
/// 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 LEFT JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let teamColor = Player.team.select(\.color)
/// let request = Player.annotated(withOptional: teamColor)
/// ```
///
@@ -750,9 +783,19 @@ extension TableRecord {
/// 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.annotated(withRequired: teamColor)
/// ```
///
@@ -67,6 +67,38 @@ extension TableRecord {
all().select(selection)
}
/// Returns a request that selects the provided result columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT score FROM player
/// let request = Player.select(\.score)
/// ```
public static func select(
_ selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> QueryInterfaceRequest<Self> {
try all().select(selection)
}
/// Returns a request that selects the provided result columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT id, score FROM player
/// let request = Player.select { [$0.id, $0.score] }
/// ```
public static func select(
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> QueryInterfaceRequest<Self> {
try all().select(selection)
}
/// Returns a request that selects the provided SQL string.
///
/// For example:
@@ -163,6 +195,35 @@ extension TableRecord {
all().select(selection, as: type)
}
/// Returns a request that selects the provided 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.select(\.id, as: Int.self)
/// let scores = try request.fetchSet(db) // Set<Int>
///
/// // SELECT MAX(score) FROM player
/// let request = Player.select({ max($0.score) }, as: Int.self)
/// let maxScore = try request.fetchOne(db) // Int?
/// ```
public static func select<RowDecoder>(
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
as type: RowDecoder.Type = RowDecoder.self
) rethrows -> QueryInterfaceRequest<RowDecoder>
{
try all().select(selection, as: type)
}
/// Returns a request that selects the provided SQL string, and defines the
/// type of decoded rows.
///
@@ -251,6 +312,36 @@ extension TableRecord {
all().selectPrimaryKey(as: type)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// // SELECT id FROM player
/// let request = try Player.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.selectID().fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try Player.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public static func selectID() -> QueryInterfaceRequest<Self.ID>
where Self: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// record selection.
///
@@ -289,6 +380,46 @@ extension TableRecord {
all().annotated(with: selection)
}
/// Returns a request with the provided result columns appended to the
/// record selection.
///
/// The record selection is determined by
/// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT *, score + bonus AS totalScore FROM player
/// let request = Player.annotated { ($0.score + $0.bonus).forKey("totalScore") }
/// ```
public static func annotated(
with selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> QueryInterfaceRequest<Self> {
try all().annotated(with: selection)
}
/// Returns a request with the provided result columns appended to the
/// record selection.
///
/// The record selection is determined by
/// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT *, score + bonus AS totalScore FROM player
/// let request = Player.annotated { [($0.score + $0.bonus).forKey("totalScore")] }
/// ```
public static func annotated(
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> QueryInterfaceRequest<Self> {
try all().annotated(with: selection)
}
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
// prevent the `Player.filter(42)` misuse.
// See https://github.com/groue/GRDB.swift/pull/864
@@ -307,6 +438,26 @@ extension TableRecord {
all().filter(predicate)
}
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
// prevent the `Player.filter(42)` misuse.
// See https://github.com/groue/GRDB.swift/pull/864
/// Returns a request filtered with a boolean SQL expression.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = Player.filter { $0.name == name }
/// ```
public static func filter(
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
) rethrows -> QueryInterfaceRequest<Self> {
try all().filter(predicate)
}
/// Returns a request filtered by primary key.
///
/// All single-column primary keys are supported:
@@ -470,6 +621,38 @@ extension TableRecord {
all().order(orderings)
}
/// Returns a request sorted according to the given SQL ordering term.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT * FROM player ORDER BY score DESC
/// let request = Player.order(\.score.desc)
/// ```
public static func order(
_ orderings: (DatabaseComponents) throws -> any SQLOrderingTerm
) rethrows -> QueryInterfaceRequest<Self> {
try all().order(orderings)
}
/// Returns a request sorted according to the given SQL ordering terms.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = Player.order { [$0.score.desc, $0.name] }
/// ```
public static func order(
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
) rethrows -> QueryInterfaceRequest<Self> {
try all().order(orderings)
}
/// Returns a request sorted by primary key.
///
/// All primary keys are supported:
@@ -565,8 +748,45 @@ extension TableRecord {
/// .joining(required: Book.author.filter(Column("deathDate") <= bookAlias[Column("publishDate")])
/// ```
///
/// See ``TableRequest/aliased(_:)`` for more information.
public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self> {
/// See ``TableRequest/aliased(_:)-772vb`` for more information.
public static func aliased(_ alias: TableAlias<Void>) -> QueryInterfaceRequest<Self> {
all().aliased(alias)
}
/// Returns a request that can be referred to with the provided alias.
///
/// Use this method when you need to refer to this table from
/// another request.
///
/// For example, the request below fetches posthumous books:
///
/// ```swift
/// struct Author: TableRecord {
/// enum Columns {
/// static let deathDate = Column("deathDate")
/// }
/// }
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
///
/// enum Columns {
/// static let publishDate = Column("publishDate")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // AND author.deathDate <= book.publishDate
/// let bookAlias = TableAlias<Book>()
/// let request = Book
/// .aliased(bookAlias)
/// .joining(required: Book.author.filter { $0.deathDate <= bookAlias.publishDate })
/// ```
///
/// See ``TableRequest/aliased(_:)-3k5h4`` for more information.
public static func aliased(_ alias: TableAlias<Self>) -> QueryInterfaceRequest<Self> {
all().aliased(alias)
}
@@ -576,18 +796,31 @@ extension TableRecord {
/// 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
+7 -2
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord {
public protocol EncodableRecord: SendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
@@ -524,7 +524,12 @@ public enum DatabaseDataEncodingStrategy: Sendable {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy: Sendable {
public enum DatabaseDateEncodingStrategy: @unchecked Sendable {
// @unchecked Sendable because of `DateFormatter`, which lost its
// `Sendable` conformance with Xcode 16.3 beta. See
// <https://github.com/swiftlang/swift/issues/78635>.
// TODO: remove @unchecked when the compiler issue is fixed.
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
+14 -14
View File
@@ -212,20 +212,20 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// swiftlint:disable comma
// swiftlint:disable line_length
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
// swiftlint:enable line_length
// swiftlint:enable comma
+134 -27
View File
@@ -26,10 +26,16 @@ import Foundation
/// struct Player: FetchableRecord, TableRecord, Decodable {
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let name = Column("name")
/// static let score = Column("score")
/// }
/// }
///
/// let players = try Player.fetchAll(db)
/// let players = try Player.order(Column("score")).fetchAll(db)
/// let player = try Player.filter { $0.name == "O'Brien" }.fetchOne(db)
/// let players = try Player.order(\.score).fetchAll(db)
/// ```
///
/// ## Topics
@@ -552,20 +558,32 @@ extension FetchableRecord {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// SELECT * FROM player WHERE name = \(name)
/// """
///
/// let players = try Player.fetchCursor(db, request)
/// while let player = try players.next() {
/// print(player.name)
/// print(player.score)
/// }
/// }
/// ```
@@ -592,15 +610,27 @@ extension FetchableRecord {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// SELECT * FROM player WHERE name = \(name)
/// """
///
/// let players = try Player.fetchAll(db, request)
@@ -628,15 +658,27 @@ extension FetchableRecord {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
/// SELECT * FROM player WHERE name = \(name) LIMIT 1
/// """
///
/// let player = try Player.fetchOne(db, request)
@@ -667,15 +709,27 @@ extension FetchableRecord where Self: Hashable {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord, Hashable {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// SELECT * FROM player WHERE name = \(name)
/// """
///
/// let players = try Player.fetchSet(db, request)
@@ -711,15 +765,27 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// SELECT * FROM player WHERE name = \(name)
/// """
///
/// let players = try request.fetchCursor(db)
@@ -748,15 +814,27 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// SELECT * FROM player WHERE name = \(name)
/// """
///
/// let players = try request.fetchAll(db)
@@ -776,15 +854,27 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
/// SELECT * FROM player WHERE name = \(name) LIMIT 1
/// """
///
/// let player = try request.fetchOne(db)
@@ -805,15 +895,27 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord, Hashable {
/// var id: Int64
/// var name: String
/// var score: Int
///
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let score = Column(CodingKeys.score)
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let name = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.name == name }
///
/// // SQL request
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE lastName = \(lastName)
/// SELECT * FROM player WHERE name = \(name)
/// """
///
/// let players = try request.fetchSet(db)
@@ -929,7 +1031,12 @@ public enum DatabaseDataDecodingStrategy: Sendable {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy: Sendable {
public enum DatabaseDateDecodingStrategy: @unchecked Sendable {
// @unchecked Sendable because of `DateFormatter`, which lost its
// `Sendable` conformance with Xcode 16.3 beta. See
// <https://github.com/swiftlang/swift/issues/78635>.
// TODO: remove @unchecked when the compiler issue is fixed.
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more