added better database get api
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
#include "crow.h"
|
||||
#include "utils.hpp"
|
||||
#include "database.hpp"
|
||||
#include <optional>
|
||||
|
||||
using namespace std;
|
||||
|
||||
@@ -72,18 +73,6 @@ map<string, string> Database::getStrMap(const std::string sql, const Database::Q
|
||||
return map;
|
||||
}
|
||||
|
||||
string Database::getStr(const std::string sql, const Database::QueryData& data){
|
||||
sqlite3_stmt* stmt = bind(sql, data);
|
||||
string str;
|
||||
if (stmt == nullptr)
|
||||
return str;
|
||||
|
||||
str = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return str;
|
||||
}
|
||||
|
||||
set<string> Database::getStrSet(const string& sql){
|
||||
sqlite3_stmt* stmt = prepareStmt(sql);
|
||||
set<string> vec;
|
||||
@@ -99,20 +88,6 @@ set<string> Database::getStrSet(const string& sql){
|
||||
return vec;
|
||||
}
|
||||
|
||||
std::optional<int64_t> Database::getInt(const char* sql) {
|
||||
sqlite3_stmt* stmt = prepareStmt(sql);
|
||||
if (stmt == nullptr)
|
||||
return {};
|
||||
|
||||
std::optional<int64_t> id;
|
||||
if (sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
id = sqlite3_column_int64(stmt, 0);
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return id;
|
||||
}
|
||||
|
||||
std::optional<int64_t> Database::insert(const char* sql) {
|
||||
sqlite3_stmt* stmt = prepareStmt(sql);
|
||||
if (stmt == nullptr)
|
||||
|
||||
@@ -21,14 +21,27 @@ public:
|
||||
bool exec(const char* sqlQuery);
|
||||
bool exec(const std::string& sqlQuery);
|
||||
|
||||
/// returns true if the sql statment returns at least one row
|
||||
std::optional<int64_t> getInt(const char* sql);
|
||||
|
||||
std::optional<int64_t> insert(const char* sql);
|
||||
|
||||
std::set<std::string> getStrSet(const std::string& sql);
|
||||
|
||||
std::string getStr(const std::string sql, const QueryData& data);
|
||||
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);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user