Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for custom aggregate functions #237

Merged
merged 2 commits into from
Jul 1, 2017
Merged

Conversation

groue
Copy link
Owner

@groue groue commented Jul 1, 2017

As requested by @hashemi in #236, here is the support for custom aggregate functions:

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.inDatabase { db in
    try db.execute("CREATE TABLE test(i)")
    try db.execute("INSERT INTO test(i) VALUES (1)")
    try db.execute("INSERT INTO test(i) VALUES (2)")
    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
}

@groue groue merged commit ae3c28d into development Jul 1, 2017
@groue groue deleted the DatabaseAggregate branch July 1, 2017 09:39
@groue
Copy link
Owner Author

groue commented Jul 1, 2017

Shipped in v1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant