Skip to content

Improve Interactive CLI documentation #20013

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
81 changes: 72 additions & 9 deletions ydb/docs/en/core/reference/ydb-cli/interactive-cli.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Interactive query execution mode

After executing `ydb` command without subcommands, the interactive query execution mode will be launched. The console or terminal will be switched to interactive mode. After that, you can enter queries directly into the console or terminal, and when you enter a newline character, the query is considered complete and it starts to execute. The query text can be either a YQL query or a [special command](#spec-commands). Also, query history is saved between runs, command autocomplete is available, and there is a search function for query history.
Executing `{{ ydb-cli }}` command without subcommands launches the interactive query execution mode. The console or terminal will be switched to the interactive mode. After that, you can enter queries directly into the console or terminal. When you enter a newline character, the query is considered completed and it starts to execute. The query text can be either a YQL query or a [special command](#spec-commands).

General format of the command:

Expand All @@ -10,23 +10,86 @@ General format of the command:

* `global options` — [global parameters](commands/global-options.md).

Example usage:

![Example](_assets/general-example.gif)

## Features {#features}

* [Syntax highlighting](#syntax-highlighting)
* [Hotkeys](#hotkeys)
* [Query history](#query-history)
* [Auto completion](#auto-completion)
* [Special commands](#spec-commands)

### Syntax highlighting {#syntax-highlighting}

![Syntax highlighting](_assets/highlighting.jpg)

Interactive mode supports YQL syntax highlighting, which helps to better understand query structure. Different colors are used for the following groups of elements:

* YQL keywords (SELECT, FROM, WHERE, INSERT, UPDATE and others)
* Table and column names
* String literals (text in quotes)
* Numeric literals
* Operators (=, <, >, +, - and others)
* Special characters (brackets, commas, dots)
* Comments

## Hotkeys {#hotkeys}

| Hotkey | Description |
|---------------|---------------------------------------------------------------------------|
| `CTRL + D` | Allows you to exit interactive mode. |
| `Up arrow` | Scrolls through query history toward older queries. |
| `Down arrow` | Scrolls through query history toward newer queries. |
| `TAB` | Autocompletes the entered text to a suitable YQL command. |
| `CTRL + R` | Allows searching for a query in history containing a specified substring. |
| `Up arrow` | Shows previous query from history. |
| `Down arrow` | Shows next query from history. |
| `TAB` | Completes the current word based on YQL syntax. |
| `CTRL + R` | Searches for a query in history containing a specified substring. |
| `CTRL + D` | Exits interactive mode. |

### Query history {#query-history}

You can navigate through the query history using up and down arrow keys:

![History](_assets/history.gif)

History is stored locally and persists between CLI launches.

A query search function (`CTRL + R`) is also supported:

![Search](_assets/history-search.gif)

## Auto completion {#auto-completion}

Auto completion helps you write queries more efficiently. While typing, it suggests possible completions for the current word based on YQL syntax.

It also searches for schema object names in database where possible.

There are two types of suggestions: auto completion by pressing `TAB` key and interactive hints.

### Auto completion by pressing `TAB` key {#auto-completion-tab}

While in interactive mode, pressing `TAB` key will show a list of suggestions of completion of current word according to the YQL syntax.

![Auto completion](_assets/candidates.gif)

If there is only one available option, pressing TAB will automatically complete the current word.
If all available options share a common prefix, pressing TAB will automatically insert it.

### Interactive Hints {#interactive-hints}

While typing in interactive mode, a list of hints will appear under the cursor, showing first 4 suggestions of completion of current word according to the YQL grammar.

![Interactive hints](_assets/hints.gif)

This feature provides quick guidance without overwhelming you with all possible options, helping you stay on track while writing queries.

## Special commands {#spec-commands}

Special commands are CLI-specific commands and are not part of the YQL syntax. They are intended for performing various functions that cannot be accomplished through a YQL query.
Special commands are CLI-specific commands and are not part of the YQL syntax. Their purpose is to perform various functions that cannot be accomplished through a YQL query.

| Command | Description |
|--------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `SET param = value` | The `SET` command sets the value of the [internal variable](#internal-vars) `param` to `value`. |
| `SET param = value` | Sets the value of the [internal variable](#internal-vars) `param` to `value`. |
| `EXPLAIN query-text` | Outputs the query plan for `query-text`. Equivalent to the command [ydb table query explain](commands/explain-plan.md#explain-plan). |
| `EXPLAIN AST query-text` | Outputs the query plan for `query-text` along with the [AST](commands/explain-plan.md). Equivalent to the command [ydb table query explain --ast](commands/explain-plan.md#ast). |

Expand All @@ -38,7 +101,7 @@ Internal variables determine the behavior of commands and are set using the [spe
|----------|---|
| `stats` | The statistics collection mode for subsequent queries.<br/>Acceptable values:<ul><li>`none` (default): Do not collect.</li><li>`basic`: Collect statistics.</li><li>`full`: Collect statistics and query plan.</li></ul> |

## Examples {#examples}
### Example {#examples}

Executing a query in the `full` statistics collection mode:

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
79 changes: 71 additions & 8 deletions ydb/docs/ru/core/reference/ydb-cli/interactive-cli.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Интерактивный режим выполнения запросов

Выполнив команду `ydb` без подкоманд, запустится интерактивный режим выполнения запросов. Консоль или терминал будут переведены в интерактивный режим. После этого можно вводить запросы напрямую в консоль или терминал, при вводе символа перевода строки запрос считается законченным и он начинает исполняться. Текст запроса может представлять из себя как YQL запрос, так и [специальную команду](#spec-commands). Также между запусками сохраняется история запросов, доступны автодополнение команд и поиск по истории запросов.
После выполнения команды `ydb` без подкоманд запускается интерактивный режим выполнения запросов. Консоль или терминал будут переведены в интерактивный режим. После этого можно вводить запросы напрямую в консоль или терминал. При вводе символа перевода строки запрос считается законченным и он начинает исполняться. Текст запроса может представлять из себя как YQL запрос, так и [специальную команду](#spec-commands).

Общий вид команды:

Expand All @@ -10,23 +10,86 @@

* `global options` — [глобальные параметры](commands/global-options.md).

Пример использования:

![Пример](_assets/general-example.gif)

## Возможности {#features}

* [Подсветка синтаксиса](#syntax-highlighting)
* [Горячие клавиши](#hotkeys)
* [История запросов](#query-history)
* [Автодополнение](#auto-completion)
* [Специальные команды](#spec-commands)

### Подсветка синтаксиса {#syntax-highlighting}

![Подсветка синтаксиса](_assets/highlighting.jpg)

Интерактивный режим поддерживает цветовую подсветку синтаксиса YQL, которая помогает лучше воспринимать структуру запросов. Разными цветами выделяются следующие группы элементов:

* Ключевые слова YQL (SELECT, FROM, WHERE, INSERT, UPDATE и другие)
* Имена таблиц и столбцов
* Строковые литералы (текст в кавычках)
* Числовые литералы
* Операторы (=, <, >, +, - и другие)
* Специальные символы (скобки, запятые, точки)
* Комментарии

## Горячие клавиши {#hotkeys}

Горячая клавиша | Описание
---|---
`CTRL + D` | Позволяет выйти из интерактивного режима.
`Up arrow` | Пролистывает историю запросов в сторону более старых запросов.
`Down arrow` | Пролистывает историю запросов в сторону более новых запросов.
`TAB` | Дополняет введенный текст до подходящей YQL команды.
`CTRL + R` | Позволяет найти в истории запрос, содержащий заданную подстроку.
`Up arrow` | Показывает предыдущий запрос из истории.
`Down arrow` | Показывает следующий запрос из истории.
`TAB` | Дополняет текущее слово на основе синтаксиса YQL.
`CTRL + R` | Поиск запроса в истории по введенной подстроке.
`CTRL + D` | Выход из интерактивного режима.

### История запросов {#query-history}

Клавиши со стрелками вверх и вниз позволяют перемещаться по истории запросов:

![История](_assets/history.gif)

История сохраняется локально и доступна между запусками CLI.

Также поддерживается функция поиска по запросам (`CTRL + R`):

![Поиск](_assets/history-search.gif)

## Автодополнение {#auto-completion}

Автодополнение помогает эффективнее писать запросы. Во время ввода предлагаются возможные варианты завершения текущего слова на основе синтаксиса YQL.

Также выполняется поиск имен объектов схемы в базе данных, где это возможно.

Существует два типа подсказок: автодополнение по нажатию клавиши `TAB` и интерактивные подсказки.

### Автодополнение по нажатию клавиши TAB {#auto-completion-tab}

В интерактивном режиме при нажатии клавиши `TAB` отображается список вариантов завершения текущего слова в соответствии с синтаксисом YQL.

![Автодополнение](_assets/candidates.gif)

Если доступен только один вариант, нажатие TAB автоматически дополнит текущее слово до него.
Если у всех доступных вариантов общий префикс, нажатие TAB автоматически его подставит.

### Интерактивные подсказки {#interactive-hints}

В процессе ввода в интерактивном режиме под курсором появляется список подсказок, показывающий первые 4 варианта завершения текущего слова согласно грамматике YQL.

![Интерактивные подсказки](_assets/hints.gif)

Эта функция предоставляет быстрые подсказки без перегрузки всеми возможными вариантами, помогая придерживаться правильного синтаксиса при написании запросов.

## Специальные команды {#spec-commands}

Специальные команды специфичны для CLI и не являются частью синтаксиса YQL. Они предназначены для выполнения различных функций, которые нельзя выполнить через YQL запрос.

Команда | Описание
---|---
`SET param = value` | Команда `SET` устанавливает значение [внутренней переменной](#internal-vars) `param` в `value`.
`SET param = value` | Устанавливает значение [внутренней переменной](#internal-vars) `param` в `value`.
`EXPLAIN query-text` | Выводит план запроса `query-text`. Эквивалентна команде [ydb sql --explain](sql.md).
`EXPLAIN AST query-text` | Выводит план запроса `query-text` вместе с [AST](commands/explain-plan.md). Эквивалентна команде [ydb sql --explain-ast](sql.md).

Expand All @@ -38,7 +101,7 @@
---|---
`stats` | Режим сбора статистики для последующих запросов.<br/>Возможные значения:<ul><li>`none` (по умолчанию) — не собирать;</li><li>`basic` — собирать статистику;</li><li>`full` — собирать статистику и план запроса.</li></ul>

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

Выполнение запроса в режиме сбора статистики `full`:

Expand Down