#include "helpers.h"

#include "exit_codes.h"

#include <maps/libs/common/include/profiletimer.h>
#include <maps/libs/log8/include/log8.h>

#include <exception>
#include <utility>

namespace maps {
namespace wiki {
namespace ymapsdf_splitter {

std::string printQuery(const std::string& description, const std::string& query)
{
    return
        description + "\n"
        "-8<-----------------------------------------------------------------------------\n"
        + query + (query.back() == '\n' ? "" : "\n") +
        "----------------------------------------------------------------------------->8-";
}


pqxx::result exec(const std::string& connStr, const std::string& query, bool dryRun, const std::string& name)
try {
    std::string printedName = name.size() ? name + " " : "";

    DEBUG() << printQuery(printedName + "query:", query);

    pqxx::result result;

    if (!dryRun) {
        pqxx::connection conn{connStr};
        pqxx::work txn{conn};
        ProfileTimer execTimer;
        result = std::move(txn.exec(query));
        txn.commit();
        DEBUG() << printedName << "execution time: " << execTimer << " s";
    }

    return result;
}
catch (const pqxx::broken_connection& e) {
    FATAL() << e.what();
    exit(EXITCODE_POSTGRESQL_BROKEN_CONNECTION);
}

} // namespace ymapsdf_splitter
} // namespace wiki
} // namespace maps
