new db interface
This commit is contained in:
@@ -1,65 +1,25 @@
|
||||
#include <format>
|
||||
#include "database.hpp"
|
||||
#include "databasepool.h"
|
||||
#include "crow.h"
|
||||
#include "sqlite_orm.h"
|
||||
|
||||
using namespace std;
|
||||
using namespace sqlite_orm;
|
||||
|
||||
namespace shadowrun {
|
||||
|
||||
bool initDb() {
|
||||
auto db = Database();
|
||||
|
||||
if (!db.open()){
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create a tables
|
||||
const char* create_sql_chars = "CREATE TABLE IF NOT EXISTS shadowrun_characters ("
|
||||
"id INTEGER PRIMARY KEY,"
|
||||
"name TEXT NOT NULL,"
|
||||
"created_at DATETIME DEFAULT CURRENT_TIMESTAMP);";
|
||||
|
||||
if (!db.exec(create_sql_chars)){
|
||||
CROW_LOG_ERROR << "Failed to create shadowrun_characters table";
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* create_sql_data = "CREATE TABLE IF NOT EXISTS shadowrun_data ("
|
||||
"id INTEGER PRIMARY KEY,"
|
||||
"character_id INTEGER NOT NULL,"
|
||||
"name TEXT NOT NULL,"
|
||||
"value TEXT,"
|
||||
"created_at DATETIME DEFAULT CURRENT_TIMESTAMP,"
|
||||
"updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,"
|
||||
"FOREIGN KEY (character_id) REFERENCES shadowrun_characters(id) ON DELETE CASCADE);";
|
||||
|
||||
if (!db.exec(create_sql_data)){
|
||||
CROW_LOG_ERROR << "Failed to create shadowrun_data table";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int64_t getKeyOfCharacter(const string& name){
|
||||
std::string sql = "SELECT id FROM shadowrun_characters WHERE name = ? LIMIT 1;";
|
||||
auto db = Database();
|
||||
|
||||
if (!db.open())
|
||||
return -1;
|
||||
auto db = dbpool.acquire();
|
||||
|
||||
auto opt_int = db.get<int>(sql, {name});
|
||||
if (opt_int.has_value()) {
|
||||
return opt_int.value();
|
||||
auto character = db->get_all<ShadowrunCharacter>(
|
||||
where(c(&ShadowrunCharacter::name) == name),
|
||||
limit(1)
|
||||
);
|
||||
|
||||
if (!character.empty()) {
|
||||
return character[0].id;
|
||||
} else {
|
||||
sql = format("INSERT INTO shadowrun_characters (name) VALUES ('{}');", name);
|
||||
auto key = db.insert(sql.c_str());
|
||||
|
||||
if(key.has_value()){
|
||||
return key.value();
|
||||
} else {
|
||||
CROW_LOG_ERROR << "Failed to insert character " << name;
|
||||
return -1;
|
||||
}
|
||||
return db->insert(ShadowrunCharacter{-1, name, ""});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user