franta-hg@57: #include franta-hg@57: #include franta-hg@57: #include franta-hg@57: franta-hg@57: /** franta-hg@57: * This is just an example – use official documentation: https://www.sqlite.org/loadext.html franta-hg@57: */ franta-hg@57: franta-hg@57: #define C_API extern "C" franta-hg@58: #define SQL_FN(functionName) void functionName (sqlite3_context* ctx, int valueCount, sqlite3_value** values) franta-hg@57: franta-hg@57: SQLITE_EXTENSION_INIT1 franta-hg@57: franta-hg@57: /** franta-hg@57: * Returns number of values passed to the SQL function. franta-hg@57: */ franta-hg@57: SQL_FN(valueCount) { franta-hg@57: sqlite3_result_int(ctx, valueCount); franta-hg@57: } franta-hg@57: franta-hg@57: /** franta-hg@57: * Returns current PID (process id). franta-hg@57: */ franta-hg@57: SQL_FN(getPID) { franta-hg@57: sqlite3_result_int(ctx, getpid()); franta-hg@57: } franta-hg@57: franta-hg@57: /** franta-hg@57: * Returns multiplication of all arguments or zero, if there are no arguments. franta-hg@57: */ franta-hg@57: SQL_FN(multiply) { franta-hg@57: sqlite3_int64 result = valueCount == 0 ? 0 : 1; franta-hg@57: for (int i = 0; i < valueCount; i++) result *= sqlite3_value_int64(values[i]); franta-hg@57: sqlite3_result_int64(ctx, result); franta-hg@57: } franta-hg@57: franta-hg@57: /** franta-hg@57: * Function name should match the library file name: libdemo.so → sqlite3_demo_init. franta-hg@57: * Or we can specify different entry point when loading the module. franta-hg@57: */ franta-hg@57: C_API int sqlite3_demo_init(sqlite3* db, char** error, const sqlite3_api_routines* api) { franta-hg@57: SQLITE_EXTENSION_INIT2(api); franta-hg@57: franta-hg@57: sqlite3_create_function(db, "value_count", -1, SQLITE_UTF8, nullptr, valueCount, nullptr, nullptr); franta-hg@57: sqlite3_create_function(db, "get_pid", 0, SQLITE_UTF8, nullptr, getPID, nullptr, nullptr); franta-hg@57: sqlite3_create_function(db, "multiply", -1, SQLITE_UTF8, nullptr, multiply, nullptr, nullptr); franta-hg@57: // -1 = function accepts arbitrary number of arguments franta-hg@57: franta-hg@57: return SQLITE_OK; franta-hg@57: }