DatabaseAggregate

public protocol DatabaseAggregate

The protocol for custom SQLite aggregates.

For example:

struct MySum : DatabaseAggregate {
    var sum: Int = 0

    mutating func step(_ dbValues: [DatabaseValue]) {
        if let int = Int.fromDatabaseValue(dbValues[0]) {
            sum += int
        }
    }

    func finalize() -> DatabaseValueConvertible? {
        return sum
    }
}

let dbQueue = DatabaseQueue()
let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
dbQueue.add(function: fn)
try dbQueue.write { db in
    try db.execute(sql: "CREATE TABLE test(i)")
    try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
    try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
    try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
}
  • Creates an aggregate.

    Declaration

    Swift

    init()
  • This method is called at each step of the aggregation.

    The dbValues argument contains as many values as given to the SQL aggregate function.

    – One value SELECT maxLength(name) FROM player

    – Two values SELECT maxFullNameLength(firstName, lastName) FROM player

    This method is never called after the finalize() method has been called.

    Declaration

    Swift

    mutating func step(_ dbValues: [DatabaseValue]) throws
  • Returns the final result

    Declaration

    Swift

    func finalize() throws -> DatabaseValueConvertible?