Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added connection string to clickhouse-client #50689

Merged
merged 16 commits into from
Jun 14, 2023
Merged
134 changes: 133 additions & 1 deletion docs/en/interfaces/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,139 @@ You can pass parameters to `clickhouse-client` (all parameters have a default va
- `--print-profile-events` – Print `ProfileEvents` packets.
- `--profile-events-delay-ms` – Delay between printing `ProfileEvents` packets (-1 - print only totals, 0 - print every single packet).

Since version 20.5, `clickhouse-client` has automatic syntax highlighting (always enabled).
Instead of --host, --port, --user and --password options, ClickHouse client also supports connection strings.
Demilivor marked this conversation as resolved.
Show resolved Hide resolved


## Connection string {#connection_string}

clickhouse-client alternatively supports connecting to clickhouse server using a connection string similar to [MongoDB](https://www.mongodb.com/docs/manual/reference/connection-string/), [PostgreSQL](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING), [MySQL](https://dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html#connecting-using-uri). It has the following syntax:

```text
clickhouse:[//[user[:password]@][hosts_and_ports]][/database][?query_parameters]
```

Where

- `user` - (optional) is a user name,
- `password` - (optional) is a user password. If `:` is specified and the password is blank, the client will prompt for the user's password.
- `hosts_and_ports` - (optional) is a list of hosts and optional ports `host[:port] [, host:[port]], ...`,
- `database` - (optional) is the database name,
- `query_parameters` - (optional) is a list of key-value pairs `param1=value1[,&param2=value2], ...`. For some parameters, no value is required. Parameter names and values are case-sensitive.



The host component can either be an IP address or a host name. Put an IPv6 address in square brackets to specify it:
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

```text
clickhouse://[2001:db8::1234]
```

If user is not specified, `default` user without password will be used.
Demilivor marked this conversation as resolved.
Show resolved Hide resolved
If host is not specified, the `localhost` will be used (localhost).
If port is not specified, `9000` will be used as port.
If database is not specified, the `default` database will be used.

If the user name, password or database was specified in the connection string, it cannot be specified using `--user`, `--password` or `--database` (and vice versa).

The connection string must be specified in the first argument of clickhouse-client. The connection string can be combined with other [command-line-options](#command-line-options) except `--host(h)` and `--port`.
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

### Multiple hosts {#connection_string_multiple_hosts}

URI allows multiple hosts to be connected to. Connection strings can contain multiple hosts. ClickHouse-client will try to connect to these hosts in order (i.e. from left to right). After the connection is established, no attempt to connect to the remaining hosts is made.
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

### Allowed query_parameters keys {#connection_string_query_parameters}
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

- `secure` or shorthanded `s` - no value. If specified, client will connect to the server over a secure connection (TLS). See `secure` in [command-line-options](#command-line-options)

### Percent encoding {#connection_string_uri_percent_encoding}

Non-US ASCII, spaces and special characters in the `user`, `password`, `hosts`, `database` and `query parameters` must be [percent-encoded](https://en.wikipedia.org/wiki/URL_encoding).

### Examples {#connection_string_examples}

Connect to localhost using port 9000 and execute the query "SELECT 1".
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

``` bash
clickhouse-client clickhouse://localhost:9000 --query "SELECT 1"
```

Connect to localhost using user `john` with password `secret`, host `127.0.0.1` and port `9000`

``` bash
clickhouse-client clickhouse://john:secret@127.0.0.1:9000
```

Connect to localhost using default user, host with IPV6 address `[::1]` and port `9000`.

``` bash
clickhouse-client clickhouse://[::1]:9000
```

Connect to localhost using default user, host with IPV6 address `[2001:db8:3333:4444:5555:6666:7777:8888]` and port `9000`.
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

``` bash
clickhouse-client clickhouse://[2001:db8:3333:4444:5555:6666:7777:8888]:9000
```

Connect to localhost using port 9000 in multiline mode.

``` bash
clickhouse-client clickhouse://localhost:9000 '-m'
```

Connect to localhost using port 9000 with the user `default`.

``` bash
clickhouse-client clickhouse://default@localhost:9000 --user default
Demilivor marked this conversation as resolved.
Show resolved Hide resolved

# equivalent to:
clickhouse-client clickhouse://localhost:9000 --user default
```

Connect to localhost using port 9000 to `my_database` database.

``` bash
clickhouse-client clickhouse://localhost:9000/my_database

# equivalent to:
clickhouse-client clickhouse://localhost:9000 --database my_database
```

Connect to localhost using port 9000 to `my_database` database specified in the connection string and a secure connection using shorthanded 's' URI parameter.

```bash
clickhouse-client clickhouse://localhost/my_database?s

# equivalent to:
clickhouse-client clickhouse://localhost/my_database -s
```

Connect to default host using default port, default user, and default database.

``` bash
clickhouse-client clickhouse:
```

Demilivor marked this conversation as resolved.
Show resolved Hide resolved
Connect to the default host using the default port, using user `my_user` and no password.

``` bash
clickhouse-client clickhouse://my_user@

# Using a blank password between : and @ means to asking user to enter the password before starting the connection.
clickhouse-client clickhouse://my_user:@
```

Connect to localhost using email as the user name. `@` symbol is percent encoded to `%40`.

``` bash
clickhouse-client clickhouse://some_user%40some_mail.com@localhost:9000
```

Connect to one of provides hosts: `192.168.1.15`, `192.168.1.25`.

``` bash
clickhouse-client clickhouse://192.168.1.15,192.168.1.25
```

### Configuration Files {#configuration_files}

Expand Down
128 changes: 127 additions & 1 deletion docs/ru/interfaces/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,133 @@ $ clickhouse-client --param_tbl="numbers" --param_db="system" --param_col="numbe
- `--history_file` - путь к файлу с историей команд.
- `--param_<name>` — значение параметра для [запроса с параметрами](#cli-queries-with-parameters).

Начиная с версии 20.5, в `clickhouse-client` есть автоматическая подсветка синтаксиса (включена всегда).
## Строка подключения {#connection_string}

clickhouse-client также поддерживает подключение к серверу clickhouse с помощью строки подключения, аналогичной [MongoDB](https://www.mongodb.com/docs/manual/reference/connection-string/), [PostgreSQL](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING), [MySQL](https://dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html#connecting-using-uri). Она имеет следующий синтаксис:

```text
clickhouse:[//[user[:password]@][hosts_and_ports]][/database][?query_parameters]
```

Где

- `user` - (необязательно) - это имя пользователя,
- `password` - (необязательно) - Пароль пользователя. Если символ `:` укаказан, и пароль пуст, то клиент запросит ввести пользователя пароль.
- `hostspec` - (необязательно) - список хостов и необязательных портов. `host[:port] [, host:[port]], ...`,
- `database` - (необязательно) - это имя базы данных,
- `paramspec` - (опционально) список пар ключ-значение `param1=value1[,&param2=value2], ...`. Для некоторых параметров значение не требуется. Имена и значения параметров чувствительны к регистру.

Параметр host может быть либо IP-адресом, либо именем хоста. Для указания IPv6-адреса поместите его в квадратные скобки:

```text
clickhouse://[2001:db8::1234]
```

Если user не указан, будут использоваться имя пользователя `default`.
Если host не указан, будет использован хост `localhost`.
Если port не указан, будет использоваться порт `9000`.
Если база данных не указана, будет использоваться база данных `default`.

Если имя пользователя, пароль или база данных были указаны в строке подключения, их нельзя указать с помощью `--user`, `--password` или `--database` (и наоборот).

Строка подключения должна быть указана в первом аргументе clickhouse-client. Строка подключения может комбинироваться с другими [параметрами командной строки] (#command-line-options) кроме `--host (h)` и `--port`.

### Несколько хостов {#connection_string_multiple_hosts}

URI позволяет подключаться к нескольким хостам. Строки подключения могут содержать несколько хостов. ClickHouse-client будет пытаться подключиться к этим хостам по порядку (т.е. слева направо). После установления соединения попытки подключения к оставшимся хостам не предпринимаются.

### Допустимые ключи query_parameters {#connection_string_query_parameters}

- `secure` или сокращенно `s` - без значение. Если параметр указан, то соединение с сервером будет осуществляться по защищенному каналу (TLS). См. `secure` в [command-line-options](#command-line-options).

### Кодирование URI {#connection_string_uri_percent_encoding}

Не US ASCII и специальные символы в имени пользователя, пароле, хостах, базе данных и параметрах запроса должны быть [закодированы](https://ru.wikipedia.org/wiki/URL#%D0%9A%D0%BE%D0%B4%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_URL).

### Примеры {#connection_string_examples}

Подключиться к localhost через порт 9000 и выполнить запрос "SELECT 1"

``` bash
clickhouse-client clickhouse://localhost:9000 --query "SELECT 1"
```
Подключиться к localhost, используя пользователя `john` с паролем `secret`, хост `127.0.0.1` и порт `9000`

``bash
clickhouse-client clickhouse://john:secret@127.0.0.1:9000
```

Подключиться к localhost, используя пользователя по умолчанию, хост с IPV6 адресом `[::1]` и порт `9000`.

``` bash
clickhouse-client clickhouse://[::1]:9000
```

Подключиться к localhost, используя пользователя по умолчанию, хост с IPV6 адресом `[2001:db8:3333:4444:5555:6666:7777:8888]` и портом `9000`.

`` bash
clickhouse-client clickhouse://[2001:db8:3333:4444:5555:6666:7777:8888]:9000
```

Подключиться к localhost через порт 9000 многострочном режиме.

``` bash
clickhouse-client clickhouse://localhost:9000 '-m'
```

Подключиться к localhost через порт 9000 с пользователем default.

``` bash
clickhouse-client clickhouse://default@localhost:9000

# Эквивалетно:
clickhouse-client clickhouse://localhost:9000 --user default
```

Подключиться к localhost через порт 9000 с базой данных `my_database`

``` bash
clickhouse-client clickhouse://localhost:9000/my_database

# Эквивалетно:
clickhouse-client clickhouse://localhost:9000 --database my_database
```

Подключиться к localhost через порт 9000 с базой данных `my_database`, указанной в строке подключения, используя безопасным соединением при помощи короткого варианта параметра URI 's'.

``` bash
clickhouse-client clickhouse://localhost/my_database?s

# Эквивалетно:
clickhouse-client clickhouse://localhost/my_database -s
```

Подключиться к хосту по умолчанию с использованием порта по умолчанию, пользователя по умолчанию, и базы данных по умолчанию.

``` bash
clickhouse-client clickhouse:
```

Подключиться к хосту по умолчанию через порт по умолчанию, используя имя пользователя `my_user` без пароля.

``` bash
clickhouse-client clickhouse://my_user@

# Использование пустого пароля между : и @ означает, что пользователь должен ввести пароль перед началом соединения.
clickhouse-client clickhouse://my_user:@
```

Подключиться к localhost, используя электронную почту, как имя пользователя. Символ `@` закодирован как `%40`.

``` bash
clickhouse-client clickhouse://some_user%40some_mail.com@localhost:9000
```

Подключится к одному из хостов: `192.168.1.15`, `192.168.1.25`.

``` bash
clickhouse-client clickhouse://192.168.1.15,192.168.1.25
```

### Конфигурационные файлы {#configuration_files}

Expand Down
10 changes: 8 additions & 2 deletions programs/client/Client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
#include <iostream>
#include <iomanip>
#include <optional>
#include <string_view>
#include <Common/scope_guard_safe.h>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <filesystem>
#include <string>
#include "Client.h"
#include "Client/ConnectionString.h"
#include "Core/Protocol.h"
#include "Parsers/formatAST.h"

Expand Down Expand Up @@ -1248,6 +1248,9 @@ void Client::readArguments(
std::vector<Arguments> & external_tables_arguments,
std::vector<Arguments> & hosts_and_ports_arguments)
{
bool has_connection_string = argc >= 2 && tryParseConnectionString(std::string_view(argv[1]), common_arguments, hosts_and_ports_arguments);
int start_argument_index = has_connection_string ? 2 : 1;

/** We allow different groups of arguments:
* - common arguments;
* - arguments for any number of external tables each in form "--external args...",
Expand All @@ -1260,10 +1263,13 @@ void Client::readArguments(
std::string prev_host_arg;
std::string prev_port_arg;

for (int arg_num = 1; arg_num < argc; ++arg_num)
for (int arg_num = start_argument_index; arg_num < argc; ++arg_num)
{
std::string_view arg = argv[arg_num];

if (has_connection_string)
validateConnectionStringClientOption(arg);

if (arg == "--external")
{
in_external_group = true;
Expand Down
Loading
Loading