src/CLIParser.h
author František Kučera <franta-hg@frantovo.cz>
Mon, 29 Jul 2019 19:49:12 +0200
branchv_0
changeset 2 362f2689cb87
parent 0 c205f5d06418
child 5 cbc7817a3346
permissions -rw-r--r--
configuration and CLI parser

/**
 * Relational pipes
 * Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once

#include <vector>

#include <relpipe/writer/typedefs.h>
#include <relpipe/cli/CLI.h>
#include <relpipe/cli/RelpipeCLIException.h>

#include "Configuration.h"

namespace relpipe {
namespace tr {
namespace sql {

class CLIParser {
private:

	// FIXME: move common methods/classes to relpipe-lib-cli or relpipe-lib-helper

	string_t readNext(std::vector<string_t> arguments, int& i) {
		if (i < arguments.size()) return arguments[i++];
		else throw relpipe::cli::RelpipeCLIException(L"Missing CLI argument" + (i > 0 ? (L" after " + arguments[i - 1]) : L""), relpipe::cli::CLI::EXIT_CODE_BAD_CLI_ARGUMENTS);
	}

	void addQuery(Configuration& c, Statement& currentQuery) {
		if (currentQuery.sql.size()) {
			c.statements.push_back(currentQuery);
			currentQuery = Statement();
		}
	}

public:

	static const string_t OPTION_RELATION;
	static const string_t OPTION_PARAMETER;

	Configuration parse(const std::vector<string_t>& arguments) {
		Configuration c;
		Statement currentQuery;

		for (int i = 0; i < arguments.size();) {
			string_t option = readNext(arguments, i);

			if (option == OPTION_RELATION) {
				addQuery(c, currentQuery); // previous relation
				currentQuery.relation = readNext(arguments, i);
				currentQuery.sql = readNext(arguments, i);
			} else if (option == OPTION_PARAMETER) {
				Parameter parameter;
				parameter.value = readNext(arguments, i);
				currentQuery.parameters.push_back(parameter);
			} else throw relpipe::cli::RelpipeCLIException(L"Unsupported CLI option: " + option, relpipe::cli::CLI::EXIT_CODE_BAD_CLI_ARGUMENTS);
		}
		addQuery(c, currentQuery); // last relation

		return c;
	}

	virtual ~CLIParser() {
	}
};


// relpipe-tr-sql --relation "tabulka" "SELECT * FROM fstab WHERE id = ?" --parameter "123"
// TODO: --file db.sqlite --keep-file
// TODO: --type string/integer/boolean (default is string)

const string_t CLIParser::OPTION_RELATION = L"--relation";
const string_t CLIParser::OPTION_PARAMETER = L"--parameter";

}
}
}