Last active
May 29, 2024 00:03
-
-
Save kamahen/7ebf9b44cca992f8745c4165024154ac to your computer and use it in GitHub Desktop.
swiplite.c converted to C++ API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SWI-cpp2.h> | |
#include <sqlite3.h> | |
#include <string.h> | |
static PL_option_t sqlite3_open_options[] = { | |
PL_OPTION("mode", OPT_ATOM), | |
PL_OPTION("memory", OPT_BOOL), | |
PL_OPTION("mutex", OPT_ATOM), | |
PL_OPTIONS_END | |
}; | |
PREDICATE(pl_sqlite3_open, 3) | |
{ | |
auto db_name = A1, opts = A2, db_handle = A3; | |
char *file; | |
PlEx<bool>(db_name.get_chars(&file, | |
CVT_ATOM | CVT_STRING | CVT_LIST | |
| CVT_EXCEPTION | |
| BUF_STACK | |
| REP_UTF8)); | |
int flags = SQLITE_OPEN_EXRESCODE; | |
PlAtom mode(PlAtom::null); | |
int memory = false; | |
PlAtom mutex(PlAtom::null); | |
PlEx<bool>(PL_scan_options(opts.unwrap(), OPT_ALL, | |
"sqlite3_open_options", sqlite3_open_options, | |
mode.unwrap_as_ptr(), &memory, mutex.unwrap_as_ptr())); | |
const char *m; | |
if (mode.not_null() && (m = Plx_atom_nchars(mode.unwrap(), nullptr))) { | |
if (0 == strcmp("read", m)) { | |
flags |= SQLITE_OPEN_READONLY; | |
} | |
else if (0 == strcmp("write", m)) { | |
flags |= SQLITE_OPEN_READWRITE; | |
} | |
else if (0 == strcmp("create", m)) { | |
flags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; | |
} | |
else throw PlDomainError("mode(read|write|create)", PlTerm_atom(mode)); | |
} | |
else flags |= SQLITE_OPEN_READONLY; | |
if (memory) flags |= SQLITE_OPEN_MEMORY; | |
/* reusing m for mode as m for mutex */ | |
if (mutex.not_null() && (m = Plx_atom_nchars(mutex.unwrap(), nullptr))) { | |
if (0 == strcmp("no", m)) { | |
flags |= SQLITE_OPEN_NOMUTEX; | |
} | |
else if (0 == strcmp("full", m)) { | |
flags |= SQLITE_OPEN_FULLMUTEX; | |
} | |
else throw PlDomainError("mutex(no|full)", PlTerm_atom(mutex)); | |
} | |
sqlite3 *db; | |
if (SQLITE_OK != sqlite3_open_v2(file, &db, flags, NULL)) { | |
throw PlPermissionError("open", sqlite3_errmsg(db), db_name); | |
} | |
else return db_handle.unify_pointer(db); | |
} | |
PREDICATE(pl_sqlite3_close, 1) | |
{ | |
auto db_handle = A1; | |
sqlite3 *db; | |
db_handle.get_pointer_ex((void **)&db); | |
if (SQLITE_OK != sqlite3_close_v2(db)) { | |
throw PlResourceError(sqlite3_errmsg(db)); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment