Skip to content

Commit

Permalink
Merge pull request #573 from vapor/sum-results
Browse files Browse the repository at this point in the history
sum results fix
  • Loading branch information
tanner0101 authored Oct 17, 2018
2 parents 25eeedf + 0985282 commit dc258fe
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions Sources/Fluent/QueryBuilder/QueryBuilder+Aggregate.swift
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
extension QueryBuilder {
// MARK: Aggregate

/// Returns the sum of all entries for the supplied field, falling back to the default value if the Future containing the sum resolves to an Error.
/// Returns the sum of all entries for the supplied field.
///
/// let totalLikes = try Post.query(on: conn).sum(\.likes)
/// let totalViralPostLikes = try Post.query(on: conn).filter(\.likes >= 10_000_000).sum(\.likes, default: 0)
///
/// If a default value is supplied, it will be used when the sum's result
/// set is empty and no sum can be determined.
///
/// let totalViralPostLikes = try Post.query(on: conn)
/// .filter(\.likes >= 10_000_000)
/// .sum(\.likes, default: 0)
///
/// - parameters:
/// - field: Field to sum.
/// - default: Optional default to use.
/// - returns: A `Future` containing the sum.
public func sum<T>(_ field: KeyPath<Result, T>, default: T? = nil) -> Future<T> where T: Decodable {
return aggregate(Database.queryAggregateSum, field: field).catchMap { error in
guard let d = `default` else {
throw error
return self.count().flatMap { count in
switch count {
case 0:
if let d = `default` {
return self.connection.map { _ in d }
} else {
throw FluentError(identifier: "noSumResults", reason: "Sum query returned 0 results and no default was supplied.")
}
default:
return self.aggregate(Database.queryAggregateSum, field: field)
}
return d
}
}

Expand Down

0 comments on commit dc258fe

Please sign in to comment.