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
nameThe function name.
argumentCountThe number of arguments of the aggregate. If omitted, or nil, the aggregate accepts any number of arguments.
pureWhether 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.
aggregateA type that implements the
SQLiteCustomAggregateprotocol. For each step of the aggregation, itsstep(_:)method is called with an array of DatabaseValue arguments. The array is guaranteed to have exactlyargumentCountelements, providedargumentCountis 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