diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index d2dc5b911..3d9cdaf16 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1775,64 +1775,64 @@ for info in authorInfos { } ``` -As seen in the above example, some aggregated values are given a **default name**, such as "bookCount" or "maxBookYear". The default name is built from the aggregating method, 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", which directly feeds the decoded records. -| Method | Key | Column | Default name | -| --------- | --- | ------ | ------------- | -| `Author.books.isEmpty ` | `books` | - | - | -| `Author.books.count ` | `books` | - | `bookCount` | +The default name is built from the aggregating method, the **[association key](#the-structure-of-a-joined-request)**, and the aggregated column name: + +| Method | Association Key | Aggregated Column | Aggregate name | +| ------ | --------------- | ----------------- | -------------- | +| `Author.books.isEmpty`. | `books` | - | `hasNoBook` | +| `Author.books.count`. | `books` | - | `bookCount` | | `Author.books.min(Column("year"))` | `books` | `year` | `minBookYear` | | `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` | | `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` | -| `Author.books.sum(Column("awards")) ` | `books` | `awards` | `bookAwardsSum` | +| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` | -You give a custom name to an aggregated value with the `aliased` method: +Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever). + +You can name or rename aggregates with the `aliased` method: ```swift struct AuthorInfo: Decodable, FetchableRecord { var author: Author var numberOfBooks: Int } +let numberOfBooks = Author.books.count.aliased("numberOfBooks") // <-- +let request = Author.annotated(with: numberOfBooks) +let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) -// 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.annotated(with: Author.books.count.aliased("numberOfBooks")) +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var hasBooks: Bool +} +let hasBooks = (Author.books.isEmpty == false).aliased("hasBooks") // <-- +let request = Author.annotated(with: hasBooks) +let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) + +struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var workCount: Int +} +let workCount = (Author.books.count + Author.paintings.count).aliased("workCount") // <-- +let request = Author.annotated(with: workCount) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` -The `aliased` method also accept coding keys: +Coding keys are also accepted: ```swift struct AuthorInfo: Decodable, FetchableRecord { var author: Author var numberOfBooks: Int - static func fetchAll(_ db: Database) throws -> [AuthorInfo] { - let request = Author.annotated(with: Author.books.count.aliased(CodingKey.numberOfBooks)) - return try AuthorInfo.fetchAll(db, request) + static func all() -> QueryInterfaceRequest { + let numberOfBooks = Author.books.count.aliased(CodingKey.numberOfBooks) // <-- + return Author + .annotated(with: numberOfBooks) + .asRequest(of: AuthorInfo.self) } } -``` - -Custom names help consuming complex aggregates that have no name by default: - -```swift -struct AuthorInfo: Decodable, FetchableRecord { - var author: Author - var workCount: Int -} - -// SELECT author.*, -// (COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) AS workCount -// FROM author -// LEFT JOIN book ON book.authorId = author.id -// LEFT JOIN painting ON painting.authorId = author.id -// GROUP BY author.id -let aggregate = Author.books.count + Author.paintings.count -let request = Author.annotated(with: aggregate.aliased("workCount")) -let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) +let authorInfos: [AuthorInfo] = try AuthorInfo.all().fetchAll(db) ``` diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index df04dca45..ad26599c0 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -391,29 +391,61 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// The number of associated records. /// + /// It has a default name, which is "[key]Count", where key is the key of + /// the association. For example: + /// /// For example: /// - /// Team.annotated(with: Team.players.count()) + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerCount: Int + /// } + /// let request = Team.annotated(with: Team.players.count()) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - return makeAggregate(SQLExpressionCountDistinct(Column.rowID)).aliased("\(key.singularizedName)Count") + return makeAggregate(SQLExpressionCountDistinct(Column.rowID)) + .aliased("\(key.singularizedName)Count") } - /// An aggregate that is true if there exists no associated records. + /// Creates an aggregate that is true if there exists no associated records. /// - /// For example: + /// It has a default name, which is "hasNo[Key]", where key is the key of + /// the association. For example: /// - /// Team.having(Team.players.isEmpty()) - /// Team.having(!Team.players.isEmpty()) - /// Team.having(Team.players.isEmpty() == false) + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var hasNoPlayer: Bool + /// } + /// let request = Team.annotated(with: Team.players.isEmpty()) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db) + /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) + /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) + .aliased("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } - /// The average value of the given expression in associated records. + /// Creates an aggregate which evaluate to the average value of the given + /// expression in associated records. + /// + /// When the averaged expression is a column, the aggregate has a default + /// name which is "average[Key][Column]", where key is the key of the + /// association. For example: /// /// For example: /// - /// Team.annotated(with: Team.players.average(Column("score"))) + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var averagePlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.average(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) public func average(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression)) if let column = expression as? ColumnExpression { @@ -424,11 +456,23 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { } } - /// The maximum value of the given expression in associated records. + /// Creates an aggregate which evaluate to the maximum value of the given + /// expression in associated records. + /// + /// When the maximized expression is a column, the aggregate has a default + /// name which is "maximum[Key][Column]", where key is the key of the + /// association. For example: /// /// For example: /// - /// Team.annotated(with: Team.players.max(Column("score"))) + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var maxPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.max(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) public func max(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression)) if let column = expression as? ColumnExpression { @@ -439,11 +483,23 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { } } - /// The minimum value of the given expression in associated records. + /// Creates an aggregate which evaluate to the minimum value of the given + /// expression in associated records. + /// + /// When the minimized expression is a column, the aggregate has a default + /// name which is "minimum[Key][Column]", where key is the key of the + /// association. For example: /// /// For example: /// - /// Team.annotated(with: Team.players.min(Column("score"))) + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var minPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.min(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) public func min(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression)) if let column = expression as? ColumnExpression { @@ -454,11 +510,23 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { } } - /// The sum of the given expression in associated records. + /// Creates an aggregate which evaluate to the sum of the given expression + /// in associated records. + /// + /// When the summed expression is a column, the aggregate has a default + /// name which is "[key][Column]Sum", where key is the key of the + /// association. For example: /// /// For example: /// - /// Team.annotated(with: Team.players.min(Column("score"))) + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// let request = Team.annotated(with: Team.players.sum(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) public func sum(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression)) if let column = expression as? ColumnExpression { diff --git a/TODO.md b/TODO.md index fd5bb3f48..5b9ea6168 100644 --- a/TODO.md +++ b/TODO.md @@ -46,6 +46,7 @@ GRDB 4.0 - [ ] FTS: prefix queries - [ ] Test NOT TESTED methods +- [ ] Update best practices and stop fostering CodingKeys that adopt ColumnExpression Swift 4.2 diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 6ad6b6d8b..3528ad734 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -751,6 +751,28 @@ class AssociationAggregateTests: GRDBTestCase { func testHasManyIsEmpty() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in + do { + let request = Team.annotated(with: Team.players.isEmpty) + try assertEqualSQL(db, request, """ + SELECT "team".*, (COUNT(DISTINCT "player"."rowid") = 0) AS "hasNoPlayer" \ + FROM "team" \ + LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \ + GROUP BY "team"."id" + """) + try XCTAssertEqual(request.fetchAll(db).count, 4) + try XCTAssertEqual(request.fetchCount(db), 4) + } + do { + let request = Team.annotated(with: !Team.players.isEmpty) + try assertEqualSQL(db, request, """ + SELECT "team".*, (COUNT(DISTINCT "player"."rowid") > 0) \ + FROM "team" \ + LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \ + GROUP BY "team"."id" + """) + try XCTAssertEqual(request.fetchAll(db).count, 4) + try XCTAssertEqual(request.fetchCount(db), 4) + } do { let request = Team.having(Team.players.isEmpty) try assertEqualSQL(db, request, """