Support for the TOTAL SQL aggregate function

This commit is contained in:
Gwendal Roué committed 2021-12-12 14:46:43 +01:00
1 parent 8ba89a398a
commit ae609cec3b
7 files changed
+149 -2

No files matched your search

+1
View File
@@ -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
+4
View File
@@ -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).
@@ -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
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@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<OriginRowDecoder> {
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
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
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
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(_ expression: SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
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
@@ -101,6 +101,10 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression {
/// Returns an expression that evaluates the `SUM` SQL function.
///
/// See <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// 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 <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// See also `sum(_:)`.
///
/// // TOTAL(amount)
/// total(Column("amount"))
public func total(_ value: SQLSpecificExpressible) -> SQLExpression {
.aggregate("TOTAL", [value.sqlExpression])
}
// MARK: - String functions
/// :nodoc:
+2 -2
View File
@@ -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
@@ -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
@@ -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