Allow specifying --query multiple times in the command line

This commit is contained in:
Ziy1-Tan 2023-05-31 00:17:03 +08:00 committed by Robert Schulze
parent 64f8d7bc85
commit 5db1961129
No known key found for this signature in database
GPG Key ID: 26703B55FB13728A
7 changed files with 52 additions and 14 deletions

View File

@ -30,7 +30,7 @@ It may lack support for new features.
## Usage {#cli_usage}
The client can be used in interactive and non-interactive (batch) mode.
The client can be used in interactive and non-interactive (batch) mode.
### Gather your connection details
<ConnectionDetails />
@ -177,7 +177,7 @@ You can pass parameters to `clickhouse-client` (all parameters have a default va
- `--user, -u` The username. Default value: default.
- `--password` The password. Default value: empty string.
- `--ask-password` - Prompt the user to enter a password.
- `--query, -q` The query to process when using non-interactive mode. Cannot be used simultaneously with `--queries-file`.
- `--query, -q` The query to process when using non-interactive mode. Specifying `--query` multiple times are allowed(`--query "SELECT 1;" --query "SELECT 2;"...`). Cannot be used simultaneously with `--queries-file`.
- `--queries-file` file path with queries to execute. Cannot be used simultaneously with `--query`.
- `--multiquery, -n` If specified, multiple queries separated by semicolons can be listed after the `--query` option. For convenience, it is also possible to omit `--query` and pass the queries directly after `--multiquery`.
- `--multiline, -m` If specified, allow multiline queries (do not send the query on Enter).

View File

@ -128,7 +128,7 @@ $ clickhouse-client --param_tbl="numbers" --param_db="system" --param_col="numbe
- `--port` — порт для подключения, по умолчанию — 9000. Обратите внимание: для HTTP-интерфейса и нативного интерфейса используются разные порты.
- `--user, -u` — имя пользователя, по умолчанию — default.
- `--password` — пароль, по умолчанию — пустая строка.
- `--query, -q` — запрос для выполнения, при использовании в неинтерактивном режиме.
- `--query, -q` — запрос для выполнения, при использовании в неинтерактивном режиме. Допускается указание `--query` несколько раз (`--query "SELECT 1;" --query "SELECT 2;"...`).
- `--queries-file` - путь к файлу с запросами для выполнения. Необходимо указать только одну из опций: `query` или `queries-file`.
- `--database, -d` — выбрать текущую БД. Без указания значение берется из настроек сервера (по умолчанию — БД default).
- `--multiline, -m` — если указано — разрешить многострочные запросы, не отправлять запрос по нажатию Enter.

View File

@ -116,7 +116,7 @@ $ clickhouse-client --param_tuple_in_tuple="(10, ('dt', 10))" -q "SELECT * FROM
- `--port` 连接的端口默认值9000。注意HTTP接口以及TCP原生接口使用的是不同端口。
- `--user, -u` 用户名。 默认值:`default`。
- `--password` 密码。 默认值:空字符串。
- `--query, -q` 使用非交互模式查询。
- `--query, -q` 使用非交互模式查询。 允许多次指定 `--query``--query "SELECT 1;" --query "SELECT 2;"...`)。
- `--database, -d` 默认当前操作的数据库. 默认值:服务端默认的配置(默认是`default`)。
- `--multiline, -m` 如果指定允许多行语句查询Enter仅代表换行不代表查询语句完结
- `--multiquery, -n` 如果指定, 允许处理用`;`号分隔的多个查询,只在非交互模式下生效。

View File

@ -2484,23 +2484,23 @@ void ClientBase::runNonInteractive()
return;
}
String text;
if (config().has("query"))
if (!queries.empty())
{
text += config().getRawString("query"); /// Poco configuration should not process substitutions in form of ${...} inside query.
for (const auto & query : queries)
{
bool result = query_fuzzer_runs ? processWithFuzzing(query) : processQueryText(query);
if (!result)
return;
}
}
else
{
/// If 'query' parameter is not set, read a query from stdin.
/// The query is read entirely into memory (streaming is disabled).
ReadBufferFromFileDescriptor in(STDIN_FILENO);
String text;
readStringUntilEOF(text, in);
}
if (query_fuzzer_runs)
processWithFuzzing(text);
else
processQueryText(text);
}
@ -2700,7 +2700,7 @@ void ClientBase::init(int argc, char ** argv)
("config-file,C", po::value<std::string>(), "config-file path")
("query,q", po::value<std::string>(), "query")
("query,q", po::value<std::vector<std::string>>(), R"(query; specifying --query multiple times are allowed(--query "SELECT 1;" --query "SELECT 2;"...))")
("queries-file", po::value<std::vector<std::string>>()->multitoken(),
"file path with queries to execute; multiple files can be specified (--queries-file file1 file2...)")
("multiquery,n", "If specified, multiple queries separated by semicolons can be listed after --query. For convenience, it is also possible to omit --query and pass the queries directly after --multiquery.")
@ -2789,7 +2789,7 @@ void ClientBase::init(int argc, char ** argv)
if (options.count("time"))
print_time_to_stderr = true;
if (options.count("query"))
config().setString("query", options["query"].as<std::string>());
queries = options["query"].as<std::vector<std::string>>();
if (options.count("query_id"))
config().setString("query_id", options["query_id"].as<std::string>());
if (options.count("database"))

View File

@ -202,6 +202,7 @@ protected:
std::optional<Suggest> suggest;
bool load_suggestions = false;
std::vector<String> queries; /// If not empty, queries will be read from these strings
std::vector<String> queries_files; /// If not empty, queries will be read from these files
std::vector<String> interleave_queries_files; /// If not empty, run queries from these files before processing every file from 'queries_files'.
std::vector<String> cmd_options;

View File

@ -0,0 +1,13 @@
101
202
303
404
404
404
505
Syntax error
Syntax error
Empty query
Empty query
BAD_ARGUMENTS
Bad arguments

View File

@ -0,0 +1,24 @@
#!/usr/bin/env bash
CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh
$CLICKHOUSE_LOCAL --query "SELECT 101"
$CLICKHOUSE_LOCAL --query "SELECT 202" --query "SELECT 303"
$CLICKHOUSE_LOCAL --query "SELECT 404" --query "SELECT 404" --query "SELECT 404"
$CLICKHOUSE_LOCAL --query --query 2>&1
$CLICKHOUSE_LOCAL --query "" --query "" 2>&1
$CLICKHOUSE_LOCAL --query "SELECT 505;"--query
# Abort if any invalid SQL
$CLICKHOUSE_LOCAL --query "SELECT 606; S" --query "SELECT 606" 2>&1 | grep -o 'Syntax error'
$CLICKHOUSE_LOCAL --query "SELECT 707" --query "SELECT 808; S" 2>&1 | grep -o '201'
$CLICKHOUSE_LOCAL --query "SELECT 909" --query "SELECT 909; S" 2>&1 | grep -o 'Syntax error'
$CLICKHOUSE_LOCAL --query "; SELECT 111;" --query "SELECT 111;" 2>&1 | grep -o 'Empty query'
$CLICKHOUSE_LOCAL --query "SELECT 222;" --query "; SELECT 222;" 2>&1 | grep -o '201'
$CLICKHOUSE_LOCAL --query "SELECT 333;" --query "; SELECT 333;" 2>&1 | grep -o 'Empty query'
$CLICKHOUSE_LOCAL --query --query "SELECT 444;" 2>&1 | grep -o 'BAD_ARGUMENTS'
$CLICKHOUSE_LOCAL --query "SELECT 555;" --query 2>&1 | grep -o 'Bad arguments'