1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/c++/sqlite-demo-modul/demo.cpp Fri May 08 00:02:05 2020 +0200
1.3 @@ -0,0 +1,50 @@
1.4 +#include <cstdio>
1.5 +#include <sqlite3ext.h>
1.6 +#include <unistd.h>
1.7 +
1.8 +/**
1.9 + * This is just an example – use official documentation: https://www.sqlite.org/loadext.html
1.10 + */
1.11 +
1.12 +#define C_API extern "C"
1.13 +#define SQL_FN(functionName) C_API void functionName (sqlite3_context* ctx, int valueCount, sqlite3_value** values)
1.14 +
1.15 +SQLITE_EXTENSION_INIT1
1.16 +
1.17 +/**
1.18 + * Returns number of values passed to the SQL function.
1.19 + */
1.20 +SQL_FN(valueCount) {
1.21 + sqlite3_result_int(ctx, valueCount);
1.22 +}
1.23 +
1.24 +/**
1.25 + * Returns current PID (process id).
1.26 + */
1.27 +SQL_FN(getPID) {
1.28 + sqlite3_result_int(ctx, getpid());
1.29 +}
1.30 +
1.31 +/**
1.32 + * Returns multiplication of all arguments or zero, if there are no arguments.
1.33 + */
1.34 +SQL_FN(multiply) {
1.35 + sqlite3_int64 result = valueCount == 0 ? 0 : 1;
1.36 + for (int i = 0; i < valueCount; i++) result *= sqlite3_value_int64(values[i]);
1.37 + sqlite3_result_int64(ctx, result);
1.38 +}
1.39 +
1.40 +/**
1.41 + * Function name should match the library file name: libdemo.so → sqlite3_demo_init.
1.42 + * Or we can specify different entry point when loading the module.
1.43 + */
1.44 +C_API int sqlite3_demo_init(sqlite3* db, char** error, const sqlite3_api_routines* api) {
1.45 + SQLITE_EXTENSION_INIT2(api);
1.46 +
1.47 + sqlite3_create_function(db, "value_count", -1, SQLITE_UTF8, nullptr, valueCount, nullptr, nullptr);
1.48 + sqlite3_create_function(db, "get_pid", 0, SQLITE_UTF8, nullptr, getPID, nullptr, nullptr);
1.49 + sqlite3_create_function(db, "multiply", -1, SQLITE_UTF8, nullptr, multiply, nullptr, nullptr);
1.50 + // -1 = function accepts arbitrary number of arguments
1.51 +
1.52 + return SQLITE_OK;
1.53 +}