#include <sqlite3.h>
#include <iostream>
#include <cstring>
#include <filesystem>
#include <stdexcept>
#include "sqliteinterface.hpp"
#include "video.hpp"
namespace fs = std::filesystem;
using namespace std;
void SqliteInterface::openDB()
{
fs::path appdata = DEF_APPDATA;
if (!fs::exists(appdata))
{
error_code ec;
fs::create_directories(appdata, ec);
if (ec.value() != 0)
{
char errmsg[] = "Can't create folder: ";
strcat(errmsg, ec.message().c_str());
throw runtime_error(errmsg);
}
}
fs::path filename = appdata / "ytcpp.db";
int rc = sqlite3_open(filename.c_str(), &db);
if (rc)
{
char errmsg[] = "Can't open database: ";
strcat(errmsg, sqlite3_errmsg(db));
throw runtime_error(errmsg);
}
}
void SqliteInterface::closeDB()
{
sqlite3_close(db);
db = nullptr;
}
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
void SqliteInterface::createTables() {
char *errmsg = 0;
int rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS INSTANCES (url TEXT PRIMARY KEY, health FLOAT, location TEXT);", callback, 0, &errmsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmsg);
sqlite3_free(errmsg);
}
}
void SqliteInterface::saveInstance(const string& uri, float health, const string& location) {
char *errmsg = 0;
int rc = sqlite3_exec(db, sqlite3_mprintf("INSERT INTO INSTANCES (%Q, %F.2, %Q)", uri, health, location), callback, 0, &errmsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmsg);
sqlite3_free(errmsg);
}
}
void SqliteInterface::saveVideo(const Video::video& vid) {
}
SqliteInterface::SqliteInterface() {
openDB();
createTables();
}
SqliteInterface::~SqliteInterface() {
closeDB();
}