db:create_aggregate

Creates an aggregate callback function

Prototype

db:create_aggregate(name,nargs,step,final)

Description

This function creates an aggregate callback function. Aggregates perform an operation over all rows in a query. name is a string with the name of the aggregate function as given in an SQL statement; nargs is the number of arguments this call will provide. step is the actual Lua function that gets called once for every row; it should accept a function context (see below for callback contexts) plus the same number of parameters as given in nargs. final is a function that is called once after all rows have been processed; it receives one argument, the function context.

The function context can be used inside the two callback functions to communicate with SQLite3. Here is a simple example:

db:exec[=[
CREATE TABLE numbers(num1,num2);
INSERT INTO numbers VALUES(1,11);
INSERT INTO numbers VALUES(2,22);
INSERT INTO numbers VALUES(3,33);
]=]
local num_sum=0
local function oneRow(context,num) -- add one column in all rows
num_sum=num_sum+num
end
local function afterLast(context) -- return sum after last row has been processed
context:result_number(num_sum)
num_sum=0
end
db:create_aggregate("do_the_sums",1,oneRow,afterLast)
for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end
for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end

This prints:

Sum of col 1: 6
Sum of col 2: 66


CALLBACK CONTEXTS

A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.

The various context functions are:

context:aggregate_count
context:get_aggregate_data
context:result
context:result_blob
context:result_error
context:result_int
context:result_null
context:result_number
context:result_text
context:set_aggregate_data
context:user_data

Lua functions

Topics