Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

YDBDOCS-632: Documentation of temporary tables #3137

Merged
merged 12 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ydb/docs/en/core/_includes/temp-table-description.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`TEMPORARY` / `TEMP` – a temporary table that is automatically deleted at the end of the session. If this parameter is not set (left empty), a permanent table is created. Any indexes created on a temporary table will also be deleted at the end of the session, which means that they are temporary as well. A temporary table and a permanent table with the same name are allowed, in which case a temporary table will be selected.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
```sql
CREATE [TEMPORARY] TABLE <table name> (
CREATE [TEMPORARY | TEMP] TABLE <table name> (

<column name> <column data type> [COLLATE][PRIMARY KEY]

Expand Down
19 changes: 6 additions & 13 deletions ydb/docs/en/core/postgresql/statements/create_table.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ The `CREATE TABLE` statement is used to create an empty table in the current dat


When creating a table, you can specify:
1. **Table Type**: `TEMPORARY` (not fully supported yet and used only in tests) – a temporary table that is automatically deleted at the end of the session or at the end of the current transaction. If this parameter is not set (left empty), a permanent table is created.
2. **Table Name**: `<table name>` – you can use English letters in lowercase, numbers, and underscores. For example, the table name "People" will be stored as "people". For more information, see [Identifiers and Key Words](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).
1. **Table Type**: {% include [temp-table-description.md](../../_includes/temp-table-description.md) %}
2. **Table Name**: `<table name>` – you can use English letters in lowercase, numbers, underscores and dollar signs ($). For example, the table name "People" will be stored as "people". For more information, see [Identifiers and Key Words](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS).
3. **Column Name**: `<column name>` – the same naming rules apply as for table names.
4. **Data Type**: `<column data type>` – [standard PostgreSQL data types](https://www.postgresql.org/docs/14/datatype.html) are specified.
5. **Collation Rule**: `COLLATE` – [collation rules](https://www.postgresql.org/docs/current/collation.html) allow setting sorting order and character classification features in individual columns or even when performing individual operations. Sortable types include: `text`, `varchar`, and `char`. You can specify the locale (e.g., `en_US`, `ru_RU`) used to determine the sorting and string comparison rules in the specified columns.
Expand All @@ -26,12 +26,12 @@ When creating a table, you can specify:
## Creating two tables with primary key autoincrement {#create_table_pk_serial}
#|
|| **Table people** | **Table social_card** ||
||
||


{% include [create_table_people](../_includes/statements/create_table/create_table_people.md) %}

|
|

{% include [create_table_social_card](../_includes/statements/create_table/create_table_social_card.md) %}

Expand All @@ -51,16 +51,9 @@ In this example, we created the "people" table with a constraint block (`CONSTRA

## Creating a temporary table {#create_table_temp_table}

{% include [create_table_temp.md](../_includes/statements/create_table/create_table_temp.md) %}

{% note warning %}

The temporary table functionality is not fully implemented. Temporary tables may not be deleted. Therefore, they can be used for testing, but not for production.

{% endnote %}

{% include [create_table_temp](../_includes/statements/create_table/create_table_temp.md) %}

The temporary table is defined using the `TEMPORARY` keyword. It exists until the end of the session or the completion of the transaction, after which it is automatically deleted.
The temporary table is defined using the `TEMPORARY` or `TEMP` keywords.


## Creating a table with sorting conditions {#create_table_collate}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ The table is created automatically during the first [INSERT INTO](insert_into.md

The `CREATE TABLE` call creates a {% if concept_table %}[table]({{ concept_table }}){% else %}table{% endif %} with the specified data schema{% if feature_map_tables %} and key columns (`PRIMARY KEY`){% endif %}. {% if feature_secondary_index == true %}It lets you define secondary indexes on the created table.{% endif %}

