From 649386ff0f37ff3c4fd0440efefa90adfd43d9bb Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Fri, 29 Jan 2021 23:15:42 +0300 Subject: [PATCH 01/22] Edit and translate to Russian MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Поправил английскую версию и перевел на русский язык. --- docs/en/operations/opentelemetry.md | 41 +++++----------- .../functions/other-functions.md | 6 +-- docs/en/sql-reference/statements/optimize.md | 2 +- docs/ru/operations/opentelemetry.md | 49 +++++++++++++++++++ .../functions/date-time-functions.md | 2 - .../functions/other-functions.md | 17 +++++-- docs/ru/sql-reference/statements/optimize.md | 5 +- 7 files changed, 80 insertions(+), 42 deletions(-) create mode 100644 docs/ru/operations/opentelemetry.md diff --git a/docs/en/operations/opentelemetry.md b/docs/en/operations/opentelemetry.md index 2afeabc7956..db0a0e9779a 100644 --- a/docs/en/operations/opentelemetry.md +++ b/docs/en/operations/opentelemetry.md @@ -5,52 +5,32 @@ toc_title: OpenTelemetry Support # [experimental] OpenTelemetry Support -[OpenTelemetry](https://opentelemetry.io/) is an open standard for collecting -traces and metrics from distributed application. ClickHouse has some support -for OpenTelemetry. +[OpenTelemetry](https://opentelemetry.io/) is an open standard for collecting traces and metrics from the distributed application. ClickHouse has some support for `OpenTelemetry`. !!! warning "Warning" -This is an experimental feature that will change in backwards-incompatible ways in the future releases. - +This is an experimental feature that will change in backward-incompatible ways in future releases. ## Supplying Trace Context to ClickHouse -ClickHouse accepts trace context HTTP headers, as described by -the [W3C recommendation](https://www.w3.org/TR/trace-context/). -It also accepts trace context over native protocol that is used for -communication between ClickHouse servers or between the client and server. -For manual testing, trace context headers conforming to the Trace Context -recommendation can be supplied to `clickhouse-client` using -`--opentelemetry-traceparent` and `--opentelemetry-tracestate` flags. - -If no parent trace context is supplied, ClickHouse can start a new trace, with -probability controlled by the `opentelemetry_start_trace_probability` setting. +ClickHouse accepts trace context HTTP headers, as described by the [W3C recommendation](https://www.w3.org/TR/trace-context/). It also accepts trace context over a native protocol that is used for communication between ClickHouse servers or between the client and server. For manual testing, trace context headers conforming to the Trace Context recommendation can be supplied to `clickhouse-client` using `--opentelemetry-traceparent` and `--opentelemetry-tracestate` flags. +If no parent trace context is supplied, ClickHouse can start a new trace, with probability controlled by the `opentelemetry_start_trace_probability` setting. ## Propagating the Trace Context The trace context is propagated to downstream services in the following cases: -* Queries to remote ClickHouse servers, such as when using `Distributed` table - engine. +* Queries to remote ClickHouse servers, such as when using `Distributed` table engine. * `URL` table function. Trace context information is sent in HTTP headers. - ## Tracing the ClickHouse Itself -ClickHouse creates _trace spans_ for each query and some of the query execution -stages, such as query planning or distributed queries. +ClickHouse creates _trace spans_ for each query and some of the query execution stages, such as query planning or distributed queries. -To be useful, the tracing information has to be exported to a monitoring system -that supports OpenTelemetry, such as Jaeger or Prometheus. ClickHouse avoids -a dependency on a particular monitoring system, instead only providing the -tracing data through a system table. OpenTelemetry trace span information -[required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) -is stored in the `system.opentelemetry_span_log` table. +To be useful, the tracing information has to be exported to a monitoring system that supports `OpenTelemetry`, such as `Jaeger` or `Prometheus`. ClickHouse avoids a dependency on a particular monitoring system, instead only providing the tracing data through a system table. `OpenTelemetry` trace span information [required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) is stored in the `system.opentelemetry_span_log` table. -The table must be enabled in the server configuration, see the `opentelemetry_span_log` -element in the default config file `config.xml`. It is enabled by default. +The table must be enabled in the server configuration, see the `opentelemetry_span_log` element in the default config file `config.xml`. It is enabled by default. The table has the following columns: @@ -64,8 +44,7 @@ The table has the following columns: - `attribute.name` - `attribute.values` -The tags or attributes are saved as two parallel arrays, containing the keys -and values. Use `ARRAY JOIN` to work with them. +The tags or attributes are saved as two parallel arrays, containing the keys and values. Use `ARRAY JOIN` to work with them. ## Integration with monitoring systems @@ -94,3 +73,5 @@ FROM system.opentelemetry_span_log ``` In case of any errors, the part of the log data for which the error has occurred will be silently lost. Check the server log for error messages if the data does not arrive. + +[Original article](https://clickhouse.tech/docs/en/operations/opentelemetry/) diff --git a/docs/en/sql-reference/functions/other-functions.md b/docs/en/sql-reference/functions/other-functions.md index 08d34770f57..86ce53b56f6 100644 --- a/docs/en/sql-reference/functions/other-functions.md +++ b/docs/en/sql-reference/functions/other-functions.md @@ -639,7 +639,7 @@ The result of the function depends on the affected data blocks and the order of It can reach the neighbor rows only inside the currently processed data block. The rows order used during the calculation of `neighbor` can differ from the order of rows returned to the user. -To prevent that you can make a subquery with ORDER BY and call the function from outside the subquery. +To prevent that you can make a subquery with `ORDER BY` and call the function from outside the subquery. **Parameters** @@ -745,12 +745,12 @@ Calculates the difference between successive row values ​​in the data block. Returns 0 for the first row and the difference from the previous row for each subsequent row. !!! warning "Warning" - It can reach the previos row only inside the currently processed data block. + It can reach the previous row only inside the currently processed data block. The result of the function depends on the affected data blocks and the order of data in the block. The rows order used during the calculation of `runningDifference` can differ from the order of rows returned to the user. -To prevent that you can make a subquery with ORDER BY and call the function from outside the subquery. +To prevent that you can make a subquery with `ORDER BY` and call the function from outside the subquery. Example: diff --git a/docs/en/sql-reference/statements/optimize.md b/docs/en/sql-reference/statements/optimize.md index a67f282e793..9b16a12d2e2 100644 --- a/docs/en/sql-reference/statements/optimize.md +++ b/docs/en/sql-reference/statements/optimize.md @@ -17,7 +17,7 @@ When `OPTIMIZE` is used with the [ReplicatedMergeTree](../../engines/table-engin - If `OPTIMIZE` doesn’t perform a merge for any reason, it doesn’t notify the client. To enable notifications, use the [optimize_throw_if_noop](../../operations/settings/settings.md#setting-optimize_throw_if_noop) setting. - If you specify a `PARTITION`, only the specified partition is optimized. [How to set partition expression](../../sql-reference/statements/alter/index.md#alter-how-to-specify-part-expr). -- If you specify `FINAL`, optimization is performed even when all the data is already in one part. +- If you specify `FINAL`, optimization is performed even when all the data is already in one part. Also merge is forced even if concurrent merges are performed. - If you specify `DEDUPLICATE`, then completely identical rows will be deduplicated (all columns are compared), it makes sense only for the MergeTree engine. !!! warning "Warning" diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md new file mode 100644 index 00000000000..2131128e17d --- /dev/null +++ b/docs/ru/operations/opentelemetry.md @@ -0,0 +1,49 @@ +--- +toc_priority: 62 +toc_title: Поддержка OpenTelemetry +--- + +# [экспериментально] Поддержка OpenTelemetry + +[OpenTelemetry](https://opentelemetry.io/) — это открытый стандарт для сбора трассировок и метрик из распределенного приложения. В ClickHouse есть поддержка `OpenTelemetry`. + +!!! warning "Предупреждение" +Этот стандарт экспериментальный и будет изменяться в будущих релизах. + +## Обеспечение поддержки контекста трассировки в ClickHouse + +ClickHouse принимает контекст трассировки HTTP заголовков, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекст трассировки через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. В ручном тестировании заголовки контекста трассировки, соответствующие рекомендации контекста трассировки, могут быть переданы в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. + +Если доставлен не родительский контекст трассировки, ClickHouse может запустить новую трассировку, которая будет контролироваться настройкой `opentelemetry_start_trace_probability`. + +## Распространение контекста трассировки + +Контекст трассировки распространяется на нижестоящие сервисы в следующих случаях: + +* При использовании запросов к удаленным серверам ClickHouse, например при использовании движка таблиц `Distributed`. + +* При использовании табличной функции `URL`. Информация контекста трассировки передается в HTTP заголовки. + +## Трассировка ClickHouse + +ClickHouse создает _trace spans_ для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. + +Чтобы быть полезной, информация трассировки должна быть экспортирована в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице `system.opentelemetry_span_log`. + +Таблица должна быть включена в конфигурации сервера, смотрите элемент `opentelemetry_span_log` в файле конфигурации `config.xml`. По умолчанию таблица уже включена. + +В таблице имеются следующие столбцы: + +- `trace_id` +- `span_id` +- `parent_span_id` +- `operation_name` +- `start_time` +- `finish_time` +- `finish_date` +- `attribute.name` +- `attribute.values` + +Теги или атрибуты сохраняются в виде двух параллельных массивов, содержащих ключи и значения. Для работы с ними используйте `ARRAY JOIN`. + +[Оригинальная статья](https://clickhouse.tech/docs/ru/operations/opentelemetry/) diff --git a/docs/ru/sql-reference/functions/date-time-functions.md b/docs/ru/sql-reference/functions/date-time-functions.md index 31482cde77f..384b6eb58f7 100644 --- a/docs/ru/sql-reference/functions/date-time-functions.md +++ b/docs/ru/sql-reference/functions/date-time-functions.md @@ -23,8 +23,6 @@ SELECT └─────────────────────┴────────────┴────────────┴─────────────────────┘ ``` -Поддерживаются только часовые пояса, отличающиеся от UTC на целое число часов. - ## toTimeZone {#totimezone} Переводит дату или дату-с-временем в указанный часовой пояс. Часовой пояс (таймзона) это атрибут типов Date/DateTime, внутреннее значение (количество секунд) поля таблицы или колонки результата не изменяется, изменяется тип поля и автоматически его текстовое отображение. diff --git a/docs/ru/sql-reference/functions/other-functions.md b/docs/ru/sql-reference/functions/other-functions.md index 68afb3e24ce..1de34df9126 100644 --- a/docs/ru/sql-reference/functions/other-functions.md +++ b/docs/ru/sql-reference/functions/other-functions.md @@ -562,7 +562,7 @@ SELECT ## neighbor {#neighbor} -Функция позволяет получить доступ к значению в колонке `column`, находящемуся на смещении `offset` относительно текущей строки. Является частичной реализацией [оконных функций](https://en.wikipedia.org/wiki/SQL_window_function) `LEAD()` и `LAG()`. +Функция позволяет получить доступ к значению в столбце `column`, находящемуся на смещении `offset` относительно текущей строки. Является частичной реализацией [оконных функций](https://en.wikipedia.org/wiki/SQL_window_function) `LEAD()` и `LAG()`. **Синтаксис** @@ -570,7 +570,13 @@ SELECT neighbor(column, offset[, default_value]) ``` -Результат функции зависит от затронутых блоков данных и порядка данных в блоке. Если сделать подзапрос с ORDER BY и вызывать функцию извне подзапроса, можно будет получить ожидаемый результат. +Результат функции зависит от затронутых блоков данных и порядка данных в блоке. + +!!! warning "Предупреждение" + Функция может получить доступ к значению в столбце соседней строки только внутри обрабатываемого в данный момент блока данных. + +Порядок строк, используемый при вычислении функции `neighbor`, может отличаться от порядка строк, возвращаемых пользователю. +Чтобы этого не случилось, вы можете сделать подзапрос с `ORDER BY` и вызвать функцию изне подзапроса. **Параметры** @@ -675,8 +681,13 @@ FROM numbers(16) Считает разницу между последовательными значениями строк в блоке данных. Возвращает 0 для первой строки и разницу с предыдущей строкой для каждой последующей строки. +!!! warning "Предупреждение" + Функция может взять значение предыдущей строки только внутри текущего обработанного блока данных. + Результат функции зависит от затронутых блоков данных и порядка данных в блоке. -Если сделать подзапрос с ORDER BY и вызывать функцию извне подзапроса, можно будет получить ожидаемый результат. + +Порядок строк, используемый при вычислении функции `runningDifference`, может отличаться от порядка строк, возвращаемых пользователю. +Чтобы этого не случилось, вы можете сделать подзапрос с `ORDER BY` и вызвать функцию извне подзапроса. Пример: diff --git a/docs/ru/sql-reference/statements/optimize.md b/docs/ru/sql-reference/statements/optimize.md index 9b94c31a8f7..8b1d72fed80 100644 --- a/docs/ru/sql-reference/statements/optimize.md +++ b/docs/ru/sql-reference/statements/optimize.md @@ -15,11 +15,10 @@ OPTIMIZE TABLE [db.]name [ON CLUSTER cluster] [PARTITION partition | PARTITION I - Если `OPTIMIZE` не выполняет мёрж по любой причине, ClickHouse не оповещает об этом клиента. Чтобы включить оповещения, используйте настройку [optimize_throw_if_noop](../../operations/settings/settings.md#setting-optimize_throw_if_noop). - Если указать `PARTITION`, то оптимизация выполняется только для указанной партиции. [Как задавать имя партиции в запросах](alter/index.md#alter-how-to-specify-part-expr). -- Если указать `FINAL`, то оптимизация выполняется даже в том случае, если все данные уже лежат в одном куске. +- Если указать `FINAL`, то оптимизация выполняется даже в том случае, если все данные уже лежат в одном куске. Кроме того, слияние является принудительным, даже если выполняются параллельные слияния. - Если указать `DEDUPLICATE`, то произойдет схлопывание полностью одинаковых строк (сравниваются значения во всех колонках), имеет смысл только для движка MergeTree. !!! warning "Внимание" Запрос `OPTIMIZE` не может устранить причину появления ошибки «Too many parts». - -[Оригинальная статья](https://clickhouse.tech/docs/ru/sql-reference/statements/optimize/) \ No newline at end of file +[Оригинальная статья](https://clickhouse.tech/docs/ru/sql-reference/statements/optimize/) From 4529cdac8139623cc3d352884702a7c0ee3b5dad Mon Sep 17 00:00:00 2001 From: zhang2014 Date: Sun, 21 Feb 2021 14:06:43 +0800 Subject: [PATCH 02/22] try fix MaterializeMySQL integration test --- .../materialize_with_ddl.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py b/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py index c9be2387fc7..35633827a95 100644 --- a/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py +++ b/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py @@ -471,16 +471,18 @@ def select_without_columns(clickhouse_node, mysql_node, service_name): mysql_node.query("CREATE DATABASE db") mysql_node.query("CREATE TABLE db.t (a INT PRIMARY KEY, b INT)") clickhouse_node.query( - "CREATE DATABASE db ENGINE = MaterializeMySQL('{}:3306', 'db', 'root', 'clickhouse')".format(service_name)) + "CREATE DATABASE db ENGINE = MaterializeMySQL('{}:3306', 'db', 'root', 'clickhouse') SETTINGS max_flush_data_time = 100000".format(service_name)) check_query(clickhouse_node, "SHOW TABLES FROM db FORMAT TSV", "t\n") clickhouse_node.query("SYSTEM STOP MERGES db.t") clickhouse_node.query("CREATE VIEW v AS SELECT * FROM db.t") mysql_node.query("INSERT INTO db.t VALUES (1, 1), (2, 2)") - mysql_node.query("DELETE FROM db.t WHERE a=2;") + mysql_node.query("DELETE FROM db.t WHERE a = 2;") + # We need to execute a DDL for flush data buffer + mysql_node.query("CREATE TABLE db.temporary(a INT PRIMARY KEY, b INT)") optimize_on_insert = clickhouse_node.query("SELECT value FROM system.settings WHERE name='optimize_on_insert'").strip() if optimize_on_insert == "0": - res = ["3\n", "2\n", "2\n"] + res = ["3\n", "2\n", "1\n"] else: res = ["2\n", "2\n", "1\n"] check_query(clickhouse_node, "SELECT count((_sign, _version)) FROM db.t FORMAT TSV", res[0]) From 521891edec62b47e81e51ae015b096acff69ae0e Mon Sep 17 00:00:00 2001 From: Winter Zhang Date: Mon, 22 Feb 2021 12:47:38 +0800 Subject: [PATCH 03/22] Update materialize_with_ddl.py --- .../test_materialize_mysql_database/materialize_with_ddl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py b/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py index 35633827a95..a4417d05924 100644 --- a/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py +++ b/tests/integration/test_materialize_mysql_database/materialize_with_ddl.py @@ -482,7 +482,7 @@ def select_without_columns(clickhouse_node, mysql_node, service_name): optimize_on_insert = clickhouse_node.query("SELECT value FROM system.settings WHERE name='optimize_on_insert'").strip() if optimize_on_insert == "0": - res = ["3\n", "2\n", "1\n"] + res = ["3\n", "2\n", "2\n"] else: res = ["2\n", "2\n", "1\n"] check_query(clickhouse_node, "SELECT count((_sign, _version)) FROM db.t FORMAT TSV", res[0]) From 187eb837dbd754863103ff2dc675e90ffbcb46fe Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Sun, 28 Feb 2021 20:10:44 +0300 Subject: [PATCH 04/22] Add the links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Добавил ссылки. --- docs/en/operations/opentelemetry.md | 27 +++++-------------- .../functions/other-functions.md | 4 +-- docs/ru/operations/opentelemetry.md | 26 +++++------------- .../functions/other-functions.md | 4 +-- 4 files changed, 18 insertions(+), 43 deletions(-) diff --git a/docs/en/operations/opentelemetry.md b/docs/en/operations/opentelemetry.md index db0a0e9779a..d0e7fbc6ef0 100644 --- a/docs/en/operations/opentelemetry.md +++ b/docs/en/operations/opentelemetry.md @@ -14,44 +14,31 @@ This is an experimental feature that will change in backward-incompatible ways i ClickHouse accepts trace context HTTP headers, as described by the [W3C recommendation](https://www.w3.org/TR/trace-context/). It also accepts trace context over a native protocol that is used for communication between ClickHouse servers or between the client and server. For manual testing, trace context headers conforming to the Trace Context recommendation can be supplied to `clickhouse-client` using `--opentelemetry-traceparent` and `--opentelemetry-tracestate` flags. -If no parent trace context is supplied, ClickHouse can start a new trace, with probability controlled by the `opentelemetry_start_trace_probability` setting. +If no parent trace context is supplied, ClickHouse can start a new trace, with probability controlled by the [opentelemetry_start_trace_probability](../operations/settings/settings.md#opentelemetry-start-trace-probability) setting. ## Propagating the Trace Context The trace context is propagated to downstream services in the following cases: -* Queries to remote ClickHouse servers, such as when using `Distributed` table engine. +* Queries to remote ClickHouse servers, such as when using [Distributed](../engines/table-engines/special/distributed.md) table engine. -* `URL` table function. Trace context information is sent in HTTP headers. +* [url](../sql-reference/table-functions/url.md) table function. Trace context information is sent in HTTP headers. ## Tracing the ClickHouse Itself ClickHouse creates _trace spans_ for each query and some of the query execution stages, such as query planning or distributed queries. -To be useful, the tracing information has to be exported to a monitoring system that supports `OpenTelemetry`, such as `Jaeger` or `Prometheus`. ClickHouse avoids a dependency on a particular monitoring system, instead only providing the tracing data through a system table. `OpenTelemetry` trace span information [required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) is stored in the `system.opentelemetry_span_log` table. +To be useful, the tracing information has to be exported to a monitoring system that supports `OpenTelemetry`, such as `Jaeger` or `Prometheus`. ClickHouse avoids a dependency on a particular monitoring system, instead only providing the tracing data through a system table. `OpenTelemetry` trace span information [required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) is stored in the [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md) table. The table must be enabled in the server configuration, see the `opentelemetry_span_log` element in the default config file `config.xml`. It is enabled by default. -The table has the following columns: - -- `trace_id` -- `span_id` -- `parent_span_id` -- `operation_name` -- `start_time` -- `finish_time` -- `finish_date` -- `attribute.name` -- `attribute.values` - -The tags or attributes are saved as two parallel arrays, containing the keys and values. Use `ARRAY JOIN` to work with them. +The tags or attributes are saved as two parallel arrays, containing the keys and values. Use [ARRAY JOIN](../sql-reference/statements/select/array-join.md) to work with them. ## Integration with monitoring systems -At the moment, there is no ready tool that can export the tracing data from -ClickHouse to a monitoring system. +At the moment, there is no ready tool that can export the tracing data from ClickHouse to a monitoring system. -For testing, it is possible to setup the export using a materialized view with the URL engine over the `system.opentelemetry_span_log` table, which would push the arriving log data to an HTTP endpoint of a trace collector. For example, to push the minimal span data to a Zipkin instance running at `http://localhost:9411`, in Zipkin v2 JSON format: +For testing, it is possible to setup the export using a materialized view with the [URL](../engines/table-engines/special/url.md) engine over the [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md) table, which would push the arriving log data to an HTTP endpoint of a trace collector. For example, to push the minimal span data to a Zipkin instance running at `http://localhost:9411`, in Zipkin v2 JSON format: ```sql CREATE MATERIALIZED VIEW default.zipkin_spans diff --git a/docs/en/sql-reference/functions/other-functions.md b/docs/en/sql-reference/functions/other-functions.md index 86ce53b56f6..819b4838005 100644 --- a/docs/en/sql-reference/functions/other-functions.md +++ b/docs/en/sql-reference/functions/other-functions.md @@ -639,7 +639,7 @@ The result of the function depends on the affected data blocks and the order of It can reach the neighbor rows only inside the currently processed data block. The rows order used during the calculation of `neighbor` can differ from the order of rows returned to the user. -To prevent that you can make a subquery with `ORDER BY` and call the function from outside the subquery. +To prevent that you can make a subquery with [ORDER BY](../../sql-reference/statements/select/order-by.md) and call the function from outside the subquery. **Parameters** @@ -750,7 +750,7 @@ Returns 0 for the first row and the difference from the previous row for each su The result of the function depends on the affected data blocks and the order of data in the block. The rows order used during the calculation of `runningDifference` can differ from the order of rows returned to the user. -To prevent that you can make a subquery with `ORDER BY` and call the function from outside the subquery. +To prevent that you can make a subquery with [ORDER BY](../../sql-reference/statements/select/order-by.md) and call the function from outside the subquery. Example: diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 2131128e17d..b84ad3fc8b1 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -8,42 +8,30 @@ toc_title: Поддержка OpenTelemetry [OpenTelemetry](https://opentelemetry.io/) — это открытый стандарт для сбора трассировок и метрик из распределенного приложения. В ClickHouse есть поддержка `OpenTelemetry`. !!! warning "Предупреждение" -Этот стандарт экспериментальный и будет изменяться в будущих релизах. +Поддержка стандарта экспериментальная и будет со временем меняться. ## Обеспечение поддержки контекста трассировки в ClickHouse -ClickHouse принимает контекст трассировки HTTP заголовков, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекст трассировки через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. В ручном тестировании заголовки контекста трассировки, соответствующие рекомендации контекста трассировки, могут быть переданы в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. +ClickHouse принимает контекст трассировки HTTP заголовков, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекст трассировки через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. Для ручного тестирования заголовки контекста трассировки, соответствующие рекомендации контекста трассировки, могут быть переданы в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. -Если доставлен не родительский контекст трассировки, ClickHouse может запустить новую трассировку, которая будет контролироваться настройкой `opentelemetry_start_trace_probability`. +Если входящий контекст трассировки не указан, ClickHouse может начать трассировку с вероятностью, задаваемой настройкой [opentelemetry_start_trace_probability](../operations/settings/settings.md#opentelemetry-start-trace-probability). ## Распространение контекста трассировки Контекст трассировки распространяется на нижестоящие сервисы в следующих случаях: -* При использовании запросов к удаленным серверам ClickHouse, например при использовании движка таблиц `Distributed`. +* При использовании запросов к удаленным серверам ClickHouse, например при использовании движка таблиц [Distributed](../engines/table-engines/special/distributed.md). -* При использовании табличной функции `URL`. Информация контекста трассировки передается в HTTP заголовки. +* При использовании табличной функции [url](../sql-reference/table-functions/url.md). Информация контекста трассировки передается в HTTP заголовки. ## Трассировка ClickHouse ClickHouse создает _trace spans_ для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. -Чтобы быть полезной, информация трассировки должна быть экспортирована в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице `system.opentelemetry_span_log`. +Чтобы быть полезной, информация трассировки должна быть экспортирована в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). Таблица должна быть включена в конфигурации сервера, смотрите элемент `opentelemetry_span_log` в файле конфигурации `config.xml`. По умолчанию таблица уже включена. -В таблице имеются следующие столбцы: - -- `trace_id` -- `span_id` -- `parent_span_id` -- `operation_name` -- `start_time` -- `finish_time` -- `finish_date` -- `attribute.name` -- `attribute.values` - -Теги или атрибуты сохраняются в виде двух параллельных массивов, содержащих ключи и значения. Для работы с ними используйте `ARRAY JOIN`. +Теги или атрибуты сохраняются в виде двух параллельных массивов, содержащих ключи и значения. Для работы с ними используйте [ARRAY JOIN](../sql-reference/statements/select/array-join.md). [Оригинальная статья](https://clickhouse.tech/docs/ru/operations/opentelemetry/) diff --git a/docs/ru/sql-reference/functions/other-functions.md b/docs/ru/sql-reference/functions/other-functions.md index 1de34df9126..3a430fb9f93 100644 --- a/docs/ru/sql-reference/functions/other-functions.md +++ b/docs/ru/sql-reference/functions/other-functions.md @@ -576,7 +576,7 @@ neighbor(column, offset[, default_value]) Функция может получить доступ к значению в столбце соседней строки только внутри обрабатываемого в данный момент блока данных. Порядок строк, используемый при вычислении функции `neighbor`, может отличаться от порядка строк, возвращаемых пользователю. -Чтобы этого не случилось, вы можете сделать подзапрос с `ORDER BY` и вызвать функцию изне подзапроса. +Чтобы этого не случилось, вы можете сделать подзапрос с [ORDER BY](../../sql-reference/statements/select/order-by.md) и вызвать функцию изне подзапроса. **Параметры** @@ -687,7 +687,7 @@ FROM numbers(16) Результат функции зависит от затронутых блоков данных и порядка данных в блоке. Порядок строк, используемый при вычислении функции `runningDifference`, может отличаться от порядка строк, возвращаемых пользователю. -Чтобы этого не случилось, вы можете сделать подзапрос с `ORDER BY` и вызвать функцию извне подзапроса. +Чтобы этого не случилось, вы можете сделать подзапрос с [ORDER BY](../../sql-reference/statements/select/order-by.md) и вызвать функцию извне подзапроса. Пример: From a43ce6dc16490b9b500dd5ef53728ef955389eab Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:02:48 +0300 Subject: [PATCH 05/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index b84ad3fc8b1..abcf6165ba0 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -5,7 +5,7 @@ toc_title: Поддержка OpenTelemetry # [экспериментально] Поддержка OpenTelemetry -[OpenTelemetry](https://opentelemetry.io/) — это открытый стандарт для сбора трассировок и метрик из распределенного приложения. В ClickHouse есть поддержка `OpenTelemetry`. + ClickHouse поддерживает [OpenTelemetry](https://opentelemetry.io/) — открытый стандарт для сбора трассировок и метрик из распределенного приложения. !!! warning "Предупреждение" Поддержка стандарта экспериментальная и будет со временем меняться. From 5b638653e40566edbc188d4f1c6307741943a676 Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:03:44 +0300 Subject: [PATCH 06/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index abcf6165ba0..5a3bba143ac 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -12,7 +12,7 @@ toc_title: Поддержка OpenTelemetry ## Обеспечение поддержки контекста трассировки в ClickHouse -ClickHouse принимает контекст трассировки HTTP заголовков, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекст трассировки через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. Для ручного тестирования заголовки контекста трассировки, соответствующие рекомендации контекста трассировки, могут быть переданы в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. +ClickHouse принимает контекстную информацию трассировки через HTTP заголовки, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекстную информацию через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. Для ручного тестирования заголовки контекста трассировки, соответствующие рекомендации контекста трассировки, могут быть переданы в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. Если входящий контекст трассировки не указан, ClickHouse может начать трассировку с вероятностью, задаваемой настройкой [opentelemetry_start_trace_probability](../operations/settings/settings.md#opentelemetry-start-trace-probability). From 281b18827b38dc515c01252c27e745ec50cd58b0 Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:04:25 +0300 Subject: [PATCH 07/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 5a3bba143ac..7cb051c10c1 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -20,7 +20,7 @@ ClickHouse принимает контекстную информацию тра Контекст трассировки распространяется на нижестоящие сервисы в следующих случаях: -* При использовании запросов к удаленным серверам ClickHouse, например при использовании движка таблиц [Distributed](../engines/table-engines/special/distributed.md). +* При использовании запросов к удаленным серверам ClickHouse, например, при использовании движка таблиц [Distributed](../engines/table-engines/special/distributed.md). * При использовании табличной функции [url](../sql-reference/table-functions/url.md). Информация контекста трассировки передается в HTTP заголовки. From 51af0bd2d1f56f1649001bc25cb661af19338d25 Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:04:43 +0300 Subject: [PATCH 08/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 7cb051c10c1..21e0bffde48 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -24,7 +24,7 @@ ClickHouse принимает контекстную информацию тра * При использовании табличной функции [url](../sql-reference/table-functions/url.md). Информация контекста трассировки передается в HTTP заголовки. -## Трассировка ClickHouse +## Как ClickHouse выполняет трассировку ClickHouse создает _trace spans_ для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. From 25ff24dfee95f1b452f21ca9309f4130330f549d Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:05:04 +0300 Subject: [PATCH 09/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 21e0bffde48..a131e1eafe4 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -28,7 +28,7 @@ ClickHouse принимает контекстную информацию тра ClickHouse создает _trace spans_ для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. -Чтобы быть полезной, информация трассировки должна быть экспортирована в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). +Чтобы анализировать информацию трассировки, ее следует экспортировать в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). Таблица должна быть включена в конфигурации сервера, смотрите элемент `opentelemetry_span_log` в файле конфигурации `config.xml`. По умолчанию таблица уже включена. From b3095d0ba0383e5f9ad53f8f09366922236404cc Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 20:05:24 +0300 Subject: [PATCH 10/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index a131e1eafe4..35b2acf86b7 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -30,7 +30,7 @@ ClickHouse создает _trace spans_ для каждого запроса и Чтобы анализировать информацию трассировки, ее следует экспортировать в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). -Таблица должна быть включена в конфигурации сервера, смотрите элемент `opentelemetry_span_log` в файле конфигурации `config.xml`. По умолчанию таблица уже включена. +Таблица должна быть включена в конфигурации сервера, смотрите элемент `opentelemetry_span_log` в файле конфигурации `config.xml`. По умолчанию таблица включена всегда. Теги или атрибуты сохраняются в виде двух параллельных массивов, содержащих ключи и значения. Для работы с ними используйте [ARRAY JOIN](../sql-reference/statements/select/array-join.md). From 08a49dd28a5bf941a6e86a98c5277395b4c2dc93 Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Mon, 1 Mar 2021 20:24:18 +0300 Subject: [PATCH 11/22] Update opentelemetry.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Исправил небольшую опечатку. --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 35b2acf86b7..044255398f4 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -5,7 +5,7 @@ toc_title: Поддержка OpenTelemetry # [экспериментально] Поддержка OpenTelemetry - ClickHouse поддерживает [OpenTelemetry](https://opentelemetry.io/) — открытый стандарт для сбора трассировок и метрик из распределенного приложения. +ClickHouse поддерживает [OpenTelemetry](https://opentelemetry.io/) — открытый стандарт для сбора трассировок и метрик из распределенного приложения. !!! warning "Предупреждение" Поддержка стандарта экспериментальная и будет со временем меняться. From c912c966d8dea171b46a10eb0f895b5eec6ec72f Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 21:46:21 +0300 Subject: [PATCH 12/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 044255398f4..727697a00be 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -12,7 +12,7 @@ ClickHouse поддерживает [OpenTelemetry](https://opentelemetry.io/) ## Обеспечение поддержки контекста трассировки в ClickHouse -ClickHouse принимает контекстную информацию трассировки через HTTP заголовки, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекстную информацию через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. Для ручного тестирования заголовки контекста трассировки, соответствующие рекомендации контекста трассировки, могут быть переданы в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. +ClickHouse принимает контекстную информацию трассировки через HTTP заголовок `tracecontext`, как описано в [рекомендации W3C](https://www.w3.org/TR/trace-context/). Также он принимает контекстную информацию через нативный протокол, который используется для связи между серверами ClickHouse или между клиентом и сервером. Для ручного тестирования стандартный заголовок `tracecontext`, содержащий контекст трассировки, может быть передан в `clickhouse-client` через флаги: `--opentelemetry-traceparent` и `--opentelemetry-tracestate`. Если входящий контекст трассировки не указан, ClickHouse может начать трассировку с вероятностью, задаваемой настройкой [opentelemetry_start_trace_probability](../operations/settings/settings.md#opentelemetry-start-trace-probability). From 02ebe453a599289294c51d05699c55dddb11cfca Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 21:46:39 +0300 Subject: [PATCH 13/22] Update docs/ru/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/ru/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 727697a00be..2cc470a0087 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -26,7 +26,7 @@ ClickHouse принимает контекстную информацию тра ## Как ClickHouse выполняет трассировку -ClickHouse создает _trace spans_ для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. +ClickHouse создает `trace spans` для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. Чтобы анализировать информацию трассировки, ее следует экспортировать в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). From f47bd5fae8a2e6c072158dd4033b9bcaf9a61bc2 Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 21:46:52 +0300 Subject: [PATCH 14/22] Update docs/en/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/en/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/operations/opentelemetry.md b/docs/en/operations/opentelemetry.md index d0e7fbc6ef0..e5c4632c99d 100644 --- a/docs/en/operations/opentelemetry.md +++ b/docs/en/operations/opentelemetry.md @@ -26,7 +26,7 @@ The trace context is propagated to downstream services in the following cases: ## Tracing the ClickHouse Itself -ClickHouse creates _trace spans_ for each query and some of the query execution stages, such as query planning or distributed queries. +ClickHouse creates `trace spans` for each query and some of the query execution stages, such as query planning or distributed queries. To be useful, the tracing information has to be exported to a monitoring system that supports `OpenTelemetry`, such as `Jaeger` or `Prometheus`. ClickHouse avoids a dependency on a particular monitoring system, instead only providing the tracing data through a system table. `OpenTelemetry` trace span information [required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) is stored in the [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md) table. From 9d98c8ea2efd63cdaa41c372431cdfba9fde2416 Mon Sep 17 00:00:00 2001 From: sevirov <72220289+sevirov@users.noreply.github.com> Date: Mon, 1 Mar 2021 21:47:02 +0300 Subject: [PATCH 15/22] Update docs/en/operations/opentelemetry.md Co-authored-by: Anna <42538400+adevyatova@users.noreply.github.com> --- docs/en/operations/opentelemetry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/operations/opentelemetry.md b/docs/en/operations/opentelemetry.md index e5c4632c99d..3acd1340b02 100644 --- a/docs/en/operations/opentelemetry.md +++ b/docs/en/operations/opentelemetry.md @@ -8,7 +8,7 @@ toc_title: OpenTelemetry Support [OpenTelemetry](https://opentelemetry.io/) is an open standard for collecting traces and metrics from the distributed application. ClickHouse has some support for `OpenTelemetry`. !!! warning "Warning" -This is an experimental feature that will change in backward-incompatible ways in future releases. + This is an experimental feature that will change in backwards-incompatible ways in future releases. ## Supplying Trace Context to ClickHouse From 4022418ff341b7473147f0e152f7221d0f10961f Mon Sep 17 00:00:00 2001 From: Vladimir Chebotarev Date: Wed, 3 Mar 2021 14:51:09 +0300 Subject: [PATCH 16/22] Case-insensitive compression methods. --- src/IO/CompressionMethod.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/IO/CompressionMethod.cpp b/src/IO/CompressionMethod.cpp index 8c0c2744a0a..6e437e34c10 100644 --- a/src/IO/CompressionMethod.cpp +++ b/src/IO/CompressionMethod.cpp @@ -15,6 +15,8 @@ # include #endif +#include + namespace DB { @@ -55,23 +57,24 @@ CompressionMethod chooseCompressionMethod(const std::string & path, const std::s file_extension = path.substr(pos + 1, std::string::npos); } - const std::string * method_str = file_extension.empty() ? &hint : &file_extension; + std::string method_str = file_extension.empty() ? hint : std::move(file_extension); + boost::algorithm::to_lower(method_str); - if (*method_str == "gzip" || *method_str == "gz") + if (method_str == "gzip" || method_str == "gz") return CompressionMethod::Gzip; - if (*method_str == "deflate") + if (method_str == "deflate") return CompressionMethod::Zlib; - if (*method_str == "brotli" || *method_str == "br") + if (method_str == "brotli" || method_str == "br") return CompressionMethod::Brotli; - if (*method_str == "LZMA" || *method_str == "xz") + if (method_str == "lzma" || method_str == "xz") return CompressionMethod::Xz; - if (*method_str == "zstd" || *method_str == "zst") + if (method_str == "zstd" || method_str == "zst") return CompressionMethod::Zstd; if (hint.empty() || hint == "auto" || hint == "none") return CompressionMethod::None; throw Exception( - "Unknown compression method " + hint + ". Only 'auto', 'none', 'gzip', 'br', 'xz', 'zstd' are supported as compression methods", + "Unknown compression method " + hint + ". Only 'auto', 'none', 'gzip', 'deflate', 'br', 'xz', 'zstd' are supported as compression methods", ErrorCodes::NOT_IMPLEMENTED); } From e7948819f973756c4ddc80454b2b38e5e54f5788 Mon Sep 17 00:00:00 2001 From: Azat Khuzhin Date: Wed, 3 Mar 2021 23:44:51 +0300 Subject: [PATCH 17/22] Fix ParsingException::displayText() Before it was silently try-catched for messages with additional {}, and it is very easy to trigger, i.e.: SELECT toDateTime(format('{}-{}-01 00:00:00', '2021', '1')) Will print: Code: 41. DB::Exception: Received from localhost:9000. DB::Exception: Cannot parse datetime 2021-1-01 00:00:00{}: Cannot parse DateTime from String: while executing 'FUNCTION toDateTime(format('{}-{}-01 00:00:00', '2021', '1') :: 3) -> toDateTime(format('{}-{}-01 00:00:00', '2021', '1')) DateTime : 2'. --- src/Common/Exception.cpp | 14 +++----------- src/Common/Exception.h | 4 +--- .../0_stateless/01750_parsing_exception.reference | 0 .../queries/0_stateless/01750_parsing_exception.sh | 8 ++++++++ 4 files changed, 12 insertions(+), 14 deletions(-) create mode 100644 tests/queries/0_stateless/01750_parsing_exception.reference create mode 100755 tests/queries/0_stateless/01750_parsing_exception.sh diff --git a/src/Common/Exception.cpp b/src/Common/Exception.cpp index f5a40a11d9c..16f15d4e6f2 100644 --- a/src/Common/Exception.cpp +++ b/src/Common/Exception.cpp @@ -458,33 +458,25 @@ ExecutionStatus ExecutionStatus::fromCurrentException(const std::string & start_ return ExecutionStatus(getCurrentExceptionCode(), msg); } -ParsingException::ParsingException() -{ - Exception::message(Exception::message() + "{}"); -} - +ParsingException::ParsingException() = default; ParsingException::ParsingException(const std::string & msg, int code) : Exception(msg, code) { - Exception::message(Exception::message() + "{}"); } - ParsingException::ParsingException(int code, const std::string & message) : Exception(message, code) { - Exception::message(Exception::message() + "{}"); } - /// We use additional field formatted_message_ to make this method const. std::string ParsingException::displayText() const { try { if (line_number_ == -1) - formatted_message_ = fmt::format(message(), ""); + formatted_message_ = message(); else - formatted_message_ = fmt::format(message(), fmt::format(": (at row {})\n", line_number_)); + formatted_message_ = message() + fmt::format(": (at row {})\n", line_number_); } catch (...) {} diff --git a/src/Common/Exception.h b/src/Common/Exception.h index 661d31469fe..e487badafa5 100644 --- a/src/Common/Exception.h +++ b/src/Common/Exception.h @@ -115,9 +115,7 @@ public: template ParsingException(int code, const std::string & fmt, Args&&... args) : Exception(fmt::format(fmt, std::forward(args)...), code) - { - Exception::message(Exception::message() + "{}"); - } + {} std::string displayText() const diff --git a/tests/queries/0_stateless/01750_parsing_exception.reference b/tests/queries/0_stateless/01750_parsing_exception.reference new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/queries/0_stateless/01750_parsing_exception.sh b/tests/queries/0_stateless/01750_parsing_exception.sh new file mode 100755 index 00000000000..cd50d769f6d --- /dev/null +++ b/tests/queries/0_stateless/01750_parsing_exception.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# if it will not match, the exit code of grep will be non-zero and the test will fail +$CLICKHOUSE_CLIENT -q "SELECT toDateTime(format('{}-{}-01 00:00:00', '2021', '1'))" |& grep -F -q 'Cannot parse datetime 2021-1-01 00:00:00: Cannot parse DateTime from String:' From 39de525c74c320d117f79dc8189b6f8288b59d0f Mon Sep 17 00:00:00 2001 From: alesapin Date: Thu, 4 Mar 2021 16:48:06 +0300 Subject: [PATCH 18/22] Simplify config --- tests/config/config.d/test_keeper_port.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/config/config.d/test_keeper_port.xml b/tests/config/config.d/test_keeper_port.xml index d66183514d5..86179d96ca3 100644 --- a/tests/config/config.d/test_keeper_port.xml +++ b/tests/config/config.d/test_keeper_port.xml @@ -2,7 +2,6 @@ 9181 1 - /var/lib/clickhouse/coordination/log 10000 From de94f33b055a0bfe0ff2e70f632fddd8c786df2c Mon Sep 17 00:00:00 2001 From: Amos Bird Date: Fri, 5 Mar 2021 00:21:52 +0800 Subject: [PATCH 19/22] Tiny fix --- src/Functions/FunctionsBitmap.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Functions/FunctionsBitmap.h b/src/Functions/FunctionsBitmap.h index 054f8800630..a79365ec16c 100644 --- a/src/Functions/FunctionsBitmap.h +++ b/src/Functions/FunctionsBitmap.h @@ -1100,14 +1100,14 @@ public: return executeBitmapData(arguments, input_rows_count); else if (which.isUInt64()) return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt8()) - return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt16()) - return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt32()) - return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt64()) - return executeBitmapData(arguments, input_rows_count); + else if (which.isInt8()) + return executeBitmapData(arguments, input_rows_count); + else if (which.isInt16()) + return executeBitmapData(arguments, input_rows_count); + else if (which.isInt32()) + return executeBitmapData(arguments, input_rows_count); + else if (which.isInt64()) + return executeBitmapData(arguments, input_rows_count); else throw Exception( "Unexpected type " + from_type->getName() + " of argument of function " + getName(), ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); From fbc4791db746137ce05126367f8bcd3562c3fe9e Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Thu, 4 Mar 2021 20:13:22 +0300 Subject: [PATCH 20/22] Add the links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Добавил ссылки на продукты, убрал кавычки со стандарта. --- docs/en/operations/opentelemetry.md | 4 ++-- docs/ru/operations/opentelemetry.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/en/operations/opentelemetry.md b/docs/en/operations/opentelemetry.md index 3acd1340b02..74c9c6dd18f 100644 --- a/docs/en/operations/opentelemetry.md +++ b/docs/en/operations/opentelemetry.md @@ -5,7 +5,7 @@ toc_title: OpenTelemetry Support # [experimental] OpenTelemetry Support -[OpenTelemetry](https://opentelemetry.io/) is an open standard for collecting traces and metrics from the distributed application. ClickHouse has some support for `OpenTelemetry`. +[OpenTelemetry](https://opentelemetry.io/) is an open standard for collecting traces and metrics from the distributed application. ClickHouse has some support for OpenTelemetry. !!! warning "Warning" This is an experimental feature that will change in backwards-incompatible ways in future releases. @@ -28,7 +28,7 @@ The trace context is propagated to downstream services in the following cases: ClickHouse creates `trace spans` for each query and some of the query execution stages, such as query planning or distributed queries. -To be useful, the tracing information has to be exported to a monitoring system that supports `OpenTelemetry`, such as `Jaeger` or `Prometheus`. ClickHouse avoids a dependency on a particular monitoring system, instead only providing the tracing data through a system table. `OpenTelemetry` trace span information [required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) is stored in the [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md) table. +To be useful, the tracing information has to be exported to a monitoring system that supports OpenTelemetry, such as [Jaeger](https://jaegertracing.io/) or [Prometheus](https://prometheus.io/). ClickHouse avoids a dependency on a particular monitoring system, instead only providing the tracing data through a system table. OpenTelemetry trace span information [required by the standard](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span) is stored in the [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md) table. The table must be enabled in the server configuration, see the `opentelemetry_span_log` element in the default config file `config.xml`. It is enabled by default. diff --git a/docs/ru/operations/opentelemetry.md b/docs/ru/operations/opentelemetry.md index 2cc470a0087..a60f1b3e085 100644 --- a/docs/ru/operations/opentelemetry.md +++ b/docs/ru/operations/opentelemetry.md @@ -28,7 +28,7 @@ ClickHouse принимает контекстную информацию тра ClickHouse создает `trace spans` для каждого запроса и некоторых этапов выполнения запроса, таких как планирование запросов или распределенные запросы. -Чтобы анализировать информацию трассировки, ее следует экспортировать в систему мониторинга, поддерживающую `OpenTelemetry`, такую как `Jaeger` или `Prometheus`. ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в `OpenTelemetry`, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). +Чтобы анализировать информацию трассировки, ее следует экспортировать в систему мониторинга, поддерживающую OpenTelemetry, такую как [Jaeger](https://jaegertracing.io/) или [Prometheus](https://prometheus.io/). ClickHouse не зависит от конкретной системы мониторинга, вместо этого предоставляя данные трассировки только через системную таблицу. Информация о диапазоне трассировки в OpenTelemetry, [требуемая стандартом](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md#span), хранится в системной таблице [system.opentelemetry_span_log](../operations/system-tables/opentelemetry_span_log.md). Таблица должна быть включена в конфигурации сервера, смотрите элемент `opentelemetry_span_log` в файле конфигурации `config.xml`. По умолчанию таблица включена всегда. From 1985364c8fca251f943e9c5bb413d0868adc837a Mon Sep 17 00:00:00 2001 From: alexey-milovidov Date: Fri, 5 Mar 2021 02:35:54 +0300 Subject: [PATCH 21/22] Update datetime.md --- docs/en/sql-reference/data-types/datetime.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/en/sql-reference/data-types/datetime.md b/docs/en/sql-reference/data-types/datetime.md index 07a6e38a5fa..a9001b8eed8 100644 --- a/docs/en/sql-reference/data-types/datetime.md +++ b/docs/en/sql-reference/data-types/datetime.md @@ -19,15 +19,17 @@ Resolution: 1 second. ## Usage Remarks {#usage-remarks} -The point in time is saved as a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time), regardless of the time zone or daylight saving time. Additionally, the `DateTime` type can store time zone that is the same for the entire column, that affects how the values of the `DateTime` type values are displayed in text format and how the values specified as strings are parsed (‘2020-01-01 05:00:01’). The time zone is not stored in the rows of the table (or in resultset), but is stored in the column metadata. -A list of supported time zones can be found in the [IANA Time Zone Database](https://www.iana.org/time-zones). -The `tzdata` package, containing [IANA Time Zone Database](https://www.iana.org/time-zones), should be installed in the system. Use the `timedatectl list-timezones` command to list timezones known by a local system. +The point in time is saved as a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time), regardless of the time zone or daylight saving time. The time zone affects how the values of the `DateTime` type values are displayed in text format and how the values specified as strings are parsed (‘2020-01-01 05:00:01’). -You can explicitly set a time zone for `DateTime`-type columns when creating a table. If the time zone isn’t set, ClickHouse uses the value of the [timezone](../../operations/server-configuration-parameters/settings.md#server_configuration_parameters-timezone) parameter in the server settings or the operating system settings at the moment of the ClickHouse server start. +Timezone agnostic unix timestamp is stored in tables, and the timezone is used to transform it to text format or back during data import/export or to make calendar calculations on the values (example: `toDate`, `toHour` functions et cetera). The time zone is not stored in the rows of the table (or in resultset), but is stored in the column metadata. + +A list of supported time zones can be found in the [IANA Time Zone Database](https://www.iana.org/time-zones) and also can be queried by `SELECT * FROM system.time_zones`. + +You can explicitly set a time zone for `DateTime`-type columns when creating a table. Example: `DateTime('UTC')`. If the time zone isn’t set, ClickHouse uses the value of the [timezone](../../operations/server-configuration-parameters/settings.md#server_configuration_parameters-timezone) parameter in the server settings or the operating system settings at the moment of the ClickHouse server start. The [clickhouse-client](../../interfaces/cli.md) applies the server time zone by default if a time zone isn’t explicitly set when initializing the data type. To use the client time zone, run `clickhouse-client` with the `--use_client_time_zone` parameter. -ClickHouse outputs values depending on the value of the [date\_time\_output\_format](../../operations/settings/settings.md#settings-date_time_output_format) setting. `YYYY-MM-DD hh:mm:ss` text format by default. Additionaly you can change the output with the [formatDateTime](../../sql-reference/functions/date-time-functions.md#formatdatetime) function. +ClickHouse outputs values depending on the value of the [date_time_output_format](../../operations/settings/settings.md#settings-date_time_output_format) setting. `YYYY-MM-DD hh:mm:ss` text format by default. Additionaly you can change the output with the [formatDateTime](../../sql-reference/functions/date-time-functions.md#formatdatetime) function. When inserting data into ClickHouse, you can use different formats of date and time strings, depending on the value of the [date_time_input_format](../../operations/settings/settings.md#settings-date_time_input_format) setting. @@ -114,6 +116,8 @@ FROM dt └─────────────────────┴─────────────────────┘ ``` +As timezone conversion only changes the metadata, the operation has no computation cost. + ## See Also {#see-also} - [Type conversion functions](../../sql-reference/functions/type-conversion-functions.md) From 643b06584991a8d409010d995c7008741dd2eced Mon Sep 17 00:00:00 2001 From: alexey-milovidov Date: Fri, 5 Mar 2021 02:55:12 +0300 Subject: [PATCH 22/22] Update datetime.md --- docs/en/sql-reference/data-types/datetime.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/en/sql-reference/data-types/datetime.md b/docs/en/sql-reference/data-types/datetime.md index a9001b8eed8..d95abe57510 100644 --- a/docs/en/sql-reference/data-types/datetime.md +++ b/docs/en/sql-reference/data-types/datetime.md @@ -118,6 +118,22 @@ FROM dt As timezone conversion only changes the metadata, the operation has no computation cost. + +## Limitations on timezones support + +Some timezones may not be supported completely. There are a few cases: + +If the offset from UTC is not a multiple of 15 minutes, the calculation of hours and minutes can be incorrect. For example, the time zone in Monrovia, Liberia has offset UTC -0:44:30 before 7 Jan 1972. If you are doing calculations on the historical time in Monrovia timezone, the time processing functions may give incorrect results. The results after 7 Jan 1972 will be correct nevertheless. + +If the time transition (due to daylight saving time or for other reasons) was performed at a point of time that is not a multiple of 15 minutes, you can also get incorrect results at this specific day. + +Non-monotonic calendar dates. For example, in Happy Valley - Goose Bay, the time was transitioned one hour backwards at 00:01:00 7 Nov 2010 (one minute after midnight). So after 6th Nov has ended, people observed a whole one minute of 7th Nov, then time was changed back to 23:01 6th Nov and after another 59 minutes the 7th Nov started again. ClickHouse does not (yet) support this kind of fun. During these days the results of time processing functions may be slightly incorrect. + +Similar issue exists for Casey Antarctic station in year 2010. They changed time three hours back at 5 Mar, 02:00. If you are working in antarctic station, please don't afraid to use ClickHouse. Just make sure you set timezone to UTC or be aware of inaccuracies. + +Time shifts for multiple days. Some pacific islands changed their timezone offset from UTC+14 to UTC-12. That's alright but some inaccuracies may present if you do calculations with their timezone for historical time points at the days of conversion. + + ## See Also {#see-also} - [Type conversion functions](../../sql-reference/functions/type-conversion-functions.md)