Documentation on constraints (RU, EN)

This commit is contained in:
Gleb Novikov 2019-06-06 01:25:57 +03:00
parent 375e464086
commit 76772d1de0
6 changed files with 79 additions and 0 deletions

View File

@ -166,6 +166,22 @@ are available:
These commands are lightweight in a sense that they only change metadata or remove files.
Also, they are replicated (syncing indices metadata through ZooKeeper).
### Manipulations with constraints
See more on [constraints](create.md#constraints)
Constraints could be added or deleted using following syntax:
```
ALTER TABLE [db].name ADD CONSTRAINT constraint_name CHECK expression;
ALTER TABLE [db].name DROP CONSTRAINT constraint_name;
```
Queries will add or remove metadata about constraints from table so they are processed immediately.
Constraint check *will not be executed* on existing table if it was added. For now, we recommend to create new table and use `INSERT SELECT` query to fill new table.
All changes on distributed tables are broadcasting to ZooKeeper so will be applied on other replicas.
### Manipulations With Partitions and Parts {#alter_manipulations-with-partitions}
The following operations with [partitions](../operations/table_engines/custom_partitioning_key.md) are available:

View File

@ -80,6 +80,26 @@ If you add a new column to a table but later change its default expression, the
It is not possible to set default values for elements in nested data structures.
### Constraints {#constraints}
WARNING: This feature is experimental. Correct work is not guaranteed on non-MergeTree family engines.
Along with columns descriptions constraints could be defined:
``sql
CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
(
name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1] [compression_codec] [TTL expr1],
...
CONSTRAINT constraint_name_1 CHECK boolean_expr_1,
...
) ENGINE = engine
```
`boolean_expr_1` could by any boolean expression. If constraints are defined for the table, each of them will be checked for every row in `INSERT` query. If any constraint is not satisfied — server will raise an exception with constraint name and checking expression.
Adding large amount of constraints can negatively affect performance of big `INSERT` queries.
### TTL expression
Can be specified only for MergeTree-family tables. An expression for setting storage time for values. It must depends on `Date` or `DateTime` column and has one `Date` or `DateTime` column as a result. Example:

View File

@ -40,6 +40,9 @@ INSERT INTO t FORMAT TabSeparated
You can insert data separately from the query by using the command-line client or the HTTP interface. For more information, see the section "[Interfaces](../interfaces/index.md#interfaces)".
### Constraints
If table has [constraints](create.md#constraints), their expressions will be checked for each row of inserted data. If any of those constraints is not satisfied — server will raise an exception containing constraint name and expression, the query will be stopped.
### Inserting The Results of `SELECT` {#insert_query_insert-select}

View File

@ -165,6 +165,22 @@ ALTER TABLE [db].name DROP INDEX name
Запрос на изменение индексов реплицируется, сохраняя новые метаданные в ZooKeeper и применяя изменения на всех репликах.
### Манипуляции с ограничениями (constraints)
Про ограничения подробнее написано [тут](create.md#constraints).
Добавить или удалить ограничение можно с помощью запросов
```
ALTER TABLE [db].name ADD CONSTRAINT constraint_name CHECK expression;
ALTER TABLE [db].name DROP CONSTRAINT constraint_name;
```
Запросы выполняют добавление или удаление метаданных об ограничениях таблицы `[db].name`, поэтому выполняются мнгновенно.
Если ограничение появилось для непустой таблицы, то *проверка ограничения вызвана не будет*. Если же важно добавить ограничение на существующую таблицу, то рекомендуется создать новую таблицу с нужным ограничением и выполнить `INSERT SELECT` запрос для перекачки данных из одной таблицы в другую.
Запрос на изменение ограничений так же, как и с индексами, реплицируется через ZooKeeper.
### Манипуляции с партициями и кусками {#alter_manipulations-with-partitions}
Для работы с [партициями](../operations/table_engines/custom_partitioning_key.md) доступны следующие операции:

View File

@ -80,6 +80,26 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name ENGINE = engine AS SELECT ...
Отсутствует возможность задать значения по умолчанию для элементов вложенных структур данных.
### Ограничения (constraints) {#constraints}
WARNING: Находится в экспериментальном режиме, поддержано в MergeTree (работоспособность на других типах движков таблиц не гарантируется).
Наряду с объявлением столбцов можно объявить ограчения на значения в столбцах таблицы:
```sql
CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
(
name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1] [compression_codec] [TTL expr1],
...
CONSTRAINT constraint_name_1 CHECK boolean_expr_1,
...
) ENGINE = engine
```
`boolean_expr_1` может быть любым булевым выражением, состоящим из операторов сравнения или функций. При наличии одного или нескольких ограничений в момент вставки данных выражения ограничений будут проверяться на истинность для каждой вставляемой строки данных. В случае, если в теле INSERT запроса придут некорректные данные — клиентов будет выкинуто исключение с нарушенным ограничением.
Добавление большого числа ограничений может негативно повлиять на производительность объёмных `INSERT` запросов.
### Выражение для TTL
Может быть указано только для таблиц семейства MergeTree. Выражение для указания времени хранения значений. Оно должно зависеть от стобца типа `Date` или `DateTime` и в качестве результата вычислять столбец типа `Date` или `DateTime`. Пример:

View File

@ -40,6 +40,10 @@ INSERT INTO t FORMAT TabSeparated
С помощью консольного клиента или HTTP интерфейса можно вставлять данные отдельно от запроса. Как это сделать, читайте в разделе "[Интерфейсы](../interfaces/index.md#interfaces)".
### Ограничения (constraints)
Если в таблице объявлены [ограничения](create.md#constraints), то их выполнимость будет проверена для каждой вставляемой строки. Если для хотя бы одной строки ограничения не будут выполнены, запрос будет остановлен.
### Вставка результатов `SELECT` {#insert_query_insert-select}
``` sql