view database/sqlite/src/driver.cpp @ 40:1e206fdc7021

Server: switch to Boost.DLL, closes #583
author David Demelier <markand@malikania.fr>
date Sun, 27 Nov 2016 20:00:13 +0100
parents 56ab2f0c90dc
children b0593a3e2ca8
line wrap: on
line source

#include <boost/dll.hpp>

#include <unordered_map>
#include <string>

#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" {

BOOST_SYMBOL_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
}

BOOST_SYMBOL_EXPORT void malikania_driver_unload()
{
    // Explicit destruction, optional.
    sqlite::database = nullptr;
}

} // !C