CREATE TABLE table_name (
CREATE [TEMPORARY | TEMP] TABLE table_name (
column1 type1,
{% if feature_not_null == true %} column2 type2 NOT NULL,{% else %} column2 type2,{% endif %}
...
Expand Down Expand Up @@ -113,6 +113,18 @@ CREATE TABLE my_table (
```
{% endif %}

{% if feature_temp_tables %}
{% if feature_olap_tables %}#{%endif%}## Creating a temporary table {#temporary_tables}
```sql
CREATE TEMPORARY TABLE table_name (
shnikd marked this conversation as resolved.
Show resolved Hide resolved
...
);
```

{% include [temp-table-description.md](../../../../_includes/temp-table-description.md) %}

{% endif %}

{% if feature_map_tables and concept_table %}
{% if feature_olap_tables %}#{% endif %}## Additional parameters {#row-additional}

Expand Down
1 change: 1 addition & 0 deletions ydb/docs/presets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ default:
oss: true
feature_not_null_for_pk: true
feature_not_null: true
feature_temp_tables: true
has_create_table_link: true
ydb_non_deterministic_functions: true

Expand Down
1 change: 1 addition & 0 deletions ydb/docs/ru/core/_includes/temp-table-description.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`TEMPORARY` / `TEMP` – временная таблица, которая автоматически удаляется при завершении сессии. Если параметр не задан (оставлен пустым) – создается постоянная таблица. Любые индексы, созданные во временных таблицах, также будут удалены при завершении сессиии, следовательно они тоже являются временными. Допускается существование временной таблицы и постоянной таблицы с одинаковым именем, в этом случае будет выбрана временная таблица.
28 changes: 10 additions & 18 deletions ydb/docs/ru/core/postgresql/statements/create_table.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Инструкция `CREATE TABLE` предназначена для создания пустой таблицы в текущей базе данных. Синтаксис команды:

```sql
CREATE [TEMPORARY] TABLE <table name> (
CREATE [TEMPORARY | TEMP] TABLE <table name> (

<column name> <column data type> [COLLATE][PRIMARY KEY]

Expand All @@ -15,8 +15,8 @@ CREATE [TEMPORARY] TABLE <table name> (
);
```
При создании таблицы можно задать:
1. **Тип таблицы**: `TEMPORARY` (поддерживается не полностью и используется только в тестах) – временная таблица, которая автоматически удаляется в конце сеанса или в конце текущей транзакции. Если параметр не задан (оставлен пустым) – создается постоянная таблица;
2. **Имя таблицы**: `<table name>` – можно использовать английские буквы в нижнем регистре, цифры и нижнее подчёркивание. Например, название таблицы "People" будет сохранено как "people";
1. **Тип таблицы**: {% include [temp-table-description.md](../../_includes/temp-table-description.md) %}
2. **Имя таблицы**: `<table name>` – можно использовать английские буквы в нижнем регистре, цифры, нижнее подчёркивание и знак доллара ($). Например, название таблицы "People" будет сохранено как "people";
3. **Имя столбца/колонки**: <column name> – действую такие же правила нейминга как и для имен таблиц;
4. **Тип данных**: <column data type> – указываются [стандартные типы](https://www.postgresql.org/docs/current/datatype.html) данных PostgreSQL;
5. **Правило сортировки**: `COLLATE` – [правила сортировки](https://www.postgresql.org/docs/current/collation.html) позволяют устанавливать порядок сортировки и особенности классификации символов в отдельных столбцах или даже при выполнении отдельных операций. К сортируемым типам относятся: `text`, `varchar` и `char`. Можно указать локализацию (`ru_RU`, `en_US`), используемую для определения правил сортировки и сравнения строк в указанных столбцах.
Expand All @@ -30,7 +30,7 @@ CREATE [TEMPORARY] TABLE <table name> (
## Создание двух таблиц с первичным ключом и автоинкрементом {#create_table_pk_serial}
#|
|| **Таблица people** | **Таблица social_card** ||
||
||
```sql
CREATE TABLE people (
id Serial PRIMARY KEY,
Expand All @@ -44,8 +44,8 @@ CREATE TABLE people (
sex Text,
social_card_number Int
);
```
|
```
|
```sql
CREATE TABLE social_card (
id Serial PRIMARY KEY,
Expand All @@ -55,8 +55,8 @@ CREATE TABLE social_card (
issue Date,
expiry Date,
issuing_authority Text,
category Text
);
category Text
);
```
||
|#
Expand All @@ -83,27 +83,19 @@ CREATE TABLE people (
);
```

В этом примере мы создали таблицу "people" с ограничением (блоком `CONSTRAINT`), в котором задали первичный ключ (`PRIMARY KEY`) для колонки "id". Альтернативная запись может выглядеть так: `PRIMARY KEY(id)` без указания ключевого слова `CONSTRAINT`.
В этом примере мы создали таблицу "people" с ограничением (блоком `CONSTRAINT`), в котором задали первичный ключ (`PRIMARY KEY`) для колонки "id". Альтернативная запись может выглядеть так: `PRIMARY KEY(id)` без указания ключевого слова `CONSTRAINT`.


## Создание временной таблицы {#create_table_temp_table}


{% note warning %}

Функциональность временной таблицы реализована не полностью.

{% endnote %}


```sql
CREATE TEMPORARY TABLE people (
id serial PRIMARY KEY,
name TEXT NOT NULL
);
```

Временная таблица задается через ключевое слово `TEMPORARY`. Она существует до конца сеанса или до завершения транзакции, далее она автоматически удаляется.
Временная таблица задается через ключевые слова `TEMPORARY` или `TEMP`.


## Создание таблицы с условиями сортировки {#create_table_collate}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

Вызов `CREATE TABLE` создает {% if concept_table %}[таблицу]({{ concept_table }}){% else %}таблицу{% endif %} с указанной схемой данных{% if feature_map_tables %} и ключевыми колонками (`PRIMARY KEY`){% endif %}. {% if feature_secondary_index == true %}Позволяет определить вторичные индексы на создаваемой таблице.{% endif %}

CREATE TABLE table_name (
CREATE [TEMP | TEMPORARY] TABLE table_name (
column1 type1,
{% if feature_not_null == true %} column2 type2 NOT NULL,{% else %} column2 type2,{% endif %}
...
Expand Down Expand Up @@ -86,7 +86,7 @@
Конструкция INDEX используется для определения {% if concept_secondary_index %}[вторичного индекса]({{ concept_secondary_index }}){% else %}вторичного индекса{% endif %} на таблице:

```sql
CREATE TABLE table_name (
CREATE TABLE table_name (
...
INDEX <index_name> GLOBAL [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> ),
...
Expand Down Expand Up @@ -114,6 +114,17 @@ CREATE TABLE my_table (
```
{% endif %}

{% if feature_temp_tables %}
{% if feature_olap_tables %}#{%endif%}## Создание временных таблиц {#temporary_tables}
```sql
CREATE TEMPORARY TABLE table_name (
...
);
```
{% include [temp-table-description.md](../../../../_includes/temp-table-description.md) %}

{% endif %}

{% if feature_map_tables and concept_table %}
{% if feature_olap_tables %}#{%endif%}## Дополнительные параметры {#row-additional}

Expand Down Expand Up @@ -210,10 +221,10 @@ CREATE TABLE table_name (
...
)
PARTITION BY HASH(column1, column2, ...)
WITH (
WITH (
STORE = COLUMN,
key = value,
...
key = value,
...
)
```

Expand Down
Loading