From ae609cec3b6f7988cb7a67be910e9da9c13e68ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 12 Dec 2021 14:41:21 +0100 Subject: [PATCH] Support for the `TOTAL` SQL aggregate function --- CHANGELOG.md | 1 + Documentation/AssociationsBasics.md | 4 + .../Association/AssociationAggregate.swift | 38 ++++++++++ GRDB/QueryInterface/SQL/SQLFunctions.swift | 19 +++++ README.md | 4 +- .../GRDBTests/AssociationAggregateTests.swift | 74 +++++++++++++++++++ .../QueryInterfaceExpressionsTests.swift | 11 +++ 7 files changed, 149 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 605744498..3c6914b0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: `DatabaseRegion(table: tableName)` is deprecated. Use `Table(tableName)` instead. - **New**: The `ABS` and `LENGTH` SQL functions are now available on association aggregates, through `abs(aggregate)` and `length(aggregate)`. +- **New**: Support for the [`TOTAL` aggregate function](https://www.sqlite.org/lang_aggfunc.html#sumunc). You can use `total` in Swift, at all places `sum` is available. ## 5.16.0 diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 8ad0b3920..6ddca9107 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -2331,6 +2331,7 @@ for info in authorInfos { - `books.max(column)` - `books.average(column)` - `books.sum(column)` +- `books.total(column)` ### Annotating a Request with Aggregates @@ -2379,6 +2380,9 @@ The default name is built from the aggregating method, the **[association key](# | `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` | | `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` | | `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` | +| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ | + +¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions. Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever). diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index f340141c0..b442506ae 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -227,6 +227,9 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + /// + /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and + /// . @available(*, deprecated, message: "Did you mean sum(Column(...))? If not, prefer sum(value.databaseValue) instead.") // swiftlint:disable:this line_length public func sum(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) @@ -255,6 +258,9 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + /// + /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and + /// . public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -264,6 +270,38 @@ extension AssociationToMany { return aggregate } } + + /// 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: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// let request = Team.annotated(with: Team.players.total(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.total(Column("score")) > 100).fetchAll(db) + /// + /// This aggregate invokes the `TOTAL` SQL function. See also `sum(_:)`, and + /// . + public func total(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + // Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)` + // and `sum(_:)` compute sums. + return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") + } else { + return aggregate + } + } } /// An AssociationAggregate is able to compute aggregated values from a diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 3d35294a8..55fc2d5c6 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -101,6 +101,10 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// Returns an expression that evaluates the `SUM` SQL function. /// +/// See . +/// +/// See also `total(_:)`. +/// /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { @@ -108,6 +112,21 @@ public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { } +// MARK: - TOTAL(...) + +/// Returns an expression that evaluates the `TOTAL` SQL function. +/// +/// See . +/// +/// See also `sum(_:)`. +/// +/// // TOTAL(amount) +/// total(Column("amount")) +public func total(_ value: SQLSpecificExpressible) -> SQLExpression { + .aggregate("TOTAL", [value.sqlExpression]) +} + + // MARK: - String functions /// :nodoc: diff --git a/README.md b/README.md index 9a2c8715d..6ef4adc37 100644 --- a/README.md +++ b/README.md @@ -4948,9 +4948,9 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators). -- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`: +- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: - Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min` and `sum` Swift functions: + Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum` and `total` Swift functions: ```swift // SELECT MIN(score), MAX(score) FROM player diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 0d5bdd953..e16f00ab8 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -382,6 +382,43 @@ class AssociationAggregateTests: GRDBTestCase { } } + func testAnnotatedWithHasManyDefaultTotal() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let request = Team + .annotated(with: Team.players.total(Column("score"))) + .orderByPrimaryKey() + .asRequest(of: TeamInfo.self) + + try assertEqualSQL(db, request, """ + SELECT "team".*, TOTAL("player"."score") AS "playerScoreSum" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."id" \ + ORDER BY "team"."id" + """) + + let teamInfos = try request.fetchAll(db) + XCTAssertEqual(teamInfos.count, 4) + + XCTAssertEqual(teamInfos[0].team.id, 1) + XCTAssertEqual(teamInfos[0].team.name, "Reds") + XCTAssertEqual(teamInfos[0].playerScoreSum, 1100) + + XCTAssertEqual(teamInfos[1].team.id, 2) + XCTAssertEqual(teamInfos[1].team.name, "Blues") + XCTAssertEqual(teamInfos[1].playerScoreSum, 1500) + + XCTAssertEqual(teamInfos[2].team.id, 3) + XCTAssertEqual(teamInfos[2].team.name, "Greens") + XCTAssertEqual(teamInfos[2].playerScoreSum, 0) + + XCTAssertEqual(teamInfos[3].team.id, 4) + XCTAssertEqual(teamInfos[3].team.name, "Oranges") + XCTAssertEqual(teamInfos[3].playerScoreSum, 0) + } + } + func testAnnotatedWithHasManyMultipleDefaultAggregates() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in @@ -628,6 +665,43 @@ class AssociationAggregateTests: GRDBTestCase { } } + func testAnnotatedWithHasManyCustomTotal() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let request = Team + .annotated(with: Team.customPlayers.total(Column("score"))) + .orderByPrimaryKey() + .asRequest(of: CustomTeamInfo.self) + + try assertEqualSQL(db, request, """ + SELECT "team".*, TOTAL("player"."score") AS "customPlayerScoreSum" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."id" \ + ORDER BY "team"."id" + """) + + let teamInfos = try request.fetchAll(db) + XCTAssertEqual(teamInfos.count, 4) + + XCTAssertEqual(teamInfos[0].team.id, 1) + XCTAssertEqual(teamInfos[0].team.name, "Reds") + XCTAssertEqual(teamInfos[0].customPlayerScoreSum, 1100) + + XCTAssertEqual(teamInfos[1].team.id, 2) + XCTAssertEqual(teamInfos[1].team.name, "Blues") + XCTAssertEqual(teamInfos[1].customPlayerScoreSum, 1500) + + XCTAssertEqual(teamInfos[2].team.id, 3) + XCTAssertEqual(teamInfos[2].team.name, "Greens") + XCTAssertEqual(teamInfos[2].customPlayerScoreSum, 0) + + XCTAssertEqual(teamInfos[3].team.id, 4) + XCTAssertEqual(teamInfos[3].team.name, "Oranges") + XCTAssertEqual(teamInfos[3].customPlayerScoreSum, 0) + } + } + func testAnnotatedWithHasManyMultipleCustomAggregates() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 855f3fd81..67cfcf5ca 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1344,6 +1344,17 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT SUM(\"age\" / 2) FROM \"readers\"") } + func testTotalExpression() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Col.age))), + "SELECT TOTAL(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Col.age / 2))), + "SELECT TOTAL(\"age\" / 2) FROM \"readers\"") + } + // MARK: - LIKE operator