Skip to content

Instantly share code, notes, and snippets.

@little-brother
Created April 26, 2021 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save little-brother/3b2c79e422d4e6797faf318b8484c6c5 to your computer and use it in GitHub Desktop.
Save little-brother/3b2c79e422d4e6797faf318b8484c6c5 to your computer and use it in GitHub Desktop.
Attach an user defined function to SQLite database example
// gcc main.c sqlite3.c -o main.exe
#include <stdio.h>
#include "sqlite3.h"
static void square (sqlite3_context *ctx, int argc, sqlite3_value **argv) {
int type = sqlite3_value_type(argv[0]);
double d = sqlite3_value_double(argv[0]);
switch (type) {
case SQLITE_NULL:
sqlite3_result_null(ctx);
break;
case SQLITE_INTEGER:
case SQLITE_FLOAT:
sqlite3_result_double(ctx, d * d);
break;
case SQLITE_TEXT:
case SQLITE_BLOB:
sqlite3_result_error(ctx, "Unsupported", -1);
break;
default:
sqlite3_result_error(ctx, "Impossible", -1);
}
}
int main() {
sqlite3* db;
if (SQLITE_OK != sqlite3_open_v2(":memory:", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, NULL)) {
printf("Error: can't open a database");
return -1;
}
if (SQLITE_OK != sqlite3_create_function(db, "square", 1, SQLITE_UTF8, 0, square, 0, 0)) {
printf("Error: can't register function");
return -1;
}
sqlite3_stmt* stmt;
if (SQLITE_OK == sqlite3_prepare_v2(db, "select ?1, square(?1) union all select ?2, square(?2) union all select ?3, square(?3)", -1, &stmt, 0)) {
sqlite3_bind_int(stmt, 1, 5);
sqlite3_bind_null(stmt, 2);
sqlite3_bind_text(stmt, 3, "abcdef", 6, SQLITE_TRANSIENT);
int rc = 0;
while (SQLITE_ROW == (rc = sqlite3_step(stmt)))
printf("x: %s, square: %s\n", sqlite3_column_text(stmt, 0), sqlite3_column_text(stmt, 1));
if (SQLITE_ERROR == rc)
printf(sqlite3_errmsg(db));
} else {
printf(sqlite3_errmsg(db));
}
sqlite3_finalize(stmt);
sqlite3_close_v2(db);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment