sql: introduce FINALIZE for custom aggregate
This patch introduces a way to create a FINALIZER for user-defined aggregate functions. Closes #2579 @TarantoolBot document Title: User-defined aggregate functions User-defined aggregate functions are now available. To create a user-defined aggregate function, the 'aggregate' option should be set to 'group'. The function must have at least one argument. The last argument is always the result of the function in the previous step, or NULL if it is the first step. The last argument will be added automatically. Example: ``` box.schema.func.create("F1", {language = "Lua", body = [[ function(x, state) if state == nil then state = {sum = 0, count = 0} end state.sum = state.sum + x state.count = state.count + 1 return state end ]], param_list = {"integer", "map"}, returns = "map", aggregate = "group", exports = {"SQL"}, }) box.execute('CREATE TABLE t (i INT PRIMARY KEY);') box.execute('INSERT INTO t VALUES(1), (2), (3), (4), (5);') box.execute('SELECT f1(i) FROM t;') ``` The result will be: ``` tarantool> box.execute([[select f1(i) from t;]]) --- - metadata: - name: COLUMN_1 type: map rows: - [{'sum': 15, 'count': 5}] ... ``` To create a finalizer for a function, another function should be created. This function should follow the following rules: 1) its name should be '<function name>_finalize'; 2) it must take exactly one argument; 3) it must be a non-aggregate function. If an aggregate function has a finalizer, the result of the aggregate function will be determined by the finalizer. Example: ``` box.schema.func.create("F1_finalize", { language = "Lua", body = [[ function(state) if state == nil then return 0 end return state.sum / state.count end ]], param_list = {"map"}, returns = "number", exports = {'LUA', 'SQL'}, }) box.execute('SELECT f1(i) FROM t;') ``` The result will be: ``` tarantool> box.execute([[select f1(i) from t;]]) --- - metadata: - name: COLUMN_1 type: number rows: - [3] ... ```
Showing
- changelogs/unreleased/gh-2579-introduce-custom-aggregates.md 3 additions, 0 deletionschangelogs/unreleased/gh-2579-introduce-custom-aggregates.md
- src/box/sql/func.c 13 additions, 0 deletionssrc/box/sql/func.c
- src/box/sql/resolve.c 12 additions, 0 deletionssrc/box/sql/resolve.c
- src/box/sql/select.c 7 additions, 0 deletionssrc/box/sql/select.c
- src/box/sql/sqlInt.h 4 additions, 0 deletionssrc/box/sql/sqlInt.h
- test/sql-tap/gh-2579-custom-aggregate.test.lua 112 additions, 1 deletiontest/sql-tap/gh-2579-custom-aggregate.test.lua
Loading
Please register or sign in to comment