comparison 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
comparison
equal deleted inserted replaced
38:ecf316d52f5d 39:56ab2f0c90dc
1 #include <unordered_map>
2 #include <string>
3
4 #include <malikania/dynlib.hpp>
5
6 #include "driver.hpp"
7
8 namespace sqlite {
9
10 std::unique_ptr<sqlite3, int (*)(sqlite3 *)> database{nullptr, nullptr};
11
12 statement prepare(const std::string& sql)
13 {
14 sqlite3_stmt* stmt;
15
16 if (sqlite3_prepare_v2(database.get(), sql.c_str(), sql.length(), &stmt, nullptr) != SQLITE_OK) {
17 throw std::runtime_error(sqlite3_errmsg(database.get()));
18 }
19
20 return {stmt, &sqlite3_finalize};
21 }
22
23 } // !sqlite
24
25 extern "C" {
26
27 DYNLIB_EXPORT void malikania_driver_load(const std::unordered_map<std::string, std::string>& params)
28 {
29 auto path = params.find("path");
30
31 if (path == params.end()) {
32 throw std::runtime_error("missing 'path' parameter");
33 }
34
35 sqlite3* db;
36
37 if (sqlite3_open(path->second.c_str(), &db) != SQLITE_OK) {
38 throw std::runtime_error(sqlite3_errmsg(db));
39 }
40
41 sqlite::database = {db, &sqlite3_close};
42
43 #if 0
44 // Not needed with SQLITE_DEFAULT_FOREIGN_KEYS
45 if (sqlite3_exec(db, "PRAGMA foreign_keys = ON", nullptr, nullptr, nullptr) != SQLITE_OK) {
46 throw std::runtime_error(sqlite3_errmsg(db));
47 }
48 #endif
49 }
50
51 DYNLIB_EXPORT void malikania_driver_unload()
52 {
53 // Explicit destruction, optional.
54 sqlite::database = nullptr;
55 }
56
57 } // !C