forked from Shubham-Saha/Secure-Multi-Execution-SME-Based-Vulnerability-Detection-Framework-for-Cpp-Applications
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLiteDB.cpp
47 lines (42 loc) · 1.67 KB
/
SQLiteDB.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "SQLiteDB.h"
#include <iostream>
SQLiteDB::SQLiteDB(const std::string& dbPath) : db(nullptr) {
if (sqlite3_open(dbPath.c_str(), &db)) {
std::cerr << "Error opening SQLite database: " << sqlite3_errmsg(db) << std::endl;
sqlite3_close(db);
exit(1);
}
execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, hashed_password TEXT, role TEXT, sensitive_info TEXT, security_level INTEGER);");
}
SQLiteDB::~SQLiteDB() {
if (db) {
sqlite3_close(db);
}
}
sqlite3* SQLiteDB::getDB() const {
return db;
}
bool SQLiteDB::execute(const std::string& sql) {
char* errMsg = nullptr;
if (sqlite3_exec(db, "BEGIN TRANSACTION;", nullptr, nullptr, &errMsg) != SQLITE_OK ||
sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &errMsg) != SQLITE_OK ||
sqlite3_exec(db, "COMMIT;", nullptr, nullptr, &errMsg) != SQLITE_OK) {
std::cerr << "SQL Error: " << errMsg << std::endl;
sqlite3_free(errMsg);
return false;
}
return true;
}
std::optional<std::vector<std::string>> SQLiteDB::query(const std::string& sql) {
sqlite3_stmt* stmt;
std::vector<std::string> results;
if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
results.push_back(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)));
}
sqlite3_finalize(stmt);
} else {
std::cerr << "Failed to prepare statement: " << sqlite3_errmsg(db) << std::endl;
}
return results.empty() ? std::nullopt : std::optional<std::vector<std::string>>(results);
}