about summary refs log tree commit diff stats
path: root/src/sqliteinterface.cpp
blob: c34576b9f463b47ff60fd5bc46b25aae87ba568f (plain) (blame)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#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();
}