From 4d79d922a740e35386620f5d5d11246b6b03053d Mon Sep 17 00:00:00 2001 From: Mergen Imeev <imeevma@gmail.com> Date: Thu, 9 Sep 2021 18:02:59 +0300 Subject: [PATCH] sql: refactor TOTAL() function Part of #4145 --- src/box/sql/func.c | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/box/sql/func.c b/src/box/sql/func.c index f18f1b4d1e..c3c7ebec06 100644 --- a/src/box/sql/func.c +++ b/src/box/sql/func.c @@ -76,6 +76,32 @@ fin_sum(struct sql_context *ctx) mem_copy_as_ephemeral(ctx->pOut, ctx->pMem); } +/** Implementation of the TOTAL() function. */ +static void +step_total(struct sql_context *ctx, int argc, struct Mem **argv) +{ + assert(argc == 1); + (void)argc; + assert(mem_is_null(ctx->pMem) || mem_is_num(ctx->pMem)); + if (mem_is_null(argv[0])) + return; + if (mem_is_null(ctx->pMem)) + mem_set_double(ctx->pMem, 0.0); + if (mem_add(ctx->pMem, argv[0], ctx->pMem) != 0) + ctx->is_aborted = true; +} + +/** Finalizer for the TOTAL() function. */ +static void +fin_total(struct sql_context *ctx) +{ + assert(mem_is_null(ctx->pMem) || mem_is_double(ctx->pMem)); + if (mem_is_null(ctx->pMem)) + mem_set_double(ctx->pOut, 0.0); + else + mem_copy_as_ephemeral(ctx->pOut, ctx->pMem); +} + static const unsigned char * mem_as_ustr(struct Mem *mem) { @@ -1700,17 +1726,6 @@ avgFinalize(sql_context * context) context->is_aborted = true; } -static void -totalFinalize(sql_context * context) -{ - SumCtx *p; - p = sql_aggregate_context(context, 0); - if (p == NULL || p->count == 0) - mem_set_double(context->pOut, 0.0); - else - mem_copy_as_ephemeral(context->pOut, &p->mem); -} - /* * The following structure keeps track of state information for the * count() aggregate function. @@ -2134,10 +2149,10 @@ static struct sql_func_definition definitions[] = { FIELD_TYPE_VARBINARY, substrFunc, NULL}, {"SUM", 1, {FIELD_TYPE_INTEGER}, FIELD_TYPE_INTEGER, step_sum, fin_sum}, {"SUM", 1, {FIELD_TYPE_DOUBLE}, FIELD_TYPE_DOUBLE, step_sum, fin_sum}, - {"TOTAL", 1, {FIELD_TYPE_INTEGER}, FIELD_TYPE_DOUBLE, sum_step, - totalFinalize}, - {"TOTAL", 1, {FIELD_TYPE_DOUBLE}, FIELD_TYPE_DOUBLE, sum_step, - totalFinalize}, + {"TOTAL", 1, {FIELD_TYPE_INTEGER}, FIELD_TYPE_DOUBLE, step_total, + fin_total}, + {"TOTAL", 1, {FIELD_TYPE_DOUBLE}, FIELD_TYPE_DOUBLE, step_total, + fin_total}, {"TRIM", 2, {FIELD_TYPE_STRING, FIELD_TYPE_INTEGER}, FIELD_TYPE_STRING, trim_func, NULL}, -- GitLab