Mercurial > malikania
diff database/sqlite/src/driver.cpp @ 39:56ab2f0c90dc
Server: add sqlite basic backend, closes #558
author | David Demelier <markand@malikania.fr> |
---|---|
date | Sun, 27 Nov 2016 18:00:49 +0100 |
parents | |
children | 1e206fdc7021 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/database/sqlite/src/driver.cpp Sun Nov 27 18:00:49 2016 +0100 @@ -0,0 +1,57 @@ +#include <unordered_map> +#include <string> + +#include <malikania/dynlib.hpp> + +#include "driver.hpp" + +namespace sqlite { + +std::unique_ptr<sqlite3, int (*)(sqlite3 *)> database{nullptr, nullptr}; + +statement prepare(const std::string& sql) +{ + sqlite3_stmt* stmt; + + if (sqlite3_prepare_v2(database.get(), sql.c_str(), sql.length(), &stmt, nullptr) != SQLITE_OK) { + throw std::runtime_error(sqlite3_errmsg(database.get())); + } + + return {stmt, &sqlite3_finalize}; +} + +} // !sqlite + +extern "C" { + +DYNLIB_EXPORT void malikania_driver_load(const std::unordered_map<std::string, std::string>& params) +{ + auto path = params.find("path"); + + if (path == params.end()) { + throw std::runtime_error("missing 'path' parameter"); + } + + sqlite3* db; + + if (sqlite3_open(path->second.c_str(), &db) != SQLITE_OK) { + throw std::runtime_error(sqlite3_errmsg(db)); + } + + sqlite::database = {db, &sqlite3_close}; + +#if 0 + // Not needed with SQLITE_DEFAULT_FOREIGN_KEYS + if (sqlite3_exec(db, "PRAGMA foreign_keys = ON", nullptr, nullptr, nullptr) != SQLITE_OK) { + throw std::runtime_error(sqlite3_errmsg(db)); + } +#endif +} + +DYNLIB_EXPORT void malikania_driver_unload() +{ + // Explicit destruction, optional. + sqlite::database = nullptr; +} + +} // !C