From 13cc6fb80cd59865fec529692ceb7cb134ab5fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=B6rnquist?= <hugo@lysator.liu.se> Date: Wed, 28 Feb 2024 11:29:18 +0100 Subject: [PATCH] Add sqlite extension for generating uuid's. --- Makefile | 11 +++++++++++ sqlite-uuid.c | 35 +++++++++++++++++++++++++++++++++++ test.sql | 2 ++ 3 files changed, 48 insertions(+) create mode 100644 Makefile create mode 100644 sqlite-uuid.c create mode 100644 test.sql diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3f202e5 --- /dev/null +++ b/Makefile @@ -0,0 +1,11 @@ +libs = sqlite3 uuid +CFLAGS = -Wall -pedantic -std=c2x -fPIC \ + -ggdb \ + $(shell pkg-config --cflags $(libs)) +LDLIBS = $(shell pkg-config --libs $(libs)) + +C_FILES = sqlite-uuid.c +O_FILES = $(C_FILES:%.c=%.o) + +sqlite-uuid.so: $(O_FILES) + $(CC) -shared -o $@ $^ $(LDLIBS) diff --git a/sqlite-uuid.c b/sqlite-uuid.c new file mode 100644 index 0000000..b9a6696 --- /dev/null +++ b/sqlite-uuid.c @@ -0,0 +1,35 @@ +#include <sqlite3ext.h> +SQLITE_EXTENSION_INIT1 +#include <uuid.h> + +static void sqlite_uuid(sqlite3_context *context, int argc, sqlite3_value **argv) { + uuid_t uuid; + uuid_generate_random(uuid); + + char str[37]; + uuid_unparse(uuid, &str[0]); + + sqlite3_result_text(context, str, 37, SQLITE_TRANSIENT); + + uuid_clear(uuid); +} + +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_extension_init ( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +) { + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + + (void) pzErrMsg; + + rc = sqlite3_create_function(db, "uuid", 0, + SQLITE_UTF8|SQLITE_INNOCUOUS, + 0, sqlite_uuid, 0, 0); + + return rc; +} diff --git a/test.sql b/test.sql new file mode 100644 index 0000000..da30454 --- /dev/null +++ b/test.sql @@ -0,0 +1,2 @@ +.load sqlite-uuid +SELECT uuid(); -- GitLab