#include "postgresHandler.h" #include #include #include #define INT_INDEX 2 #define STRING_INDEX 3 #define LIST_OF_INT_INDEX 4 #define NULL_INDEX 5 const pqxx::result execute_query(pqxx::work &t_transaction, std::string_view t_query) { return t_transaction.exec(t_query); } void display_query_result(const pqxx::result &t_r) { const int nb_columns = t_r.columns(); for (const auto &row : t_r) { for (int i = 0; i < nb_columns; i++) { std::cout << row[i].c_str() << " | "; } std::cout << std::endl; } } static const unsigned int get_type_of_regex_iterator(const std::sregex_iterator &t_sregex_it) { std::array types{INT_INDEX, STRING_INDEX, LIST_OF_INT_INDEX, NULL_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 INT_INDEX: case STRING_INDEX: return t_json_value; case NULL_INDEX: return "NULL"; case LIST_OF_INT_INDEX: { std::string json_copy = t_json_value; *json_copy.begin() = '('; *std::prev(json_copy.end()) = ')'; return json_copy; } default: throw std::invalid_argument("type index is invalid: "); } } void add_cards_to_database(const std::string &t_cards, pqxx::work &t_tx) { // TODO: to complete std::regex key_regex( "\"[^\"?]+\":(([0-9]+)|(\"[^\"?]*\")|(\\[[0-9,]*\\])|(null))"); auto words_begin = std::sregex_iterator(t_cards.begin(), t_cards.end(), key_regex); auto words_end = std::sregex_iterator(); if (words_begin != words_end) { std::string insert_query("INSERT INTO cards (id, collectible, slug, " "class_id, multi_class_ids, " "card_type_id, card_set_id, rarity_id, " "artist_name, health, attack, " "mana_cost, name, text, image, image_gold, " "flavor_text, crop_image, " "keyword_ids, is_zilliax_functional_module, " "is_zilliax_cosmetic_module) VALUES ("); // std::prev(words_end) before for (auto it = words_begin; it != words_end; ++it) { const unsigned int type_index = get_type_of_regex_iterator(it); // TODO: format info depending on type_index then add it to // insert_query insert_query.append( format_json_value_to_sql(type_index, (*it)[type_index].str()) + ", "); } *std::prev(insert_query.end()) = ';'; *std::prev(insert_query.end(), 2) = ')'; std::cout << insert_query << std::endl; execute_query(t_tx, insert_query); } }