1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/c++/sqlite-demo-modul/Makefile Fri May 08 00:02:05 2020 +0200
1.3 @@ -0,0 +1,20 @@
1.4 +all: libdemo.so
1.5 +
1.6 +libdemo.so: demo.cpp
1.7 + g++ -g -shared -fPIC demo.cpp -o libdemo.so
1.8 +
1.9 +clean:
1.10 + rm -f libdemo.so
1.11 +
1.12 +run: libdemo.so
1.13 + echo "\
1.14 + SELECT 'load_extension', load_extension('./libdemo.so'); \
1.15 + SELECT 'get_pid', get_pid(); \
1.16 + SELECT 'value_count', value_count(), value_count('a'), value_count('a', 'b'), value_count(1,2,3); \
1.17 + SELECT 'multiply', multiply(2, 4); \
1.18 + " | sqlite3
1.19 +
1.20 +info: libdemo.so
1.21 + nm libdemo.so
1.22 + ldd libdemo.so
1.23 + file libdemo.so
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/c++/sqlite-demo-modul/demo.cpp Fri May 08 00:02:05 2020 +0200
2.3 @@ -0,0 +1,50 @@
2.4 +#include <cstdio>
2.5 +#include <sqlite3ext.h>
2.6 +#include <unistd.h>
2.7 +
2.8 +/**
2.9 + * This is just an example – use official documentation: https://www.sqlite.org/loadext.html
2.10 + */
2.11 +
2.12 +#define C_API extern "C"
2.13 +#define SQL_FN(functionName) C_API void functionName (sqlite3_context* ctx, int valueCount, sqlite3_value** values)
2.14 +
2.15 +SQLITE_EXTENSION_INIT1
2.16 +
2.17 +/**
2.18 + * Returns number of values passed to the SQL function.
2.19 + */
2.20 +SQL_FN(valueCount) {
2.21 + sqlite3_result_int(ctx, valueCount);
2.22 +}
2.23 +
2.24 +/**
2.25 + * Returns current PID (process id).
2.26 + */
2.27 +SQL_FN(getPID) {
2.28 + sqlite3_result_int(ctx, getpid());
2.29 +}
2.30 +
2.31 +/**
2.32 + * Returns multiplication of all arguments or zero, if there are no arguments.
2.33 + */
2.34 +SQL_FN(multiply) {
2.35 + sqlite3_int64 result = valueCount == 0 ? 0 : 1;
2.36 + for (int i = 0; i < valueCount; i++) result *= sqlite3_value_int64(values[i]);
2.37 + sqlite3_result_int64(ctx, result);
2.38 +}
2.39 +
2.40 +/**
2.41 + * Function name should match the library file name: libdemo.so → sqlite3_demo_init.
2.42 + * Or we can specify different entry point when loading the module.
2.43 + */
2.44 +C_API int sqlite3_demo_init(sqlite3* db, char** error, const sqlite3_api_routines* api) {
2.45 + SQLITE_EXTENSION_INIT2(api);
2.46 +
2.47 + sqlite3_create_function(db, "value_count", -1, SQLITE_UTF8, nullptr, valueCount, nullptr, nullptr);
2.48 + sqlite3_create_function(db, "get_pid", 0, SQLITE_UTF8, nullptr, getPID, nullptr, nullptr);
2.49 + sqlite3_create_function(db, "multiply", -1, SQLITE_UTF8, nullptr, multiply, nullptr, nullptr);
2.50 + // -1 = function accepts arbitrary number of arguments
2.51 +
2.52 + return SQLITE_OK;
2.53 +}