#include "postgresHandler.h" #include #include #include #define KEY_INDEX 1 #define INT_INDEX 3 #define STRING_INDEX 4 #define LIST_OF_INT_INDEX 5 #define NULL_INDEX 6 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: 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: { if (t_json_value.size() == 2) { return "NULL"; } 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: "); } } std::string format_key(const std::string &key) { // FIXME: add _ before an uppercase char, and set all chars to lowercase // ones return key; } 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) { // FIXME: add parent_id:int and copy_of_card_id:list_of_ints columns 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()) + ","); } // TODO: may be modified *std::prev(insert_columns.end()) = ')'; *std::prev(values.end()) = ')'; values.append(";"); execute_query(t_tx, insert_columns + values); } }