Merge pull request #936 from groue/dev/more-eager-loading

Complete Associations and the DerivableRequest Protocol
This commit is contained in:
Gwendal Roué authored and GitHub committed 2021-03-11 19:35:39 +01:00
commit c3dcd7636e
21 files changed
+1558 -718

No files matched your search

+9
View File
@@ -75,8 +75,17 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Development Branch
- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher
- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol
- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936).
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions.
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details).
## 5.5.0
Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0)
+131 -2
View File
@@ -26,6 +26,7 @@ GRDB Associations
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
- [Fetching Values from Associations]
@@ -781,6 +782,7 @@ Fetch requests do not visit the database until you fetch values from them. This
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
@@ -855,14 +857,22 @@ Before we describe them in detail, let's see a few requests they can build:
let request = Author
.including(all: Author.books)
/// All authors with their three most popular books
let request = Author
.including(all: Author.books.order(Column("popularity").desc).limit(3))
/// All authors with their awarded books
let request = Author
.including(all: Author.books.having(Book.awards.isEmpty == false))
/// All books with their respective author
let request = Book
.including(required: Book.author)
/// All books with their respective author, sorted by title
let request = Book
.order(Column("title"))
.including(required: Book.author)
.order(Column("title"))
/// All books written by a French author
let request = Book
@@ -1235,7 +1245,6 @@ let teamInfos = try Team
.fetchAll(db)
```
## Columns Selected by an Association
By default, associated records include all their columns:
@@ -1262,6 +1271,124 @@ let request = Book.including(required: restrictedAuthor)
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
## Further Refinements to Associations
Associations support more refinements:
- `limit`
Fetch all authors with their three most popular books:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var books: [Book]
}
let mostPopularBooks = Author.books
.order(Column("popularity").desc)
.limit(3)
let authorInfos: [AuthorInfo] = try Author
.including(all: mostPopularBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- `distinct`
Fetch all authors with the kinds of books they write (novels, poems, plays, etc):
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKinds: Set<Book.Kind>
}
let distinctBookKinds = Author.books
.select(Column("kind"))
.distinct()
.forKey("bookKinds")
let authorInfos: [AuthorInfo] = try Author
.including(all: distinctBookKinds)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- `group`, `having`
Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc):
```swift
struct BookKindInfo: Decodable {
var kind: Book.Kind
var maxYear: Int
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKindInfos: [BookKindInfo]
}
let bookKindInfos = Author.books
.select(
Column("kind"),
max(Column("year")).forKey("maxYear"))
.group(Column("kind"))
.forKey("bookKindInfos")
let authorInfos: [AuthorInfo] = try Author
.including(all: bookKindInfos)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Association Aggregates]
Fetch all authors with their awarded books:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var awardedBooks: [Book]
}
let awardedBooks = Author.books
.having(Book.awards.isEmpty == false)
.forKey("awardedBooks")
let authorInfos: [AuthorInfo] = try Author
.including(all: awardedBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Common Table Expressions]
Association can use their own CTEs:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var specialBooks: [Book]
}
let specialCTE = CommonTableExpression(...)
let specialBooks = Author.books
.with(specialCTE)
... // use the CTE in the book association
.forKey("specialBooks")
let authorInfos = try Author
.including(all: specialBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
## Table Aliases
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
@@ -2447,6 +2574,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
[Self Joins]: #self-joins
[Ordered Associations]: #ordered-associations
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: Migrations.md
@@ -2497,4 +2625,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[ValueObservation]: ../README.md#valueobservation
[FAQ]: ../README.md#faq-associations
[common table expressions]: CommonTableExpressions.md
[Common Table Expressions]: CommonTableExpressions.md
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
@@ -9,6 +9,7 @@ To support this guide, we'll design a simple library application that lets the u
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Record Types Hide Intimate Database Details]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
@@ -139,11 +140,91 @@ That's it. The `Author` type can read and write in the `author` database table.
> }
> ```
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
## Record Types Hide Intimate Database Details
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
Let's look at three examples:
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case novel, poems, essay, play
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
```swift
extension Book.Kind: DatabaseValueConvertible { }
```
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
```swift
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get { Decimal(priceCents) / 100 }
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
}
}
```
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
## Define Record Requests
@@ -166,7 +247,7 @@ extension Author {
}
```
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
```swift
// For a non-codable record
@@ -180,29 +261,44 @@ extension Author {
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
Here is how you define those requests:
The `DerivableRequest` protocol generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc.
```swift
// Some requests of Author --------------------v
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
extension DerivableRequest where RowDecoder == Author {
/// Returns a request for all authors ordered by name, in a localized
/// case-insensitive fashion
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Returns a request for all authors from a country
/// Filters authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
/// Filters authors with at least one book
func havingBooks() -> Self {
having(Author.books.isEmpty == false)
}
}
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
extension DerivableRequest where RowDecoder == Book {
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
/// Filters books from a country
func filter(country: String) -> Self {
// Books have no country column. But their author does:
joining(required: Book.author.filter(country: authorCountry))
}
}
```
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
```swift
try dbQueue.read { db in
@@ -214,72 +310,24 @@ try dbQueue.read { db in
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthors: [Author] = try Author.all()
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
.filter(country: "Spain")
.havingBooks()
.orderByName()
.fetchAll(db)
}
```
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
```swift
// Some requests of Book
extension DerivableRequest where RowDecoder == Book {
/// Returns a request for all books from a country
func filter(authorCountry: String) -> Self {
// A book is from a country if it can be
// joined with an author from that country:
// ---------------------------v
joining(required: Book.author.filter(country: authorCountry))
}
}
try dbQueue.read { db in
let italianBooks = try Book.all()
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
```swift
// More requests of Author -------------------------v
extension QueryInterfaceRequest where RowDecoder == Author {
/// Returns a request for all authors with at least one book
func havingBooks() -> QueryInterfaceRequest<Author> {
having(Author.books.isEmpty == false)
}
}
```
Those requests defined on `QueryInterfaceRequest` still compose fluently:
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(country:)` for books, above, uses the `filter(country:)` for authors.
```swift
try dbQueue.read { db in
let sortedFrenchAuthorsHavingBooks = try Author.all()
.filter(country: "France")
.havingBooks() // <-
.orderByName()
let italianBooks: [Book] = try Book.all()
.filter(country: "Italy")
.fetchAll(db)
}
```
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
```swift
extension MySingletonRecord {
/// The one any only record stored in the database
static let shared = all().limit(1)
}
let singleton = try dbQueue.read { db
try MySingletonRecord.shared.fetchOne(db)
}
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
@@ -696,7 +744,6 @@ Instead, have a look at [Database Observation]:
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
@@ -713,6 +760,7 @@ Instead, have a look at [Database Observation]:
[TransactionObserver]: ../README.md#transactionobserver-protocol
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[How to Design Database Managers]: #how-to-design-database-managers
@@ -727,3 +775,4 @@ Instead, have a look at [Database Observation]:
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
[Value]: ../README.md#values
-10
View File
@@ -829,9 +829,6 @@
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
@@ -953,7 +950,6 @@
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; };
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
@@ -1565,7 +1561,6 @@
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = "<group>"; };
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = "<group>"; };
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
@@ -2042,7 +2037,6 @@
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */,
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */,
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */,
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
56D91AA12205E03700770D8D /* SQLRelation.swift */,
568ECA8925D7013000B71526 /* SQLSelection.swift */,
568ECB1725D9161500B71526 /* SQLSubquery.swift */,
@@ -2866,7 +2860,6 @@
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */,
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
@@ -3070,7 +3063,6 @@
56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */,
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
@@ -3655,7 +3647,6 @@
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */,
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */,
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */,
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */,
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */,
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */,
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */,
@@ -3946,7 +3937,6 @@
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
@@ -72,13 +72,12 @@ extension Association {
}
extension Association {
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
.init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform))
}
}
extension Association {
/// The association key defines how rows fetched from this association
/// should be consumed.
///
@@ -105,6 +104,67 @@ extension Association {
/// }
var key: SQLAssociationKey { _sqlAssociation.destination.key }
/// Creates an association with the given key.
///
/// This new key helps Decodable records decode rows fetched from the
/// resulting association:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// struct PlayerInfo: FetchableRecord, Decodable {
/// let player: Player
/// let team: Team
///
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
/// return Player
/// .including(required: Player.team.forKey(CodingKeys.team))
/// .asRequest(of: PlayerInfo.self)
/// }
/// }
///
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
/// a specific database table.
///
/// In the example below, the "team.color = 'red'" condition in the where
/// clause could be not achieved without table aliases.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // JOIN team ON ...
/// // WHERE team.color = 'red'
/// let teamAlias = TableAlias()
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(teamAlias[Column("color")] == "red")
///
/// When you give a name to a table alias, you can reliably inject sql
/// snippets in your requests:
///
/// // SELECT player.*, custom.*
/// // JOIN team custom ON ...
/// // WHERE custom.color = 'red'
/// let teamAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
mapDestinationRelation { $0.aliased(alias) }
}
}
extension Association where Self: SelectionRequest {
/// Creates an association which selects *selection*.
///
/// struct Player: TableRecord {
@@ -146,7 +206,9 @@ extension Association {
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } }
}
}
extension Association where Self: FilteredRequest {
/// Creates an association with the provided *predicate promise* added to
/// the eventual set of already applied predicates.
///
@@ -162,7 +224,9 @@ extension Association {
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } }
}
}
extension Association where Self: OrderedRequest {
/// Creates an association with the provided *orderings promise*.
///
/// struct Player: TableRecord {
@@ -229,71 +293,45 @@ extension Association {
public func unordered() -> Self {
mapDestinationRelation { $0.unordered() }
}
/// Creates an association with the given key.
///
/// This new key helps Decodable records decode rows fetched from the
/// resulting association:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// struct PlayerInfo: FetchableRecord, Decodable {
/// let player: Player
/// let team: Team
///
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
/// return Player
/// .including(required: Player.team.forKey(CodingKeys.team))
/// .asRequest(of: PlayerInfo.self)
/// }
/// }
///
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
/// a specific database table.
///
/// In the example below, the "team.color = 'red'" condition in the where
/// clause could be not achieved without table aliases.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // JOIN team ON ...
/// // WHERE team.color = 'red'
/// let teamAlias = TableAlias()
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(teamAlias[Column("color")] == "red")
///
/// When you give a name to a table alias, you can reliably inject sql
/// snippets in your requests:
///
/// // SELECT player.*, custom.*
/// // JOIN team custom ON ...
/// // WHERE custom.color = 'red'
/// let teamAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
mapDestinationRelation { $0.aliased(alias) }
}
extension Association where Self: TableRequest {
public var databaseTableName: String {
_sqlAssociation.destination.relation.source.tableName
}
}
// TableRequest
extension Association {
/// :nodoc:
public var databaseTableName: String {
_sqlAssociation.destination.relation.source.tableName
extension Association where Self: AggregatingRequest {
/// Creates an association grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self {
mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } }
}
/// Creates an association with the provided *predicate promise* added to
/// the eventual set of already applied predicates.
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
mapDestinationRelation { $0.having { try predicate($0).sqlExpression } }
}
}
extension Association where Self: DerivableRequest {
/// Creates an association for returns distinct rows.
public func distinct() -> Self {
mapDestinationRelation { $0.with(\.isDistinct, true) }
}
/// Creates an association that fetches *limit* rows, starting at *offset*.
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) }
}
/// Returns an association that embeds the common table expression.
///
/// See `QueryInterfaceRequest.with(_:)` for more information.
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) }
}
}
@@ -1,25 +1,8 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(inout QueryInterfaceRequest<RowDecoder>)
-> DatabasePromise<SQLExpression>
extension AssociationToMany {
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>)
-> AssociationAggregate<OriginRowDecoder>
{
AssociationAggregate { request in
let tableAlias = TableAlias()
request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
return expressionPromise.map { tableAlias[$0] }
}
}
// Convenience
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
makeAggregate(DatabasePromise(value: expression))
AssociationAggregate(preparation: BasePreparation(association: self, expression: expression))
}
/// The number of associated records.
@@ -194,9 +177,13 @@ extension AssociationToMany {
/// // Won't compile because Fruit is not Author.
/// let request = Fruit.annotated(with: bookCount)
public struct AssociationAggregate<RowDecoder> {
/// Extend the request with the associated records used to compute the
/// aggregate, and return an expression promise which resolves to the
/// aggregated value.
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
///
/// For example:
///
@@ -208,7 +195,7 @@ public struct AssociationAggregate<RowDecoder> {
/// var request = Author.all()
///
/// let aggregate = Author.books.count
/// let expressionPromise = aggregate.prepare(&request)
/// let expression = aggregate.prepare(&request)
///
/// // The request has been extended with associated records:
/// //
@@ -220,17 +207,18 @@ public struct AssociationAggregate<RowDecoder> {
/// // The aggregated value:
/// //
/// // COUNT(DISTINCT book.id)
/// try expressionPromise.resolve(db)
/// expression
///
/// The aggregated value is not right away embedded in the extended request:
/// The aggregated expression is not embedded in the extended request:
///
/// - We don't know yet if the aggregated value will be used in the
/// - We don't know yet if the aggregated expression will be used in the
/// SQL selection, or in the HAVING clause.
/// - It helps implementing aggregate operators such as `&&`, `+`, etc.
let prepare: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
preparation.prepare(&request)
}
}
extension AssociationAggregate: Refinable {
@@ -265,12 +253,110 @@ extension AssociationAggregate: Refinable {
public func forKey(_ key: CodingKey) -> Self {
forKey(key.stringValue)
}
}
// MARK: - AssociationAggregatePreparation
/// An abstract class that only exists as support for
/// `AssociationAggregate.prepare(_:)`, which needs to prepare both query
/// interface requests and associations through their conformance
/// to `DerivableRequest`:
///
/// aggregate.prepare(&request)
/// aggregate.prepare(&association)
///
/// We could have used a generic closure instead of this class... if only Swift
/// would support generic closures.
private class AssociationAggregatePreparation<RowDecoder> {
func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
fatalError("subclass must override")
}
}
// swiftlint:disable:next colon
/// Prepares a request so that it can use association aggregates.
private class BasePreparation<Association: AssociationToMany>:
AssociationAggregatePreparation<Association.OriginRowDecoder>
{
private let association: Association
private let expression: SQLExpression
init(association: Association, expression: SQLExpression) {
self.association = association
self.expression = expression
}
override func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder
{
// The fundamental request that supports association aggregate:
//
// SELECT parent.*
// LEFT JOIN child ON child.parentID = parent.id
// GROUP BY parent.id
let tableAlias = TableAlias()
request = request
.joining(optional: association.aliased(tableAlias))
.groupByPrimaryKey()
// The fundamental request can now be annotated, or filtered in the
// having clause, with the association aggregate expression:
// MIN(child.score), COUNT(DISTINCT child.id), etc.
return expression.qualified(with: tableAlias)
}
}
/// Transforms the expression of an aggregate.
private class MapPreparation<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
private let base: AssociationAggregatePreparation<RowDecoder>
private let transform: (SQLExpression) -> SQLExpression
init(
base: AssociationAggregatePreparation<RowDecoder>,
transform: @escaping (SQLExpression) -> SQLExpression)
{
self.base = base
self.transform = transform
}
override func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
transform(base.prepare(&request))
}
}
extension AssociationAggregate {
/// Transforms the expression, and does not preserve key.
fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self {
AssociationAggregate { request in
self.prepare(&request).map(transform)
}
fileprivate func map(_ transform: @escaping (SQLExpression) -> SQLExpression) -> Self {
AssociationAggregate(preparation: MapPreparation(base: preparation, transform: transform))
}
}
/// Combines the expressions of two aggregates.
private class CombinePreparation<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
private let lhs: AssociationAggregatePreparation<RowDecoder>
private let rhs: AssociationAggregatePreparation<RowDecoder>
private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression
init(
_ lhs: AssociationAggregatePreparation<RowDecoder>,
_ rhs: AssociationAggregatePreparation<RowDecoder>,
combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression)
{
self.lhs = lhs
self.rhs = rhs
self.combine = combine
}
override func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
let lhsExpression = lhs.prepare(&request)
let rhsExpression = rhs.prepare(&request)
return combine(lhsExpression, rhsExpression)
}
}
@@ -278,18 +364,10 @@ extension AssociationAggregate: Refinable {
private func combine<RowDecoder>(
_ lhs: AssociationAggregate<RowDecoder>,
_ rhs: AssociationAggregate<RowDecoder>,
with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let lhsPromise = lhs.prepare(&request)
let rhsPromise = rhs.prepare(&request)
return DatabasePromise { db in
try combineExpressions(
lhsPromise.resolve(db),
rhsPromise.resolve(db))
}
}
AssociationAggregate(preparation: CombinePreparation(lhs.preparation, rhs.preparation, combine: combine))
}
// MARK: - Logical Operators (AND, OR, NOT)
@@ -406,83 +406,3 @@ extension CommonTableExpression {
JoinAssociation(to: Destination.relationForAll, condition: .none)
}
}
// MARK: - With
extension QueryInterfaceRequest {
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest message:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat.all()
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
///
/// - parameter cte: A common table expression.
/// - returns: A request.
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
with(\.query.ctes[cte.tableName], cte.cte)
}
}
extension TableRecord {
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest post:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
///
/// - parameter cte: A common table expression.
/// - returns: A request.
public static func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> QueryInterfaceRequest<Self> {
all().with(cte)
}
}
@@ -29,24 +29,18 @@
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<RowDecoder> {
var query: SQLQuery
}
extension QueryInterfaceRequest {
init(relation: SQLRelation) {
self.init(query: SQLQuery(relation: relation))
}
var relation: SQLRelation
}
extension QueryInterfaceRequest: Refinable { }
extension QueryInterfaceRequest: FetchRequest {
public var sqlSubquery: SQLSubquery {
.query(query)
.relation(relation)
}
public func fetchCount(_ db: Database) throws -> Int {
try query.fetchCount(db)
try relation.fetchCount(db)
}
public func makePreparedRequest(
@@ -54,13 +48,13 @@ extension QueryInterfaceRequest: FetchRequest {
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult)
var preparedRequest = try generator.makePreparedRequest(db)
let associations = query.relation.prefetchedAssociations
let associations = relation.prefetchedAssociations
if associations.isEmpty == false {
// Eager loading of prefetched associations
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [query] db, rows in
try prefetch(db, associations: associations, from: query, into: rows)
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [relation] db, rows in
try prefetch(db, associations: associations, from: relation, into: rows)
}
}
return preparedRequest
@@ -83,7 +77,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select { db in [Column("id")] }
/// .select { db in [Column("email")] }
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.select { try selection($0).map(\.sqlSelection) } }
map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } }
}
/// Creates a request which selects *selection*, and fetches values of
@@ -174,7 +168,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select([Column("id"), Column("email")])
/// .annotated(with: { db in [Column("name")] })
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated { try selection($0).map(\.sqlSelection) } }
map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } }
}
}
@@ -186,7 +180,7 @@ extension QueryInterfaceRequest: FilteredRequest {
/// var request = Player.all()
/// request = request.filter { db in true }
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.filter { try predicate($0).sqlExpression } }
map(\.relation) { $0.filter { try predicate($0).sqlExpression } }
}
}
@@ -205,7 +199,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// .reversed()
/// .order{ _ in [Column("name")] }
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
map(\.query) { $0.order { try orderings($0).map(\.sqlOrdering) } }
map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } }
}
/// Creates a request that reverses applied orderings.
@@ -220,7 +214,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all()
/// request = request.reversed()
public func reversed() -> QueryInterfaceRequest {
map(\.query) { $0.reversed() }
map(\.relation) { $0.reversed() }
}
/// Creates a request without any ordering.
@@ -229,20 +223,20 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all().order(Column("name"))
/// request = request.unordered()
public func unordered() -> QueryInterfaceRequest {
map(\.query) { $0.unordered() }
map(\.relation) { $0.unordered() }
}
}
extension QueryInterfaceRequest: AggregatingRequest {
/// Creates a request grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
map(\.query) { $0.group { try expressions($0).map(\.sqlExpression) } }
map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } }
}
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.having { try predicate($0).sqlExpression } }
map(\.relation) { $0.having { try predicate($0).sqlExpression } }
}
}
@@ -250,27 +244,27 @@ extension QueryInterfaceRequest: AggregatingRequest {
extension QueryInterfaceRequest: _JoinableRequest {
/// :nodoc:
public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(all: association) }
map(\.relation) { $0._including(all: association) }
}
/// :nodoc:
public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(optional: association) }
map(\.relation) { $0._including(optional: association) }
}
/// :nodoc:
public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(required: association) }
map(\.relation) { $0._including(required: association) }
}
/// :nodoc:
public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._joining(optional: association) }
map(\.relation) { $0._joining(optional: association) }
}
/// :nodoc:
public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._joining(required: association) }
map(\.relation) { $0._joining(required: association) }
}
}
@@ -279,7 +273,7 @@ extension QueryInterfaceRequest: JoinableRequest { }
extension QueryInterfaceRequest: TableRequest {
/// :nodoc:
public var databaseTableName: String {
query.relation.source.tableName
relation.source.tableName
}
/// Creates a request that allows you to define expressions that target
@@ -300,37 +294,25 @@ extension QueryInterfaceRequest: TableRequest {
/// .aliased(playerAlias)
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
map(\.query) { $0.aliased(alias) }
map(\.relation) { $0.aliased(alias) }
}
}
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest: DerivableRequest {
public func distinct() -> QueryInterfaceRequest {
with(\.relation.isDistinct, true)
}
public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest {
with(\.relation.limit, SQLLimit(limit: limit, offset: offset))
}
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
with(\.relation.ctes[cte.tableName], cte.cte)
}
}
extension QueryInterfaceRequest {
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM player
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest {
map(\.query) { $0.distinct() }
}
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
map(\.query) { $0.limit(limit, offset: offset) }
}
/// Creates a request bound to type RowDecoder.
///
/// The returned request can fetch if the type RowDecoder is fetchable (Row,
@@ -345,58 +327,7 @@ extension QueryInterfaceRequest {
/// - parameter type: The fetched type RowDecoder
/// - returns: A request bound to type RowDecoder.
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest<RowDecoder>(query: query)
}
}
// MARK: - Aggregates
extension QueryInterfaceRequest {
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = aggregate.prepare(&request)
if let key = aggregate.key {
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
} else {
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest {
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = predicate.prepare(&request)
return request.having(expressionPromise.resolve)
QueryInterfaceRequest<RowDecoder>(relation: relation)
}
}
@@ -410,7 +341,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
try SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute()
return db.changesCount
}
}
@@ -440,7 +371,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments) else
@@ -582,7 +513,7 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
private func prefetch(
_ db: Database,
associations: [_SQLAssociation],
from originQuery: SQLQuery,
from originRelation: SQLRelation,
into originRows: [Row]) throws
{
guard let firstOriginRow = originRows.first else {
@@ -598,7 +529,7 @@ private func prefetch(
fatalError("Not implemented: prefetch association without any foreign key")
case let .foreignKey(pivotForeignKey):
let originTable = originQuery.relation.source.tableName
let originTable = originRelation.source.tableName
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
@@ -647,17 +578,16 @@ private func prefetch(
// FROM country
// JOIN passport ON passport.countryCode = country.code
// AND (passport.a, passport.b) IN grdb_base
let originQuery = originQuery.map(\.relation) { baseRelation in
// Ordering and including(all:) children are
// useless, and we only need pivoting columns:
baseRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
}
//
// In the CTE, ordering and including(all:) children are
// useless, and we only need to select pivot columns:
let originRelation = originRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
let originCTE = CommonTableExpression(
named: "grdb_base",
request: SQLSubquery.query(originQuery))
request: SQLSubquery.relation(originRelation))
let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))!
let pivotFilter = originCTE.contains(pivotRowValue)
@@ -785,9 +715,7 @@ throws -> DatabaseRegion
.map(\.pivot.relation) { $0.filter(pivotFilter) }
.destinationRelation()
let prefetchQuery = SQLQuery(relation: prefetchRelation)
return try SQLQueryGenerator(query: prefetchQuery)
return try SQLQueryGenerator(relation: prefetchRelation)
.makeSelectStatement(db)
.databaseRegion // contains region of nested associations
}
@@ -590,4 +590,118 @@ extension JoinableRequest {
// MARK: - DerivableRequest
/// The base protocol for all requests that can be refined.
public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { }
public protocol DerivableRequest: AggregatingRequest, FilteredRequest,
JoinableRequest, OrderedRequest,
SelectionRequest, TableRequest
{
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM player
/// var request = Player.select(Column("name"))
/// request = request.distinct()
func distinct() -> Self
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 10 OFFSET 20
/// var request = Player.all()
/// request = request.limit(10, offset: 20)
///
/// Any previous limit is replaced.
func limit(_ limit: Int, offset: Int?) -> Self
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest message:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat.all()
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
}
extension DerivableRequest {
/// Creates a request which fetches *limit* rows.
///
/// // SELECT * FROM player LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
///
/// Any previous limit is replaced.
public func limit(_ limit: Int) -> Self {
self.limit(limit, offset: nil)
}
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = aggregate.prepare(&request)
if let key = aggregate.key {
return request.annotated(with: expression.forKey(key))
} else {
return request.annotated(with: expression)
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> Self {
annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> Self {
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = predicate.prepare(&request)
return request.having(expression)
}
}
-164
View File
@@ -1,164 +0,0 @@
/// SQLQuery is a representation of an SQL query.
///
/// See SQLQueryGenerator for actual SQL generation.
struct SQLQuery {
var relation: SQLRelation
var isDistinct: Bool = false
var groupPromise: DatabasePromise<[SQLExpression]>?
var havingExpressionPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
var limit: SQLLimit?
var ctes: OrderedDictionary<String, SQLCTE> = [:]
}
extension SQLQuery: Refinable {
func distinct() -> Self {
with(\.isDistinct, true)
}
func limit(_ limit: Int, offset: Int? = nil) -> Self {
with(\.limit, SQLLimit(limit: limit, offset: offset))
}
func aliased(_ alias: TableAlias) -> Self {
map(\.relation) { $0.aliased(alias) }
}
}
extension SQLQuery {
func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
map(\.relation) { $0.select(selection) }
}
// Convenience
func select(_ expressions: SQLExpression...) -> Self {
select { _ in expressions.map { .expression($0) } }
}
func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
map(\.relation) { $0.annotated(with: selection) }
}
}
extension SQLQuery {
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.relation) { $0.filter(predicate) }
}
}
extension SQLQuery {
func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
map(\.relation) { $0.order(orderings) }
}
func reversed() -> Self {
map(\.relation) { $0.reversed() }
}
func unordered() -> Self {
map(\.relation) { $0.unordered() }
}
}
extension SQLQuery {
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with(\.groupPromise, DatabasePromise(expressions))
}
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.havingExpressionPromise) { promise in
DatabasePromise { db in
if let filter = try promise.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
}
}
}
}
}
extension SQLQuery{
func _including(all association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(all: association) }
}
func _including(optional association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(optional: association) }
}
func _including(required association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(required: association) }
}
func _joining(optional association: _SQLAssociation) -> Self {
map(\.relation) { $0._joining(optional: association) }
}
func _joining(required association: _SQLAssociation) -> Self {
map(\.relation) { $0._joining(required: association) }
}
}
extension SQLQuery {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
// WITH ... SELECT ...
return try fetchTrivialCount(db)
}
if relation.children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested
// SELECT ... FROM ... JOIN ...
return try fetchTrivialCount(db)
}
let selection = try relation.selectionPromise.resolve(db)
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = selection[0].count(distinct: isDistinct) else {
return try fetchTrivialCount(db)
}
var countQuery = self.unordered()
countQuery.isDistinct = false
switch count {
case .all:
countQuery = countQuery.select(.countAll)
case .distinct(let expression):
countQuery = countQuery.select(.countDistinct(expression))
}
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
let countQuery = unordered().select(.countAll)
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
}
}
// SELECT COUNT(*) FROM (self)
func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.query(unordered())))"
return try countRequest.fetchOne(db)!
}
}
struct SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
+210 -46
View File
@@ -2,23 +2,20 @@
/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// is "a set of tuples sharing the same attributes; a set of columns and rows."
///
/// SQLRelation is defined with a selection, a source table of query, and an
/// eventual filter and ordering.
///
/// SELECT ... FROM ... WHERE ... ORDER BY ...
/// | | | |
/// | | | • ordering
/// | | • filter
/// | • source
/// • selection
///
/// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the
/// `SQLQuery` type.
/// WITH ... -- ctes
/// SELECT ... -- selectionPromise
/// FROM ... -- source
/// JOIN ... -- children
/// WHERE ... -- filterPromise
/// GROUP BY ... -- groupPromise
/// HAVING ... -- havingExpressionPromise
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
///
/// ## Promises
///
/// Selection, filter, and ordering are "promises" which are resolved when a
/// database connection is available. This is how we can implement requests such
/// Most relation elements are "promises" which are resolved when a database
/// connection is available. This is how we can implement requests such
/// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a
/// database connection in order to introspect the primary key. For example:
///
@@ -29,7 +26,7 @@
///
/// ## Children
///
/// Relations may also have children. A child is a link to another relation, and
/// Relations have children. A child is a link to another relation, and
/// provide support for joins and prefetched relations.
///
/// Relations and their children constitute a tree of relations, which the user
@@ -123,6 +120,27 @@ struct SQLRelation {
}
}
init(kind: SQLRelation.Child.Kind, condition: SQLAssociationCondition, relation: SQLRelation) {
switch kind {
case .oneOptional, .oneRequired, .bridge:
if relation.isDistinct {
fatalError("Can't join an association that selects DISTINCT rows")
}
if relation.groupPromise != nil || relation.havingExpressionPromise != nil {
fatalError("Not implemented: join an association with a GROUP BY clause")
}
if relation.limit != nil {
fatalError("Can't join an association with a LIMIT clause")
}
case .all:
break
}
self.kind = kind
self.condition = condition
self.relation = relation
}
fileprivate func makeAssociationForKey(_ key: String) -> _SQLAssociation {
let key = SQLAssociationKey.fixed(key)
@@ -143,30 +161,18 @@ struct SQLRelation {
}
var source: SQLSource
var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: [])
var filterPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
var selectionPromise: DatabasePromise<[SQLSelection]>
var filterPromise: DatabasePromise<SQLExpression>?
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
var ctes: OrderedDictionary<String, SQLCTE> = [:] // See also `allCTEs`
var children: OrderedDictionary<String, Child> = [:]
/// All prefetched associations (`including(all:)`), recursively
var prefetchedAssociations: [_SQLAssociation] {
children.flatMap { key, child -> [_SQLAssociation] in
switch child.kind {
case .all:
return [child.makeAssociationForKey(key)]
case .oneOptional, .oneRequired, .bridge:
return child.relation.prefetchedAssociations.map { association in
// Remove redundant pivot child
let pivotKey = association.pivot.keyName
let child = child.map(\.relation) { relation in
assert(relation.children[pivotKey] != nil)
return relation.removingChild(forKey: pivotKey)
}
return association.through(child.makeAssociationForKey(key))
}
}
}
}
// Properties below MUST NOT be used when joining to-one associations.
// This is guaranteed by Child.init().
var isDistinct = false
var groupPromise: DatabasePromise<[SQLExpression]>?
var havingExpressionPromise: DatabasePromise<SQLExpression>?
var limit: SQLLimit?
}
extension SQLRelation {
@@ -192,10 +198,17 @@ extension SQLRelation: Refinable {
select { _ in selection }
}
/// Removes all selections from chidren
// Convenience
func select(_ expressions: SQLExpression...) -> Self {
select { _ in expressions.map { .expression($0) } }
}
/// Sets the selection, removes all selections from chidren, and clears the
/// `isDistinct` flag.
func selectOnly(_ selection: [SQLSelection]) -> Self {
self
.select(selection)
.with(\.isDistinct, false)
.map(\.children) { children in
children.mapValues { child in
child.map(\.relation) { $0.selectOnly([]) }
@@ -219,7 +232,7 @@ extension SQLRelation: Refinable {
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.filterPromise) { promise in
DatabasePromise { db in
if let filter = try promise.resolve(db) {
if let filter = try promise?.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
@@ -251,12 +264,60 @@ extension SQLRelation: Refinable {
}
}
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with(\.groupPromise, DatabasePromise(expressions))
}
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.havingExpressionPromise) { promise in
DatabasePromise { db in
if let filter = try promise?.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
}
}
}
}
func aliased(_ alias: TableAlias) -> Self {
map(\.source) { $0.aliased(alias) }
}
}
extension SQLRelation {
/// All prefetched associations (`including(all:)`), recursively
var prefetchedAssociations: [_SQLAssociation] {
children.flatMap { key, child -> [_SQLAssociation] in
switch child.kind {
case .all:
return [child.makeAssociationForKey(key)]
case .oneOptional, .oneRequired, .bridge:
return child.relation.prefetchedAssociations.map { association in
// Remove redundant pivot child
let pivotKey = association.pivot.keyName
let child = child.map(\.relation) { relation in
assert(relation.children[pivotKey] != nil)
return relation.removingChild(forKey: pivotKey)
}
return association.through(child.makeAssociationForKey(key))
}
}
}
}
/// All common table expressions, including those of joined children.
var allCTEs: OrderedDictionary<String, SQLCTE> {
children.values.reduce(into: ctes) { (ctes, child) in
switch child.kind {
case .all, .bridge:
break
case .oneOptional, .oneRequired:
ctes.merge(child.relation.allCTEs, uniquingKeysWith: { (_, new) in new })
}
}
}
/// Returns a relation extended with an association.
///
/// This method provides support for public joining methods such
@@ -466,6 +527,72 @@ extension SQLRelation {
}
}
extension SQLRelation {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
// WITH ... SELECT ...
return try fetchTrivialCount(db)
}
if children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested
// SELECT ... FROM ... JOIN ...
return try fetchTrivialCount(db)
}
let selection = try selectionPromise.resolve(db)
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = selection[0].count(distinct: isDistinct) else {
return try fetchTrivialCount(db)
}
var countRelation = self.unordered()
countRelation.isDistinct = false
switch count {
case .all:
countRelation = countRelation.select(.countAll)
case .distinct(let expression):
countRelation = countRelation.select(.countDistinct(expression))
}
return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)!
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
let countRelation = unordered().select(.countAll)
return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)!
}
}
// SELECT COUNT(*) FROM (self)
private func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))"
return try countRequest.fetchOne(db)!
}
}
// MARK: - SQLLimit
struct SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
// MARK: - SQLSource
struct SQLSource {
@@ -839,19 +966,26 @@ extension PersistenceContainer: ColumnAddressable {
extension SQLRelation {
/// Returns nil if relations can't be merged (conflict in source, joins...)
func merged(with other: SQLRelation) -> Self? {
// Source
guard let mergedSource = source.merged(with: other.source) else {
// can't merge
return nil
}
let mergedFilterPromise = DatabasePromise<SQLExpression?> { db in
switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) {
case let (lhs?, rhs?): return lhs && rhs
case let (nil, expr?), let (expr?, nil): return expr
case (nil, nil): return nil
// Filter: merge with AND
let mergedFilterPromise: DatabasePromise<SQLExpression>?
switch (filterPromise, other.filterPromise) {
case let (lhs?, rhs?):
mergedFilterPromise = DatabasePromise {
try lhs.resolve($0) && rhs.resolve($0)
}
case let (nil, promise?), let (promise?, nil):
mergedFilterPromise = promise
case (nil, nil):
mergedFilterPromise = nil
}
// Children: merge recursively
var mergedChildren: OrderedDictionary<String, SQLRelation.Child> = [:]
for (key, child) in children {
if let otherChild = other.children[key] {
@@ -868,7 +1002,7 @@ extension SQLRelation {
mergedChildren.appendValue(child, forKey: key)
}
// replace selection unless empty
// Selection: replace unless empty
let mergedSelectionPromise = DatabasePromise { db -> [SQLSelection] in
let otherSelection = try other.selectionPromise.resolve(db)
if otherSelection.isEmpty {
@@ -878,15 +1012,45 @@ extension SQLRelation {
}
}
// replace ordering unless empty
// Ordering: prefer other
let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering
// Distinct
let mergedDistinct = isDistinct || other.isDistinct
// Grouping: prefer other
let mergedGroupPromise = other.groupPromise ?? groupPromise
// Having: merge with AND
let mergedHavingExpressionPromise: DatabasePromise<SQLExpression>?
switch (havingExpressionPromise, other.havingExpressionPromise) {
case let (lhs?, rhs?):
mergedHavingExpressionPromise = DatabasePromise {
try lhs.resolve($0) && rhs.resolve($0)
}
case let (nil, promise?), let (promise?, nil):
mergedHavingExpressionPromise = promise
case (nil, nil):
mergedHavingExpressionPromise = nil
}
// Limit: prefer other
let mergedLimit = other.limit ?? limit
// CTEs: merge & prefer other
let mergedCTEs = ctes.merging(other.ctes, uniquingKeysWith: { (_, other) in other })
return SQLRelation(
source: mergedSource,
selectionPromise: mergedSelectionPromise,
filterPromise: mergedFilterPromise,
ordering: mergedOrdering,
children: mergedChildren)
ctes: mergedCTEs,
children: mergedChildren,
isDistinct: mergedDistinct,
groupPromise: mergedGroupPromise,
havingExpressionPromise: mergedHavingExpressionPromise,
limit: mergedLimit)
}
}
+8 -8
View File
@@ -6,16 +6,16 @@ public struct SQLSubquery {
/// A literal SQL query
case literal(SQLLiteral)
/// A query interface query
case query(SQLQuery)
/// A query interface relation
case relation(SQLRelation)
}
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
self.init(impl: .literal(sqlLiteral))
}
static func query(_ query: SQLQuery) -> Self {
self.init(impl: .query(query))
static func relation(_ relation: SQLRelation) -> Self {
self.init(impl: .relation(relation))
}
}
@@ -48,8 +48,8 @@ extension SQLSubquery {
let statement = try db.cachedSelectStatement(sql: sql)
return statement.columnCount
case let .query(query):
return try SQLQueryGenerator(query: query).columnsCount(db)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).columnsCount(db)
}
}
}
@@ -77,8 +77,8 @@ extension SQLSubquery {
case let .literal(sqlLiteral):
return try sqlLiteral.sql(context)
case let .query(query):
return try SQLQueryGenerator(query: query, forSingleResult: false).requestSQL(context)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).requestSQL(context)
}
}
}
@@ -1,12 +1,7 @@
/// SQLQueryGenerator is able to generate an SQL SELECT query.
struct SQLQueryGenerator: Refinable {
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
private let havingExpressionPromise: DatabasePromise<SQLExpression?>
private let limit: SQLLimit?
private let singleResult: Bool
private let ctes: OrderedDictionary<String, SQLCTE>
// For database region
private let prefetchedAssociations: [_SQLAssociation]
@@ -15,49 +10,12 @@ struct SQLQueryGenerator: Refinable {
/// - parameter singleResult: A hint as to whether the query should be
/// optimized for a single result.
init(
query: SQLQuery,
relation: SQLRelation,
forSingleResult singleResult: Bool = false)
{
// To generate SQL, we need a "qualified" relation, where all tables,
// expressions, etc, are identified with table aliases.
//
// All those aliases let us disambiguate tables at the SQL level, and
// prefix columns names. For example, the following request...
//
// Book.filter(Column("kind") == Book.Kind.novel)
// .including(optional: Book.author)
// .including(optional: Book.translator)
// .annotated(with: Book.awards.count)
//
// ... generates the following SQL, where all identifiers are correctly
// disambiguated and qualified:
//
// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id)
// FROM book
// LEFT JOIN person person1 ON person1.id = book.authorId
// LEFT JOIN person person2 ON person2.id = book.translatorId
// LEFT JOIN award ON award.bookId = book.id
// GROUP BY book.id
// WHERE book.kind = 'novel'
relation = SQLQualifiedRelation(query.relation)
// Qualify group expressions and having clause with the relation alias.
//
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
let sourceAlias = relation.source.alias
groupPromise = query.groupPromise?.map {
$0.map { $0.qualified(with: sourceAlias) }
}
havingExpressionPromise = query.havingExpressionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
}
limit = query.limit
isDistinct = query.isDistinct
self.relation = SQLQualifiedRelation(relation)
self.prefetchedAssociations = relation.prefetchedAssociations
self.singleResult = singleResult
prefetchedAssociations = query.relation.prefetchedAssociations
ctes = query.ctes
}
func requestSQL(_ context: SQLGenerationContext) throws -> String {
@@ -66,7 +24,7 @@ struct SQLQueryGenerator: Refinable {
var sql = try commonTableExpressionsPrefix(context)
sql += "SELECT"
if isDistinct {
if relation.isDistinct {
sql += " DISTINCT"
}
@@ -88,13 +46,13 @@ struct SQLQueryGenerator: Refinable {
}
}
let filter = try relation.filterPromise.resolve(context.db)
let filter = try relation.filterPromise?.resolve(context.db)
if let filter = filter {
sql += " WHERE "
sql += try filter.sql(context)
}
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
let groupExpressions = try relation.groupPromise?.resolve(context.db) ?? []
if !groupExpressions.isEmpty {
sql += " GROUP BY "
sql += try groupExpressions
@@ -102,7 +60,7 @@ struct SQLQueryGenerator: Refinable {
.joined(separator: ", ")
}
if let havingExpression = try havingExpressionPromise.resolve(context.db) {
if let havingExpression = try relation.havingExpressionPromise?.resolve(context.db) {
sql += " HAVING "
sql += try havingExpression.sql(context)
}
@@ -115,8 +73,8 @@ struct SQLQueryGenerator: Refinable {
.joined(separator: ", ")
}
var limit = self.limit
if try singleResult && !expectsSingleResult(
var limit = relation.limit
if try limit == nil && singleResult && !expectsSingleResult(
context.db,
selection: selection,
filter: filter,
@@ -199,7 +157,7 @@ struct SQLQueryGenerator: Refinable {
}
// The filter knows better
guard let filter = try relation.filterPromise.resolve(db),
guard let filter = try relation.filterPromise?.resolve(db),
let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias)
else {
return selectedRegion
@@ -255,12 +213,12 @@ struct SQLQueryGenerator: Refinable {
var sql = try commonTableExpressionsPrefix(context)
sql += try "DELETE FROM " + relation.source.sql(context)
if let filter = try relation.filterPromise.resolve(db) {
if let filter = try relation.filterPromise?.resolve(db) {
sql += " WHERE "
sql += try filter.sql(context)
}
if let limit = limit {
if let limit = relation.limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
@@ -341,12 +299,12 @@ struct SQLQueryGenerator: Refinable {
.map { try $0.sql(context) }
.joined(separator: ", ")
if let filter = try relation.filterPromise.resolve(db) {
if let filter = try relation.filterPromise?.resolve(db) {
sql += " WHERE "
sql += try filter.sql(context)
}
if let limit = limit {
if let limit = relation.limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
@@ -416,15 +374,15 @@ struct SQLQueryGenerator: Refinable {
}
private func commonTableExpressionsPrefix(_ context: SQLGenerationContext) throws -> String {
if ctes.isEmpty {
if relation.ctes.isEmpty {
return ""
}
var sql = "WITH "
if ctes.values.contains(where: \.isRecursive) {
if relation.ctes.values.contains(where: \.isRecursive) {
sql += "RECURSIVE "
}
sql += try ctes
sql += try relation.ctes
.map { tableName, cte in
var columnsSQL = ""
if let columns = cte.columns, !columns.isEmpty {
@@ -457,7 +415,7 @@ struct SQLQueryGenerator: Refinable {
private func grouping(_ db: Database) throws -> GroupingInfo {
// Empty group clause: no grouping
// SELECT * FROM player
guard let groupExpressions = try groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
guard let groupExpressions = try relation.groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
return .none
}
@@ -518,15 +476,40 @@ struct SQLQueryGenerator: Refinable {
}
}
/// A "qualified" relation, where all tables are identified with a table alias.
/// To generate SQL, we need a "qualified" relation, where all tables,
/// expressions, etc, are qualified with table aliases.
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// | | | | |
/// | | | | • ordering
/// | | | • filterPromise
/// | | • joins
/// | • source
/// • selectionPromise
/// All those aliases let us disambiguate tables at the SQL level, and
/// prefix columns names. For example, the following request...
///
/// Book.filter(Column("kind") == Book.Kind.novel)
/// .including(optional: Book.author)
/// .including(optional: Book.translator)
/// .annotated(with: Book.awards.count)
///
/// ... generates the following SQL, where all identifiers are correctly
/// disambiguated and qualified:
///
/// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id)
/// FROM book
/// LEFT JOIN person person1 ON person1.id = book.authorId
/// LEFT JOIN person person2 ON person2.id = book.translatorId
/// LEFT JOIN award ON award.bookId = book.id
/// GROUP BY book.id
/// WHERE book.kind = 'novel'
///
/// `SQLQualifiedRelation` contains the following information:
///
/// WITH ... -- ctes
/// SELECT ... -- selectionPromise
/// FROM ... -- source
/// JOIN ... -- joins
/// WHERE ... -- filterPromise
/// GROUP BY ... -- groupPromise
/// HAVING ... -- havingExpressionPromise
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
private struct SQLQualifiedRelation {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
@@ -536,20 +519,14 @@ private struct SQLQualifiedRelation {
}
/// The source
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • source
let source: SQLQualifiedSource
/// The selection from source, not including selection of joined relations
private var sourceSelectionPromise: DatabasePromise<[SQLSelection]>
var isDistinct: Bool
/// The full selection, including selection of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • selectionPromise
var selectionPromise: DatabasePromise<[SQLSelection]> {
DatabasePromise { db in
let selection = try self.sourceSelectionPromise.resolve(db)
@@ -560,34 +537,24 @@ private struct SQLQualifiedRelation {
}
}
/// The filtering clause
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • filterPromise
let filterPromise: DatabasePromise<SQLExpression?>
let filterPromise: DatabasePromise<SQLExpression>?
/// The ordering of source, not including ordering of joined relations
private let sourceOrdering: SQLRelation.Ordering
/// The full ordering, including orderings of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • ordering
var ordering: SQLRelation.Ordering {
joins.reduce(sourceOrdering) {
$0.appending($1.value.relation.ordering)
}
}
/// The joins
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • joins
private(set) var joins: OrderedDictionary<String, SQLQualifiedJoin>
let groupPromise: DatabasePromise<[SQLExpression]>?
let havingExpressionPromise: DatabasePromise<SQLExpression>?
let limit: SQLLimit?
let ctes: OrderedDictionary<String, SQLCTE>
init(_ relation: SQLRelation) {
// Qualify the source, so that it be disambiguated with an SQL alias
// if needed (when a select query uses the same table several times).
@@ -596,9 +563,8 @@ private struct SQLQualifiedRelation {
// this SQLQualifiedRelation generates SQL.
source = SQLQualifiedSource(relation.source)
// Qualify all joins, selection, filter, and ordering, so that all
// identifiers can be correctly disambiguated and qualified.
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
// Qualify all selection, filter, etc, so that all identifiers
// can be correctly disambiguated and qualified.
let sourceAlias = source.alias
sourceSelectionPromise = relation.selectionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
@@ -607,6 +573,21 @@ private struct SQLQualifiedRelation {
$0.map { $0.qualified(with: sourceAlias) }
}
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
groupPromise = relation.groupPromise?.map {
$0.map { $0.qualified(with: sourceAlias) }
}
havingExpressionPromise = relation.havingExpressionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
}
// Turns relation children into joins. `including(all:)` children are
// discarded on the way.
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
// Copy other flags
limit = relation.limit
isDistinct = relation.isDistinct
ctes = relation.allCTEs
}
/// See SQLQueryGenerator.rowAdapter(_:)
@@ -669,14 +650,20 @@ private struct SQLQualifiedRelation {
return (adapter: adapter, endIndex: endIndex)
}
/// Removes all selections from joins
/// Sets the selection, removes all selections from joins, and clears the
/// `isDistinct` flag.
func selectOnly(_ selection: [SQLSelection]) -> Self {
let sourceSelectionPromise = DatabasePromise(value: selection.map {
$0.qualified(with: source.alias)
})
return self
.with(\.sourceSelectionPromise, sourceSelectionPromise)
.map(\.joins, { $0.mapValues { $0.selectOnly([]) } })
.with(\.isDistinct, false)
.map(\.joins, { joins in
joins.mapValues { join in
join.map(\.relation) { $0.selectOnly([]) }
}
})
}
}
@@ -738,11 +725,6 @@ private struct SQLQualifiedJoin: Refinable {
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelection]) -> SQLQualifiedJoin {
map(\.relation) { $0.selectOnly(selection) }
}
private func sql(
_ context: SQLGenerationContext,
leftAlias: TableAlias,
@@ -779,7 +761,7 @@ private struct SQLQualifiedJoin: Refinable {
conditions.append(expression)
}
if let filter = try relation.filterPromise.resolve(context.db) {
if let filter = try relation.filterPromise?.resolve(context.db) {
conditions.append(filter.qualified(with: rightAlias))
}
@@ -373,4 +373,41 @@ extension TableRecord {
public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self> {
all().aliased(alias)
}
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest post:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
///
/// - parameter cte: A common table expression.
/// - returns: A request.
public static func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> QueryInterfaceRequest<Self> {
all().with(cte)
}
}
+2 -1
View File
@@ -51,7 +51,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
func singleValueContainer() throws -> SingleValueDecodingContainer {
guard let key = codingPath.last else {
fatalError("single value decoding from database row is not supported")
// Decoding an array of scalars from rows: pick the first column
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
}
guard let index = row.index(forColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
+52
View File
@@ -118,6 +118,58 @@ struct OrderedDictionary<Key: Hashable, Value> {
let keys = self.keys.filter(dictionary.keys.contains)
return OrderedDictionary(keys: keys, dictionary: dictionary)
}
mutating func merge<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows
where S: Sequence, S.Element == (Key, Value)
{
for (key, value) in other {
if let current = self[key] {
self[key] = try combine(current, value)
} else {
self[key] = value
}
}
}
mutating func merge<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows
where S: Sequence, S.Element == (key: Key, value: Value)
{
for (key, value) in other {
if let current = self[key] {
self[key] = try combine(current, value)
} else {
self[key] = value
}
}
}
func merging<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows -> OrderedDictionary<Key, Value>
where S: Sequence, S.Element == (Key, Value)
{
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
func merging<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows -> OrderedDictionary<Key, Value>
where S: Sequence, S.Element == (key: Key, value: Value)
{
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
}
extension OrderedDictionary: Collection {
-6
View File
@@ -256,8 +256,6 @@
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; };
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
@@ -907,7 +905,6 @@
5656A84A2295BD56001FF3FF /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
5656A8502295BD56001FF3FF /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = "<group>"; };
@@ -1549,7 +1546,6 @@
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */,
5656A8462295BD56001FF3FF /* SQLOperators.swift */,
5656A8452295BD56001FF3FF /* SQLOrdering.swift */,
5656A8502295BD56001FF3FF /* SQLQuery.swift */,
5656A84E2295BD56001FF3FF /* SQLRelation.swift */,
568ECB0C25D904CA00B71526 /* SQLSelection.swift */,
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */,
@@ -2355,7 +2351,6 @@
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
@@ -2713,7 +2708,6 @@
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
@@ -230,6 +230,86 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
}
}
func testIncludingAllHasManyScalar() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.select(Column("colb2"))
.distinct()
.order(Column("colb2")))
.orderByPrimaryKey()
// Array
do {
struct Record: FetchableRecord, Decodable, Equatable {
var a: A
var bs: [Int64]
}
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]),
Record(
a: A(row: ["cola1": 2, "cola2": "a2"]),
bs: [2]),
Record(
a: A(row: ["cola1": 3, "cola2": "a3"]),
bs: []),
])
}
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]))
}
}
// Set
do {
struct Record: FetchableRecord, Decodable, Equatable {
var a: A
var bs: Set<Int64>
}
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]),
Record(
a: A(row: ["cola1": 2, "cola2": "a2"]),
bs: [2]),
Record(
a: A(row: ["cola1": 3, "cola2": "a3"]),
bs: []),
])
}
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]))
}
}
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -157,6 +157,37 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyScalar() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.select(Column("colb2"))
.distinct()
.order(Column("colb2")))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE "colb2" IN (1, 2, 3) \
ORDER BY "colb2"
"""])
}
}
}
func testIncludingAllHasManyWithCompoundForeignKey() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
@@ -1720,6 +1751,205 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testAggregate() throws {
struct Award: TableRecord { }
struct Player: TableRecord {
static let awards = hasMany(Award.self)
}
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
t.column("score")
t.column("category")
}
try db.create(table: "award") { t in
t.autoIncrementedPrimaryKey("awardId")
t.column("playerId", .integer).references("player")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
// Group an association
sqlQueries.removeAll()
let association = Team.players.select(max(Column("score"))).group(Column("category"))
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT MAX("score"), "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE "parentId" = 1 \
GROUP BY "category"
"""])
}
do {
// Filter an association with an association aggregate
sqlQueries.removeAll()
let association = Team.players.having(Player.awards.isEmpty)
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT "player".*, "player"."parentId" AS "grdb_parentId" \
FROM "player" \
LEFT JOIN "award" ON "award"."playerId" = "player"."playerId" \
WHERE "player"."parentId" = 1 \
GROUP BY "player"."playerId" \
HAVING COUNT(DISTINCT "award"."awardId") = 0
"""])
}
do {
// Annotate an association with an association aggregate
sqlQueries.removeAll()
let association = Team.players.annotated(with: Player.awards.count)
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT "player".*, COUNT(DISTINCT "award"."awardId") AS "awardCount", "player"."parentId" AS "grdb_parentId" \
FROM "player" \
LEFT JOIN "award" ON "award"."playerId" = "player"."playerId" \
WHERE "player"."parentId" = 1 \
GROUP BY "player"."playerId"
"""])
}
}
}
func testDistinct() throws {
struct Player: TableRecord { }
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
sqlQueries.removeAll()
let association = Team.players.distinct()
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT DISTINCT *, "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE "parentId" = 1
"""])
}
}
}
func testLimit() throws {
struct Player: TableRecord { }
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
sqlQueries.removeAll()
let association = Team.players.limit(10, offset: 5)
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT *, "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE "parentId" = 1 \
LIMIT 10 OFFSET 5
"""])
}
}
}
func testCTE() throws {
struct Player: TableRecord { }
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
sqlQueries.removeAll()
let cte = CommonTableExpression(named: "cte", sql: "SELECT 42")
let association = Team.players.with(cte).filter(Column("playerId") == cte.all())
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
WITH "cte" AS (SELECT 42) \
SELECT *, "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE ("playerId" = (SELECT * FROM "cte")) AND ("parentId" = 1)
"""])
}
}
}
// Return SELECT queries, but omit schema queries.
private func isSelectQuery(_ query: String) -> Bool {
return query.contains("SELECT") && !query.contains("sqlite_") && !query.contains("pragma_table_xinfo")
@@ -619,4 +619,164 @@ class CommonTableExpressionTests: GRDBTestCase {
""")
}
}
func testAssociation() throws {
try makeDatabaseQueue().write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
}
try db.create(table: "award") { t in
t.autoIncrementedPrimaryKey("id")
t.column("playerId", .integer).references("player")
}
struct Team: TableRecord { }
struct Player: TableRecord {
static let team = belongsTo(Team.self)
}
struct Award: TableRecord {
static let player = belongsTo(Player.self)
static let team = hasOne(Team.self, through: player, using: Player.team)
}
do {
// CTE on association
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
let request = Award
.joining(optional: Award.player.with(cte))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId"
""")
}
do {
// CTE on hasOneThrough association
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
let request = Award
.joining(optional: Award.team.with(cte))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// CTE on pivot of hasOneThrough association
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
let team = Award.hasOne(Team.self, through: Award.player.with(cte), using: Player.team)
let request = Award
.joining(optional: team)
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// Distinct CTEs on association and main request
let cte1 = CommonTableExpression(named: "cte1", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 2")
let request = Award
.with(cte1)
.joining(optional: Award.player.with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte1" AS (SELECT 1), \
"cte2" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId"
""")
}
do {
// Conflicting CTEs. The rule is: the last one wins.
do {
// Conflicting CTE on association and main request
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.with(cte1)
.joining(optional: Award.player.with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId"
""")
}
do {
// Conflicting CTE on two associations
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.joining(optional: Award.player.with(cte1))
.joining(optional: Award.team.with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// Conflicting CTE on two associations
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.joining(optional: Award.team.with(cte1))
.joining(optional: Award.player.with(cte2))
_ = try Row.fetchAll(db, request)
// There's a trick here. The last CTE wins, and the last cte
// is cte1: it is plugged on top of Award.player, where cte2
// is attached.
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// Conflicting CTE on two associations
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.joining(optional: Award.player.forKey("player1").with(cte1))
.joining(optional: Award.player.forKey("player2").with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" "player1" ON "player1"."id" = "award"."playerId" \
LEFT JOIN "player" "player2" ON "player2"."id" = "award"."playerId"
""")
}
}
}
}
}
@@ -8,4 +8,53 @@ class OrderedDictionaryTests: GRDBTestCase {
dict["a", default: []].append("bar")
XCTAssertEqual(dict, ["a": ["foo", "bar"]])
}
func testMergingUniquingKeysWith() {
do {
let dict: OrderedDictionary = ["a": 1, "b": 2]
let otherDictionary = ["a": 3, "c": 4]
let otherOrderedDictionary: OrderedDictionary = ["a": 3, "c": 4]
let otherSequence = zip(["a", "c"], [3, 4])
do {
let result = dict.merging(otherDictionary, uniquingKeysWith: { (current, _) in current })
XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { (current, _) in current })
XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherSequence, uniquingKeysWith: { (current, _) in current })
XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherDictionary, uniquingKeysWith: { (_, new) in new })
XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { (_, new) in new })
XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherSequence, uniquingKeysWith: { (_, new) in new })
XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherDictionary, uniquingKeysWith: { $0 + $1 })
XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { $0 + $1 })
XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherSequence, uniquingKeysWith: { $0 + $1 })
XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4])
}
}
}
}