c++/sqlite-demo-modul/demo.cpp
author František Kučera <franta-hg@frantovo.cz>
Fri, 15 May 2020 20:32:37 +0200
changeset 59 d6614ad97bed
parent 58 2f84ed5f3abf
permissions -rw-r--r--
LV2: modul zesilovače, dle oficiálního příkladu, ale bez závislosti na Pythonu – stačí gcc a make
     1 #include <cstdio>
     2 #include <sqlite3ext.h>
     3 #include <unistd.h>
     4 
     5 /**
     6  * This is just an example – use official documentation: https://www.sqlite.org/loadext.html
     7  */
     8 
     9 #define C_API extern "C"
    10 #define SQL_FN(functionName) void functionName (sqlite3_context* ctx, int valueCount, sqlite3_value** values)
    11 
    12 SQLITE_EXTENSION_INIT1
    13 
    14 /**
    15  * Returns number of values passed to the SQL function.
    16  */
    17 SQL_FN(valueCount) {
    18 	sqlite3_result_int(ctx, valueCount);
    19 }
    20 
    21 /**
    22  * Returns current PID (process id).
    23  */
    24 SQL_FN(getPID) {
    25 	sqlite3_result_int(ctx, getpid());
    26 }
    27 
    28 /**
    29  * Returns multiplication of all arguments or zero, if there are no arguments.
    30  */
    31 SQL_FN(multiply) {
    32 	sqlite3_int64 result = valueCount == 0 ? 0 : 1;
    33 	for (int i = 0; i < valueCount; i++) result *= sqlite3_value_int64(values[i]);
    34 	sqlite3_result_int64(ctx, result);
    35 }
    36 
    37 /**
    38  * Function name should match the library file name: libdemo.so → sqlite3_demo_init.
    39  * Or we can specify different entry point when loading the module.
    40  */
    41 C_API int sqlite3_demo_init(sqlite3* db, char** error, const sqlite3_api_routines* api) {
    42 	SQLITE_EXTENSION_INIT2(api);
    43 
    44 	sqlite3_create_function(db, "value_count", -1, SQLITE_UTF8, nullptr, valueCount, nullptr, nullptr);
    45 	sqlite3_create_function(db, "get_pid", 0, SQLITE_UTF8, nullptr, getPID, nullptr, nullptr);
    46 	sqlite3_create_function(db, "multiply", -1, SQLITE_UTF8, nullptr, multiply, nullptr, nullptr);
    47 	// -1 = function accepts arbitrary number of arguments
    48 
    49 	return SQLITE_OK;
    50 }