56 lines
1.3 KiB
C++
56 lines
1.3 KiB
C++
#ifndef __DATABASE_H__
|
|
#define __DATABASE_H__
|
|
|
|
#include "sqlite3.h"
|
|
#include <string>
|
|
#include <vector>
|
|
#include <variant>
|
|
#include <optional>
|
|
#include <set>
|
|
#include <map>
|
|
|
|
class Database {
|
|
|
|
typedef std::vector<std::variant<int64_t, std::string>> QueryData;
|
|
|
|
public:
|
|
Database();
|
|
~Database();
|
|
|
|
bool open();
|
|
bool exec(const char* sqlQuery);
|
|
bool exec(const std::string& sqlQuery);
|
|
|
|
std::optional<int64_t> insert(const char* sql);
|
|
|
|
std::set<std::string> getStrSet(const std::string& sql);
|
|
|
|
template <typename T>
|
|
std::optional<T> get(const std::string sql, const QueryData& data){
|
|
sqlite3_stmt* stmt = bind(sql, data);
|
|
T ret;
|
|
if ((stmt == nullptr) || (sqlite3_step(stmt) != SQLITE_ROW))
|
|
return {};
|
|
|
|
if constexpr (std::is_same_v<T, int>) {
|
|
ret = sqlite3_column_int64(stmt, 0);
|
|
}
|
|
else if constexpr (std::is_same_v<T, std::string>){
|
|
ret = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
|
}
|
|
|
|
sqlite3_finalize(stmt);
|
|
return ret;
|
|
}
|
|
|
|
sqlite3_stmt* bind(const std::string sql, const QueryData& data);
|
|
|
|
std::map<std::string, std::string> getStrMap(const std::string sql, const QueryData& data);
|
|
|
|
private:
|
|
sqlite3_stmt* prepareStmt(const std::string& sql);
|
|
|
|
sqlite3* m_db;
|
|
};
|
|
|
|
#endif // __DATABASE_H__
|