From 24e8ee2d0077ae025529f68478602988ef4f24fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Oct 2018 22:08:58 +0200 Subject: [PATCH] Stabilize annotation aliases, and allow aggregate any expression --- Documentation/AssociationsBasics.md | 127 +++++++++++------- .../Association/Annotation.swift | 3 +- .../Association/HasManyAssociation.swift | 72 +++++++--- Tests/GRDBTests/AnnotationTests.swift | 72 ++++++++-- 4 files changed, 194 insertions(+), 80 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 7cea33eff..b2578ebce 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1397,22 +1397,13 @@ You can also perform custom navigation in the tree by using *row scopes*. See [R ## Association Aggregates -It is possible to fetch aggregated values from a to-many association: +It is possible to fetch aggregated values from a **HasMany** association. You can count associated records, or fetch the minimum, maximum, average value of an associated record column, or compute the sum of an associated record column. -For example, in order to fetch all authors with their number of books, you'd write: +In the example below, we fetch all authors with their number of books: ```swift -struct Author: TableRecord { - static let books = hasMany(Book.self) - ... -} - -struct Book: TableRecord { - ... -} - struct AuthorInfo: Decodable, FetchableRecord { var author: Author var bookCount: Int @@ -1422,23 +1413,26 @@ struct AuthorInfo: Decodable, FetchableRecord { // FROM author // LEFT JOIN book ON book.authorId = author.id // GROUP BY author.id -let request = Author.annotate(with: Author.books.count) -let authorInfos = try AuthorInfo.fetchAll(db, request) +let request = Author.annotate(with: Author.books.count()) +let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) -for info in authorInfo { +for info in authorInfos { print("\(info.author.name) wrote \(info.bookCount) book(s).") } ``` -**HasMany** associations let you build five aggregates: -- `association.count` +### Available Aggregates + +An **HasMany** association lets you build the following aggregates: + +- `association.count()` - `association.min(column)` - `association.max(column)` - `association.avg(column)` - `association.sum(column)` -The request `annotate(with:)` method appends an aggregated value to the request selection. In order to access those values, you fetch a record type that contains the necessary properties. +The `annotate(with:)` method appends an aggregated value to the selected columns of a request. You can append as many aggregates values as needed. In order to access those values, you fetch a record type that has matching properties. For example: @@ -1446,51 +1440,90 @@ For example: struct AuthorInfo: Decodable, FetchableRecord { var author: Author var bookCount: Int - var minBookPrice: Int? - var maxBookPrice: Int? + var minBookYear: Int? + var maxBookYear: Int? var averageBookPrice: Double? - var bookPriceSum: Int? + var bookAwardsSum: Int? } // SELECT author.*, // COUNT(DISTINCT book.rowid) AS bookCount, -// MIN(book.price) AS minBookPrice -// MAX(book.price) AS maxBookPrice -// AVG(book.price) AS avgBookPrice -// SUM(book.price) AS sumBookPrice +// MIN(book.year) AS minBookYear +// MAX(book.year) AS maxBookYear +// AVG(book.price) AS averageBookPrice +// SUM(book.awards) AS sumBookAwards // FROM author // LEFT JOIN book ON book.authorId = author.id // WHERE author.id = 1 // GROUP BY author.id let request = Author .filter(key: 1) - .annotate(with: Author.books.count) - .annotate(with: Author.books.min(Column("price"))) - .annotate(with: Author.books.max(Column("price"))) + .annotate(with: Author.books.count()) + .annotate(with: Author.books.min(Column("year"))) + .annotate(with: Author.books.max(Column("year"))) .annotate(with: Author.books.avg(Column("price"))) - .annotate(with: Author.books.sum(Column("price"))) + .annotate(with: Author.books.sum(Column("awards"))) -if let authorInfo = try AuthorInfo.fetchOne(db, request) { +let info: AuthorInfo? = try AuthorInfo.fetchOne(db, request) + +if let info = info { print(info.author.name) - print("number of books: \(info.bookCount)") - print("minimum book price: \(info.minBookPrice)") - print("maximum book price: \(info.maxBookPrice)") - print("average book price: \(info.avgBookPrice)") - print("sum of book prices: \(info.bookPriceSum)") + print("- number of books: \(info.bookCount)") + print("- first book published on: \(info.minBookYear)") + print("- last book published on: \(info.maxBookYear)") + print("- average book price: \(info.averageBookPrice)") + print("- total awards received: \(info.bookAwardsSum)") } ``` -The names of the decoded properties are built from the **[association key](#the-structure-of-a-joined-request)**, and the aggregated column name: +As seen in the above example, aggregated values are given a **default name**, such as "bookCount" or "maxBookYear". The default name is built from the **[association key](#the-structure-of-a-joined-request)**, and the aggregated column name: | Aggregate | Key | Column | Property name | | --------- | --- | ------ | ------------- | -| `Author.books.count` | `book` | | `bookCount` | -| `Author.books.min(Column("price"))` | `book` | `price` | `minBookPrice` | -| `Author.books.max(Column("price"))` | `book` | `price` | `maxBookPrice` | -| `Author.books.avg(Column("price"))` | `book` | `price` | `averageBookPrice` | -| `Author.books.sum(Column("price"))` | `book` | `price` | `bookPriceSum` | +| `Author.books.count()` | `book` | | `bookCount` | +| `Author.books.min(Column("year"))` | `book` | `year` | `minBookYear` | +| `Author.books.max(Column("year"))` | `book` | `year` | `maxBookYear` | +| `Author.books.avg(Column("price"))` | `book` | `price` | `averageBookPrice` | +| `Author.books.sum(Column("awards"))` | `book` | `awards` | `bookAwardsSum` | -When you need to compute aggregates on various subsets of associated records, use distinct association keys. For example: +You can rename aggregated values with the `aliased` parameter: + +```swift +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var numberOfBooks: Int +} + +// SELECT author.*, COUNT(DISTINCT book.rowid) AS numberOfBooks +// FROM author +// LEFT JOIN book ON book.authorId = author.id +// GROUP BY author.id +let request = Author.annotate(with: Author.books.count(aliased: "numberOfBooks")) +let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) +``` + + +### Subset Aggregates + +You can compute aggregates on subsets of associated records with the `filter` method: + +```swift +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var bookCount: Int +} + +// SELECT author.*, +// COUNT(DISTINCT book.rowid) AS novelCount +// FROM author +// LEFT JOIN book ON book.authorId = author.id AND book.kind = 'novel' +// GROUP BY author.id +let novels = Author.books.filter(Column("kind") == "novel") +let request = Author.annotate(with: novels.count()) +let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) +``` + +When you need to compute aggregates on *several distinct subsets* of associated records, make sure you use distinct **association keys**, one for each subset. For example: ```swift struct AuthorInfo: Decodable, FetchableRecord { @@ -1509,15 +1542,13 @@ struct AuthorInfo: Decodable, FetchableRecord { let request = Author .annotate(with: Author.books .filter(Column("kind") == "novel") - .forKey("novel")) + .forKey("novel") + .count()) .annotate(with: Author.books .filter(Column("kind") == "theatrePlay") - .forKey("theatrePlay")) -let authorInfos = try AuthorInfo.fetchAll(db, request) - -for info in authorInfo { - ... -} + .forKey("theatrePlay") + .count()) +let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` diff --git a/GRDB/QueryInterface/Association/Annotation.swift b/GRDB/QueryInterface/Association/Annotation.swift index e7b44d283..ab377b47b 100644 --- a/GRDB/QueryInterface/Association/Annotation.swift +++ b/GRDB/QueryInterface/Association/Annotation.swift @@ -8,8 +8,9 @@ import Foundation +/// TODO public struct Annotation { let association: A let expression: SQLExpression - let alias: String + var alias: String } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 51db95148..232895b1f 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -98,64 +98,94 @@ extension HasManyAssociation where Destination: TableRecord { /// /// For example: /// - /// Team.annotated(with: Team.players.count) - public var count: Annotation> { + /// Team.annotated(with: Team.players.count()) + public func count() -> Annotation> { + return count(aliased: "\(key)Count") + } + + /// An annotation that counts the number of associated records. + /// + /// For example: + /// + /// Team.annotated(with: Team.players.count(aliased: "numberOfPlayers")) + public func count(aliased name: String) -> Annotation> { return Annotation( association: self, expression: SQLExpressionCountDistinct(Column.rowID), - alias: "\(key)Count") + alias: name) } - - /// An annotation that evaluaes to the aaverage value of the given column + + /// An annotation that evaluates to the average value of the given column /// in associated records. /// /// For example: /// - /// Team.annotated(with: Team.players.avg(Column("score"))) - public func avg(_ column: Column) -> Annotation> { + /// Team.annotated(with: Team.players.average(Column("score"))) + public func average(_ column: Column) -> Annotation> { + return average(column, aliased: "average\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } + + /// An annotation that evaluates to the average value in associated records. + public func average(_ value: SQLSpecificExpressible, aliased name: String) -> Annotation> { return Annotation( association: self, - expression: SQLExpressionFunction(.avg, arguments: column), - alias: "average\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + expression: SQLExpressionFunction(.avg, arguments: value), + alias: name) } - - /// An annotation that evaluaes to the maximum value of the given column + + /// An annotation that evaluates to the maximum value of the given column /// in associated records. /// /// For example: /// /// Team.annotated(with: Team.players.max(Column("score"))) public func max(_ column: Column) -> Annotation> { + return max(column, aliased: "max\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } + + /// An annotation that evaluates to the maximum value in associated records. + public func max(_ value: SQLSpecificExpressible, aliased name: String) -> Annotation> { return Annotation( association: self, - expression: SQLExpressionFunction(.max, arguments: column), - alias: "max\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + expression: SQLExpressionFunction(.max, arguments: value), + alias: name) } - - /// An annotation that evaluaes to the minimum value of the given column + + /// An annotation that evaluates to the minimum value of the given column /// in associated records. /// /// For example: /// /// Team.annotated(with: Team.players.min(Column("score"))) public func min(_ column: Column) -> Annotation> { + return min(column, aliased: "min\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } + + /// An annotation that evaluates to the minimum value in associated records. + public func min(_ value: SQLSpecificExpressible, aliased name: String) -> Annotation> { return Annotation( association: self, - expression: SQLExpressionFunction(.min, arguments: column), - alias: "min\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + expression: SQLExpressionFunction(.min, arguments: value), + alias: name) } - - /// An annotation that evaluaes to the sum of the given column + + /// An annotation that evaluates to the sum of the given column /// in associated records. /// /// For example: /// /// Team.annotated(with: Team.players.min(Column("score"))) public func sum(_ column: Column) -> Annotation> { + return sum(column, aliased: "\(key)\(column.name.uppercasingFirstCharacter)Sum") + } + + /// An annotation that evaluates to the sum of the given value in + /// associated records. + public func sum(_ value: SQLSpecificExpressible, aliased name: String) -> Annotation> { return Annotation( association: self, - expression: SQLExpressionFunction(.sum, arguments: column), - alias: "\(key)\(column.name.uppercasingFirstCharacter)Sum") + expression: SQLExpressionFunction(.sum, arguments: value), + alias: name) } } diff --git a/Tests/GRDBTests/AnnotationTests.swift b/Tests/GRDBTests/AnnotationTests.swift index fd071e2b8..9d0d2c41b 100644 --- a/Tests/GRDBTests/AnnotationTests.swift +++ b/Tests/GRDBTests/AnnotationTests.swift @@ -69,7 +69,7 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.avg(Column("score"))) + .annotated(with: Team.players.average(Column("score"))) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -102,7 +102,7 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.count) + .annotated(with: Team.players.count()) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -234,8 +234,8 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.avg(Column("score"))) - .annotated(with: Team.players.count) + .annotated(with: Team.players.average(Column("score"))) + .annotated(with: Team.players.count()) .annotated(with: Team.players.max(Column("score"))) .annotated(with: Team.players.min(Column("score"))) .annotated(with: Team.players.sum(Column("score"))) @@ -288,7 +288,7 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.avg(Column("score"))) + .annotated(with: Team.customPlayers.average(Column("score"))) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -321,7 +321,7 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.count) + .annotated(with: Team.customPlayers.count()) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -453,8 +453,8 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.avg(Column("score"))) - .annotated(with: Team.customPlayers.count) + .annotated(with: Team.customPlayers.average(Column("score"))) + .annotated(with: Team.customPlayers.count()) .annotated(with: Team.customPlayers.max(Column("score"))) .annotated(with: Team.customPlayers.min(Column("score"))) .annotated(with: Team.customPlayers.sum(Column("score"))) @@ -503,6 +503,58 @@ class AnnotationTests: GRDBTestCase { } } + func testAnnotationAlias() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let request = Team + .annotated(with: Team.players.average(Column("score"), aliased: "a1")) + .annotated(with: Team.players.count(aliased: "a2")) + .annotated(with: Team.players.max(Column("score"), aliased: "a3")) + .annotated(with: Team.players.min(Column("score"), aliased: "a4")) + .annotated(with: Team.players.sum(Column("score"), aliased: "a5")) + .orderByPrimaryKey() + .asRequest(of: CustomTeamInfo.self) + + try assertEqualSQL(db, request, """ + SELECT "team".*, \ + AVG("player"."score") AS "a1", \ + COUNT(DISTINCT "player"."rowid") AS "a2", \ + MAX("player"."score") AS "a3", \ + MIN("player"."score") AS "a4", \ + SUM("player"."score") AS "a5" \ + FROM "team" \ + LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \ + GROUP BY "team"."id" \ + ORDER BY "team"."id" + """) + } + } + + func testAnnotationExpression() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let request = Team + .annotated(with: Team.players.average(Column("score") * Column("score"), aliased: "a1")) + .annotated(with: Team.players.max(Column("score") * 10, aliased: "a3")) + .annotated(with: Team.players.min(-Column("score"), aliased: "a4")) + .annotated(with: Team.players.sum(Column("score") * Column("score"), aliased: "a5")) + .orderByPrimaryKey() + .asRequest(of: CustomTeamInfo.self) + + try assertEqualSQL(db, request, """ + SELECT "team".*, \ + AVG(("player"."score" * "player"."score")) AS "a1", \ + MAX(("player"."score" * 10)) AS "a3", \ + MIN(-"player"."score") AS "a4", \ + SUM(("player"."score" * "player"."score")) AS "a5" \ + FROM "team" \ + LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \ + GROUP BY "team"."id" \ + ORDER BY "team"."id" + """) + } + } + func testMultipleCount() throws { struct TeamInfo: Decodable, FetchableRecord { var team: Team @@ -512,8 +564,8 @@ class AnnotationTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.filter(Column("score") < 500).forKey("lowPlayer").count) - .annotated(with: Team.players.filter(Column("score") >= 500).forKey("highPlayer").count) + .annotated(with: Team.players.filter(Column("score") < 500).forKey("lowPlayer").count()) + .annotated(with: Team.players.filter(Column("score") >= 500).forKey("highPlayer").count()) .orderByPrimaryKey() .asRequest(of: TeamInfo.self)