mirror of
https://github.com/ClickHouse/ClickHouse.git
synced 2024-11-10 09:32:06 +00:00
Merge branch 'master' into create-user-defined-lambda-function
This commit is contained in:
commit
2a6aa50d49
2
.github/PULL_REQUEST_TEMPLATE.md
vendored
2
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -3,7 +3,7 @@ I hereby agree to the terms of the CLA available at: https://yandex.ru/legal/cla
|
||||
Changelog category (leave one):
|
||||
- New Feature
|
||||
- Improvement
|
||||
- Bug Fix
|
||||
- Bug Fix (user-visible misbehaviour in official stable or prestable release)
|
||||
- Performance Improvement
|
||||
- Backward Incompatible Change
|
||||
- Build/Testing/Packaging Improvement
|
||||
|
@ -303,6 +303,7 @@ function run_tests
|
||||
01683_codec_encrypted # Depends on OpenSSL
|
||||
01776_decrypt_aead_size_check # Depends on OpenSSL
|
||||
01811_filter_by_null # Depends on OpenSSL
|
||||
02012_sha512_fixedstring # Depends on OpenSSL
|
||||
01281_unsucceeded_insert_select_queries_counter
|
||||
01292_create_user
|
||||
01294_lazy_database_concurrent
|
||||
|
@ -23,3 +23,5 @@ You can also use the following database engines:
|
||||
- [PostgreSQL](../../engines/database-engines/postgresql.md)
|
||||
|
||||
- [Replicated](../../engines/database-engines/replicated.md)
|
||||
|
||||
- [SQLite](../../engines/database-engines/sqlite.md)
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
toc_priority: 29
|
||||
toc_title: "[experimental] MaterializedMySQL"
|
||||
toc_title: MaterializedMySQL
|
||||
---
|
||||
|
||||
# [experimental] MaterializedMySQL {#materialized-mysql}
|
||||
|
80
docs/en/engines/database-engines/sqlite.md
Normal file
80
docs/en/engines/database-engines/sqlite.md
Normal file
@ -0,0 +1,80 @@
|
||||
---
|
||||
toc_priority: 32
|
||||
toc_title: SQLite
|
||||
---
|
||||
|
||||
# SQLite {#sqlite}
|
||||
|
||||
Allows to connect to [SQLite](https://www.sqlite.org/index.html) database and perform `INSERT` and `SELECT` queries to exchange data between ClickHouse and SQLite.
|
||||
|
||||
## Creating a Database {#creating-a-database}
|
||||
|
||||
``` sql
|
||||
CREATE DATABASE sqlite_database
|
||||
ENGINE = SQLite('db_path')
|
||||
```
|
||||
|
||||
**Engine Parameters**
|
||||
|
||||
- `db_path` — Path to a file with SQLite database.
|
||||
|
||||
## Data Types Support {#data_types-support}
|
||||
|
||||
| SQLite | ClickHouse |
|
||||
|---------------|---------------------------------------------------------|
|
||||
| INTEGER | [Int32](../../sql-reference/data-types/int-uint.md) |
|
||||
| REAL | [Float32](../../sql-reference/data-types/float.md) |
|
||||
| TEXT | [String](../../sql-reference/data-types/string.md) |
|
||||
| BLOB | [String](../../sql-reference/data-types/string.md) |
|
||||
|
||||
## Specifics and Recommendations {#specifics-and-recommendations}
|
||||
|
||||
SQLite stores the entire database (definitions, tables, indices, and the data itself) as a single cross-platform file on a host machine. During writing SQLite locks the entire database file, therefore write operations are performed sequentially. Read operations can be multitasked.
|
||||
SQLite does not require service management (such as startup scripts) or access control based on `GRANT` and passwords. Access control is handled by means of file-system permissions given to the database file itself.
|
||||
|
||||
## Usage Example {#usage-example}
|
||||
|
||||
Database in ClickHouse, connected to the SQLite:
|
||||
|
||||
``` sql
|
||||
CREATE DATABASE sqlite_db ENGINE = SQLite('sqlite.db');
|
||||
SHOW TABLES FROM sqlite_db;
|
||||
```
|
||||
|
||||
``` text
|
||||
┌──name───┐
|
||||
│ table1 │
|
||||
│ table2 │
|
||||
└─────────┘
|
||||
```
|
||||
|
||||
Shows the tables:
|
||||
|
||||
``` sql
|
||||
SELECT * FROM sqlite_db.table1;
|
||||
```
|
||||
|
||||
``` text
|
||||
┌─col1──┬─col2─┐
|
||||
│ line1 │ 1 │
|
||||
│ line2 │ 2 │
|
||||
│ line3 │ 3 │
|
||||
└───────┴──────┘
|
||||
```
|
||||
Inserting data into SQLite table from ClickHouse table:
|
||||
|
||||
``` sql
|
||||
CREATE TABLE clickhouse_table(`col1` String,`col2` Int16) ENGINE = MergeTree() ORDER BY col2;
|
||||
INSERT INTO clickhouse_table VALUES ('text',10);
|
||||
INSERT INTO sqlite_db.table1 SELECT * FROM clickhouse_table;
|
||||
SELECT * FROM sqlite_db.table1;
|
||||
```
|
||||
|
||||
``` text
|
||||
┌─col1──┬─col2─┐
|
||||
│ line1 │ 1 │
|
||||
│ line2 │ 2 │
|
||||
│ line3 │ 3 │
|
||||
│ text │ 10 │
|
||||
└───────┴──────┘
|
||||
```
|
@ -19,3 +19,4 @@ List of supported integrations:
|
||||
- [EmbeddedRocksDB](../../../engines/table-engines/integrations/embedded-rocksdb.md)
|
||||
- [RabbitMQ](../../../engines/table-engines/integrations/rabbitmq.md)
|
||||
- [PostgreSQL](../../../engines/table-engines/integrations/postgresql.md)
|
||||
- [SQLite](../../../engines/table-engines/integrations/sqlite.md)
|
||||
|
59
docs/en/engines/table-engines/integrations/sqlite.md
Normal file
59
docs/en/engines/table-engines/integrations/sqlite.md
Normal file
@ -0,0 +1,59 @@
|
||||
---
|
||||
toc_priority: 7
|
||||
toc_title: SQLite
|
||||
---
|
||||
|
||||
# SQLite {#sqlite}
|
||||
|
||||
The engine allows to import and export data to SQLite and supports queries to SQLite tables directly from ClickHouse.
|
||||
|
||||
## Creating a Table {#creating-a-table}
|
||||
|
||||
``` sql
|
||||
CREATE TABLE [IF NOT EXISTS] [db.]table_name
|
||||
(
|
||||
name1 [type1],
|
||||
name2 [type2], ...
|
||||
) ENGINE = SQLite('db_path', 'table')
|
||||
```
|
||||
|
||||
**Engine Parameters**
|
||||
|
||||
- `db_path` — Path to SQLite file with a database.
|
||||
- `table` — Name of a table in the SQLite database.
|
||||
|
||||
## Usage Example {#usage-example}
|
||||
|
||||
Shows a query creating the SQLite table:
|
||||
|
||||
```sql
|
||||
SHOW CREATE TABLE sqlite_db.table2;
|
||||
```
|
||||
|
||||
``` text
|
||||
CREATE TABLE SQLite.table2
|
||||
(
|
||||
`col1` Nullable(Int32),
|
||||
`col2` Nullable(String)
|
||||
)
|
||||
ENGINE = SQLite('sqlite.db','table2');
|
||||
```
|
||||
|
||||
Returns the data from the table:
|
||||
|
||||
``` sql
|
||||
SELECT * FROM sqlite_db.table2 ORDER BY col1;
|
||||
```
|
||||
|
||||
```text
|
||||
┌─col1─┬─col2──┐
|
||||
│ 1 │ text1 │
|
||||
│ 2 │ text2 │
|
||||
│ 3 │ text3 │
|
||||
└──────┴───────┘
|
||||
```
|
||||
|
||||
**See Also**
|
||||
|
||||
- [SQLite](../../../engines/database-engines/sqlite.md) engine
|
||||
- [sqlite](../../../sql-reference/table-functions/sqlite.md) table function
|
@ -105,7 +105,7 @@ We use `Decimal` data type to store prices. Everything else is quite straightfor
|
||||
|
||||
## Import Data
|
||||
|
||||
Upload data into ClickHouse in parallel:
|
||||
Upload data into ClickHouse:
|
||||
|
||||
```
|
||||
clickhouse-client --format_csv_allow_single_quotes 0 --input_format_null_as_default 0 --query "INSERT INTO dish FORMAT CSVWithNames" < Dish.csv
|
||||
|
@ -114,5 +114,5 @@ Seamlessly migration from ZooKeeper to `clickhouse-keeper` is impossible you hav
|
||||
clickhouse-keeper-converter --zookeeper-logs-dir /var/lib/zookeeper/version-2 --zookeeper-snapshots-dir /var/lib/zookeeper/version-2 --output-dir /path/to/clickhouse/keeper/snapshots
|
||||
```
|
||||
|
||||
4. Copy snapshot to `clickhouse-server` nodes with configured `keeper` or start `clickhouse-keeper` instead of ZooKeeper. Snapshot must persist only on leader node, leader will sync it automatically to other nodes.
|
||||
4. Copy snapshot to `clickhouse-server` nodes with configured `keeper` or start `clickhouse-keeper` instead of ZooKeeper. Snapshot must persist on all nodes, otherwise empty nodes can be faster and one of them can becamse leader.
|
||||
|
||||
|
@ -255,7 +255,7 @@ windowFunnel(window, [mode, [mode, ... ]])(timestamp, cond1, cond2, ..., condN)
|
||||
|
||||
- `window` — Length of the sliding window, it is the time interval between the first and the last condition. The unit of `window` depends on the `timestamp` itself and varies. Determined using the expression `timestamp of cond1 <= timestamp of cond2 <= ... <= timestamp of condN <= timestamp of cond1 + window`.
|
||||
- `mode` — It is an optional argument. One or more modes can be set.
|
||||
- `'strict'` — If same condition holds for sequence of events then such non-unique events would be skipped.
|
||||
- `'strict_deduplication'` — If the same condition holds for the sequence of events, then such repeating event interrupts further processing.
|
||||
- `'strict_order'` — Don't allow interventions of other events. E.g. in the case of `A->B->D->C`, it stops finding `A->B->C` at the `D` and the max event level is 2.
|
||||
- `'strict_increase'` — Apply conditions only to events with strictly increasing timestamps.
|
||||
|
||||
|
@ -143,7 +143,9 @@ It works faster than intHash32. Average quality.
|
||||
|
||||
## SHA256 {#sha256}
|
||||
|
||||
Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
|
||||
## SHA512 {#sha512}
|
||||
|
||||
Calculates SHA-1, SHA-224, SHA-256 or SHA-512 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), FixedString(32), or FixedString(64).
|
||||
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million).
|
||||
We recommend using this function only in cases when you need a specific hash function and you can’t select it.
|
||||
Even in these cases, we recommend applying the function offline and pre-calculating values when inserting them into the table, instead of applying it in SELECTS.
|
||||
|
@ -6,7 +6,7 @@ toc_title: JOIN
|
||||
|
||||
Join produces a new table by combining columns from one or multiple tables by using values common to each. It is a common operation in databases with SQL support, which corresponds to [relational algebra](https://en.wikipedia.org/wiki/Relational_algebra#Joins_and_join-like_operators) join. The special case of one table join is often referred to as “self-join”.
|
||||
|
||||
Syntax:
|
||||
**Syntax**
|
||||
|
||||
``` sql
|
||||
SELECT <expr_list>
|
||||
@ -38,7 +38,7 @@ Additional join types available in ClickHouse:
|
||||
|
||||
## Settings {#join-settings}
|
||||
|
||||
The default join type can be overriden using [join_default_strictness](../../../operations/settings/settings.md#settings-join_default_strictness) setting.
|
||||
The default join type can be overridden using [join_default_strictness](../../../operations/settings/settings.md#settings-join_default_strictness) setting.
|
||||
|
||||
The behavior of ClickHouse server for `ANY JOIN` operations depends on the [any_join_distinct_right_table_keys](../../../operations/settings/settings.md#any_join_distinct_right_table_keys) setting.
|
||||
|
||||
@ -52,6 +52,61 @@ The behavior of ClickHouse server for `ANY JOIN` operations depends on the [any_
|
||||
- [join_on_disk_max_files_to_merge](../../../operations/settings/settings.md#join_on_disk_max_files_to_merge)
|
||||
- [any_join_distinct_right_table_keys](../../../operations/settings/settings.md#any_join_distinct_right_table_keys)
|
||||
|
||||
## ON Section Conditions {on-section-conditions}
|
||||
|
||||
An `ON` section can contain several conditions combined using the `AND` operator. Conditions specifying join keys must refer both left and right tables and must use the equality operator. Other conditions may use other logical operators but they must refer either the left or the right table of a query.
|
||||
Rows are joined if the whole complex condition is met. If the conditions are not met, still rows may be included in the result depending on the `JOIN` type. Note that if the same conditions are placed in a `WHERE` section and they are not met, then rows are always filtered out from the result.
|
||||
|
||||
!!! note "Note"
|
||||
The `OR` operator inside an `ON` section is not supported yet.
|
||||
|
||||
!!! note "Note"
|
||||
If a condition refers columns from different tables, then only the equality operator (`=`) is supported so far.
|
||||
|
||||
**Example**
|
||||
|
||||
Consider `table_1` and `table_2`:
|
||||
|
||||
```
|
||||
┌─Id─┬─name─┐ ┌─Id─┬─text───────────┬─scores─┐
|
||||
│ 1 │ A │ │ 1 │ Text A │ 10 │
|
||||
│ 2 │ B │ │ 1 │ Another text A │ 12 │
|
||||
│ 3 │ C │ │ 2 │ Text B │ 15 │
|
||||
└────┴──────┘ └────┴────────────────┴────────┘
|
||||
```
|
||||
|
||||
Query with one join key condition and an additional condition for `table_2`:
|
||||
|
||||
``` sql
|
||||
SELECT name, text FROM table_1 LEFT OUTER JOIN table_2
|
||||
ON table_1.Id = table_2.Id AND startsWith(table_2.text, 'Text');
|
||||
```
|
||||
|
||||
Note that the result contains the row with the name `C` and the empty text column. It is included into the result because an `OUTER` type of a join is used.
|
||||
|
||||
```
|
||||
┌─name─┬─text───┐
|
||||
│ A │ Text A │
|
||||
│ B │ Text B │
|
||||
│ C │ │
|
||||
└──────┴────────┘
|
||||
```
|
||||
|
||||
Query with `INNER` type of a join and multiple conditions:
|
||||
|
||||
``` sql
|
||||
SELECT name, text, scores FROM table_1 INNER JOIN table_2
|
||||
ON table_1.Id = table_2.Id AND table_2.scores > 10 AND startsWith(table_2.text, 'Text');
|
||||
```
|
||||
|
||||
Result:
|
||||
|
||||
```
|
||||
┌─name─┬─text───┬─scores─┐
|
||||
│ B │ Text B │ 15 │
|
||||
└──────┴────────┴────────┘
|
||||
```
|
||||
|
||||
## ASOF JOIN Usage {#asof-join-usage}
|
||||
|
||||
`ASOF JOIN` is useful when you need to join records that have no exact match.
|
||||
@ -59,7 +114,7 @@ The behavior of ClickHouse server for `ANY JOIN` operations depends on the [any_
|
||||
Algorithm requires the special column in tables. This column:
|
||||
|
||||
- Must contain an ordered sequence.
|
||||
- Can be one of the following types: [Int*, UInt*](../../../sql-reference/data-types/int-uint.md), [Float\*](../../../sql-reference/data-types/float.md), [Date](../../../sql-reference/data-types/date.md), [DateTime](../../../sql-reference/data-types/datetime.md), [Decimal\*](../../../sql-reference/data-types/decimal.md).
|
||||
- Can be one of the following types: [Int, UInt](../../../sql-reference/data-types/int-uint.md), [Float](../../../sql-reference/data-types/float.md), [Date](../../../sql-reference/data-types/date.md), [DateTime](../../../sql-reference/data-types/datetime.md), [Decimal](../../../sql-reference/data-types/decimal.md).
|
||||
- Can’t be the only column in the `JOIN` clause.
|
||||
|
||||
Syntax `ASOF JOIN ... ON`:
|
||||
@ -84,7 +139,7 @@ ASOF JOIN table_2
|
||||
USING (equi_column1, ... equi_columnN, asof_column)
|
||||
```
|
||||
|
||||
`ASOF JOIN` uses `equi_columnX` for joining on equality and `asof_column` for joining on the closest match with the `table_1.asof_column >= table_2.asof_column` condition. The `asof_column` column always the last one in the `USING` clause.
|
||||
`ASOF JOIN` uses `equi_columnX` for joining on equality and `asof_column` for joining on the closest match with the `table_1.asof_column >= table_2.asof_column` condition. The `asof_column` column is always the last one in the `USING` clause.
|
||||
|
||||
For example, consider the following tables:
|
||||
|
||||
|
@ -34,5 +34,6 @@ You can use table functions in:
|
||||
| [odbc](../../sql-reference/table-functions/odbc.md) | Creates a [ODBC](../../engines/table-engines/integrations/odbc.md)-engine table. |
|
||||
| [hdfs](../../sql-reference/table-functions/hdfs.md) | Creates a [HDFS](../../engines/table-engines/integrations/hdfs.md)-engine table. |
|
||||
| [s3](../../sql-reference/table-functions/s3.md) | Creates a [S3](../../engines/table-engines/integrations/s3.md)-engine table. |
|
||||
| [sqlite](../../sql-reference/table-functions/sqlite.md) | Creates a [sqlite](../../engines/table-engines/integrations/sqlite.md)-engine table. |
|
||||
|
||||
[Original article](https://clickhouse.tech/docs/en/sql-reference/table-functions/) <!--hide-->
|
||||
|
45
docs/en/sql-reference/table-functions/sqlite.md
Normal file
45
docs/en/sql-reference/table-functions/sqlite.md
Normal file
@ -0,0 +1,45 @@
|
||||
---
|
||||
toc_priority: 55
|
||||
toc_title: sqlite
|
||||
---
|
||||
|
||||
## sqlite {#sqlite}
|
||||
|
||||
Allows to perform queries on a data stored in an [SQLite](../../engines/database-engines/sqlite.md) database.
|
||||
|
||||
**Syntax**
|
||||
|
||||
``` sql
|
||||
sqlite('db_path', 'table_name')
|
||||
```
|
||||
|
||||
**Arguments**
|
||||
|
||||
- `db_path` — Path to a file with an SQLite database. [String](../../sql-reference/data-types/string.md).
|
||||
- `table_name` — Name of a table in the SQLite database. [String](../../sql-reference/data-types/string.md).
|
||||
|
||||
**Returned value**
|
||||
|
||||
- A table object with the same columns as in the original `SQLite` table.
|
||||
|
||||
**Example**
|
||||
|
||||
Query:
|
||||
|
||||
``` sql
|
||||
SELECT * FROM sqlite('sqlite.db', 'table1') ORDER BY col2;
|
||||
```
|
||||
|
||||
Result:
|
||||
|
||||
``` text
|
||||
┌─col1──┬─col2─┐
|
||||
│ line1 │ 1 │
|
||||
│ line2 │ 2 │
|
||||
│ line3 │ 3 │
|
||||
└───────┴──────┘
|
||||
```
|
||||
|
||||
**See Also**
|
||||
|
||||
- [SQLite](../../engines/table-engines/integrations/sqlite.md) table engine
|
79
docs/ru/engines/database-engines/sqlite.md
Normal file
79
docs/ru/engines/database-engines/sqlite.md
Normal file
@ -0,0 +1,79 @@
|
||||
---
|
||||
toc_priority: 32
|
||||
toc_title: SQLite
|
||||
---
|
||||
|
||||
# SQLite {#sqlite}
|
||||
|
||||
Движок баз данных позволяет подключаться к базе [SQLite](https://www.sqlite.org/index.html) и выполнять запросы `INSERT` и `SELECT` для обмена данными между ClickHouse и SQLite.
|
||||
|
||||
## Создание базы данных {#creating-a-database}
|
||||
|
||||
``` sql
|
||||
CREATE DATABASE sqlite_database
|
||||
ENGINE = SQLite('db_path')
|
||||
```
|
||||
|
||||
**Параметры движка**
|
||||
|
||||
- `db_path` — путь к файлу с базой данных SQLite.
|
||||
|
||||
## Поддерживаемые типы данных {#data_types-support}
|
||||
|
||||
| SQLite | ClickHouse |
|
||||
|---------------|---------------------------------------------------------|
|
||||
| INTEGER | [Int32](../../sql-reference/data-types/int-uint.md) |
|
||||
| REAL | [Float32](../../sql-reference/data-types/float.md) |
|
||||
| TEXT | [String](../../sql-reference/data-types/string.md) |
|
||||
| BLOB | [String](../../sql-reference/data-types/string.md) |
|
||||
|
||||
## Особенности и рекомендации {#specifics-and-recommendations}
|
||||
|
||||
SQLite хранит всю базу данных (определения, таблицы, индексы и сами данные) в виде единого кроссплатформенного файла на хост-машине. Во время записи SQLite блокирует весь файл базы данных, поэтому операции записи выполняются последовательно. Операции чтения могут быть многозадачными.
|
||||
SQLite не требует управления службами (например, сценариями запуска) или контроля доступа на основе `GRANT` и паролей. Контроль доступа осуществляется с помощью разрешений файловой системы, предоставляемых самому файлу базы данных.
|
||||
|
||||
## Примеры использования {#usage-example}
|
||||
|
||||
Отобразим список таблиц базы данных в ClickHouse, подключенной к SQLite:
|
||||
|
||||
``` sql
|
||||
CREATE DATABASE sqlite_db ENGINE = SQLite('sqlite.db');
|
||||
SHOW TABLES FROM sqlite_db;
|
||||
```
|
||||
|
||||
``` text
|
||||
┌──name───┐
|
||||
│ table1 │
|
||||
│ table2 │
|
||||
└─────────┘
|
||||
```
|
||||
Отобразим содержимое таблицы:
|
||||
|
||||
``` sql
|
||||
SELECT * FROM sqlite_db.table1;
|
||||
```
|
||||
|
||||
``` text
|
||||
┌─col1──┬─col2─┐
|
||||
│ line1 │ 1 │
|
||||
│ line2 │ 2 │
|
||||
│ line3 │ 3 │
|
||||
└───────┴──────┘
|
||||
```
|
||||
Вставим данные в таблицу SQLite из таблицы ClickHouse:
|
||||
|
||||
``` sql
|
||||
CREATE TABLE clickhouse_table(`col1` String,`col2` Int16) ENGINE = MergeTree() ORDER BY col2;
|
||||
INSERT INTO clickhouse_table VALUES ('text',10);
|
||||
INSERT INTO sqlite_db.table1 SELECT * FROM clickhouse_table;
|
||||
SELECT * FROM sqlite_db.table1;
|
||||
```
|
||||
|
||||
``` text
|
||||
┌─col1──┬─col2─┐
|
||||
│ line1 │ 1 │
|
||||
│ line2 │ 2 │
|
||||
│ line3 │ 3 │
|
||||
│ text │ 10 │
|
||||
└───────┴──────┘
|
||||
```
|
59
docs/ru/engines/table-engines/integrations/sqlite.md
Normal file
59
docs/ru/engines/table-engines/integrations/sqlite.md
Normal file
@ -0,0 +1,59 @@
|
||||
---
|
||||
toc_priority: 7
|
||||
toc_title: SQLite
|
||||
---
|
||||
|
||||
# SQLite {#sqlite}
|
||||
|
||||
Движок позволяет импортировать и экспортировать данные из SQLite, а также поддерживает отправку запросов к таблицам SQLite напрямую из ClickHouse.
|
||||
|
||||
## Создание таблицы {#creating-a-table}
|
||||
|
||||
``` sql
|
||||
CREATE TABLE [IF NOT EXISTS] [db.]table_name
|
||||
(
|
||||
name1 [type1],
|
||||
name2 [type2], ...
|
||||
) ENGINE = SQLite('db_path', 'table')
|
||||
```
|
||||
|
||||
**Параметры движка**
|
||||
|
||||
- `db_path` — путь к файлу с базой данных SQLite.
|
||||
- `table` — имя таблицы в базе данных SQLite.
|
||||
|
||||
## Примеры использования {#usage-example}
|
||||
|
||||
Отобразим запрос, с помощью которого была создана таблица SQLite:
|
||||
|
||||
```sql
|
||||
SHOW CREATE TABLE sqlite_db.table2;
|
||||
```
|
||||
|
||||
``` text
|
||||
CREATE TABLE SQLite.table2
|
||||
(
|
||||
`col1` Nullable(Int32),
|
||||
`col2` Nullable(String)
|
||||
)
|
||||
ENGINE = SQLite('sqlite.db','table2');
|
||||
```
|
||||
|
||||
Получим данные из таблицы:
|
||||
|
||||
``` sql
|
||||
SELECT * FROM sqlite_db.table2 ORDER BY col1;
|
||||
```
|
||||
|
||||
```text
|
||||
┌─col1─┬─col2──┐
|
||||
│ 1 │ text1 │
|
||||
│ 2 │ text2 │
|
||||
│ 3 │ text3 │
|
||||
└──────┴───────┘
|
||||
```
|
||||
|
||||
**См. также**
|
||||
|
||||
- [SQLite](../../../engines/database-engines/sqlite.md) движок баз данных
|
||||
- [sqlite](../../../sql-reference/table-functions/sqlite.md) табличная функция
|
@ -6,7 +6,7 @@ toc_title: JOIN
|
||||
|
||||
`JOIN` создаёт новую таблицу путем объединения столбцов из одной или нескольких таблиц с использованием общих для каждой из них значений. Это обычная операция в базах данных с поддержкой SQL, которая соответствует join из [реляционной алгебры](https://en.wikipedia.org/wiki/Relational_algebra#Joins_and_join-like_operators). Частный случай соединения одной таблицы часто называют self-join.
|
||||
|
||||
Синтаксис:
|
||||
**Синтаксис**
|
||||
|
||||
``` sql
|
||||
SELECT <expr_list>
|
||||
@ -19,7 +19,7 @@ FROM <left_table>
|
||||
|
||||
## Поддерживаемые типы соединения {#select-join-types}
|
||||
|
||||
Все типы из стандартого [SQL JOIN](https://en.wikipedia.org/wiki/Join_(SQL)) поддерживаются:
|
||||
Все типы из стандартного [SQL JOIN](https://en.wikipedia.org/wiki/Join_(SQL)) поддерживаются:
|
||||
|
||||
- `INNER JOIN`, возвращаются только совпадающие строки.
|
||||
- `LEFT OUTER JOIN`, не совпадающие строки из левой таблицы возвращаются в дополнение к совпадающим строкам.
|
||||
@ -33,7 +33,7 @@ FROM <left_table>
|
||||
|
||||
- `LEFT SEMI JOIN` и `RIGHT SEMI JOIN`, белый список по ключам соединения, не производит декартово произведение.
|
||||
- `LEFT ANTI JOIN` и `RIGHT ANTI JOIN`, черный список по ключам соединения, не производит декартово произведение.
|
||||
- `LEFT ANY JOIN`, `RIGHT ANY JOIN` и `INNER ANY JOIN`, Частично (для противоположных сторон `LEFT` и `RIGHT`) или полностью (для `INNER` и `FULL`) отключает декартово произведение для стандартых видов `JOIN`.
|
||||
- `LEFT ANY JOIN`, `RIGHT ANY JOIN` и `INNER ANY JOIN`, Частично (для противоположных сторон `LEFT` и `RIGHT`) или полностью (для `INNER` и `FULL`) отключает декартово произведение для стандартных видов `JOIN`.
|
||||
- `ASOF JOIN` и `LEFT ASOF JOIN`, Для соединения последовательностей по нечеткому совпадению. Использование `ASOF JOIN` описано ниже.
|
||||
|
||||
## Настройки {#join-settings}
|
||||
@ -52,6 +52,61 @@ FROM <left_table>
|
||||
- [join_on_disk_max_files_to_merge](../../../operations/settings/settings.md#join_on_disk_max_files_to_merge)
|
||||
- [any_join_distinct_right_table_keys](../../../operations/settings/settings.md#any_join_distinct_right_table_keys)
|
||||
|
||||
## Условия в секции ON {on-section-conditions}
|
||||
|
||||
Секция `ON` может содержать несколько условий, связанных оператором `AND`. Условия, задающие ключи соединения, должны содержать столбцы левой и правой таблицы и должны использовать оператор равенства. Прочие условия могут использовать другие логические операторы, но в отдельном условии могут использоваться столбцы либо только левой, либо только правой таблицы.
|
||||
Строки объединяются только тогда, когда всё составное условие выполнено. Если оно не выполнено, то строки могут попасть в результат в зависимости от типа `JOIN`. Обратите внимание, что если то же самое условие поместить в секцию `WHERE`, то строки, для которых оно не выполняется, никогда не попаду в результат.
|
||||
|
||||
!!! note "Примечание"
|
||||
Оператор `OR` внутри секции `ON` пока не поддерживается.
|
||||
|
||||
!!! note "Примечание"
|
||||
Если в условии использованы столбцы из разных таблиц, то пока поддерживается только оператор равенства (`=`).
|
||||
|
||||
**Пример**
|
||||
|
||||
Рассмотрим `table_1` и `table_2`:
|
||||
|
||||
```
|
||||
┌─Id─┬─name─┐ ┌─Id─┬─text───────────┬─scores─┐
|
||||
│ 1 │ A │ │ 1 │ Text A │ 10 │
|
||||
│ 2 │ B │ │ 1 │ Another text A │ 12 │
|
||||
│ 3 │ C │ │ 2 │ Text B │ 15 │
|
||||
└────┴──────┘ └────┴────────────────┴────────┘
|
||||
```
|
||||
|
||||
Запрос с одним условием, задающим ключ соединения, и дополнительным условием для `table_2`:
|
||||
|
||||
``` sql
|
||||
SELECT name, text FROM table_1 LEFT OUTER JOIN table_2
|
||||
ON table_1.Id = table_2.Id AND startsWith(table_2.text, 'Text');
|
||||
```
|
||||
|
||||
Обратите внимание, что результат содержит строку с именем `C` и пустым текстом. Строка включена в результат, потому что использован тип соединения `OUTER`.
|
||||
|
||||
```
|
||||
┌─name─┬─text───┐
|
||||
│ A │ Text A │
|
||||
│ B │ Text B │
|
||||
│ C │ │
|
||||
└──────┴────────┘
|
||||
```
|
||||
|
||||
Запрос с типом соединения `INNER` и несколькими условиями:
|
||||
|
||||
``` sql
|
||||
SELECT name, text, scores FROM table_1 INNER JOIN table_2
|
||||
ON table_1.Id = table_2.Id AND table_2.scores > 10 AND startsWith(table_2.text, 'Text');
|
||||
```
|
||||
|
||||
Результат:
|
||||
|
||||
```
|
||||
┌─name─┬─text───┬─scores─┐
|
||||
│ B │ Text B │ 15 │
|
||||
└──────┴────────┴────────┘
|
||||
```
|
||||
|
||||
## Использование ASOF JOIN {#asof-join-usage}
|
||||
|
||||
`ASOF JOIN` применим в том случае, когда необходимо объединять записи, которые не имеют точного совпадения.
|
||||
@ -59,7 +114,7 @@ FROM <left_table>
|
||||
Для работы алгоритма необходим специальный столбец в таблицах. Этот столбец:
|
||||
|
||||
- Должен содержать упорядоченную последовательность.
|
||||
- Может быть одного из следующих типов: [Int*, UInt*](../../data-types/int-uint.md), [Float*](../../data-types/float.md), [Date](../../data-types/date.md), [DateTime](../../data-types/datetime.md), [Decimal*](../../data-types/decimal.md).
|
||||
- Может быть одного из следующих типов: [Int, UInt](../../data-types/int-uint.md), [Float](../../data-types/float.md), [Date](../../data-types/date.md), [DateTime](../../data-types/datetime.md), [Decimal](../../data-types/decimal.md).
|
||||
- Не может быть единственным столбцом в секции `JOIN`.
|
||||
|
||||
Синтаксис `ASOF JOIN ... ON`:
|
||||
|
45
docs/ru/sql-reference/table-functions/sqlite.md
Normal file
45
docs/ru/sql-reference/table-functions/sqlite.md
Normal file
@ -0,0 +1,45 @@
|
||||
---
|
||||
toc_priority: 55
|
||||
toc_title: sqlite
|
||||
---
|
||||
|
||||
## sqlite {#sqlite}
|
||||
|
||||
Позволяет выполнять запросы к данным, хранящимся в базе данных [SQLite](../../engines/database-engines/sqlite.md).
|
||||
|
||||
**Синтаксис**
|
||||
|
||||
``` sql
|
||||
sqlite('db_path', 'table_name')
|
||||
```
|
||||
|
||||
**Аргументы**
|
||||
|
||||
- `db_path` — путь к файлу с базой данных SQLite. [String](../../sql-reference/data-types/string.md).
|
||||
- `table_name` — имя таблицы в базе данных SQLite. [String](../../sql-reference/data-types/string.md).
|
||||
|
||||
**Возвращаемое значение**
|
||||
|
||||
- Объект таблицы с теми же столбцами, что и в исходной таблице `SQLite`.
|
||||
|
||||
**Пример**
|
||||
|
||||
Запрос:
|
||||
|
||||
``` sql
|
||||
SELECT * FROM sqlite('sqlite.db', 'table1') ORDER BY col2;
|
||||
```
|
||||
|
||||
Результат:
|
||||
|
||||
``` text
|
||||
┌─col1──┬─col2─┐
|
||||
│ line1 │ 1 │
|
||||
│ line2 │ 2 │
|
||||
│ line3 │ 3 │
|
||||
└───────┴──────┘
|
||||
```
|
||||
|
||||
**См. также**
|
||||
|
||||
- [SQLite](../../engines/table-engines/integrations/sqlite.md) движок таблиц
|
@ -38,13 +38,13 @@ ENGINE = MySQL('host:port', ['database' | database], 'user', 'password')
|
||||
| BIGINT | [Int64](../../sql-reference/data-types/int-uint.md) |
|
||||
| FLOAT | [Float32](../../sql-reference/data-types/float.md) |
|
||||
| DOUBLE | [Float64](../../sql-reference/data-types/float.md) |
|
||||
| DATE | [日期](../../sql-reference/data-types/date.md) |
|
||||
| DATETIME, TIMESTAMP | [日期时间](../../sql-reference/data-types/datetime.md) |
|
||||
| BINARY | [固定字符串](../../sql-reference/data-types/fixedstring.md) |
|
||||
| DATE | [Date](../../sql-reference/data-types/date.md) |
|
||||
| DATETIME, TIMESTAMP | [DateTime](../../sql-reference/data-types/datetime.md) |
|
||||
| BINARY | [FixedString](../../sql-reference/data-types/fixedstring.md) |
|
||||
|
||||
其他的MySQL数据类型将全部都转换为[字符串](../../sql-reference/data-types/string.md)。
|
||||
其他的MySQL数据类型将全部都转换为[String](../../sql-reference/data-types/string.md)。
|
||||
|
||||
同时以上的所有类型都支持[可为空](../../sql-reference/data-types/nullable.md)。
|
||||
同时以上的所有类型都支持[Nullable](../../sql-reference/data-types/nullable.md)。
|
||||
|
||||
## 使用示例 {#shi-yong-shi-li}
|
||||
|
||||
|
@ -1,8 +1,8 @@
|
||||
# 功能与Yandex的工作。梅特里卡词典 {#functions-for-working-with-yandex-metrica-dictionaries}
|
||||
# 使用 Yandex.Metrica 字典函数 {#functions-for-working-with-yandex-metrica-dictionaries}
|
||||
|
||||
为了使下面的功能正常工作,服务器配置必须指定获取所有Yandex的路径和地址。梅特里卡字典. 字典在任何这些函数的第一次调用时加载。 如果无法加载引用列表,则会引发异常。
|
||||
为了使下面的功能正常工作,服务器配置必须指定获取所有 Yandex.Metrica 字典的路径和地址。Yandex.Metrica 字典在任何这些函数的第一次调用时加载。 如果无法加载引用列表,则会引发异常。
|
||||
|
||||
For information about creating reference lists, see the section «Dictionaries».
|
||||
有关创建引用列表的信息,请参阅 «字典» 部分.
|
||||
|
||||
## 多个地理基 {#multiple-geobases}
|
||||
|
||||
@ -17,18 +17,18 @@ ClickHouse支持同时使用多个备选地理基(区域层次结构),以
|
||||
|
||||
所有字典都在运行时重新加载(每隔一定数量的秒重新加载一次,如builtin_dictionaries_reload_interval config参数中定义,或默认情况下每小时一次)。 但是,可用字典列表在服务器启动时定义一次。
|
||||
|
||||
All functions for working with regions have an optional argument at the end – the dictionary key. It is referred to as the geobase.
|
||||
所有处理区域的函数都在末尾有一个可选参数—字典键。它被称为地基。
|
||||
示例:
|
||||
|
||||
regionToCountry(RegionID) – Uses the default dictionary: /opt/geo/regions_hierarchy.txt
|
||||
regionToCountry(RegionID, '') – Uses the default dictionary: /opt/geo/regions_hierarchy.txt
|
||||
regionToCountry(RegionID, 'ua') – Uses the dictionary for the 'ua' key: /opt/geo/regions_hierarchy_ua.txt
|
||||
regionToCountry(RegionID) – 使用默认路径: /opt/geo/regions_hierarchy.txt
|
||||
regionToCountry(RegionID, '') – 使用默认路径: /opt/geo/regions_hierarchy.txt
|
||||
regionToCountry(RegionID, 'ua') – 使用字典中的'ua' 键: /opt/geo/regions_hierarchy_ua.txt
|
||||
|
||||
### ツ环板(ョツ嘉ッツ偲青regionシツ氾カツ鉄ツ工ツ渉\]) {#regiontocityid-geobase}
|
||||
### regionToCity(id[, geobase]) {#regiontocityid-geobase}
|
||||
|
||||
Accepts a UInt32 number – the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0.
|
||||
从 Yandex geobase 接收一个 UInt32 数字类型的区域ID 。如果该区域是一个城市或城市的一部分,它将返回相应城市的区域ID。否则,返回0。
|
||||
|
||||
### 虏茅驴麓卤戮碌禄路戮鲁拢\]) {#regiontoareaid-geobase}
|
||||
### regionToArea(id[, geobase]) {#regiontoareaid-geobase}
|
||||
|
||||
将区域转换为区域(地理数据库中的类型5)。 在所有其他方式,这个功能是一样的 ‘regionToCity’.
|
||||
|
||||
@ -84,36 +84,58 @@ LIMIT 15
|
||||
│ Federation of Bosnia and Herzegovina │
|
||||
└──────────────────────────────────────────────────────────┘
|
||||
|
||||
### 虏茅驴麓卤戮碌禄路戮鲁拢(陆毛隆隆(803)888-8325\]) {#regiontocountryid-geobase}
|
||||
### regionToCountry(id[, geobase]) {#regiontocountryid-geobase}
|
||||
|
||||
将区域转换为国家。 在所有其他方式,这个功能是一样的 ‘regionToCity’.
|
||||
示例: `regionToCountry(toUInt32(213)) = 225` 转换莫斯科(213)到俄罗斯(225)。
|
||||
|
||||
### 掳胫((禄脢鹿脷露胫鲁隆鹿((酶-11-16""\[脪陆,ase\]) {#regiontocontinentid-geobase}
|
||||
### regionToContinent(id[, geobase]) {#regiontocontinentid-geobase}
|
||||
|
||||
将区域转换为大陆。 在所有其他方式,这个功能是一样的 ‘regionToCity’.
|
||||
示例: `regionToContinent(toUInt32(213)) = 10001` 将莫斯科(213)转换为欧亚大陆(10001)。
|
||||
|
||||
### ツ环板(ョツ嘉ッツ偲青regionャツ静ャツ青サツ催ャツ渉\]) {#regiontopopulationid-geobase}
|
||||
### regionToTopContinent (#regiontotopcontinent) {#regiontotopcontinent-regiontotopcontinent}
|
||||
|
||||
查找该区域层次结构中最高的大陆。
|
||||
|
||||
**语法**
|
||||
|
||||
``` sql
|
||||
regionToTopContinent(id[, geobase])
|
||||
```
|
||||
|
||||
**参数**
|
||||
|
||||
- `id` — Yandex geobase 的区域 ID. [UInt32](../../sql-reference/data-types/int-uint.md).
|
||||
- `geobase` — 字典的建. 参阅 [Multiple Geobases](#multiple-geobases). [String](../../sql-reference/data-types/string.md). 可选.
|
||||
|
||||
**返回值**
|
||||
|
||||
- 顶级大陆的标识符(当您在区域层次结构中攀爬时,是后者)。
|
||||
- 0,如果没有。
|
||||
|
||||
类型: `UInt32`.
|
||||
|
||||
### regionToPopulation(id\[, geobase\]) {#regiontopopulationid-geobase}
|
||||
|
||||
获取区域的人口。
|
||||
The population can be recorded in files with the geobase. See the section «External dictionaries».
|
||||
人口可以记录在文件与地球基。请参阅«外部词典»部分。
|
||||
如果没有为该区域记录人口,则返回0。
|
||||
在Yandex地理数据库中,可能会为子区域记录人口,但不会为父区域记录人口。
|
||||
|
||||
### regionIn(lhs,rhs\[,地理数据库\]) {#regioninlhs-rhs-geobase}
|
||||
|
||||
检查是否 ‘lhs’ 属于一个区域 ‘rhs’ 区域。 如果属于UInt8,则返回等于1的数字,如果不属于则返回0。
|
||||
The relationship is reflexive – any region also belongs to itself.
|
||||
这种关系是反射的——任何地区也属于自己。
|
||||
|
||||
### ツ暗ェツ氾环催ツ団ツ法ツ人\]) {#regionhierarchyid-geobase}
|
||||
### regionHierarchy(id\[, geobase\]) {#regionhierarchyid-geobase}
|
||||
|
||||
Accepts a UInt32 number – the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
|
||||
从 Yandex geobase 接收一个 UInt32 数字类型的区域ID。返回一个区域ID数组,由传递的区域和链上的所有父节点组成。
|
||||
示例: `regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]`.
|
||||
|
||||
### 地区名称(id\[,郎\]) {#regiontonameid-lang}
|
||||
### regionToName(id\[, lang\]) {#regiontonameid-lang}
|
||||
|
||||
Accepts a UInt32 number – the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language ‘ru’ is used. If the language is not supported, an exception is thrown. Returns a string – the name of the region in the corresponding language. If the region with the specified ID doesn’t exist, an empty string is returned.
|
||||
从 Yandex geobase 接收一个 UInt32 数字类型的区域ID。带有语言名称的字符串可以作为第二个参数传递。支持的语言有:ru, en, ua, uk, by, kz, tr。如果省略第二个参数,则使用' ru '语言。如果不支持该语言,则抛出异常。返回一个字符串-对应语言的区域名称。如果指定ID的区域不存在,则返回一个空字符串。
|
||||
|
||||
`ua` 和 `uk` 都意味着乌克兰。
|
||||
|
||||
|
@ -129,6 +129,7 @@ namespace ErrorCodes
|
||||
extern const int UNRECOGNIZED_ARGUMENTS;
|
||||
extern const int SYNTAX_ERROR;
|
||||
extern const int TOO_DEEP_RECURSION;
|
||||
extern const int AUTHENTICATION_FAILED;
|
||||
}
|
||||
|
||||
|
||||
@ -773,31 +774,50 @@ private:
|
||||
<< connection_parameters.host << ":" << connection_parameters.port
|
||||
<< (!connection_parameters.user.empty() ? " as user " + connection_parameters.user : "") << "." << std::endl;
|
||||
|
||||
connection = std::make_unique<Connection>(
|
||||
connection_parameters.host,
|
||||
connection_parameters.port,
|
||||
connection_parameters.default_database,
|
||||
connection_parameters.user,
|
||||
connection_parameters.password,
|
||||
"", /* cluster */
|
||||
"", /* cluster_secret */
|
||||
"client",
|
||||
connection_parameters.compression,
|
||||
connection_parameters.security);
|
||||
|
||||
String server_name;
|
||||
UInt64 server_version_major = 0;
|
||||
UInt64 server_version_minor = 0;
|
||||
UInt64 server_version_patch = 0;
|
||||
|
||||
if (max_client_network_bandwidth)
|
||||
try
|
||||
{
|
||||
ThrottlerPtr throttler = std::make_shared<Throttler>(max_client_network_bandwidth, 0, "");
|
||||
connection->setThrottler(throttler);
|
||||
}
|
||||
connection = std::make_unique<Connection>(
|
||||
connection_parameters.host,
|
||||
connection_parameters.port,
|
||||
connection_parameters.default_database,
|
||||
connection_parameters.user,
|
||||
connection_parameters.password,
|
||||
"", /* cluster */
|
||||
"", /* cluster_secret */
|
||||
"client",
|
||||
connection_parameters.compression,
|
||||
connection_parameters.security);
|
||||
|
||||
connection->getServerVersion(
|
||||
connection_parameters.timeouts, server_name, server_version_major, server_version_minor, server_version_patch, server_revision);
|
||||
if (max_client_network_bandwidth)
|
||||
{
|
||||
ThrottlerPtr throttler = std::make_shared<Throttler>(max_client_network_bandwidth, 0, "");
|
||||
connection->setThrottler(throttler);
|
||||
}
|
||||
|
||||
connection->getServerVersion(
|
||||
connection_parameters.timeouts, server_name, server_version_major, server_version_minor, server_version_patch, server_revision);
|
||||
}
|
||||
catch (const Exception & e)
|
||||
{
|
||||
/// It is typical when users install ClickHouse, type some password and instantly forget it.
|
||||
if ((connection_parameters.user.empty() || connection_parameters.user == "default")
|
||||
&& e.code() == DB::ErrorCodes::AUTHENTICATION_FAILED)
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "If you have installed ClickHouse and forgot password you can reset it in the configuration file." << std::endl
|
||||
<< "The password for default user is typically located at /etc/clickhouse-server/users.d/default-password.xml" << std::endl
|
||||
<< "and deleting this file will reset the password." << std::endl
|
||||
<< "See also /etc/clickhouse-server/users.xml on the server where ClickHouse is installed." << std::endl
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
server_version = toString(server_version_major) + "." + toString(server_version_minor) + "." + toString(server_version_patch);
|
||||
|
||||
|
@ -55,7 +55,6 @@
|
||||
#include <Interpreters/InterserverCredentials.h>
|
||||
#include <Interpreters/UserDefinedObjectsLoader.h>
|
||||
#include <Interpreters/JIT/CompiledExpressionCache.h>
|
||||
#include <Interpreters/Session.h>
|
||||
#include <Access/AccessControlManager.h>
|
||||
#include <Storages/StorageReplicatedMergeTree.h>
|
||||
#include <Storages/System/attachSystemTables.h>
|
||||
@ -359,6 +358,7 @@ void Server::createServer(const std::string & listen_host, const char * port_nam
|
||||
try
|
||||
{
|
||||
func(port);
|
||||
global_context->registerServerPort(port_name, port);
|
||||
}
|
||||
catch (const Poco::Exception &)
|
||||
{
|
||||
@ -1445,7 +1445,6 @@ if (ThreadFuzzer::instance().isEffective())
|
||||
|
||||
/// Must be done after initialization of `servers`, because async_metrics will access `servers` variable from its thread.
|
||||
async_metrics.start();
|
||||
Session::startupNamedSessions();
|
||||
|
||||
{
|
||||
String level_str = config().getString("text_log.level", "");
|
||||
|
@ -137,8 +137,8 @@ class AggregateFunctionWindowFunnel final
|
||||
private:
|
||||
UInt64 window;
|
||||
UInt8 events_size;
|
||||
/// When the 'strict' is set, it applies conditions only for the not repeating values.
|
||||
bool strict;
|
||||
/// When the 'strict_deduplication' is set, it applies conditions only for the not repeating values.
|
||||
bool strict_deduplication;
|
||||
|
||||
/// When the 'strict_order' is set, it doesn't allow interventions of other events.
|
||||
/// In the case of 'A->B->D->C', it stops finding 'A->B->C' at the 'D' and the max event level is 2.
|
||||
@ -150,7 +150,7 @@ private:
|
||||
/// Loop through the entire events_list, update the event timestamp value
|
||||
/// The level path must be 1---2---3---...---check_events_size, find the max event level that satisfied the path in the sliding window.
|
||||
/// If found, returns the max event level, else return 0.
|
||||
/// The Algorithm complexity is O(n).
|
||||
/// The algorithm works in O(n) time, but the overall function works in O(n * log(n)) due to sorting.
|
||||
UInt8 getEventLevel(Data & data) const
|
||||
{
|
||||
if (data.size() == 0)
|
||||
@ -163,10 +163,10 @@ private:
|
||||
/// events_timestamp stores the timestamp of the first and previous i-th level event happen within time window
|
||||
std::vector<std::optional<std::pair<UInt64, UInt64>>> events_timestamp(events_size);
|
||||
bool first_event = false;
|
||||
for (const auto & pair : data.events_list)
|
||||
for (size_t i = 0; i < data.events_list.size(); ++i)
|
||||
{
|
||||
const T & timestamp = pair.first;
|
||||
const auto & event_idx = pair.second - 1;
|
||||
const T & timestamp = data.events_list[i].first;
|
||||
const auto & event_idx = data.events_list[i].second - 1;
|
||||
if (strict_order && event_idx == -1)
|
||||
{
|
||||
if (first_event)
|
||||
@ -179,9 +179,9 @@ private:
|
||||
events_timestamp[0] = std::make_pair(timestamp, timestamp);
|
||||
first_event = true;
|
||||
}
|
||||
else if (strict && events_timestamp[event_idx].has_value())
|
||||
else if (strict_deduplication && events_timestamp[event_idx].has_value())
|
||||
{
|
||||
return event_idx + 1;
|
||||
return data.events_list[i - 1].second;
|
||||
}
|
||||
else if (strict_order && first_event && !events_timestamp[event_idx - 1].has_value())
|
||||
{
|
||||
@ -226,18 +226,20 @@ public:
|
||||
events_size = arguments.size() - 1;
|
||||
window = params.at(0).safeGet<UInt64>();
|
||||
|
||||
strict = false;
|
||||
strict_deduplication = false;
|
||||
strict_order = false;
|
||||
strict_increase = false;
|
||||
for (size_t i = 1; i < params.size(); ++i)
|
||||
{
|
||||
String option = params.at(i).safeGet<String>();
|
||||
if (option == "strict")
|
||||
strict = true;
|
||||
if (option == "strict_deduplication")
|
||||
strict_deduplication = true;
|
||||
else if (option == "strict_order")
|
||||
strict_order = true;
|
||||
else if (option == "strict_increase")
|
||||
strict_increase = true;
|
||||
else if (option == "strict")
|
||||
throw Exception{"strict is replaced with strict_deduplication in Aggregate function " + getName(), ErrorCodes::BAD_ARGUMENTS};
|
||||
else
|
||||
throw Exception{"Aggregate function " + getName() + " doesn't support a parameter: " + option, ErrorCodes::BAD_ARGUMENTS};
|
||||
}
|
||||
|
@ -304,7 +304,7 @@ size_t ColumnUnique<ColumnType>::uniqueInsert(const Field & x)
|
||||
if (x.getType() == Field::Types::Null)
|
||||
return getNullValueIndex();
|
||||
|
||||
if (isNumeric())
|
||||
if (valuesHaveFixedSize())
|
||||
return uniqueInsertData(&x.reinterpret<char>(), size_of_value_if_fixed);
|
||||
|
||||
auto & val = x.get<String>();
|
||||
|
@ -80,8 +80,3 @@ target_link_libraries (average PRIVATE clickhouse_common_io)
|
||||
|
||||
add_executable (shell_command_inout shell_command_inout.cpp)
|
||||
target_link_libraries (shell_command_inout PRIVATE clickhouse_common_io)
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_executable(YAML_fuzzer YAML_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(YAML_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
||||
endif ()
|
||||
|
@ -1,39 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <cstdio>
|
||||
#include <time.h>
|
||||
#include <filesystem>
|
||||
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t * data, size_t size)
|
||||
{
|
||||
/// How to test:
|
||||
/// build ClickHouse with YAML_fuzzer.cpp
|
||||
/// ./YAML_fuzzer YAML_CORPUS
|
||||
/// where YAML_CORPUS is a directory with different YAML configs for libfuzzer
|
||||
char file_name[L_tmpnam];
|
||||
if (!std::tmpnam(file_name))
|
||||
{
|
||||
std::cerr << "Cannot create temp file!\n";
|
||||
return 1;
|
||||
}
|
||||
std::string input = std::string(reinterpret_cast<const char*>(data), size);
|
||||
DB::YAMLParser parser;
|
||||
|
||||
{
|
||||
std::ofstream temp_file(file_name);
|
||||
temp_file << input;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
DB::YAMLParser::parse(std::string(file_name));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::cerr << "YAML_fuzzer failed: " << getCurrentExceptionMessage() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
@ -1,3 +1,18 @@
|
||||
if(ENABLE_EXAMPLES)
|
||||
if (ENABLE_FUZZING)
|
||||
include("${ClickHouse_SOURCE_DIR}/cmake/dbms_glob_sources.cmake")
|
||||
add_headers_and_sources(fuzz_compression .)
|
||||
|
||||
# Remove this file, because it has dependencies on DataTypes
|
||||
list(REMOVE_ITEM ${fuzz_compression_sources} CompressionFactoryAdditions.cpp)
|
||||
|
||||
add_library(fuzz_compression ${fuzz_compression_headers} ${fuzz_compression_sources})
|
||||
target_link_libraries(fuzz_compression PUBLIC clickhouse_parsers clickhouse_common_io common lz4)
|
||||
endif()
|
||||
|
||||
if (ENABLE_EXAMPLES)
|
||||
add_subdirectory(examples)
|
||||
endif()
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_subdirectory(fuzzers)
|
||||
endif()
|
||||
|
@ -22,13 +22,10 @@ namespace ErrorCodes
|
||||
{
|
||||
extern const int LOGICAL_ERROR;
|
||||
extern const int UNKNOWN_CODEC;
|
||||
extern const int BAD_ARGUMENTS;
|
||||
extern const int UNEXPECTED_AST_STRUCTURE;
|
||||
extern const int DATA_TYPE_CANNOT_HAVE_ARGUMENTS;
|
||||
}
|
||||
|
||||
static constexpr auto DEFAULT_CODEC_NAME = "Default";
|
||||
|
||||
CompressionCodecPtr CompressionCodecFactory::getDefaultCodec() const
|
||||
{
|
||||
return default_codec;
|
||||
@ -49,184 +46,6 @@ CompressionCodecPtr CompressionCodecFactory::get(const String & family_name, std
|
||||
}
|
||||
}
|
||||
|
||||
void CompressionCodecFactory::validateCodec(
|
||||
const String & family_name, std::optional<int> level, bool sanity_check, bool allow_experimental_codecs) const
|
||||
{
|
||||
if (family_name.empty())
|
||||
throw Exception("Compression codec name cannot be empty", ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
if (level)
|
||||
{
|
||||
auto literal = std::make_shared<ASTLiteral>(static_cast<UInt64>(*level));
|
||||
validateCodecAndGetPreprocessedAST(makeASTFunction("CODEC", makeASTFunction(Poco::toUpper(family_name), literal)),
|
||||
{}, sanity_check, allow_experimental_codecs);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto identifier = std::make_shared<ASTIdentifier>(Poco::toUpper(family_name));
|
||||
validateCodecAndGetPreprocessedAST(makeASTFunction("CODEC", identifier),
|
||||
{}, sanity_check, allow_experimental_codecs);
|
||||
}
|
||||
}
|
||||
|
||||
ASTPtr CompressionCodecFactory::validateCodecAndGetPreprocessedAST(
|
||||
const ASTPtr & ast, const IDataType * column_type, bool sanity_check, bool allow_experimental_codecs) const
|
||||
{
|
||||
if (const auto * func = ast->as<ASTFunction>())
|
||||
{
|
||||
ASTPtr codecs_descriptions = std::make_shared<ASTExpressionList>();
|
||||
|
||||
bool is_compression = false;
|
||||
bool has_none = false;
|
||||
std::optional<size_t> generic_compression_codec_pos;
|
||||
std::set<size_t> post_processing_codecs;
|
||||
|
||||
bool can_substitute_codec_arguments = true;
|
||||
for (size_t i = 0, size = func->arguments->children.size(); i < size; ++i)
|
||||
{
|
||||
const auto & inner_codec_ast = func->arguments->children[i];
|
||||
String codec_family_name;
|
||||
ASTPtr codec_arguments;
|
||||
if (const auto * family_name = inner_codec_ast->as<ASTIdentifier>())
|
||||
{
|
||||
codec_family_name = family_name->name();
|
||||
codec_arguments = {};
|
||||
}
|
||||
else if (const auto * ast_func = inner_codec_ast->as<ASTFunction>())
|
||||
{
|
||||
codec_family_name = ast_func->name;
|
||||
codec_arguments = ast_func->arguments;
|
||||
}
|
||||
else
|
||||
throw Exception("Unexpected AST element for compression codec", ErrorCodes::UNEXPECTED_AST_STRUCTURE);
|
||||
|
||||
/// Default codec replaced with current default codec which may depend on different
|
||||
/// settings (and properties of data) in runtime.
|
||||
CompressionCodecPtr result_codec;
|
||||
if (codec_family_name == DEFAULT_CODEC_NAME)
|
||||
{
|
||||
if (codec_arguments != nullptr)
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS,
|
||||
"{} codec cannot have any arguments, it's just an alias for codec specified in config.xml", DEFAULT_CODEC_NAME);
|
||||
|
||||
result_codec = default_codec;
|
||||
codecs_descriptions->children.emplace_back(std::make_shared<ASTIdentifier>(DEFAULT_CODEC_NAME));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (column_type)
|
||||
{
|
||||
CompressionCodecPtr prev_codec;
|
||||
IDataType::StreamCallbackWithType callback = [&](
|
||||
const ISerialization::SubstreamPath & substream_path, const IDataType & substream_type)
|
||||
{
|
||||
if (ISerialization::isSpecialCompressionAllowed(substream_path))
|
||||
{
|
||||
result_codec = getImpl(codec_family_name, codec_arguments, &substream_type);
|
||||
|
||||
/// Case for column Tuple, which compressed with codec which depends on data type, like Delta.
|
||||
/// We cannot substitute parameters for such codecs.
|
||||
if (prev_codec && prev_codec->getHash() != result_codec->getHash())
|
||||
can_substitute_codec_arguments = false;
|
||||
prev_codec = result_codec;
|
||||
}
|
||||
};
|
||||
|
||||
ISerialization::SubstreamPath stream_path;
|
||||
column_type->enumerateStreams(column_type->getDefaultSerialization(), callback, stream_path);
|
||||
|
||||
if (!result_codec)
|
||||
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot find any substream with data type for type {}. It's a bug", column_type->getName());
|
||||
}
|
||||
else
|
||||
{
|
||||
result_codec = getImpl(codec_family_name, codec_arguments, nullptr);
|
||||
}
|
||||
|
||||
if (!allow_experimental_codecs && result_codec->isExperimental())
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS,
|
||||
"Codec {} is experimental and not meant to be used in production."
|
||||
" You can enable it with the 'allow_experimental_codecs' setting.",
|
||||
codec_family_name);
|
||||
|
||||
codecs_descriptions->children.emplace_back(result_codec->getCodecDesc());
|
||||
}
|
||||
|
||||
is_compression |= result_codec->isCompression();
|
||||
has_none |= result_codec->isNone();
|
||||
|
||||
if (!generic_compression_codec_pos && result_codec->isGenericCompression())
|
||||
generic_compression_codec_pos = i;
|
||||
|
||||
if (result_codec->isPostProcessing())
|
||||
post_processing_codecs.insert(i);
|
||||
}
|
||||
|
||||
String codec_description = queryToString(codecs_descriptions);
|
||||
|
||||
if (sanity_check)
|
||||
{
|
||||
if (codecs_descriptions->children.size() > 1 && has_none)
|
||||
throw Exception(
|
||||
"It does not make sense to have codec NONE along with other compression codecs: " + codec_description
|
||||
+ ". (Note: you can enable setting 'allow_suspicious_codecs' to skip this check).",
|
||||
ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
/// Allow to explicitly specify single NONE codec if user don't want any compression.
|
||||
/// But applying other transformations solely without compression (e.g. Delta) does not make sense.
|
||||
/// It's okay to apply post-processing codecs solely without anything else.
|
||||
if (!is_compression && !has_none && post_processing_codecs.size() != codecs_descriptions->children.size())
|
||||
throw Exception(
|
||||
"Compression codec " + codec_description
|
||||
+ " does not compress anything."
|
||||
" You may want to add generic compression algorithm after other transformations, like: "
|
||||
+ codec_description
|
||||
+ ", LZ4."
|
||||
" (Note: you can enable setting 'allow_suspicious_codecs' to skip this check).",
|
||||
ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
/// It does not make sense to apply any non-post-processing codecs
|
||||
/// after post-processing one.
|
||||
if (!post_processing_codecs.empty() &&
|
||||
*post_processing_codecs.begin() != codecs_descriptions->children.size() - post_processing_codecs.size())
|
||||
throw Exception("The combination of compression codecs " + codec_description + " is meaningless,"
|
||||
" because it does not make sense to apply any non-post-processing codecs after"
|
||||
" post-processing ones. (Note: you can enable setting 'allow_suspicious_codecs'"
|
||||
" to skip this check).", ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
/// It does not make sense to apply any transformations after generic compression algorithm
|
||||
/// So, generic compression can be only one and only at the end.
|
||||
if (generic_compression_codec_pos &&
|
||||
*generic_compression_codec_pos != codecs_descriptions->children.size() - 1 - post_processing_codecs.size())
|
||||
throw Exception("The combination of compression codecs " + codec_description + " is meaningless,"
|
||||
" because it does not make sense to apply any transformations after generic compression algorithm."
|
||||
" (Note: you can enable setting 'allow_suspicious_codecs' to skip this check).", ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
}
|
||||
|
||||
/// For columns with nested types like Tuple(UInt32, UInt64) we
|
||||
/// obviously cannot substitute parameters for codecs which depend on
|
||||
/// data type, because for the first column Delta(4) is suitable and
|
||||
/// Delta(8) for the second. So we should leave codec description as is
|
||||
/// and deduce them in get method for each subtype separately. For all
|
||||
/// other types it's better to substitute parameters, for better
|
||||
/// readability and backward compatibility.
|
||||
if (can_substitute_codec_arguments)
|
||||
{
|
||||
std::shared_ptr<ASTFunction> result = std::make_shared<ASTFunction>();
|
||||
result->name = "CODEC";
|
||||
result->arguments = codecs_descriptions;
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
return ast;
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception("Unknown codec family: " + queryToString(ast), ErrorCodes::UNKNOWN_CODEC);
|
||||
}
|
||||
|
||||
|
||||
CompressionCodecPtr CompressionCodecFactory::get(
|
||||
const ASTPtr & ast, const IDataType * column_type, CompressionCodecPtr current_default, bool only_generic) const
|
||||
|
@ -14,6 +14,8 @@
|
||||
namespace DB
|
||||
{
|
||||
|
||||
static constexpr auto DEFAULT_CODEC_NAME = "Default";
|
||||
|
||||
class ICompressionCodec;
|
||||
|
||||
using CompressionCodecPtr = std::shared_ptr<ICompressionCodec>;
|
||||
|
214
src/Compression/CompressionFactoryAdditions.cpp
Normal file
214
src/Compression/CompressionFactoryAdditions.cpp
Normal file
@ -0,0 +1,214 @@
|
||||
/**
|
||||
* This file contains a part of CompressionCodecFactory methods definitions and
|
||||
* is needed only because they have dependencies on DataTypes.
|
||||
* They are not useful for fuzzers, so we leave them in other translation unit.
|
||||
*/
|
||||
|
||||
#include <Compression/CompressionFactory.h>
|
||||
|
||||
#include <Parsers/ASTFunction.h>
|
||||
#include <Parsers/ASTLiteral.h>
|
||||
#include <Parsers/ASTIdentifier.h>
|
||||
#include <Parsers/parseQuery.h>
|
||||
#include <Parsers/queryToString.h>
|
||||
#include <DataTypes/DataTypeFactory.h>
|
||||
#include <DataTypes/NestedUtils.h>
|
||||
#include <DataTypes/DataTypeArray.h>
|
||||
#include <DataTypes/DataTypeTuple.h>
|
||||
#include <DataTypes/DataTypeNested.h>
|
||||
#include <Common/Exception.h>
|
||||
|
||||
|
||||
namespace DB
|
||||
{
|
||||
|
||||
namespace ErrorCodes
|
||||
{
|
||||
extern const int UNEXPECTED_AST_STRUCTURE;
|
||||
extern const int UNKNOWN_CODEC;
|
||||
extern const int BAD_ARGUMENTS;
|
||||
extern const int LOGICAL_ERROR;
|
||||
}
|
||||
|
||||
|
||||
void CompressionCodecFactory::validateCodec(
|
||||
const String & family_name, std::optional<int> level, bool sanity_check, bool allow_experimental_codecs) const
|
||||
{
|
||||
if (family_name.empty())
|
||||
throw Exception("Compression codec name cannot be empty", ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
if (level)
|
||||
{
|
||||
auto literal = std::make_shared<ASTLiteral>(static_cast<UInt64>(*level));
|
||||
validateCodecAndGetPreprocessedAST(makeASTFunction("CODEC", makeASTFunction(Poco::toUpper(family_name), literal)),
|
||||
{}, sanity_check, allow_experimental_codecs);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto identifier = std::make_shared<ASTIdentifier>(Poco::toUpper(family_name));
|
||||
validateCodecAndGetPreprocessedAST(makeASTFunction("CODEC", identifier),
|
||||
{}, sanity_check, allow_experimental_codecs);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
ASTPtr CompressionCodecFactory::validateCodecAndGetPreprocessedAST(
|
||||
const ASTPtr & ast, const IDataType * column_type, bool sanity_check, bool allow_experimental_codecs) const
|
||||
{
|
||||
if (const auto * func = ast->as<ASTFunction>())
|
||||
{
|
||||
ASTPtr codecs_descriptions = std::make_shared<ASTExpressionList>();
|
||||
|
||||
bool is_compression = false;
|
||||
bool has_none = false;
|
||||
std::optional<size_t> generic_compression_codec_pos;
|
||||
std::set<size_t> post_processing_codecs;
|
||||
|
||||
bool can_substitute_codec_arguments = true;
|
||||
for (size_t i = 0, size = func->arguments->children.size(); i < size; ++i)
|
||||
{
|
||||
const auto & inner_codec_ast = func->arguments->children[i];
|
||||
String codec_family_name;
|
||||
ASTPtr codec_arguments;
|
||||
if (const auto * family_name = inner_codec_ast->as<ASTIdentifier>())
|
||||
{
|
||||
codec_family_name = family_name->name();
|
||||
codec_arguments = {};
|
||||
}
|
||||
else if (const auto * ast_func = inner_codec_ast->as<ASTFunction>())
|
||||
{
|
||||
codec_family_name = ast_func->name;
|
||||
codec_arguments = ast_func->arguments;
|
||||
}
|
||||
else
|
||||
throw Exception("Unexpected AST element for compression codec", ErrorCodes::UNEXPECTED_AST_STRUCTURE);
|
||||
|
||||
/// Default codec replaced with current default codec which may depend on different
|
||||
/// settings (and properties of data) in runtime.
|
||||
CompressionCodecPtr result_codec;
|
||||
if (codec_family_name == DEFAULT_CODEC_NAME)
|
||||
{
|
||||
if (codec_arguments != nullptr)
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS,
|
||||
"{} codec cannot have any arguments, it's just an alias for codec specified in config.xml", DEFAULT_CODEC_NAME);
|
||||
|
||||
result_codec = default_codec;
|
||||
codecs_descriptions->children.emplace_back(std::make_shared<ASTIdentifier>(DEFAULT_CODEC_NAME));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (column_type)
|
||||
{
|
||||
CompressionCodecPtr prev_codec;
|
||||
IDataType::StreamCallbackWithType callback = [&](
|
||||
const ISerialization::SubstreamPath & substream_path, const IDataType & substream_type)
|
||||
{
|
||||
if (ISerialization::isSpecialCompressionAllowed(substream_path))
|
||||
{
|
||||
result_codec = getImpl(codec_family_name, codec_arguments, &substream_type);
|
||||
|
||||
/// Case for column Tuple, which compressed with codec which depends on data type, like Delta.
|
||||
/// We cannot substitute parameters for such codecs.
|
||||
if (prev_codec && prev_codec->getHash() != result_codec->getHash())
|
||||
can_substitute_codec_arguments = false;
|
||||
prev_codec = result_codec;
|
||||
}
|
||||
};
|
||||
|
||||
ISerialization::SubstreamPath stream_path;
|
||||
column_type->enumerateStreams(column_type->getDefaultSerialization(), callback, stream_path);
|
||||
|
||||
if (!result_codec)
|
||||
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot find any substream with data type for type {}. It's a bug", column_type->getName());
|
||||
}
|
||||
else
|
||||
{
|
||||
result_codec = getImpl(codec_family_name, codec_arguments, nullptr);
|
||||
}
|
||||
|
||||
if (!allow_experimental_codecs && result_codec->isExperimental())
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS,
|
||||
"Codec {} is experimental and not meant to be used in production."
|
||||
" You can enable it with the 'allow_experimental_codecs' setting.",
|
||||
codec_family_name);
|
||||
|
||||
codecs_descriptions->children.emplace_back(result_codec->getCodecDesc());
|
||||
}
|
||||
|
||||
is_compression |= result_codec->isCompression();
|
||||
has_none |= result_codec->isNone();
|
||||
|
||||
if (!generic_compression_codec_pos && result_codec->isGenericCompression())
|
||||
generic_compression_codec_pos = i;
|
||||
|
||||
if (result_codec->isPostProcessing())
|
||||
post_processing_codecs.insert(i);
|
||||
}
|
||||
|
||||
String codec_description = queryToString(codecs_descriptions);
|
||||
|
||||
if (sanity_check)
|
||||
{
|
||||
if (codecs_descriptions->children.size() > 1 && has_none)
|
||||
throw Exception(
|
||||
"It does not make sense to have codec NONE along with other compression codecs: " + codec_description
|
||||
+ ". (Note: you can enable setting 'allow_suspicious_codecs' to skip this check).",
|
||||
ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
/// Allow to explicitly specify single NONE codec if user don't want any compression.
|
||||
/// But applying other transformations solely without compression (e.g. Delta) does not make sense.
|
||||
/// It's okay to apply post-processing codecs solely without anything else.
|
||||
if (!is_compression && !has_none && post_processing_codecs.size() != codecs_descriptions->children.size())
|
||||
throw Exception(
|
||||
"Compression codec " + codec_description
|
||||
+ " does not compress anything."
|
||||
" You may want to add generic compression algorithm after other transformations, like: "
|
||||
+ codec_description
|
||||
+ ", LZ4."
|
||||
" (Note: you can enable setting 'allow_suspicious_codecs' to skip this check).",
|
||||
ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
/// It does not make sense to apply any non-post-processing codecs
|
||||
/// after post-processing one.
|
||||
if (!post_processing_codecs.empty() &&
|
||||
*post_processing_codecs.begin() != codecs_descriptions->children.size() - post_processing_codecs.size())
|
||||
throw Exception("The combination of compression codecs " + codec_description + " is meaningless,"
|
||||
" because it does not make sense to apply any non-post-processing codecs after"
|
||||
" post-processing ones. (Note: you can enable setting 'allow_suspicious_codecs'"
|
||||
" to skip this check).", ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
/// It does not make sense to apply any transformations after generic compression algorithm
|
||||
/// So, generic compression can be only one and only at the end.
|
||||
if (generic_compression_codec_pos &&
|
||||
*generic_compression_codec_pos != codecs_descriptions->children.size() - 1 - post_processing_codecs.size())
|
||||
throw Exception("The combination of compression codecs " + codec_description + " is meaningless,"
|
||||
" because it does not make sense to apply any transformations after generic compression algorithm."
|
||||
" (Note: you can enable setting 'allow_suspicious_codecs' to skip this check).", ErrorCodes::BAD_ARGUMENTS);
|
||||
|
||||
}
|
||||
|
||||
/// For columns with nested types like Tuple(UInt32, UInt64) we
|
||||
/// obviously cannot substitute parameters for codecs which depend on
|
||||
/// data type, because for the first column Delta(4) is suitable and
|
||||
/// Delta(8) for the second. So we should leave codec description as is
|
||||
/// and deduce them in get method for each subtype separately. For all
|
||||
/// other types it's better to substitute parameters, for better
|
||||
/// readability and backward compatibility.
|
||||
if (can_substitute_codec_arguments)
|
||||
{
|
||||
std::shared_ptr<ASTFunction> result = std::make_shared<ASTFunction>();
|
||||
result->name = "CODEC";
|
||||
result->arguments = codecs_descriptions;
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
return ast;
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception("Unknown codec family: " + queryToString(ast), ErrorCodes::UNKNOWN_CODEC);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -439,11 +439,14 @@ bool NO_INLINE decompressImpl(
|
||||
{
|
||||
s = *ip++;
|
||||
length += s;
|
||||
} while (unlikely(s == 255));
|
||||
} while (unlikely(s == 255 && ip < input_end));
|
||||
};
|
||||
|
||||
/// Get literal length.
|
||||
|
||||
if (unlikely(ip >= input_end))
|
||||
return false;
|
||||
|
||||
const unsigned token = *ip++;
|
||||
length = token >> 4;
|
||||
if (length == 0x0F)
|
||||
@ -464,18 +467,18 @@ bool NO_INLINE decompressImpl(
|
||||
/// output: xyzHello, w
|
||||
/// ^-op (we will overwrite excessive bytes on next iteration)
|
||||
|
||||
{
|
||||
auto * target = std::min(copy_end, output_end);
|
||||
wildCopy<copy_amount>(op, ip, target); /// Here we can write up to copy_amount - 1 bytes after buffer.
|
||||
if (unlikely(copy_end > output_end))
|
||||
return false;
|
||||
|
||||
if (target == output_end)
|
||||
return true;
|
||||
}
|
||||
wildCopy<copy_amount>(op, ip, copy_end); /// Here we can write up to copy_amount - 1 bytes after buffer.
|
||||
|
||||
if (copy_end == output_end)
|
||||
return true;
|
||||
|
||||
ip += length;
|
||||
op = copy_end;
|
||||
|
||||
if (unlikely(ip > input_end))
|
||||
if (unlikely(ip + 1 >= input_end))
|
||||
return false;
|
||||
|
||||
/// Get match offset.
|
||||
@ -528,8 +531,9 @@ bool NO_INLINE decompressImpl(
|
||||
copy<copy_amount>(op, match); /// copy_amount + copy_amount - 1 - 4 * 2 bytes after buffer.
|
||||
if (length > copy_amount * 2)
|
||||
{
|
||||
auto * target = std::min(copy_end, output_end);
|
||||
wildCopy<copy_amount>(op + copy_amount, match + copy_amount, target);
|
||||
if (unlikely(copy_end > output_end))
|
||||
return false;
|
||||
wildCopy<copy_amount>(op + copy_amount, match + copy_amount, copy_end);
|
||||
}
|
||||
|
||||
op = copy_end;
|
||||
|
@ -3,8 +3,3 @@ target_link_libraries (compressed_buffer PRIVATE dbms)
|
||||
|
||||
add_executable (cached_compressed_read_buffer cached_compressed_read_buffer.cpp)
|
||||
target_link_libraries (cached_compressed_read_buffer PRIVATE dbms)
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_executable (compressed_buffer_fuzzer compressed_buffer_fuzzer.cpp)
|
||||
target_link_libraries (compressed_buffer_fuzzer PRIVATE dbms ${LIB_FUZZING_ENGINE})
|
||||
endif ()
|
||||
|
2
src/Compression/fuzzers/CMakeLists.txt
Normal file
2
src/Compression/fuzzers/CMakeLists.txt
Normal file
@ -0,0 +1,2 @@
|
||||
add_executable (compressed_buffer_fuzzer compressed_buffer_fuzzer.cpp)
|
||||
target_link_libraries (compressed_buffer_fuzzer PRIVATE fuzz_compression clickhouse_common_io ${LIB_FUZZING_ENGINE})
|
@ -1,3 +1,7 @@
|
||||
if (ENABLE_EXAMPLES)
|
||||
add_subdirectory(examples)
|
||||
endif ()
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_subdirectory(fuzzers)
|
||||
endif()
|
||||
|
@ -55,7 +55,7 @@ class IColumn;
|
||||
M(Seconds, receive_timeout, DBMS_DEFAULT_RECEIVE_TIMEOUT_SEC, "", 0) \
|
||||
M(Seconds, send_timeout, DBMS_DEFAULT_SEND_TIMEOUT_SEC, "", 0) \
|
||||
M(Seconds, drain_timeout, DBMS_DEFAULT_DRAIN_TIMEOUT_SEC, "", 0) \
|
||||
M(Seconds, tcp_keep_alive_timeout, 0, "The time in seconds the connection needs to remain idle before TCP starts sending keepalive probes", 0) \
|
||||
M(Seconds, tcp_keep_alive_timeout, 290 /* less than DBMS_DEFAULT_RECEIVE_TIMEOUT_SEC */, "The time in seconds the connection needs to remain idle before TCP starts sending keepalive probes", 0) \
|
||||
M(Milliseconds, hedged_connection_timeout_ms, DBMS_DEFAULT_HEDGED_CONNECTION_TIMEOUT_MS, "Connection timeout for establishing connection with replica for Hedged requests", 0) \
|
||||
M(Milliseconds, receive_data_timeout_ms, DBMS_DEFAULT_RECEIVE_DATA_TIMEOUT_MS, "Connection timeout for receiving first packet of data or packet with positive progress from replica", 0) \
|
||||
M(Bool, use_hedged_requests, true, "Use hedged requests for distributed queries", 0) \
|
||||
@ -114,6 +114,7 @@ class IColumn;
|
||||
M(UInt64, group_by_two_level_threshold_bytes, 50000000, "From what size of the aggregation state in bytes, a two-level aggregation begins to be used. 0 - the threshold is not set. Two-level aggregation is used when at least one of the thresholds is triggered.", 0) \
|
||||
M(Bool, distributed_aggregation_memory_efficient, true, "Is the memory-saving mode of distributed aggregation enabled.", 0) \
|
||||
M(UInt64, aggregation_memory_efficient_merge_threads, 0, "Number of threads to use for merge intermediate aggregation results in memory efficient mode. When bigger, then more memory is consumed. 0 means - same as 'max_threads'.", 0) \
|
||||
M(Bool, enable_positional_arguments, false, "Enable positional arguments in ORDER BY, GROUP BY and LIMIT BY", 0) \
|
||||
\
|
||||
M(UInt64, max_parallel_replicas, 1, "The maximum number of replicas of each shard used when the query is executed. For consistency (to get different parts of the same partition), this option only works for the specified sampling key. The lag of the replicas is not controlled.", 0) \
|
||||
M(UInt64, parallel_replicas_count, 0, "", 0) \
|
||||
@ -252,6 +253,7 @@ class IColumn;
|
||||
M(Bool, use_index_for_in_with_subqueries, true, "Try using an index if there is a subquery or a table expression on the right side of the IN operator.", 0) \
|
||||
M(Bool, joined_subquery_requires_alias, true, "Force joined subqueries and table functions to have aliases for correct name qualification.", 0) \
|
||||
M(Bool, empty_result_for_aggregation_by_empty_set, false, "Return empty result when aggregating without keys on empty set.", 0) \
|
||||
M(Bool, empty_result_for_aggregation_by_constant_keys_on_empty_set, true, "Return empty result when aggregating by constant keys on empty set.", 0) \
|
||||
M(Bool, allow_distributed_ddl, true, "If it is set to true, then a user is allowed to executed distributed DDL queries.", 0) \
|
||||
M(Bool, allow_suspicious_codecs, false, "If it is set to true, allow to specify meaningless compression codecs.", 0) \
|
||||
M(Bool, allow_experimental_codecs, false, "If it is set to true, allow to specify experimental compression codecs (but we don't have those yet and this option does nothing).", 0) \
|
||||
|
@ -8,11 +8,6 @@ target_link_libraries (field PRIVATE dbms)
|
||||
add_executable (string_ref_hash string_ref_hash.cpp)
|
||||
target_link_libraries (string_ref_hash PRIVATE clickhouse_common_io)
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_executable (names_and_types_fuzzer names_and_types_fuzzer.cpp)
|
||||
target_link_libraries (names_and_types_fuzzer PRIVATE dbms ${LIB_FUZZING_ENGINE})
|
||||
endif ()
|
||||
|
||||
add_executable (mysql_protocol mysql_protocol.cpp)
|
||||
target_link_libraries (mysql_protocol PRIVATE dbms)
|
||||
if(USE_SSL)
|
||||
|
2
src/Core/fuzzers/CMakeLists.txt
Normal file
2
src/Core/fuzzers/CMakeLists.txt
Normal file
@ -0,0 +1,2 @@
|
||||
add_executable (names_and_types_fuzzer names_and_types_fuzzer.cpp)
|
||||
target_link_libraries (names_and_types_fuzzer PRIVATE dbms ${LIB_FUZZING_ENGINE})
|
@ -26,23 +26,6 @@ namespace ErrorCodes
|
||||
|
||||
IDataType::~IDataType() = default;
|
||||
|
||||
String IDataType::getName() const
|
||||
{
|
||||
if (custom_name)
|
||||
{
|
||||
return custom_name->getName();
|
||||
}
|
||||
else
|
||||
{
|
||||
return doGetName();
|
||||
}
|
||||
}
|
||||
|
||||
String IDataType::doGetName() const
|
||||
{
|
||||
return getFamilyName();
|
||||
}
|
||||
|
||||
void IDataType::updateAvgValueSizeHint(const IColumn & column, double & avg_value_size_hint)
|
||||
{
|
||||
/// Update the average value size hint if amount of read rows isn't too small
|
||||
|
@ -62,7 +62,13 @@ public:
|
||||
/// static constexpr bool is_parametric = false;
|
||||
|
||||
/// Name of data type (examples: UInt64, Array(String)).
|
||||
String getName() const;
|
||||
String getName() const
|
||||
{
|
||||
if (custom_name)
|
||||
return custom_name->getName();
|
||||
else
|
||||
return doGetName();
|
||||
}
|
||||
|
||||
/// Name of data type family (example: FixedString, Array).
|
||||
virtual const char * getFamilyName() const = 0;
|
||||
@ -105,7 +111,7 @@ public:
|
||||
void enumerateStreams(const SerializationPtr & serialization, const StreamCallbackWithType & callback) const { enumerateStreams(serialization, callback, {}); }
|
||||
|
||||
protected:
|
||||
virtual String doGetName() const;
|
||||
virtual String doGetName() const { return getFamilyName(); }
|
||||
virtual SerializationPtr doGetDefaultSerialization() const = 0;
|
||||
|
||||
DataTypePtr getTypeForSubstream(const ISerialization::SubstreamPath & substream_path) const;
|
||||
|
@ -161,9 +161,6 @@ DictionaryStructure::DictionaryStructure(const Poco::Util::AbstractConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
if (attributes.empty())
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary has no attributes defined");
|
||||
|
||||
if (config.getBool(config_prefix + ".layout.ip_trie.access_to_key_from_attributes", false))
|
||||
access_to_key_from_attributes = true;
|
||||
}
|
||||
|
@ -496,9 +496,6 @@ void checkAST(const ASTCreateQuery & query)
|
||||
if (!query.is_dictionary || query.dictionary == nullptr)
|
||||
throw Exception(ErrorCodes::INCORRECT_DICTIONARY_DEFINITION, "Cannot convert dictionary to configuration from non-dictionary AST.");
|
||||
|
||||
if (query.dictionary_attributes_list == nullptr || query.dictionary_attributes_list->children.empty())
|
||||
throw Exception(ErrorCodes::INCORRECT_DICTIONARY_DEFINITION, "Cannot create dictionary with empty attributes list");
|
||||
|
||||
if (query.dictionary->layout == nullptr)
|
||||
throw Exception(ErrorCodes::INCORRECT_DICTIONARY_DEFINITION, "Cannot create dictionary with empty layout");
|
||||
|
||||
@ -512,8 +509,6 @@ void checkAST(const ASTCreateQuery & query)
|
||||
|
||||
if (query.dictionary->source == nullptr)
|
||||
throw Exception(ErrorCodes::INCORRECT_DICTIONARY_DEFINITION, "Cannot create dictionary with empty source");
|
||||
|
||||
/// Range can be empty
|
||||
}
|
||||
|
||||
void checkPrimaryKey(const NamesToTypeNames & all_attrs, const Names & key_attrs)
|
||||
|
@ -14,6 +14,7 @@ void registerFunctionsHashing(FunctionFactory & factory)
|
||||
factory.registerFunction<FunctionSHA1>();
|
||||
factory.registerFunction<FunctionSHA224>();
|
||||
factory.registerFunction<FunctionSHA256>();
|
||||
factory.registerFunction<FunctionSHA512>();
|
||||
#endif
|
||||
factory.registerFunction<FunctionSipHash64>();
|
||||
factory.registerFunction<FunctionSipHash128>();
|
||||
|
@ -193,6 +193,20 @@ struct SHA256Impl
|
||||
SHA256_Final(out_char_data, &ctx);
|
||||
}
|
||||
};
|
||||
|
||||
struct SHA512Impl
|
||||
{
|
||||
static constexpr auto name = "SHA512";
|
||||
enum { length = 64 };
|
||||
|
||||
static void apply(const char * begin, const size_t size, unsigned char * out_char_data)
|
||||
{
|
||||
SHA512_CTX ctx;
|
||||
SHA512_Init(&ctx);
|
||||
SHA512_Update(&ctx, reinterpret_cast<const unsigned char *>(begin), size);
|
||||
SHA512_Final(out_char_data, &ctx);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
struct SipHash64Impl
|
||||
@ -1318,6 +1332,7 @@ using FunctionMD5 = FunctionStringHashFixedString<MD5Impl>;
|
||||
using FunctionSHA1 = FunctionStringHashFixedString<SHA1Impl>;
|
||||
using FunctionSHA224 = FunctionStringHashFixedString<SHA224Impl>;
|
||||
using FunctionSHA256 = FunctionStringHashFixedString<SHA256Impl>;
|
||||
using FunctionSHA512 = FunctionStringHashFixedString<SHA512Impl>;
|
||||
#endif
|
||||
using FunctionSipHash128 = FunctionStringHashFixedString<SipHash128Impl>;
|
||||
using FunctionCityHash64 = FunctionAnyHash<ImplCityHash64>;
|
||||
|
@ -696,6 +696,8 @@ struct JSONExtractTree
|
||||
{
|
||||
if (element.isString())
|
||||
return JSONExtractStringImpl<JSONParser>::insertResultToColumn(dest, element, {});
|
||||
else if (element.isNull())
|
||||
return false;
|
||||
else
|
||||
return JSONExtractRawImpl<JSONParser>::insertResultToColumn(dest, element, {});
|
||||
}
|
||||
|
136
src/Functions/getServerPort.cpp
Normal file
136
src/Functions/getServerPort.cpp
Normal file
@ -0,0 +1,136 @@
|
||||
#include <DataTypes/DataTypesNumber.h>
|
||||
#include <Functions/FunctionFactory.h>
|
||||
#include <Functions/FunctionHelpers.h>
|
||||
#include <Interpreters/Context.h>
|
||||
|
||||
|
||||
namespace DB
|
||||
{
|
||||
|
||||
namespace ErrorCodes
|
||||
{
|
||||
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
|
||||
extern const int ILLEGAL_COLUMN;
|
||||
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
class ExecutableFunctionGetServerPort : public IExecutableFunction
|
||||
{
|
||||
public:
|
||||
explicit ExecutableFunctionGetServerPort(UInt16 port_) : port(port_) {}
|
||||
|
||||
String getName() const override { return "getServerPort"; }
|
||||
|
||||
bool useDefaultImplementationForNulls() const override { return false; }
|
||||
|
||||
ColumnPtr executeImpl(const ColumnsWithTypeAndName &, const DataTypePtr &, size_t input_rows_count) const override
|
||||
{
|
||||
return DataTypeNumber<UInt16>().createColumnConst(input_rows_count, port);
|
||||
}
|
||||
|
||||
private:
|
||||
UInt16 port;
|
||||
};
|
||||
|
||||
class FunctionBaseGetServerPort : public IFunctionBase
|
||||
{
|
||||
public:
|
||||
explicit FunctionBaseGetServerPort(bool is_distributed_, UInt16 port_, DataTypes argument_types_, DataTypePtr return_type_)
|
||||
: is_distributed(is_distributed_), port(port_), argument_types(std::move(argument_types_)), return_type(std::move(return_type_))
|
||||
{
|
||||
}
|
||||
|
||||
String getName() const override { return "getServerPort"; }
|
||||
|
||||
const DataTypes & getArgumentTypes() const override
|
||||
{
|
||||
return argument_types;
|
||||
}
|
||||
|
||||
const DataTypePtr & getResultType() const override
|
||||
{
|
||||
return return_type;
|
||||
}
|
||||
|
||||
bool isDeterministic() const override { return false; }
|
||||
bool isDeterministicInScopeOfQuery() const override { return true; }
|
||||
bool isSuitableForConstantFolding() const override { return !is_distributed; }
|
||||
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }
|
||||
|
||||
ExecutableFunctionPtr prepare(const ColumnsWithTypeAndName &) const override
|
||||
{
|
||||
return std::make_unique<ExecutableFunctionGetServerPort>(port);
|
||||
}
|
||||
|
||||
private:
|
||||
bool is_distributed;
|
||||
UInt16 port;
|
||||
DataTypes argument_types;
|
||||
DataTypePtr return_type;
|
||||
};
|
||||
|
||||
class GetServerPortOverloadResolver : public IFunctionOverloadResolver, WithContext
|
||||
{
|
||||
public:
|
||||
static constexpr auto name = "getServerPort";
|
||||
|
||||
String getName() const override { return name; }
|
||||
|
||||
static FunctionOverloadResolverPtr create(ContextPtr context_)
|
||||
{
|
||||
return std::make_unique<GetServerPortOverloadResolver>(context_);
|
||||
}
|
||||
|
||||
explicit GetServerPortOverloadResolver(ContextPtr context_) : WithContext(context_) {}
|
||||
|
||||
size_t getNumberOfArguments() const override { return 1; }
|
||||
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {0}; }
|
||||
bool isDeterministic() const override { return false; }
|
||||
bool isDeterministicInScopeOfQuery() const override { return true; }
|
||||
|
||||
DataTypePtr getReturnTypeImpl(const DataTypes & data_types) const override
|
||||
{
|
||||
size_t number_of_arguments = data_types.size();
|
||||
if (number_of_arguments != 1)
|
||||
throw Exception(
|
||||
ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH,
|
||||
"Number of arguments for function {} doesn't match: passed {}, should be 1",
|
||||
getName(),
|
||||
number_of_arguments);
|
||||
return std::make_shared<DataTypeNumber<UInt16>>();
|
||||
}
|
||||
|
||||
FunctionBasePtr buildImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & return_type) const override
|
||||
{
|
||||
if (!isString(arguments[0].type))
|
||||
throw Exception(
|
||||
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
|
||||
"The argument of function {} should be a constant string with the name of a setting",
|
||||
getName());
|
||||
const auto * column = arguments[0].column.get();
|
||||
if (!column || !checkAndGetColumnConstStringOrFixedString(column))
|
||||
throw Exception(
|
||||
ErrorCodes::ILLEGAL_COLUMN,
|
||||
"The argument of function {} should be a constant string with the name of a setting",
|
||||
getName());
|
||||
|
||||
String port_name{column->getDataAt(0)};
|
||||
auto port = getContext()->getServerPort(port_name);
|
||||
|
||||
DataTypes argument_types;
|
||||
argument_types.emplace_back(arguments.back().type);
|
||||
return std::make_unique<FunctionBaseGetServerPort>(getContext()->isDistributed(), port, argument_types, return_type);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
void registerFunctionGetServerPort(FunctionFactory & factory)
|
||||
{
|
||||
factory.registerFunction<GetServerPortOverloadResolver>();
|
||||
}
|
||||
|
||||
}
|
@ -34,6 +34,19 @@ public:
|
||||
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {0}; }
|
||||
|
||||
DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
|
||||
{
|
||||
auto value = getValue(arguments);
|
||||
return applyVisitor(FieldToDataType{}, value);
|
||||
}
|
||||
|
||||
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
|
||||
{
|
||||
auto value = getValue(arguments);
|
||||
return result_type->createColumnConst(input_rows_count, convertFieldToType(value, *result_type));
|
||||
}
|
||||
|
||||
private:
|
||||
Field getValue(const ColumnsWithTypeAndName & arguments) const
|
||||
{
|
||||
if (!isString(arguments[0].type))
|
||||
throw Exception{"The argument of function " + String{name} + " should be a constant string with the name of a setting",
|
||||
@ -44,20 +57,8 @@ public:
|
||||
ErrorCodes::ILLEGAL_COLUMN};
|
||||
|
||||
std::string_view setting_name{column->getDataAt(0)};
|
||||
value = getContext()->getSettingsRef().get(setting_name);
|
||||
|
||||
DataTypePtr type = applyVisitor(FieldToDataType{}, value);
|
||||
value = convertFieldToType(value, *type);
|
||||
return type;
|
||||
return getContext()->getSettingsRef().get(setting_name);
|
||||
}
|
||||
|
||||
ColumnPtr executeImpl(const ColumnsWithTypeAndName &, const DataTypePtr & result_type, size_t input_rows_count) const override
|
||||
{
|
||||
return result_type->createColumnConst(input_rows_count, value);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable Field value;
|
||||
};
|
||||
|
||||
}
|
||||
|
@ -71,6 +71,7 @@ void registerFunctionHasThreadFuzzer(FunctionFactory &);
|
||||
void registerFunctionInitializeAggregation(FunctionFactory &);
|
||||
void registerFunctionErrorCodeToName(FunctionFactory &);
|
||||
void registerFunctionTcpPort(FunctionFactory &);
|
||||
void registerFunctionGetServerPort(FunctionFactory &);
|
||||
void registerFunctionByteSize(FunctionFactory &);
|
||||
void registerFunctionFile(FunctionFactory & factory);
|
||||
void registerFunctionConnectionId(FunctionFactory & factory);
|
||||
@ -150,6 +151,7 @@ void registerFunctionsMiscellaneous(FunctionFactory & factory)
|
||||
registerFunctionInitializeAggregation(factory);
|
||||
registerFunctionErrorCodeToName(factory);
|
||||
registerFunctionTcpPort(factory);
|
||||
registerFunctionGetServerPort(factory);
|
||||
registerFunctionByteSize(factory);
|
||||
registerFunctionFile(factory);
|
||||
registerFunctionConnectionId(factory);
|
||||
|
@ -59,6 +59,7 @@
|
||||
#include <Interpreters/Context.h>
|
||||
#include <Interpreters/DDLWorker.h>
|
||||
#include <Interpreters/DDLTask.h>
|
||||
#include <Interpreters/Session.h>
|
||||
#include <IO/ReadBufferFromFile.h>
|
||||
#include <IO/UncompressedCache.h>
|
||||
#include <IO/MMappedFileCache.h>
|
||||
@ -227,6 +228,8 @@ struct ContextSharedPart
|
||||
ConfigurationPtr clusters_config; /// Stores updated configs
|
||||
mutable std::mutex clusters_mutex; /// Guards clusters and clusters_config
|
||||
|
||||
std::map<String, UInt16> server_ports;
|
||||
|
||||
bool shutdown_called = false;
|
||||
|
||||
Stopwatch uptime_watch;
|
||||
@ -273,6 +276,8 @@ struct ContextSharedPart
|
||||
return;
|
||||
shutdown_called = true;
|
||||
|
||||
Session::shutdownNamedSessions();
|
||||
|
||||
/** After system_logs have been shut down it is guaranteed that no system table gets created or written to.
|
||||
* Note that part changes at shutdown won't be logged to part log.
|
||||
*/
|
||||
@ -1795,13 +1800,27 @@ std::optional<UInt16> Context::getTCPPortSecure() const
|
||||
return {};
|
||||
}
|
||||
|
||||
void Context::registerServerPort(String port_name, UInt16 port)
|
||||
{
|
||||
shared->server_ports.emplace(std::move(port_name), port);
|
||||
}
|
||||
|
||||
UInt16 Context::getServerPort(const String & port_name) const
|
||||
{
|
||||
auto it = shared->server_ports.find(port_name);
|
||||
if (it == shared->server_ports.end())
|
||||
throw Exception(ErrorCodes::BAD_GET, "There is no port named {}", port_name);
|
||||
else
|
||||
return it->second;
|
||||
}
|
||||
|
||||
std::shared_ptr<Cluster> Context::getCluster(const std::string & cluster_name) const
|
||||
{
|
||||
auto res = getClusters()->getCluster(cluster_name);
|
||||
if (res)
|
||||
return res;
|
||||
|
||||
res = tryGetReplicatedDatabaseCluster(cluster_name);
|
||||
if (!cluster_name.empty())
|
||||
res = tryGetReplicatedDatabaseCluster(cluster_name);
|
||||
if (res)
|
||||
return res;
|
||||
|
||||
|
@ -580,6 +580,11 @@ public:
|
||||
|
||||
std::optional<UInt16> getTCPPortSecure() const;
|
||||
|
||||
/// Register server ports during server starting up. No lock is held.
|
||||
void registerServerPort(String port_name, UInt16 port);
|
||||
|
||||
UInt16 getServerPort(const String & port_name) const;
|
||||
|
||||
/// For methods below you may need to acquire the context lock by yourself.
|
||||
|
||||
ContextMutablePtr getQueryContext() const;
|
||||
|
@ -162,6 +162,36 @@ ExpressionAnalyzer::ExpressionAnalyzer(
|
||||
analyzeAggregation();
|
||||
}
|
||||
|
||||
static ASTPtr checkPositionalArgument(ASTPtr argument, const ASTSelectQuery * select_query, ASTSelectQuery::Expression expression)
|
||||
{
|
||||
auto columns = select_query->select()->children;
|
||||
|
||||
/// Case when GROUP BY element is position.
|
||||
/// Do not consider case when GROUP BY element is not a literal, but expression, even if all values are constants.
|
||||
if (const auto * ast_literal = typeid_cast<const ASTLiteral *>(argument.get()))
|
||||
{
|
||||
auto which = ast_literal->value.getType();
|
||||
if (which == Field::Types::UInt64)
|
||||
{
|
||||
auto pos = ast_literal->value.get<UInt64>();
|
||||
if (pos > 0 && pos <= columns.size())
|
||||
{
|
||||
const auto & column = columns[--pos];
|
||||
if (const auto * literal_ast = typeid_cast<const ASTIdentifier *>(column.get()))
|
||||
{
|
||||
return std::make_shared<ASTIdentifier>(literal_ast->name());
|
||||
}
|
||||
else
|
||||
{
|
||||
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal value for positional argument in {}",
|
||||
ASTSelectQuery::expressionToString(expression));
|
||||
}
|
||||
}
|
||||
/// Do not throw if out of bounds, see appendUnusedGroupByColumn.
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void ExpressionAnalyzer::analyzeAggregation()
|
||||
{
|
||||
@ -238,13 +268,22 @@ void ExpressionAnalyzer::analyzeAggregation()
|
||||
{
|
||||
NameSet unique_keys;
|
||||
ASTs & group_asts = select_query->groupBy()->children;
|
||||
|
||||
for (ssize_t i = 0; i < ssize_t(group_asts.size()); ++i)
|
||||
{
|
||||
ssize_t size = group_asts.size();
|
||||
getRootActionsNoMakeSet(group_asts[i], true, temp_actions, false);
|
||||
|
||||
if (getContext()->getSettingsRef().enable_positional_arguments)
|
||||
{
|
||||
auto new_argument = checkPositionalArgument(group_asts[i], select_query, ASTSelectQuery::Expression::GROUP_BY);
|
||||
if (new_argument)
|
||||
group_asts[i] = new_argument;
|
||||
}
|
||||
|
||||
const auto & column_name = group_asts[i]->getColumnName();
|
||||
const auto * node = temp_actions->tryFindInIndex(column_name);
|
||||
|
||||
if (!node)
|
||||
throw Exception("Unknown identifier (in GROUP BY): " + column_name, ErrorCodes::UNKNOWN_IDENTIFIER);
|
||||
|
||||
@ -1223,11 +1262,20 @@ ActionsDAGPtr SelectQueryExpressionAnalyzer::appendOrderBy(ExpressionActionsChai
|
||||
|
||||
bool with_fill = false;
|
||||
NameSet order_by_keys;
|
||||
|
||||
for (auto & child : select_query->orderBy()->children)
|
||||
{
|
||||
const auto * ast = child->as<ASTOrderByElement>();
|
||||
auto * ast = child->as<ASTOrderByElement>();
|
||||
if (!ast || ast->children.empty())
|
||||
throw Exception("Bad order expression AST", ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE);
|
||||
|
||||
if (getContext()->getSettingsRef().enable_positional_arguments)
|
||||
{
|
||||
auto new_argument = checkPositionalArgument(ast->children.at(0), select_query, ASTSelectQuery::Expression::ORDER_BY);
|
||||
if (new_argument)
|
||||
ast->children[0] = new_argument;
|
||||
}
|
||||
|
||||
ASTPtr order_expression = ast->children.at(0);
|
||||
step.addRequiredOutput(order_expression->getColumnName());
|
||||
|
||||
@ -1277,8 +1325,16 @@ bool SelectQueryExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain
|
||||
aggregated_names.insert(column.name);
|
||||
}
|
||||
|
||||
for (const auto & child : select_query->limitBy()->children)
|
||||
auto & children = select_query->limitBy()->children;
|
||||
for (auto & child : children)
|
||||
{
|
||||
if (getContext()->getSettingsRef().enable_positional_arguments)
|
||||
{
|
||||
auto new_argument = checkPositionalArgument(child, select_query, ASTSelectQuery::Expression::LIMIT_BY);
|
||||
if (new_argument)
|
||||
child = new_argument;
|
||||
}
|
||||
|
||||
auto child_name = child->getColumnName();
|
||||
if (!aggregated_names.count(child_name))
|
||||
step.addRequiredOutput(std::move(child_name));
|
||||
|
@ -170,15 +170,18 @@ namespace
|
||||
auto entity = access_control.tryRead(id);
|
||||
if (auto role = typeid_cast<RolePtr>(entity))
|
||||
{
|
||||
checkGranteeIsAllowed(current_user_access, id, *role);
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteeIsAllowed(current_user_access, id, *role);
|
||||
all_granted_access.makeUnion(role->access);
|
||||
}
|
||||
else if (auto user = typeid_cast<UserPtr>(entity))
|
||||
{
|
||||
checkGranteeIsAllowed(current_user_access, id, *user);
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteeIsAllowed(current_user_access, id, *user);
|
||||
all_granted_access.makeUnion(user->access);
|
||||
}
|
||||
}
|
||||
|
||||
need_check_grantees_are_allowed = false; /// already checked
|
||||
|
||||
if (!elements_to_revoke.empty() && elements_to_revoke[0].is_partial_revoke)
|
||||
@ -200,28 +203,6 @@ namespace
|
||||
current_user_access.checkGrantOption(elements_to_revoke);
|
||||
}
|
||||
|
||||
/// Checks if the current user has enough access rights granted with grant option to grant or revoke specified access rights.
|
||||
/// Also checks if grantees are allowed for the current user.
|
||||
void checkGrantOptionAndGrantees(
|
||||
const AccessControlManager & access_control,
|
||||
const ContextAccess & current_user_access,
|
||||
const std::vector<UUID> & grantees_from_query,
|
||||
const AccessRightsElements & elements_to_grant,
|
||||
AccessRightsElements & elements_to_revoke)
|
||||
{
|
||||
bool need_check_grantees_are_allowed = true;
|
||||
checkGrantOption(
|
||||
access_control,
|
||||
current_user_access,
|
||||
grantees_from_query,
|
||||
need_check_grantees_are_allowed,
|
||||
elements_to_grant,
|
||||
elements_to_revoke);
|
||||
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteesAreAllowed(access_control, current_user_access, grantees_from_query);
|
||||
}
|
||||
|
||||
/// Checks if the current user has enough roles granted with admin option to grant or revoke specified roles.
|
||||
void checkAdminOption(
|
||||
const AccessControlManager & access_control,
|
||||
@ -262,18 +243,21 @@ namespace
|
||||
auto entity = access_control.tryRead(id);
|
||||
if (auto role = typeid_cast<RolePtr>(entity))
|
||||
{
|
||||
checkGranteeIsAllowed(current_user_access, id, *role);
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteeIsAllowed(current_user_access, id, *role);
|
||||
all_granted_roles.makeUnion(role->granted_roles);
|
||||
}
|
||||
else if (auto user = typeid_cast<UserPtr>(entity))
|
||||
{
|
||||
checkGranteeIsAllowed(current_user_access, id, *user);
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteeIsAllowed(current_user_access, id, *user);
|
||||
all_granted_roles.makeUnion(user->granted_roles);
|
||||
}
|
||||
}
|
||||
const auto & all_granted_roles_set = admin_option ? all_granted_roles.getGrantedWithAdminOption() : all_granted_roles.getGranted();
|
||||
|
||||
need_check_grantees_are_allowed = false; /// already checked
|
||||
|
||||
const auto & all_granted_roles_set = admin_option ? all_granted_roles.getGrantedWithAdminOption() : all_granted_roles.getGranted();
|
||||
if (roles_to_revoke.all)
|
||||
boost::range::set_difference(all_granted_roles_set, roles_to_revoke.except_ids, std::back_inserter(roles_to_revoke_ids));
|
||||
else
|
||||
@ -283,28 +267,45 @@ namespace
|
||||
current_user_access.checkAdminOption(roles_to_revoke_ids);
|
||||
}
|
||||
|
||||
/// Checks if the current user has enough roles granted with admin option to grant or revoke specified roles.
|
||||
/// Also checks if grantees are allowed for the current user.
|
||||
void checkAdminOptionAndGrantees(
|
||||
const AccessControlManager & access_control,
|
||||
const ContextAccess & current_user_access,
|
||||
const std::vector<UUID> & grantees_from_query,
|
||||
const std::vector<UUID> & roles_to_grant,
|
||||
RolesOrUsersSet & roles_to_revoke,
|
||||
bool admin_option)
|
||||
/// Returns access rights which should be checked for executing GRANT/REVOKE on cluster.
|
||||
/// This function is less accurate than checkGrantOption() because it cannot use any information about
|
||||
/// access rights the grantees currently have (due to those grantees are located on multiple nodes,
|
||||
/// we just don't have the full information about them).
|
||||
AccessRightsElements getRequiredAccessForExecutingOnCluster(const AccessRightsElements & elements_to_grant, const AccessRightsElements & elements_to_revoke)
|
||||
{
|
||||
bool need_check_grantees_are_allowed = true;
|
||||
checkAdminOption(
|
||||
access_control,
|
||||
current_user_access,
|
||||
grantees_from_query,
|
||||
need_check_grantees_are_allowed,
|
||||
roles_to_grant,
|
||||
roles_to_revoke,
|
||||
admin_option);
|
||||
auto required_access = elements_to_grant;
|
||||
required_access.insert(required_access.end(), elements_to_revoke.begin(), elements_to_revoke.end());
|
||||
std::for_each(required_access.begin(), required_access.end(), [&](AccessRightsElement & element) { element.grant_option = true; });
|
||||
return required_access;
|
||||
}
|
||||
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteesAreAllowed(access_control, current_user_access, grantees_from_query);
|
||||
/// Checks if the current user has enough roles granted with admin option to grant or revoke specified roles on cluster.
|
||||
/// This function is less accurate than checkAdminOption() because it cannot use any information about
|
||||
/// granted roles the grantees currently have (due to those grantees are located on multiple nodes,
|
||||
/// we just don't have the full information about them).
|
||||
void checkAdminOptionForExecutingOnCluster(const ContextAccess & current_user_access,
|
||||
const std::vector<UUID> roles_to_grant,
|
||||
const RolesOrUsersSet & roles_to_revoke)
|
||||
{
|
||||
if (roles_to_revoke.all)
|
||||
{
|
||||
/// Revoking all the roles on cluster always requires ROLE_ADMIN privilege
|
||||
/// because when we send the query REVOKE ALL to each shard we don't know at this point
|
||||
/// which roles exactly this is going to revoke on each shard.
|
||||
/// However ROLE_ADMIN just allows to revoke every role, that's why we check it here.
|
||||
current_user_access.checkAccess(AccessType::ROLE_ADMIN);
|
||||
return;
|
||||
}
|
||||
|
||||
if (current_user_access.isGranted(AccessType::ROLE_ADMIN))
|
||||
return;
|
||||
|
||||
for (const auto & role_id : roles_to_grant)
|
||||
current_user_access.checkAdminOption(role_id);
|
||||
|
||||
|
||||
for (const auto & role_id : roles_to_revoke.getMatchingIDs())
|
||||
current_user_access.checkAdminOption(role_id);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
@ -382,29 +383,39 @@ BlockIO InterpreterGrantQuery::execute()
|
||||
throw Exception("A partial revoke should be revoked, not granted", ErrorCodes::LOGICAL_ERROR);
|
||||
|
||||
auto & access_control = getContext()->getAccessControlManager();
|
||||
auto current_user_access = getContext()->getAccess();
|
||||
|
||||
std::vector<UUID> grantees = RolesOrUsersSet{*query.grantees, access_control, getContext()->getUserID()}.getMatchingIDs(access_control);
|
||||
|
||||
/// Check if the current user has corresponding roles granted with admin option.
|
||||
/// Collect access rights and roles we're going to grant or revoke.
|
||||
AccessRightsElements elements_to_grant, elements_to_revoke;
|
||||
collectAccessRightsElementsToGrantOrRevoke(query, elements_to_grant, elements_to_revoke);
|
||||
|
||||
std::vector<UUID> roles_to_grant;
|
||||
RolesOrUsersSet roles_to_revoke;
|
||||
collectRolesToGrantOrRevoke(access_control, query, roles_to_grant, roles_to_revoke);
|
||||
checkAdminOptionAndGrantees(access_control, *getContext()->getAccess(), grantees, roles_to_grant, roles_to_revoke, query.admin_option);
|
||||
|
||||
/// Executing on cluster.
|
||||
if (!query.cluster.empty())
|
||||
{
|
||||
/// To execute the command GRANT the current user needs to have the access granted with GRANT OPTION.
|
||||
auto required_access = query.access_rights_elements;
|
||||
std::for_each(required_access.begin(), required_access.end(), [&](AccessRightsElement & element) { element.grant_option = true; });
|
||||
checkGranteesAreAllowed(access_control, *getContext()->getAccess(), grantees);
|
||||
auto required_access = getRequiredAccessForExecutingOnCluster(elements_to_grant, elements_to_revoke);
|
||||
checkAdminOptionForExecutingOnCluster(*current_user_access, roles_to_grant, roles_to_revoke);
|
||||
checkGranteesAreAllowed(access_control, *current_user_access, grantees);
|
||||
return executeDDLQueryOnCluster(query_ptr, getContext(), std::move(required_access));
|
||||
}
|
||||
|
||||
query.replaceEmptyDatabase(getContext()->getCurrentDatabase());
|
||||
/// Check if the current user has corresponding access rights granted with grant option.
|
||||
String current_database = getContext()->getCurrentDatabase();
|
||||
elements_to_grant.replaceEmptyDatabase(current_database);
|
||||
elements_to_revoke.replaceEmptyDatabase(current_database);
|
||||
bool need_check_grantees_are_allowed = true;
|
||||
checkGrantOption(access_control, *current_user_access, grantees, need_check_grantees_are_allowed, elements_to_grant, elements_to_revoke);
|
||||
|
||||
/// Check if the current user has corresponding access rights with grant option.
|
||||
AccessRightsElements elements_to_grant, elements_to_revoke;
|
||||
collectAccessRightsElementsToGrantOrRevoke(query, elements_to_grant, elements_to_revoke);
|
||||
checkGrantOptionAndGrantees(access_control, *getContext()->getAccess(), grantees, elements_to_grant, elements_to_revoke);
|
||||
/// Check if the current user has corresponding roles granted with admin option.
|
||||
checkAdminOption(access_control, *current_user_access, grantees, need_check_grantees_are_allowed, roles_to_grant, roles_to_revoke, query.admin_option);
|
||||
|
||||
if (need_check_grantees_are_allowed)
|
||||
checkGranteesAreAllowed(access_control, *current_user_access, grantees);
|
||||
|
||||
/// Update roles and users listed in `grantees`.
|
||||
auto update_func = [&](const AccessEntityPtr & entity) -> AccessEntityPtr
|
||||
|
@ -2080,7 +2080,9 @@ void InterpreterSelectQuery::executeAggregation(QueryPlan & query_plan, const Ac
|
||||
settings.group_by_two_level_threshold,
|
||||
settings.group_by_two_level_threshold_bytes,
|
||||
settings.max_bytes_before_external_group_by,
|
||||
settings.empty_result_for_aggregation_by_empty_set || (keys.empty() && query_analyzer->hasConstAggregationKeys()),
|
||||
settings.empty_result_for_aggregation_by_empty_set
|
||||
|| (settings.empty_result_for_aggregation_by_constant_keys_on_empty_set && keys.empty()
|
||||
&& query_analyzer->hasConstAggregationKeys()),
|
||||
context->getTemporaryVolume(),
|
||||
settings.max_threads,
|
||||
settings.min_free_disk_space_for_temporary_data,
|
||||
|
@ -54,17 +54,17 @@ class NamedSessionsStorage
|
||||
public:
|
||||
using Key = NamedSessionKey;
|
||||
|
||||
static NamedSessionsStorage & instance()
|
||||
{
|
||||
static NamedSessionsStorage the_instance;
|
||||
return the_instance;
|
||||
}
|
||||
|
||||
~NamedSessionsStorage()
|
||||
{
|
||||
try
|
||||
{
|
||||
{
|
||||
std::lock_guard lock{mutex};
|
||||
quit = true;
|
||||
}
|
||||
|
||||
cond.notify_one();
|
||||
thread.join();
|
||||
shutdown();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
@ -72,6 +72,20 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void shutdown()
|
||||
{
|
||||
{
|
||||
std::lock_guard lock{mutex};
|
||||
sessions.clear();
|
||||
if (!thread.joinable())
|
||||
return;
|
||||
quit = true;
|
||||
}
|
||||
|
||||
cond.notify_one();
|
||||
thread.join();
|
||||
}
|
||||
|
||||
/// Find existing session or create a new.
|
||||
std::pair<std::shared_ptr<NamedSessionData>, bool> acquireSession(
|
||||
const ContextPtr & global_context,
|
||||
@ -94,6 +108,10 @@ public:
|
||||
auto context = Context::createCopy(global_context);
|
||||
it = sessions.insert(std::make_pair(key, std::make_shared<NamedSessionData>(key, context, timeout, *this))).first;
|
||||
const auto & session = it->second;
|
||||
|
||||
if (!thread.joinable())
|
||||
thread = ThreadFromGlobalPool{&NamedSessionsStorage::cleanThread, this};
|
||||
|
||||
return {session, true};
|
||||
}
|
||||
else
|
||||
@ -156,11 +174,9 @@ private:
|
||||
{
|
||||
setThreadName("SessionCleaner");
|
||||
std::unique_lock lock{mutex};
|
||||
|
||||
while (true)
|
||||
while (!quit)
|
||||
{
|
||||
auto interval = closeSessions(lock);
|
||||
|
||||
if (cond.wait_for(lock, interval, [this]() -> bool { return quit; }))
|
||||
break;
|
||||
}
|
||||
@ -208,8 +224,8 @@ private:
|
||||
|
||||
std::mutex mutex;
|
||||
std::condition_variable cond;
|
||||
std::atomic<bool> quit{false};
|
||||
ThreadFromGlobalPool thread{&NamedSessionsStorage::cleanThread, this};
|
||||
ThreadFromGlobalPool thread;
|
||||
bool quit = false;
|
||||
};
|
||||
|
||||
|
||||
@ -218,13 +234,12 @@ void NamedSessionData::release()
|
||||
parent.releaseSession(*this);
|
||||
}
|
||||
|
||||
std::optional<NamedSessionsStorage> Session::named_sessions = std::nullopt;
|
||||
|
||||
void Session::startupNamedSessions()
|
||||
void Session::shutdownNamedSessions()
|
||||
{
|
||||
named_sessions.emplace();
|
||||
NamedSessionsStorage::instance().shutdown();
|
||||
}
|
||||
|
||||
|
||||
Session::Session(const ContextPtr & global_context_, ClientInfo::Interface interface_)
|
||||
: global_context(global_context_)
|
||||
{
|
||||
@ -317,15 +332,13 @@ ContextMutablePtr Session::makeSessionContext(const String & session_id_, std::c
|
||||
throw Exception("Session context already exists", ErrorCodes::LOGICAL_ERROR);
|
||||
if (query_context_created)
|
||||
throw Exception("Session context must be created before any query context", ErrorCodes::LOGICAL_ERROR);
|
||||
if (!named_sessions)
|
||||
throw Exception("Support for named sessions is not enabled", ErrorCodes::LOGICAL_ERROR);
|
||||
|
||||
/// Make a new session context OR
|
||||
/// if the `session_id` and `user_id` were used before then just get a previously created session context.
|
||||
std::shared_ptr<NamedSessionData> new_named_session;
|
||||
bool new_named_session_created = false;
|
||||
std::tie(new_named_session, new_named_session_created)
|
||||
= named_sessions->acquireSession(global_context, user_id.value_or(UUID{}), session_id_, timeout_, session_check_);
|
||||
= NamedSessionsStorage::instance().acquireSession(global_context, user_id.value_or(UUID{}), session_id_, timeout_, session_check_);
|
||||
|
||||
auto new_session_context = new_named_session->context;
|
||||
new_session_context->makeSessionContext();
|
||||
|
@ -28,9 +28,8 @@ using UserPtr = std::shared_ptr<const User>;
|
||||
class Session
|
||||
{
|
||||
public:
|
||||
/// Allow to use named sessions. The thread will be run to cleanup sessions after timeout has expired.
|
||||
/// The method must be called at the server startup.
|
||||
static void startupNamedSessions();
|
||||
/// Stops using named sessions. The method must be called at the server shutdown.
|
||||
static void shutdownNamedSessions();
|
||||
|
||||
Session(const ContextPtr & global_context_, ClientInfo::Interface interface_);
|
||||
Session(Session &&);
|
||||
@ -83,8 +82,6 @@ private:
|
||||
String session_id;
|
||||
std::shared_ptr<NamedSessionData> named_session;
|
||||
bool named_session_created = false;
|
||||
|
||||
static std::optional<NamedSessionsStorage> named_sessions;
|
||||
};
|
||||
|
||||
}
|
||||
|
@ -69,7 +69,9 @@ const std::unordered_set<String> possibly_injective_function_names
|
||||
void appendUnusedGroupByColumn(ASTSelectQuery * select_query, const NameSet & source_columns)
|
||||
{
|
||||
/// You must insert a constant that is not the name of the column in the table. Such a case is rare, but it happens.
|
||||
UInt64 unused_column = 0;
|
||||
/// Also start unused_column integer from source_columns.size() + 1, because lower numbers ([1, source_columns.size()])
|
||||
/// might be in positional GROUP BY.
|
||||
UInt64 unused_column = source_columns.size() + 1;
|
||||
String unused_column_name = toString(unused_column);
|
||||
|
||||
while (source_columns.count(unused_column_name))
|
||||
@ -111,6 +113,8 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum
|
||||
group_exprs.pop_back();
|
||||
};
|
||||
|
||||
const auto & settings = context->getSettingsRef();
|
||||
|
||||
/// iterate over each GROUP BY expression, eliminate injective function calls and literals
|
||||
for (size_t i = 0; i < group_exprs.size();)
|
||||
{
|
||||
@ -166,7 +170,22 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum
|
||||
}
|
||||
else if (is_literal(group_exprs[i]))
|
||||
{
|
||||
remove_expr_at_index(i);
|
||||
bool keep_position = false;
|
||||
if (settings.enable_positional_arguments)
|
||||
{
|
||||
const auto & value = group_exprs[i]->as<ASTLiteral>()->value;
|
||||
if (value.getType() == Field::Types::UInt64)
|
||||
{
|
||||
auto pos = value.get<UInt64>();
|
||||
if (pos > 0 && pos <= select_query->children.size())
|
||||
keep_position = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (keep_position)
|
||||
++i;
|
||||
else
|
||||
remove_expr_at_index(i);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
@ -7,6 +7,7 @@
|
||||
#include <Common/quoteString.h>
|
||||
#include <IO/Operators.h>
|
||||
#include <re2/re2.h>
|
||||
#include <stack>
|
||||
|
||||
|
||||
namespace DB
|
||||
@ -40,10 +41,18 @@ void ASTColumnsApplyTransformer::formatImpl(const FormatSettings & settings, For
|
||||
|
||||
if (!column_name_prefix.empty())
|
||||
settings.ostr << "(";
|
||||
settings.ostr << func_name;
|
||||
|
||||
if (parameters)
|
||||
parameters->formatImpl(settings, state, frame);
|
||||
if (lambda)
|
||||
{
|
||||
lambda->formatImpl(settings, state, frame);
|
||||
}
|
||||
else
|
||||
{
|
||||
settings.ostr << func_name;
|
||||
|
||||
if (parameters)
|
||||
parameters->formatImpl(settings, state, frame);
|
||||
}
|
||||
|
||||
if (!column_name_prefix.empty())
|
||||
settings.ostr << ", '" << column_name_prefix << "')";
|
||||
@ -64,9 +73,33 @@ void ASTColumnsApplyTransformer::transform(ASTs & nodes) const
|
||||
else
|
||||
name = column->getColumnName();
|
||||
}
|
||||
auto function = makeASTFunction(func_name, column);
|
||||
function->parameters = parameters;
|
||||
column = function;
|
||||
if (lambda)
|
||||
{
|
||||
auto body = lambda->as<const ASTFunction &>().arguments->children.at(1)->clone();
|
||||
std::stack<ASTPtr> stack;
|
||||
stack.push(body);
|
||||
while (!stack.empty())
|
||||
{
|
||||
auto ast = stack.top();
|
||||
stack.pop();
|
||||
for (auto & child : ast->children)
|
||||
{
|
||||
if (auto arg_name = tryGetIdentifierName(child); arg_name && arg_name == lambda_arg)
|
||||
{
|
||||
child = column->clone();
|
||||
continue;
|
||||
}
|
||||
stack.push(child);
|
||||
}
|
||||
}
|
||||
column = body;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto function = makeASTFunction(func_name, column);
|
||||
function->parameters = parameters;
|
||||
column = function;
|
||||
}
|
||||
if (!column_name_prefix.empty())
|
||||
column->setAlias(column_name_prefix + name);
|
||||
}
|
||||
|
@ -25,13 +25,22 @@ public:
|
||||
auto res = std::make_shared<ASTColumnsApplyTransformer>(*this);
|
||||
if (parameters)
|
||||
res->parameters = parameters->clone();
|
||||
if (lambda)
|
||||
res->lambda = lambda->clone();
|
||||
return res;
|
||||
}
|
||||
void transform(ASTs & nodes) const override;
|
||||
|
||||
// Case 1 APPLY (quantile(0.9))
|
||||
String func_name;
|
||||
String column_name_prefix;
|
||||
ASTPtr parameters;
|
||||
|
||||
// Case 2 APPLY (x -> quantile(0.9)(x))
|
||||
ASTPtr lambda;
|
||||
String lambda_arg;
|
||||
|
||||
String column_name_prefix;
|
||||
|
||||
protected:
|
||||
void formatImpl(const FormatSettings & settings, FormatState &, FormatStateStacked) const override;
|
||||
};
|
||||
|
@ -35,6 +35,44 @@ public:
|
||||
SETTINGS
|
||||
};
|
||||
|
||||
static String expressionToString(Expression expr)
|
||||
{
|
||||
switch (expr)
|
||||
{
|
||||
case Expression::WITH:
|
||||
return "WITH";
|
||||
case Expression::SELECT:
|
||||
return "SELECT";
|
||||
case Expression::TABLES:
|
||||
return "TABLES";
|
||||
case Expression::PREWHERE:
|
||||
return "PREWHERE";
|
||||
case Expression::WHERE:
|
||||
return "WHERE";
|
||||
case Expression::GROUP_BY:
|
||||
return "GROUP BY";
|
||||
case Expression::HAVING:
|
||||
return "HAVING";
|
||||
case Expression::WINDOW:
|
||||
return "WINDOW";
|
||||
case Expression::ORDER_BY:
|
||||
return "ORDER BY";
|
||||
case Expression::LIMIT_BY_OFFSET:
|
||||
return "LIMIT BY OFFSET";
|
||||
case Expression::LIMIT_BY_LENGTH:
|
||||
return "LIMIT BY LENGTH";
|
||||
case Expression::LIMIT_BY:
|
||||
return "LIMIT BY";
|
||||
case Expression::LIMIT_OFFSET:
|
||||
return "LIMIT OFFSET";
|
||||
case Expression::LIMIT_LENGTH:
|
||||
return "LIMIT LENGTH";
|
||||
case Expression::SETTINGS:
|
||||
return "SETTINGS";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** Get the text that identifies this element. */
|
||||
String getID(char) const override { return "SelectQuery"; }
|
||||
|
||||
|
@ -12,3 +12,7 @@ endif ()
|
||||
if(ENABLE_EXAMPLES)
|
||||
add_subdirectory(examples)
|
||||
endif()
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_subdirectory(fuzzers)
|
||||
endif()
|
||||
|
@ -1827,20 +1827,47 @@ bool ParserColumnsTransformers::parseImpl(Pos & pos, ASTPtr & node, Expected & e
|
||||
with_open_round_bracket = true;
|
||||
}
|
||||
|
||||
ASTPtr lambda;
|
||||
String lambda_arg;
|
||||
ASTPtr func_name;
|
||||
if (!ParserIdentifier().parse(pos, func_name, expected))
|
||||
return false;
|
||||
|
||||
ASTPtr expr_list_args;
|
||||
if (pos->type == TokenType::OpeningRoundBracket)
|
||||
auto opos = pos;
|
||||
if (ParserLambdaExpression().parse(pos, lambda, expected))
|
||||
{
|
||||
++pos;
|
||||
if (!ParserExpressionList(false).parse(pos, expr_list_args, expected))
|
||||
if (const auto * func = lambda->as<ASTFunction>(); func && func->name == "lambda")
|
||||
{
|
||||
const auto * lambda_args_tuple = func->arguments->children.at(0)->as<ASTFunction>();
|
||||
const ASTs & lambda_arg_asts = lambda_args_tuple->arguments->children;
|
||||
if (lambda_arg_asts.size() != 1)
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS, "APPLY column transformer can only accept lambda with one argument");
|
||||
|
||||
if (auto opt_arg_name = tryGetIdentifierName(lambda_arg_asts[0]); opt_arg_name)
|
||||
lambda_arg = *opt_arg_name;
|
||||
else
|
||||
throw Exception(ErrorCodes::BAD_ARGUMENTS, "lambda argument declarations must be identifiers");
|
||||
}
|
||||
else
|
||||
{
|
||||
lambda = nullptr;
|
||||
pos = opos;
|
||||
}
|
||||
}
|
||||
|
||||
if (!lambda)
|
||||
{
|
||||
if (!ParserIdentifier().parse(pos, func_name, expected))
|
||||
return false;
|
||||
|
||||
if (pos->type != TokenType::ClosingRoundBracket)
|
||||
return false;
|
||||
++pos;
|
||||
if (pos->type == TokenType::OpeningRoundBracket)
|
||||
{
|
||||
++pos;
|
||||
if (!ParserExpressionList(false).parse(pos, expr_list_args, expected))
|
||||
return false;
|
||||
|
||||
if (pos->type != TokenType::ClosingRoundBracket)
|
||||
return false;
|
||||
++pos;
|
||||
}
|
||||
}
|
||||
|
||||
String column_name_prefix;
|
||||
@ -1864,8 +1891,16 @@ bool ParserColumnsTransformers::parseImpl(Pos & pos, ASTPtr & node, Expected & e
|
||||
}
|
||||
|
||||
auto res = std::make_shared<ASTColumnsApplyTransformer>();
|
||||
res->func_name = getIdentifierName(func_name);
|
||||
res->parameters = expr_list_args;
|
||||
if (lambda)
|
||||
{
|
||||
res->lambda = lambda;
|
||||
res->lambda_arg = lambda_arg;
|
||||
}
|
||||
else
|
||||
{
|
||||
res->func_name = getIdentifierName(func_name);
|
||||
res->parameters = expr_list_args;
|
||||
}
|
||||
res->column_name_prefix = column_name_prefix;
|
||||
node = std::move(res);
|
||||
return true;
|
||||
|
@ -8,14 +8,3 @@ target_link_libraries(select_parser PRIVATE clickhouse_parsers)
|
||||
|
||||
add_executable(create_parser create_parser.cpp ${SRCS})
|
||||
target_link_libraries(create_parser PRIVATE clickhouse_parsers)
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_executable(lexer_fuzzer lexer_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(lexer_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
||||
|
||||
add_executable(select_parser_fuzzer select_parser_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(select_parser_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
||||
|
||||
add_executable(create_parser_fuzzer create_parser_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(create_parser_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
||||
endif ()
|
||||
|
8
src/Parsers/fuzzers/CMakeLists.txt
Normal file
8
src/Parsers/fuzzers/CMakeLists.txt
Normal file
@ -0,0 +1,8 @@
|
||||
add_executable(lexer_fuzzer lexer_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(lexer_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
||||
|
||||
add_executable(select_parser_fuzzer select_parser_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(select_parser_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
||||
|
||||
add_executable(create_parser_fuzzer create_parser_fuzzer.cpp ${SRCS})
|
||||
target_link_libraries(create_parser_fuzzer PRIVATE clickhouse_parsers ${LIB_FUZZING_ENGINE})
|
@ -15,7 +15,10 @@ try
|
||||
DB::ParserCreateQuery parser;
|
||||
DB::ASTPtr ast = parseQuery(parser, input.data(), input.data() + input.size(), "", 0, 0);
|
||||
|
||||
DB::formatAST(*ast, std::cerr);
|
||||
DB::WriteBufferFromOwnString wb;
|
||||
DB::formatAST(*ast, wb);
|
||||
|
||||
std::cerr << wb.str() << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
@ -14,7 +14,10 @@ try
|
||||
DB::ParserQueryWithOutput parser(input.data() + input.size());
|
||||
DB::ASTPtr ast = parseQuery(parser, input.data(), input.data() + input.size(), "", 0, 0);
|
||||
|
||||
DB::formatAST(*ast, std::cerr);
|
||||
DB::WriteBufferFromOwnString wb;
|
||||
DB::formatAST(*ast, wb);
|
||||
|
||||
std::cerr << wb.str() << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
@ -49,27 +49,6 @@
|
||||
namespace DB
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string formatHTTPErrorResponse(const Poco::Util::AbstractConfiguration& config)
|
||||
{
|
||||
std::string result = fmt::format(
|
||||
"HTTP/1.0 400 Bad Request\r\n\r\n"
|
||||
"Port {} is for clickhouse-client program\r\n",
|
||||
config.getString("tcp_port"));
|
||||
|
||||
if (config.has("http_port"))
|
||||
{
|
||||
result += fmt::format(
|
||||
"You must use port {} for HTTP.\r\n",
|
||||
config.getString("http_port"));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
namespace ErrorCodes
|
||||
{
|
||||
extern const int LOGICAL_ERROR;
|
||||
@ -925,6 +904,29 @@ bool TCPHandler::receiveProxyHeader()
|
||||
}
|
||||
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
std::string formatHTTPErrorResponseWhenUserIsConnectedToWrongPort(const Poco::Util::AbstractConfiguration& config)
|
||||
{
|
||||
std::string result = fmt::format(
|
||||
"HTTP/1.0 400 Bad Request\r\n\r\n"
|
||||
"Port {} is for clickhouse-client program\r\n",
|
||||
config.getString("tcp_port"));
|
||||
|
||||
if (config.has("http_port"))
|
||||
{
|
||||
result += fmt::format(
|
||||
"You must use port {} for HTTP.\r\n",
|
||||
config.getString("http_port"));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
void TCPHandler::receiveHello()
|
||||
{
|
||||
/// Receive `hello` packet.
|
||||
@ -940,9 +942,7 @@ void TCPHandler::receiveHello()
|
||||
*/
|
||||
if (packet_type == 'G' || packet_type == 'P')
|
||||
{
|
||||
writeString(formatHTTPErrorResponse(server.config()),
|
||||
*out);
|
||||
|
||||
writeString(formatHTTPErrorResponseWhenUserIsConnectedToWrongPort(server.config()), *out);
|
||||
throw Exception("Client has connected to wrong port", ErrorCodes::CLIENT_HAS_CONNECTED_TO_WRONG_PORT);
|
||||
}
|
||||
else
|
||||
|
@ -679,6 +679,9 @@ bool isMetadataOnlyConversion(const IDataType * from, const IDataType * to)
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (from->equals(*to))
|
||||
return true;
|
||||
|
||||
auto it_range = ALLOWED_CONVERSIONS.equal_range(typeid(*from));
|
||||
for (auto it = it_range.first; it != it_range.second; ++it)
|
||||
{
|
||||
@ -697,9 +700,9 @@ bool isMetadataOnlyConversion(const IDataType * from, const IDataType * to)
|
||||
|
||||
const auto * nullable_from = typeid_cast<const DataTypeNullable *>(from);
|
||||
const auto * nullable_to = typeid_cast<const DataTypeNullable *>(to);
|
||||
if (nullable_from && nullable_to)
|
||||
if (nullable_to)
|
||||
{
|
||||
from = nullable_from->getNestedType().get();
|
||||
from = nullable_from ? nullable_from->getNestedType().get() : from;
|
||||
to = nullable_to->getNestedType().get();
|
||||
continue;
|
||||
}
|
||||
|
@ -1,6 +1,10 @@
|
||||
add_subdirectory(MergeTree)
|
||||
add_subdirectory(System)
|
||||
|
||||
if(ENABLE_EXAMPLES)
|
||||
if (ENABLE_EXAMPLES)
|
||||
add_subdirectory(examples)
|
||||
endif()
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_subdirectory(fuzzers)
|
||||
endif()
|
||||
|
@ -48,7 +48,7 @@ WriteBufferToKafkaProducer::WriteBufferToKafkaProducer(
|
||||
|
||||
WriteBufferToKafkaProducer::~WriteBufferToKafkaProducer()
|
||||
{
|
||||
assert(rows == 0 && chunks.empty());
|
||||
assert(rows == 0);
|
||||
}
|
||||
|
||||
void WriteBufferToKafkaProducer::countRow(const Columns & columns, size_t current_row)
|
||||
|
@ -172,11 +172,21 @@ bool ReplicatedMergeTreeRestartingThread::tryStartup()
|
||||
|
||||
storage.cloneReplicaIfNeeded(zookeeper);
|
||||
|
||||
storage.queue.load(zookeeper);
|
||||
try
|
||||
{
|
||||
storage.queue.load(zookeeper);
|
||||
|
||||
/// pullLogsToQueue() after we mark replica 'is_active' (and after we repair if it was lost);
|
||||
/// because cleanup_thread doesn't delete log_pointer of active replicas.
|
||||
storage.queue.pullLogsToQueue(zookeeper, {}, ReplicatedMergeTreeQueue::LOAD);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
std::unique_lock lock(storage.last_queue_update_exception_lock);
|
||||
storage.last_queue_update_exception = getCurrentExceptionMessage(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
/// pullLogsToQueue() after we mark replica 'is_active' (and after we repair if it was lost);
|
||||
/// because cleanup_thread doesn't delete log_pointer of active replicas.
|
||||
storage.queue.pullLogsToQueue(zookeeper, {}, ReplicatedMergeTreeQueue::LOAD);
|
||||
storage.queue.removeCurrentPartsFromMutations();
|
||||
storage.last_queue_update_finish_time.store(time(nullptr));
|
||||
|
||||
|
@ -101,7 +101,7 @@ WriteBufferToRabbitMQProducer::~WriteBufferToRabbitMQProducer()
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(CONNECT_SLEEP));
|
||||
}
|
||||
|
||||
assert(rows == 0 && chunks.empty());
|
||||
assert(rows == 0);
|
||||
}
|
||||
|
||||
|
||||
|
@ -327,11 +327,13 @@ StorageDistributed::StorageDistributed(
|
||||
const String & relative_data_path_,
|
||||
const DistributedSettings & distributed_settings_,
|
||||
bool attach_,
|
||||
ClusterPtr owned_cluster_)
|
||||
ClusterPtr owned_cluster_,
|
||||
ASTPtr remote_table_function_ptr_)
|
||||
: IStorage(id_)
|
||||
, WithContext(context_->getGlobalContext())
|
||||
, remote_database(remote_database_)
|
||||
, remote_table(remote_table_)
|
||||
, remote_table_function_ptr(remote_table_function_ptr_)
|
||||
, log(&Poco::Logger::get("StorageDistributed (" + id_.table_name + ")"))
|
||||
, owned_cluster(std::move(owned_cluster_))
|
||||
, cluster_name(getContext()->getMacros()->expand(cluster_name_))
|
||||
@ -363,10 +365,13 @@ StorageDistributed::StorageDistributed(
|
||||
}
|
||||
|
||||
/// Sanity check. Skip check if the table is already created to allow the server to start.
|
||||
if (!attach_ && !cluster_name.empty())
|
||||
if (!attach_)
|
||||
{
|
||||
size_t num_local_shards = getContext()->getCluster(cluster_name)->getLocalShardCount();
|
||||
if (num_local_shards && remote_database == id_.database_name && remote_table == id_.table_name)
|
||||
if (remote_database.empty() && !remote_table_function_ptr && !getCluster()->maybeCrossReplication())
|
||||
LOG_WARNING(log, "Name of remote database is empty. Default database will be used implicitly.");
|
||||
|
||||
size_t num_local_shards = getCluster()->getLocalShardCount();
|
||||
if (num_local_shards && (remote_database.empty() || remote_database == id_.database_name) && remote_table == id_.table_name)
|
||||
throw Exception("Distributed table " + id_.table_name + " looks at itself", ErrorCodes::INFINITE_LOOP);
|
||||
}
|
||||
}
|
||||
@ -399,9 +404,9 @@ StorageDistributed::StorageDistributed(
|
||||
relative_data_path_,
|
||||
distributed_settings_,
|
||||
attach,
|
||||
std::move(owned_cluster_))
|
||||
std::move(owned_cluster_),
|
||||
remote_table_function_ptr_)
|
||||
{
|
||||
remote_table_function_ptr = std::move(remote_table_function_ptr_);
|
||||
}
|
||||
|
||||
QueryProcessingStage::Enum StorageDistributed::getQueryProcessingStage(
|
||||
@ -810,9 +815,6 @@ void StorageDistributed::alter(const AlterCommands & params, ContextPtr local_co
|
||||
|
||||
void StorageDistributed::startup()
|
||||
{
|
||||
if (remote_database.empty() && !remote_table_function_ptr && !getCluster()->maybeCrossReplication())
|
||||
LOG_WARNING(log, "Name of remote database is empty. Default database will be used implicitly.");
|
||||
|
||||
if (!storage_policy)
|
||||
return;
|
||||
|
||||
|
@ -136,7 +136,8 @@ private:
|
||||
const String & relative_data_path_,
|
||||
const DistributedSettings & distributed_settings_,
|
||||
bool attach_,
|
||||
ClusterPtr owned_cluster_ = {});
|
||||
ClusterPtr owned_cluster_ = {},
|
||||
ASTPtr remote_table_function_ptr_ = {});
|
||||
|
||||
StorageDistributed(
|
||||
const StorageID & id_,
|
||||
|
@ -49,6 +49,7 @@ namespace ErrorCodes
|
||||
{
|
||||
extern const int BAD_ARGUMENTS;
|
||||
extern const int NOT_IMPLEMENTED;
|
||||
extern const int CANNOT_FSTAT;
|
||||
extern const int CANNOT_TRUNCATE_FILE;
|
||||
extern const int DATABASE_ACCESS_DENIED;
|
||||
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
|
||||
@ -164,6 +165,12 @@ bool StorageFile::isColumnOriented() const
|
||||
StorageFile::StorageFile(int table_fd_, CommonArguments args)
|
||||
: StorageFile(args)
|
||||
{
|
||||
struct stat buf;
|
||||
int res = fstat(table_fd_, &buf);
|
||||
if (-1 == res)
|
||||
throwFromErrno("Cannot execute fstat", res, ErrorCodes::CANNOT_FSTAT);
|
||||
total_bytes_to_read = buf.st_size;
|
||||
|
||||
if (args.getContext()->getApplicationType() == Context::ApplicationType::SERVER)
|
||||
throw Exception("Using file descriptor as source of storage isn't allowed for server daemons", ErrorCodes::DATABASE_ACCESS_DENIED);
|
||||
if (args.format_name == "Distributed")
|
||||
@ -208,6 +215,8 @@ StorageFile::StorageFile(const std::string & relative_table_dir_path, CommonArgu
|
||||
String table_dir_path = fs::path(base_path) / relative_table_dir_path / "";
|
||||
fs::create_directories(table_dir_path);
|
||||
paths = {getTablePath(table_dir_path, format_name)};
|
||||
if (fs::exists(paths[0]))
|
||||
total_bytes_to_read = fs::file_size(paths[0]);
|
||||
}
|
||||
|
||||
StorageFile::StorageFile(CommonArguments args)
|
||||
|
@ -3079,6 +3079,12 @@ void StorageReplicatedMergeTree::cloneReplicaIfNeeded(zkutil::ZooKeeperPtr zooke
|
||||
zookeeper->set(fs::path(replica_path) / "is_lost", "0");
|
||||
}
|
||||
|
||||
String StorageReplicatedMergeTree::getLastQueueUpdateException() const
|
||||
{
|
||||
std::unique_lock lock(last_queue_update_exception_lock);
|
||||
return last_queue_update_exception;
|
||||
}
|
||||
|
||||
|
||||
void StorageReplicatedMergeTree::queueUpdatingTask()
|
||||
{
|
||||
@ -3097,6 +3103,9 @@ void StorageReplicatedMergeTree::queueUpdatingTask()
|
||||
{
|
||||
tryLogCurrentException(log, __PRETTY_FUNCTION__);
|
||||
|
||||
std::unique_lock lock(last_queue_update_exception_lock);
|
||||
last_queue_update_exception = getCurrentExceptionMessage(false);
|
||||
|
||||
if (e.code == Coordination::Error::ZSESSIONEXPIRED)
|
||||
{
|
||||
restarting_thread.wakeup();
|
||||
@ -3108,6 +3117,10 @@ void StorageReplicatedMergeTree::queueUpdatingTask()
|
||||
catch (...)
|
||||
{
|
||||
tryLogCurrentException(log, __PRETTY_FUNCTION__);
|
||||
|
||||
std::unique_lock lock(last_queue_update_exception_lock);
|
||||
last_queue_update_exception = getCurrentExceptionMessage(false);
|
||||
|
||||
queue_updating_task->scheduleAfter(QUEUE_UPDATE_ERROR_SLEEP_MS);
|
||||
}
|
||||
}
|
||||
@ -5565,6 +5578,7 @@ void StorageReplicatedMergeTree::getStatus(Status & res, bool with_zk_fields)
|
||||
res.log_pointer = 0;
|
||||
res.total_replicas = 0;
|
||||
res.active_replicas = 0;
|
||||
res.last_queue_update_exception = getLastQueueUpdateException();
|
||||
|
||||
if (with_zk_fields && !res.is_session_expired)
|
||||
{
|
||||
|
@ -174,6 +174,7 @@ public:
|
||||
UInt64 absolute_delay;
|
||||
UInt8 total_replicas;
|
||||
UInt8 active_replicas;
|
||||
String last_queue_update_exception;
|
||||
/// If the error has happened fetching the info from ZooKeeper, this field will be set.
|
||||
String zookeeper_exception;
|
||||
std::unordered_map<std::string, bool> replica_is_active;
|
||||
@ -331,6 +332,10 @@ private:
|
||||
std::atomic<time_t> last_queue_update_start_time{0};
|
||||
std::atomic<time_t> last_queue_update_finish_time{0};
|
||||
|
||||
mutable std::mutex last_queue_update_exception_lock;
|
||||
String last_queue_update_exception;
|
||||
String getLastQueueUpdateException() const;
|
||||
|
||||
DataPartsExchange::Fetcher fetcher;
|
||||
|
||||
/// When activated, replica is initialized and startup() method could exit
|
||||
|
@ -51,6 +51,7 @@ StorageSystemReplicas::StorageSystemReplicas(const StorageID & table_id_)
|
||||
{ "absolute_delay", std::make_shared<DataTypeUInt64>() },
|
||||
{ "total_replicas", std::make_shared<DataTypeUInt8>() },
|
||||
{ "active_replicas", std::make_shared<DataTypeUInt8>() },
|
||||
{ "last_queue_update_exception", std::make_shared<DataTypeString>() },
|
||||
{ "zookeeper_exception", std::make_shared<DataTypeString>() },
|
||||
{ "replica_is_active", std::make_shared<DataTypeMap>(std::make_shared<DataTypeString>(), std::make_shared<DataTypeUInt8>()) }
|
||||
}));
|
||||
@ -186,6 +187,7 @@ Pipe StorageSystemReplicas::read(
|
||||
res_columns[col_num++]->insert(status.absolute_delay);
|
||||
res_columns[col_num++]->insert(status.total_replicas);
|
||||
res_columns[col_num++]->insert(status.active_replicas);
|
||||
res_columns[col_num++]->insert(status.last_queue_update_exception);
|
||||
res_columns[col_num++]->insert(status.zookeeper_exception);
|
||||
|
||||
Map replica_is_active_values;
|
||||
|
@ -23,10 +23,3 @@ target_link_libraries (transform_part_zk_nodes
|
||||
string_utils
|
||||
)
|
||||
|
||||
if (ENABLE_FUZZING)
|
||||
add_executable (mergetree_checksum_fuzzer mergetree_checksum_fuzzer.cpp)
|
||||
target_link_libraries (mergetree_checksum_fuzzer PRIVATE dbms ${LIB_FUZZING_ENGINE})
|
||||
|
||||
add_executable (columns_description_fuzzer columns_description_fuzzer.cpp)
|
||||
target_link_libraries (columns_description_fuzzer PRIVATE dbms ${LIB_FUZZING_ENGINE})
|
||||
endif ()
|
||||
|
11
src/Storages/fuzzers/CMakeLists.txt
Normal file
11
src/Storages/fuzzers/CMakeLists.txt
Normal file
@ -0,0 +1,11 @@
|
||||
|
||||
add_executable (mergetree_checksum_fuzzer
|
||||
mergetree_checksum_fuzzer.cpp
|
||||
"${ClickHouse_SOURCE_DIR}/src/Storages/MergeTree/MergeTreeDataPartChecksum.cpp"
|
||||
"${ClickHouse_SOURCE_DIR}/src/Compression/CompressedReadBuffer.cpp"
|
||||
"${ClickHouse_SOURCE_DIR}/src/Compression/CompressedWriteBuffer.cpp"
|
||||
)
|
||||
target_link_libraries (mergetree_checksum_fuzzer PRIVATE clickhouse_common_io fuzz_compression ${LIB_FUZZING_ENGINE})
|
||||
|
||||
add_executable (columns_description_fuzzer columns_description_fuzzer.cpp)
|
||||
target_link_libraries (columns_description_fuzzer PRIVATE dbms ${LIB_FUZZING_ENGINE})
|
@ -474,6 +474,11 @@ class ClickHouseCluster:
|
||||
cmd += " client"
|
||||
return cmd
|
||||
|
||||
def copy_file_from_container_to_container(self, src_node, src_path, dst_node, dst_path):
|
||||
fname = os.path.basename(src_path)
|
||||
run_and_check([f"docker cp {src_node.docker_id}:{src_path} {self.instances_dir}"], shell=True)
|
||||
run_and_check([f"docker cp {self.instances_dir}/{fname} {dst_node.docker_id}:{dst_path}"], shell=True)
|
||||
|
||||
def setup_zookeeper_secure_cmd(self, instance, env_variables, docker_compose_yml_dir):
|
||||
logging.debug('Setup ZooKeeper Secure')
|
||||
zookeeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_zookeeper_secure.yml')
|
||||
@ -1836,6 +1841,10 @@ class ClickHouseInstance:
|
||||
build_opts = self.query("SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'")
|
||||
return "-fsanitize={}".format(sanitizer_name) in build_opts
|
||||
|
||||
def is_debug_build(self):
|
||||
build_opts = self.query("SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'")
|
||||
return 'NDEBUG' not in build_opts
|
||||
|
||||
def is_built_with_thread_sanitizer(self):
|
||||
return self.is_built_with_sanitizer('thread')
|
||||
|
||||
@ -2024,6 +2033,37 @@ class ClickHouseInstance:
|
||||
return None
|
||||
return None
|
||||
|
||||
def restart_with_original_version(self, stop_start_wait_sec=300, callback_onstop=None, signal=15):
|
||||
if not self.stay_alive:
|
||||
raise Exception("Cannot restart not stay alive container")
|
||||
self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(signal)], user='root')
|
||||
retries = int(stop_start_wait_sec / 0.5)
|
||||
local_counter = 0
|
||||
# wait stop
|
||||
while local_counter < retries:
|
||||
if not self.get_process_pid("clickhouse server"):
|
||||
break
|
||||
time.sleep(0.5)
|
||||
local_counter += 1
|
||||
|
||||
# force kill if server hangs
|
||||
if self.get_process_pid("clickhouse server"):
|
||||
# server can die before kill, so don't throw exception, it's expected
|
||||
self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(9)], nothrow=True, user='root')
|
||||
|
||||
if callback_onstop:
|
||||
callback_onstop(self)
|
||||
self.exec_in_container(
|
||||
["bash", "-c", "cp /usr/share/clickhouse_original /usr/bin/clickhouse && chmod 777 /usr/bin/clickhouse"],
|
||||
user='root')
|
||||
self.exec_in_container(["bash", "-c",
|
||||
"cp /usr/share/clickhouse-odbc-bridge_fresh /usr/bin/clickhouse-odbc-bridge && chmod 777 /usr/bin/clickhouse"],
|
||||
user='root')
|
||||
self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid()))
|
||||
|
||||
# wait start
|
||||
assert_eq_with_retry(self, "select 1", "1", retry_count=retries)
|
||||
|
||||
def restart_with_latest_version(self, stop_start_wait_sec=300, callback_onstop=None, signal=15):
|
||||
if not self.stay_alive:
|
||||
raise Exception("Cannot restart not stay alive container")
|
||||
@ -2044,6 +2084,9 @@ class ClickHouseInstance:
|
||||
|
||||
if callback_onstop:
|
||||
callback_onstop(self)
|
||||
self.exec_in_container(
|
||||
["bash", "-c", "cp /usr/bin/clickhouse /usr/share/clickhouse_original"],
|
||||
user='root')
|
||||
self.exec_in_container(
|
||||
["bash", "-c", "cp /usr/share/clickhouse_fresh /usr/bin/clickhouse && chmod 777 /usr/bin/clickhouse"],
|
||||
user='root')
|
||||
|
@ -53,3 +53,9 @@ def test_backward_compatability(start_cluster):
|
||||
node1.restart_with_latest_version()
|
||||
|
||||
assert (node1.query("SELECT avgMerge(x) FROM state") == '2.5\n')
|
||||
|
||||
node1.query("drop table tab")
|
||||
node1.query("drop table state")
|
||||
node2.query("drop table tab")
|
||||
node3.query("drop table tab")
|
||||
node4.query("drop table tab")
|
@ -5,7 +5,7 @@
|
||||
import pytest
|
||||
from helpers.cluster import ClickHouseCluster
|
||||
|
||||
cluster = ClickHouseCluster(__file__)
|
||||
cluster = ClickHouseCluster(__file__, name="skipping_indices")
|
||||
node = cluster.add_instance('node', image='yandex/clickhouse-server', tag='21.6', stay_alive=True, with_installed_binary=True)
|
||||
|
||||
|
||||
@ -41,4 +41,4 @@ def test_index(start_cluster):
|
||||
node.query("""
|
||||
SELECT * FROM data WHERE value = 20000 SETTINGS force_data_skipping_indices = 'value_index' SETTINGS force_data_skipping_indices = 'value_index', max_rows_to_read=1;
|
||||
DROP TABLE data;
|
||||
""")
|
||||
""")
|
@ -30,3 +30,7 @@ def test_detach_part_wrong_partition_id(start_cluster):
|
||||
|
||||
num_detached = node_21_6.query("select count() from system.detached_parts")
|
||||
assert num_detached == '1\n'
|
||||
|
||||
node_21_6.restart_with_original_version()
|
||||
|
||||
node_21_6.query("drop table tab SYNC")
|
||||
|
@ -27,3 +27,6 @@ def test_select_aggregate_alias_column(start_cluster):
|
||||
|
||||
node1.query("select sum(x_alias) from remote('node{1,2}', default, tab)")
|
||||
node2.query("select sum(x_alias) from remote('node{1,2}', default, tab)")
|
||||
|
||||
node1.query("drop table tab")
|
||||
node2.query("drop table tab")
|
@ -29,3 +29,5 @@ def test_backward_compatability(start_cluster):
|
||||
"select s, count() from remote('node{1,2}', default, tab) group by s order by toUInt64(s) limit 50")
|
||||
print(res)
|
||||
assert res == ''.join('{}\t2\n'.format(i) for i in range(50))
|
||||
node1.query("drop table tab")
|
||||
node2.query("drop table tab")
|
||||
|
@ -3,6 +3,7 @@ import os.path
|
||||
import timeit
|
||||
|
||||
import pytest
|
||||
import logging
|
||||
from helpers.cluster import ClickHouseCluster
|
||||
from helpers.network import PartitionManager
|
||||
from helpers.test_tools import TSV
|
||||
@ -11,6 +12,8 @@ cluster = ClickHouseCluster(__file__)
|
||||
|
||||
NODES = {'node' + str(i): None for i in (1, 2)}
|
||||
|
||||
IS_DEBUG = False
|
||||
|
||||
CREATE_TABLES_SQL = '''
|
||||
CREATE DATABASE test;
|
||||
|
||||
@ -104,6 +107,11 @@ def started_cluster(request):
|
||||
try:
|
||||
cluster.start()
|
||||
|
||||
if cluster.instances["node1"].is_debug_build():
|
||||
global IS_DEBUG
|
||||
IS_DEBUG = True
|
||||
logging.warning("Debug build is too slow to show difference in timings. We disable checks.")
|
||||
|
||||
for node_id, node in list(NODES.items()):
|
||||
node.query(CREATE_TABLES_SQL)
|
||||
node.query(INSERT_SQL_TEMPLATE.format(node_id=node_id))
|
||||
@ -133,8 +141,9 @@ def _check_timeout_and_exception(node, user, query_base, query):
|
||||
# And it should timeout no faster than:
|
||||
measured_timeout = timeit.default_timer() - start
|
||||
|
||||
assert expected_timeout - measured_timeout <= TIMEOUT_MEASUREMENT_EPS
|
||||
assert measured_timeout - expected_timeout <= TIMEOUT_DIFF_UPPER_BOUND[user][query_base]
|
||||
if not IS_DEBUG:
|
||||
assert expected_timeout - measured_timeout <= TIMEOUT_MEASUREMENT_EPS
|
||||
assert measured_timeout - expected_timeout <= TIMEOUT_DIFF_UPPER_BOUND[user][query_base]
|
||||
|
||||
# And exception should reflect connection attempts:
|
||||
_check_exception(exception, repeats)
|
||||
|
@ -0,0 +1,37 @@
|
||||
<yandex>
|
||||
<keeper_server>
|
||||
<tcp_port>9181</tcp_port>
|
||||
<server_id>1</server_id>
|
||||
<log_storage_path>/var/lib/clickhouse/coordination/log</log_storage_path>
|
||||
<snapshot_storage_path>/var/lib/clickhouse/coordination/snapshots</snapshot_storage_path>
|
||||
|
||||
<coordination_settings>
|
||||
<snapshot_distance>75</snapshot_distance>
|
||||
<reserved_log_items>5</reserved_log_items>
|
||||
<operation_timeout_ms>5000</operation_timeout_ms>
|
||||
<session_timeout_ms>10000</session_timeout_ms>
|
||||
<raft_logs_level>trace</raft_logs_level>
|
||||
</coordination_settings>
|
||||
|
||||
<raft_configuration>
|
||||
<server>
|
||||
<id>1</id>
|
||||
<hostname>node1</hostname>
|
||||
<port>44444</port>
|
||||
<priority>3</priority>
|
||||
</server>
|
||||
<server>
|
||||
<id>2</id>
|
||||
<hostname>node2</hostname>
|
||||
<port>44444</port>
|
||||
<priority>2</priority>
|
||||
</server>
|
||||
<server>
|
||||
<id>3</id>
|
||||
<hostname>node3</hostname>
|
||||
<port>44444</port>
|
||||
<priority>1</priority>
|
||||
</server>
|
||||
</raft_configuration>
|
||||
</keeper_server>
|
||||
</yandex>
|
@ -0,0 +1,37 @@
|
||||
<yandex>
|
||||
<keeper_server>
|
||||
<tcp_port>9181</tcp_port>
|
||||
<server_id>2</server_id>
|
||||
<log_storage_path>/var/lib/clickhouse/coordination/log</log_storage_path>
|
||||
<snapshot_storage_path>/var/lib/clickhouse/coordination/snapshots</snapshot_storage_path>
|
||||
|
||||
<coordination_settings>
|
||||
<snapshot_distance>75</snapshot_distance>
|
||||
<reserved_log_items>5</reserved_log_items>
|
||||
<operation_timeout_ms>5000</operation_timeout_ms>
|
||||
<session_timeout_ms>10000</session_timeout_ms>
|
||||
<raft_logs_level>trace</raft_logs_level>
|
||||
</coordination_settings>
|
||||
|
||||
<raft_configuration>
|
||||
<server>
|
||||
<id>1</id>
|
||||
<hostname>node1</hostname>
|
||||
<port>44444</port>
|
||||
<priority>3</priority>
|
||||
</server>
|
||||
<server>
|
||||
<id>2</id>
|
||||
<hostname>node2</hostname>
|
||||
<port>44444</port>
|
||||
<priority>2</priority>
|
||||
</server>
|
||||
<server>
|
||||
<id>3</id>
|
||||
<hostname>node3</hostname>
|
||||
<port>44444</port>
|
||||
<priority>1</priority>
|
||||
</server>
|
||||
</raft_configuration>
|
||||
</keeper_server>
|
||||
</yandex>
|
@ -0,0 +1,37 @@
|
||||
<yandex>
|
||||
<keeper_server>
|
||||
<tcp_port>9181</tcp_port>
|
||||
<server_id>3</server_id>
|
||||
<log_storage_path>/var/lib/clickhouse/coordination/log</log_storage_path>
|
||||
<snapshot_storage_path>/var/lib/clickhouse/coordination/snapshots</snapshot_storage_path>
|
||||
|
||||
<coordination_settings>
|
||||
<snapshot_distance>75</snapshot_distance>
|
||||
<reserved_log_items>5</reserved_log_items>
|
||||
<operation_timeout_ms>5000</operation_timeout_ms>
|
||||
<session_timeout_ms>10000</session_timeout_ms>
|
||||
<raft_logs_level>trace</raft_logs_level>
|
||||
</coordination_settings>
|
||||
|
||||
<raft_configuration>
|
||||
<server>
|
||||
<id>1</id>
|
||||
<hostname>node1</hostname>
|
||||
<port>44444</port>
|
||||
<priority>3</priority>
|
||||
</server>
|
||||
<server>
|
||||
<id>2</id>
|
||||
<hostname>node2</hostname>
|
||||
<port>44444</port>
|
||||
<priority>2</priority>
|
||||
</server>
|
||||
<server>
|
||||
<id>3</id>
|
||||
<hostname>node3</hostname>
|
||||
<port>44444</port>
|
||||
<priority>1</priority>
|
||||
</server>
|
||||
</raft_configuration>
|
||||
</keeper_server>
|
||||
</yandex>
|
@ -0,0 +1,12 @@
|
||||
<yandex>
|
||||
<shutdown_wait_unfinished>3</shutdown_wait_unfinished>
|
||||
<logger>
|
||||
<level>trace</level>
|
||||
<log>/var/log/clickhouse-server/log.log</log>
|
||||
<errorlog>/var/log/clickhouse-server/log.err.log</errorlog>
|
||||
<size>1000M</size>
|
||||
<count>10</count>
|
||||
<stderr>/var/log/clickhouse-server/stderr.log</stderr>
|
||||
<stdout>/var/log/clickhouse-server/stdout.log</stdout>
|
||||
</logger>
|
||||
</yandex>
|
120
tests/integration/test_keeper_snapshot_small_distance/test.py
Normal file
120
tests/integration/test_keeper_snapshot_small_distance/test.py
Normal file
@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
##!/usr/bin/env python3
|
||||
import pytest
|
||||
from helpers.cluster import ClickHouseCluster
|
||||
from multiprocessing.dummy import Pool
|
||||
from kazoo.client import KazooClient, KazooState
|
||||
import random
|
||||
import string
|
||||
import os
|
||||
import time
|
||||
|
||||
cluster = ClickHouseCluster(__file__)
|
||||
node1 = cluster.add_instance('node1', main_configs=['configs/keeper_config1.xml'], stay_alive=True)
|
||||
node2 = cluster.add_instance('node2', main_configs=['configs/keeper_config2.xml'], stay_alive=True)
|
||||
node3 = cluster.add_instance('node3', main_configs=['configs/keeper_config3.xml'], stay_alive=True)
|
||||
|
||||
def start_zookeeper(node):
|
||||
node1.exec_in_container(['bash', '-c', '/opt/zookeeper/bin/zkServer.sh start'])
|
||||
|
||||
def stop_zookeeper(node):
|
||||
node.exec_in_container(['bash', '-c', '/opt/zookeeper/bin/zkServer.sh stop'])
|
||||
|
||||
def clear_zookeeper(node):
|
||||
node.exec_in_container(['bash', '-c', 'rm -fr /zookeeper/*'])
|
||||
|
||||
def restart_and_clear_zookeeper(node):
|
||||
stop_zookeeper(node)
|
||||
clear_zookeeper(node)
|
||||
start_zookeeper(node)
|
||||
|
||||
def clear_clickhouse_data(node):
|
||||
node.exec_in_container(['bash', '-c', 'rm -fr /var/lib/clickhouse/coordination/logs/* /var/lib/clickhouse/coordination/snapshots/*'])
|
||||
|
||||
def convert_zookeeper_data(node):
|
||||
cmd = '/usr/bin/clickhouse keeper-converter --zookeeper-logs-dir /zookeeper/version-2/ --zookeeper-snapshots-dir /zookeeper/version-2/ --output-dir /var/lib/clickhouse/coordination/snapshots'
|
||||
node.exec_in_container(['bash', '-c', cmd])
|
||||
return os.path.join('/var/lib/clickhouse/coordination/snapshots', node.exec_in_container(['bash', '-c', 'ls /var/lib/clickhouse/coordination/snapshots']).strip())
|
||||
|
||||
def stop_clickhouse(node):
|
||||
node.stop_clickhouse()
|
||||
|
||||
def start_clickhouse(node):
|
||||
node.start_clickhouse()
|
||||
|
||||
def copy_zookeeper_data(make_zk_snapshots, node):
|
||||
stop_zookeeper(node)
|
||||
|
||||
if make_zk_snapshots: # force zookeeper to create snapshot
|
||||
start_zookeeper(node)
|
||||
stop_zookeeper(node)
|
||||
|
||||
stop_clickhouse(node)
|
||||
clear_clickhouse_data(node)
|
||||
convert_zookeeper_data(node)
|
||||
start_zookeeper(node)
|
||||
start_clickhouse(node)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def started_cluster():
|
||||
try:
|
||||
cluster.start()
|
||||
|
||||
yield cluster
|
||||
|
||||
finally:
|
||||
cluster.shutdown()
|
||||
|
||||
def get_fake_zk(node, timeout=30.0):
|
||||
_fake_zk_instance = KazooClient(hosts=cluster.get_instance_ip(node.name) + ":9181", timeout=timeout)
|
||||
_fake_zk_instance.start()
|
||||
return _fake_zk_instance
|
||||
|
||||
def get_genuine_zk(node, timeout=30.0):
|
||||
_genuine_zk_instance = KazooClient(hosts=cluster.get_instance_ip(node.name) + ":2181", timeout=timeout)
|
||||
_genuine_zk_instance.start()
|
||||
return _genuine_zk_instance
|
||||
|
||||
|
||||
def test_snapshot_and_load(started_cluster):
|
||||
restart_and_clear_zookeeper(node1)
|
||||
genuine_connection = get_genuine_zk(node1)
|
||||
for node in [node1, node2, node3]:
|
||||
print("Stop and clear", node.name, "with dockerid", node.docker_id)
|
||||
stop_clickhouse(node)
|
||||
clear_clickhouse_data(node)
|
||||
|
||||
for i in range(1000):
|
||||
genuine_connection.create("/test" + str(i), b"data")
|
||||
|
||||
print("Data loaded to zookeeper")
|
||||
|
||||
stop_zookeeper(node1)
|
||||
start_zookeeper(node1)
|
||||
stop_zookeeper(node1)
|
||||
|
||||
print("Data copied to node1")
|
||||
resulted_path = convert_zookeeper_data(node1)
|
||||
print("Resulted path", resulted_path)
|
||||
for node in [node2, node3]:
|
||||
print("Copy snapshot from", node1.name, "to", node.name)
|
||||
cluster.copy_file_from_container_to_container(node1, resulted_path, node, '/var/lib/clickhouse/coordination/snapshots')
|
||||
|
||||
print("Starting clickhouses")
|
||||
|
||||
p = Pool(3)
|
||||
result = p.map_async(start_clickhouse, [node1, node2, node3])
|
||||
result.wait()
|
||||
|
||||
print("Loading additional data")
|
||||
fake_zks = [get_fake_zk(node) for node in [node1, node2, node3]]
|
||||
for i in range(1000):
|
||||
fake_zk = random.choice(fake_zks)
|
||||
try:
|
||||
fake_zk.create("/test" + str(i + 1000), b"data")
|
||||
except Exception as ex:
|
||||
print("Got exception:" + str(ex))
|
||||
|
||||
print("Final")
|
||||
fake_zks[0].create("/test10000", b"data")
|
@ -37,6 +37,9 @@ def cluster():
|
||||
with_hdfs=True)
|
||||
logging.info("Starting cluster...")
|
||||
cluster.start()
|
||||
if cluster.instances["node1"].is_debug_build():
|
||||
# https://github.com/ClickHouse/ClickHouse/issues/27814
|
||||
pytest.skip("libhdfs3 calls rand function which does not pass harmful check in debug build")
|
||||
logging.info("Cluster started")
|
||||
|
||||
fs = HdfsClient(hosts=cluster.hdfs_ip)
|
||||
|
@ -180,28 +180,6 @@ def avro_confluent_message(schema_registry_client, value):
|
||||
})
|
||||
return serializer.encode_record_with_schema('test_subject', schema, value)
|
||||
|
||||
# Fixtures
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def kafka_cluster():
|
||||
try:
|
||||
global kafka_id
|
||||
cluster.start()
|
||||
kafka_id = instance.cluster.kafka_docker_id
|
||||
print(("kafka_id is {}".format(kafka_id)))
|
||||
yield cluster
|
||||
|
||||
finally:
|
||||
cluster.shutdown()
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def kafka_setup_teardown():
|
||||
instance.query('DROP DATABASE IF EXISTS test; CREATE DATABASE test;')
|
||||
wait_kafka_is_available() # ensure kafka is alive
|
||||
kafka_producer_send_heartbeat_msg() # ensure python kafka client is ok
|
||||
# print("kafka is available - running test")
|
||||
yield # run test
|
||||
|
||||
# Tests
|
||||
|
||||
def test_kafka_settings_old_syntax(kafka_cluster):
|
||||
@ -699,6 +677,8 @@ def describe_consumer_group(kafka_cluster, name):
|
||||
def kafka_cluster():
|
||||
try:
|
||||
cluster.start()
|
||||
kafka_id = instance.cluster.kafka_docker_id
|
||||
print(("kafka_id is {}".format(kafka_id)))
|
||||
yield cluster
|
||||
finally:
|
||||
cluster.shutdown()
|
||||
@ -1129,6 +1109,7 @@ def test_kafka_protobuf_no_delimiter(kafka_cluster):
|
||||
|
||||
|
||||
def test_kafka_materialized_view(kafka_cluster):
|
||||
|
||||
instance.query('''
|
||||
DROP TABLE IF EXISTS test.view;
|
||||
DROP TABLE IF EXISTS test.consumer;
|
||||
|
@ -55,6 +55,9 @@ def kafka_produce(kafka_cluster, topic, messages, timestamp=None):
|
||||
def kafka_cluster():
|
||||
try:
|
||||
cluster.start()
|
||||
if instance.is_debug_build():
|
||||
# https://github.com/ClickHouse/ClickHouse/issues/27651
|
||||
pytest.skip("librdkafka calls system function for kinit which does not pass harmful check in debug build")
|
||||
yield cluster
|
||||
finally:
|
||||
cluster.shutdown()
|
||||
|
@ -37,6 +37,7 @@
|
||||
[5, 2]
|
||||
[6, 1]
|
||||
[7, 1]
|
||||
[1]
|
||||
[1, 2]
|
||||
[2, 2]
|
||||
[3, 0]
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user