Skip to content

Initializer

init(_:argumentCount:pure:indirect:aggregate:)

Creates an SQL aggregate function.
init<Aggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, indirect: Bool = false, aggregate: Aggregate.Type) where Aggregate : SQLiteCustomAggregate

Parameters

name

The function name.

argumentCount

The number of arguments of the aggregate. If omitted, or nil, the aggregate accepts any number of arguments.

pure

Whether the aggregate is “pure”, which means that its results only depends on its inputs. When an aggregate is pure, SQLite has the opportunity to perform additional optimizations. Default value is false.

aggregate

A type that implements the SQLiteCustomAggregate protocol. For each step of the aggregation, its step(_:) method is called with an array of DatabaseValue arguments. The array is guaranteed to have exactly argumentCount elements, provided argumentCount is not nil.

Discussion

For example:

struct MySum: DatabaseAggregate {
    var sum: Int = 0

    mutating func step(_ dbValues: [SQLiteData]) {
        sum += dbValues[0].integer ?? 0
    }

    func finalize() -> (any SQLiteDataConvertible)? {
        sum
    }
}

let connection: SQLiteConnection = ...
let fn = SQLiteCustomFunction("mysum", argumentCount: 1, pure: true, aggregate: MySum.self)
try await connection.install(customFunction: fn).get()
try await connection.query("CREATE TABLE test(i)").get()
try await connection.query("INSERT INTO test(i) VALUES (1)").get()
try await connection.query("INSERT INTO test(i) VALUES (2)").get()
let sum = (try await connection.query("SELECT mysum(i) FROM test").get().first?.columns.first?.integer)! // 3