summaryrefslogtreecommitdiff
path: root/src/postgresHandler.cpp
blob: 662a6a34b54d8b4d9c716ad66f1bed8547e3166b (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#include "postgresHandler.h"
#include "hearthstoneAPIHandler.h"
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <regex>
#include <stdexcept>

#define KEY_INDEX 1
#define INT_INDEX 3
#define STRING_INDEX 4
#define LIST_OF_INT_INDEX 5
#define NULL_INDEX 6
#define BOOL_INDEX 7

const pqxx::result execute_query(pqxx::work &t_transaction,
                                 std::string_view t_query) {
    return t_transaction.exec(t_query);
}

std::ostream &operator<<(std::ostream &t_ostream, const pqxx::result &t_r) {
    const int nb_columns = t_r.columns();
    t_ostream << "| ";
    for (const auto &row : t_r) {
        for (int i = 0; i < nb_columns; i++) {
            t_ostream << row[i].c_str() << " | ";
        }
    }
    return t_ostream;
}

static const unsigned int
get_type_of_regex_iterator(const std::sregex_iterator &t_sregex_it) {
    std::array<int, 5> types{INT_INDEX, STRING_INDEX, LIST_OF_INT_INDEX,
                             NULL_INDEX, BOOL_INDEX};
    for (const int &type : types) {
        if ((*t_sregex_it)[type] != "") {
            return type;
        }
    }
    throw std::invalid_argument("regex iterator input is invalid");
}

const std::string format_json_value_to_sql(const unsigned int &t_type_index,
                                           const std::string &t_json_value) {
    switch (t_type_index) {
    case BOOL_INDEX:
    case INT_INDEX:
        return t_json_value;
    case STRING_INDEX: {
        std::string json_copy = t_json_value;
        *json_copy.begin() = '\'';
        *std::prev(json_copy.end()) = '\'';
        return json_copy;
    }
    case NULL_INDEX:
        return "NULL";
    case LIST_OF_INT_INDEX: {
        std::string json_copy = t_json_value;
        json_copy.append("\'");
        json_copy.insert(json_copy.begin(), '\'');
        return json_copy;
    }
    default:
        throw std::invalid_argument("type index is invalid: ");
    }
}

std::string format_key(const std::string &key) {
    std::string key_copy(key);
    std::stack<size_t> uppercase_indexes;
    for (size_t i = 0; i < key.length(); i++) {
        if (std::isupper(key[i])) {
            uppercase_indexes.push(i);
        }
    }
    while (!uppercase_indexes.empty()) {
        size_t top_index = uppercase_indexes.top();
        uppercase_indexes.pop();
        key_copy[top_index] = std::tolower(key_copy[top_index]);
        key_copy.insert(std::next(key_copy.begin(), top_index), '_');
    }
    return key_copy;
}

static void
add_single_card_to_database(const std::string &t_cards, pqxx::work &t_tx,
                            const std::regex &key_regex,
                            const std::string::size_type &id_pos,
                            const std::string::size_type &closing_bracket_pos) {
    auto words_begin = std::sregex_iterator(
        std::next(t_cards.begin(), id_pos),
        std::next(t_cards.begin(), closing_bracket_pos), key_regex);
    auto words_end = std::sregex_iterator();
    if (words_begin != words_end) {
        std::string insert_columns("INSERT INTO cards (");
        std::string values(" VALUES (");
        for (auto it = words_begin; it != words_end; ++it) {
            insert_columns.append(format_key((*it)[KEY_INDEX].str()) +
                                  ","); // key
            const unsigned int type_index = get_type_of_regex_iterator(it);
            values.append(
                format_json_value_to_sql(type_index, (*it)[type_index].str()) +
                ",");
        }
        *std::prev(insert_columns.end()) = ')';
        *std::prev(values.end()) = ')';

        insert_columns.append(values);
        insert_columns.append(" ON CONFLICT (id) DO NOTHING;");
        execute_query(t_tx, insert_columns);
    }
}

void add_cards_to_database(const std::string &t_cards, pqxx::work &t_tx) {
    std::regex key_regex("\"([^\"?]+)\":(([0-9]+)|(\"[^\"?]*\")|(\\[[0-9,]*\\])"
                         "|(null)|(true|false))");

    std::string::size_type id_pos = t_cards.find("{\"id");
    std::string::size_type closing_bracket_pos = t_cards.find("}");
    while (id_pos != std::string::npos &&
           closing_bracket_pos != std::string::npos) {
        add_single_card_to_database(t_cards, t_tx, key_regex, id_pos,
                                    closing_bracket_pos);
        id_pos = t_cards.find("{\"id", id_pos + 1);
        closing_bracket_pos = t_cards.find("}", closing_bracket_pos + 1);
    }
}

void refresh_cards_table() {
    HearthstoneAPIHandler hs_handler;
    pqxx::connection cx{
        "postgresql://aotrix@localhost:5432/hearthstonegameinfo"};
    pqxx::work tx{cx};

    try {
        execute_query(tx, "DELETE FROM cards");
        std::regex key_regex("\"pageCount\":([0-9]+)");
        std::string cards =
            hs_handler.get_cards("/?locale=fr_FR&gameMode=constructed");
        add_cards_to_database(cards, tx);
        auto nb_pages_begin =
            std::sregex_iterator(cards.begin(), cards.end(), key_regex);
        auto nb_pages_end = std::sregex_iterator();
        if (nb_pages_begin != nb_pages_end) {
            uint32_t nb_pages = std::stoi((*nb_pages_begin)[1].str());
            std::cout << "number of pages: " << nb_pages << std::endl;
            // FIXME: [Process exited 139]
            // for (int i = 2; i < nb_pages; i++) {
            for (uint32_t i = 2; i < 3; i++) {
                cards = hs_handler.get_cards(std::format(
                    "/?locale=fr_FR&gameMode=constructed&page={}", i));
                add_cards_to_database(cards, tx);
            }
        }
        std::cout << "number of cards in database: "
                  << execute_query(tx, "SELECT COUNT(*) FROM cards")
                  << std::endl;
        tx.commit();
    } catch (pqxx::sql_error const &e) {
        std::cerr << "SQL error: " << e.what() << std::endl;
        std::cerr << "Query was: " << e.query() << std::endl;
    } catch (std::exception const &e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}