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