Skip to content

Instantly share code, notes, and snippets.

@little-brother
Last active April 26, 2021 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save little-brother/3da82cd801d6f4569a800949d1a0518d to your computer and use it in GitHub Desktop.
Save little-brother/3da82cd801d6f4569a800949d1a0518d to your computer and use it in GitHub Desktop.
SQLite aggregate function example
// gcc -shared aggsum.c -o aggsum.dll -s -static
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
static void sum_step (sqlite3_context *ctx, int argc, sqlite3_value **argv) {
double* total = (double*)sqlite3_aggregate_context(ctx, sizeof(double));
if (total == NULL)
return sqlite3_result_error_nomem(ctx);
*total += sqlite3_value_double(argv[0]);
}
static void sum_final (sqlite3_context *ctx) {
double* total = (double*)sqlite3_aggregate_context(ctx, sizeof(double));
sqlite3_result_double(ctx, *total);
}
#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_aggsum_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi) {
SQLITE_EXTENSION_INIT2(pApi);
return sqlite3_create_function (db, "aggsum", 1, SQLITE_UTF8, NULL, NULL, sum_step, sum_final);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment