123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- #include "utils.h"
- #include <fmt/core.h>
- #include <algorithm>
- #include <fstream>
- #include <map>
- #include <nlohmann/json.hpp>
- #include <string>
- #include <vector>
- using json = nlohmann::json;
- SQLParserRes parse_sql(const std::string& sql) {
- SQLParserRes res;
- // auto stdout_name = std::tmpnam(nullptr);
- // auto stderr_name = std::tmpnam(nullptr);
- auto stdout_name = "/tmp/sql-parser-stdout";
- auto stderr_name = "/tmp/sql-parser-stderr";
- auto cmd = fmt::format("xmake run sql-parser \"{}\" > {} 2> {}", sql,
- stdout_name, stderr_name);
- res.exit_code = system(cmd.c_str());
- std::ifstream stdout_f(stdout_name);
- json stdout_j = json::parse(stdout_f);
- res.out = stdout_j;
- std::ifstream stderr_f(stderr_name);
- res.err.assign((std::istreambuf_iterator<char>(stderr_f)),
- (std::istreambuf_iterator<char>()));
- return res;
- }
- ExistTables::ExistTables(const char* file_name) {
- table_file_name = file_name;
- std::ifstream ifile(table_file_name);
- if (!ifile.good()) {
- std::ofstream ofile(table_file_name);
- ofile << "{}";
- ofile.close();
- }
- ifile.close();
- read_from_file();
- }
- ExistTables* ExistTables::read_from_file() {
- std::ifstream f(table_file_name);
- json j = json::parse(f);
- for (auto& item : j.items()) {
- tables[item.key()] = item.value();
- }
- return this;
- };
- bool ExistTables::exists(const std::string& table_name) {
- return tables.find(table_name) != tables.end();
- }
- void ExistTables::set(const std::string& table_name, const TableCols& cols) {
- tables[table_name] = cols;
- }
- TableCols ExistTables::operator[](const std::string& table_name) {
- return this->get(table_name);
- }
- TableCols ExistTables::operator[](const std::vector<std::string>& table_names) {
- return this->get(table_names);
- }
- TableCols ExistTables::get(const std::string& table_name) {
- return tables[table_name];
- }
- TableCols ExistTables::get(const std::vector<std::string>& table_names) {
- TableCols res = {};
- for (let table_name : table_names) {
- let cols = this->get(table_name);
- res.assign(cols.begin(), cols.end());
- }
- return res;
- }
- optional<TableCol> ExistTables::find_col_in_tables(
- const std::vector<std::string>& table_names,
- const std::string col_name) {
- for (let table_name : table_names) {
- let cols = this->get(table_name);
- for(let col : cols) {
- if (col.column_name == col_name) {
- return col;
- }
- }
- }
- return nullopt;
- }
- void ExistTables::remove(const std::string& table_name) {
- tables.erase(table_name);
- }
- void ExistTables::save() {
- json j;
- for (auto& item : tables) {
- j[item.first] = item.second;
- }
- std::ofstream f(table_file_name);
- f << j.dump(2);
- }
|