diff options
author | Nikolay Perfilov <pnv1@yandex-team.ru> | 2025-04-18 11:55:26 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-04-18 11:55:26 +0300 |
commit | 0fbe2c41987bb2a4c9960332eae51ea3b8cbb9c9 (patch) | |
tree | 466b4d9fd6eb64dd8f25534e1918eac92906af78 | |
parent | 5ce8784987de0655ec75ff583643b1380117be05 (diff) | |
download | ydb-0fbe2c41987bb2a4c9960332eae51ea3b8cbb9c9.tar.gz |
Add `ydb sql` documentation and update links to use new command where possible (#15262)
Co-authored-by: anton-bobkov <anton-bobkov@ydb.tech>
39 files changed, 1492 insertions, 74 deletions
diff --git a/ydb/docs/en/core/devops/ansible/initial-deployment.md b/ydb/docs/en/core/devops/ansible/initial-deployment.md index 88f6eb2ecdf..e5818fb4d0d 100644 --- a/ydb/docs/en/core/devops/ansible/initial-deployment.md +++ b/ydb/docs/en/core/devops/ansible/initial-deployment.md @@ -268,8 +268,8 @@ Command parameters and their values: You can check if the profile has been created using the command `./ydb config profile list`, which will display a list of profiles. After creating a profile, you need to activate it with the command `./ydb config profile activate <profile name>`. To verify that the profile has been activated, you can rerun the command `./ydb config profile list` – the active profile will have an (active) mark. -To execute a YQL query, you can use the command `./ydb yql -s 'select 1;'`, which will return the result of the `select 1` command in table form to the terminal. After checking the connection, you can create a test table with the command: -`./ydb workload kv init --init-upserts 1000 --cols 4`. This will create a test table `kv_test` consisting of 4 columns and 1000 rows. You can verify that the `kv_test` table was created and filled with test data by using the command `./ydb yql -s 'select * from kv_test limit 10;'`. +To execute a YQL query, you can use the command `./ydb sql -s 'select 1;'`, which will return the result of the `select 1` command in table form to the terminal. After checking the connection, you can create a test table with the command: +`./ydb workload kv init --init-upserts 1000 --cols 4`. This will create a test table `kv_test` consisting of 4 columns and 1000 rows. You can verify that the `kv_test` table was created and filled with test data by using the command `./ydb sql -s 'select * from kv_test limit 10;'`. The terminal will display a table of 10 rows. Now, you can perform cluster performance testing. The article [{#T}](../../reference/ydb-cli/workload-kv.md) describes 5 types of workloads (`upsert`, `insert`, `select`, `read-rows`, `mixed`) and the parameters for their execution. An example of executing the `upsert` test workload with the parameter to print the execution time `--print-timestamp` and standard execution parameters is: `./ydb workload kv run upsert --print-timestamp`. diff --git a/ydb/docs/en/core/devops/kubernetes/initial-deployment.md b/ydb/docs/en/core/devops/kubernetes/initial-deployment.md index 505f9a7eeef..1b0a1995217 100644 --- a/ydb/docs/en/core/devops/kubernetes/initial-deployment.md +++ b/ydb/docs/en/core/devops/kubernetes/initial-deployment.md @@ -251,7 +251,7 @@ Check how {{ ydb-short-name }} works: ydb \ --endpoint grpc://database-sample-grpc:2135 \ --database /root/database-sample \ - table query execute --query 'SELECT 2 + 2;' + sql -s 'SELECT 2 + 2;' ``` * `--endpoint`: The database endpoint. diff --git a/ydb/docs/en/core/recipes/ydb-cli/ttl.md b/ydb/docs/en/core/recipes/ydb-cli/ttl.md index 38c2b3a561f..68c386c5ee7 100644 --- a/ydb/docs/en/core/recipes/ydb-cli/ttl.md +++ b/ydb/docs/en/core/recipes/ydb-cli/ttl.md @@ -25,7 +25,7 @@ To enable data eviction, an [external data source](../../concepts/datamodel/exte The example below shows how to enable data eviction by executing a YQL-query from {{ ydb-short-name }} CLI. Rows of the table `mytable` will be moved to the bucket described in the external data source `/Root/s3_cold_data` one hour after the time recorded in the column `created_at` and will be deleted after 24 hours. ```bash -$ {{ ydb-cli }} -e <endpoint> -d <database> table query execute -q ' +$ {{ ydb-cli }} -e <endpoint> -d <database> sql -s ' ALTER TABLE `mytable` SET ( TTL = Interval("PT1H") TO EXTERNAL DATA SOURCE `/Root/s3_cold_data`, diff --git a/ydb/docs/en/core/reference/kafka-api/examples.md b/ydb/docs/en/core/reference/kafka-api/examples.md index 8e139e47d0d..751623811fa 100644 --- a/ydb/docs/en/core/reference/kafka-api/examples.md +++ b/ydb/docs/en/core/reference/kafka-api/examples.md @@ -154,7 +154,7 @@ Currently, the only available authentication mechanism with Kafka API in {{ ydb- To use authentication in a multinode self-deployed database:
-1. Create a user. [How to do this in YQL](../../yql/reference/syntax/create-user.md). [How to execute YQL from CLI](../ydb-cli/yql.md).
+1. Create a user. [How to do this in YQL](../../yql/reference/syntax/create-user.md). [How to execute YQL from CLI](../ydb-cli/sql.md).
2. Connect to the Kafka API as shown in the examples below. In all examples, it is assumed that:
- YDB is running locally with the environment variable `YDB_KAFKA_PROXY_PORT=9092`, meaning that the Kafka API is available at `localhost:9092`. For example, you can run YDB in Docker as described [here](../../quickstart.md#install).
diff --git a/ydb/docs/en/core/reference/ydb-cli/_includes/commands.md b/ydb/docs/en/core/reference/ydb-cli/_includes/commands.md index 5a48b9b56a1..5555604077b 100644 --- a/ydb/docs/en/core/reference/ydb-cli/_includes/commands.md +++ b/ydb/docs/en/core/reference/ydb-cli/_includes/commands.md @@ -53,15 +53,16 @@ Any command can be run from the command line with the `--help` option to get hel | [scheme permissions clear-inheritance](../commands/scheme-permissions.md#clear-inheritance) | Disable permission inheritance | | [scheme permissions set-inheritance](../commands/scheme-permissions.md#set-inheritance) | Enable permission inheritance | | [scheme rmdir](../commands/dir.md#rmdir) | Deleting a directory | -| [scripting yql](../scripting-yql.md) | Executing a YQL script | +| [scripting yql](../scripting-yql.md) | Executing a YQL script (deprecated, use [`ydb sql`](../sql.md)) | +| [sql](../sql.md) | Execute any query | | table attribute add | Adding a table attribute | | table attribute drop | Deleting a table attribute | | [table drop](../table-drop.md) | Deleting a table | | [table index add global-async](../commands/secondary_index.md#add) | Adding an asynchronous index | | [table index add global-sync](../commands/secondary_index.md#add) | Adding a synchronous index | | [table index drop](../commands/secondary_index.md#drop) | Deleting an index | -| [table query execute](../table-query-execute.md) | Executing a YQL query | -| [table query explain](../commands/explain-plan.md) | YQL query execution plan | +| [table query execute](../table-query-execute.md) | Executing a YQL query (deprecated, use [`ydb sql`](../sql.md)) | +| [table query explain](../commands/explain-plan.md) | YQL query execution plan (deprecated, use [`ydb sql --explain`](../sql.md)) | | [table read](../commands/readtable.md) | Streaming table reads | | [table ttl set](../table-ttl-set.md) | Setting TTL parameters | | [table ttl reset](../table-ttl-reset.md) | Resetting TTL parameters | @@ -78,8 +79,8 @@ Any command can be run from the command line with the `--help` option to get hel | [topic read](../topic-read.md) | Reading messages from a topic | | [topic write](../topic-write.md) | Writing messages to a topic | {% if ydb-cli == "ydb" %} -[update](../commands/service.md) | Update the {{ ydb-short-name }} CLI -[version](../commands/service.md) | Output details about the {{ ydb-short-name }} CLI version +| [update](../commands/service.md) | Update the {{ ydb-short-name }} CLI | +| [version](../commands/service.md) | Output details about the {{ ydb-short-name }} CLI version | {% endif %} -[workload](../commands/workload/index.md) | Generate the workload -[yql](../yql.md) | Execute a YQL script (with streaming support) +| [workload](../commands/workload/index.md) | Generate the workload | +| [yql](../yql.md) | Execute a YQL script (deprecated, use [`ydb sql`](../sql.md)) | diff --git a/ydb/docs/en/core/reference/ydb-cli/_includes/deprecated_command_warning.md b/ydb/docs/en/core/reference/ydb-cli/_includes/deprecated_command_warning.md new file mode 100644 index 00000000000..9cfb301d3e2 --- /dev/null +++ b/ydb/docs/en/core/reference/ydb-cli/_includes/deprecated_command_warning.md @@ -0,0 +1,6 @@ +{% note warning %} + +This command is deprecated. +The preferred way to run queries in {{ ydb-short-name }} CLI is to use the [`{{ ydb-cli }} sql`](../sql.md) command. + +{% endnote %}
\ No newline at end of file diff --git a/ydb/docs/en/core/reference/ydb-cli/_includes/index.md b/ydb/docs/en/core/reference/ydb-cli/_includes/index.md index 9126db280ba..cef960ee962 100644 --- a/ydb/docs/en/core/reference/ydb-cli/_includes/index.md +++ b/ydb/docs/en/core/reference/ydb-cli/_includes/index.md @@ -9,7 +9,7 @@ For a full description of {{ ydb-short-name }} CLI commands, see the following a * [List of objects](../commands/scheme-ls.md). * [Getting information about schema objects](../commands/scheme-describe.md). * [Working with directories](../commands/dir.md). -* [YQL execution](../yql-query-overview.md). +* [Query execution](../yql-query-overview.md). * [Streaming table reads](../commands/readtable.md). * [Working with secondary indexes](../commands/secondary_index.md). * [Getting a list of DB endpoints](../commands/discovery-list.md). diff --git a/ydb/docs/en/core/reference/ydb-cli/commands/_includes/scan-query.md b/ydb/docs/en/core/reference/ydb-cli/commands/_includes/scan-query.md index a1c795b5084..366fe14c15c 100644 --- a/ydb/docs/en/core/reference/ydb-cli/commands/_includes/scan-query.md +++ b/ydb/docs/en/core/reference/ydb-cli/commands/_includes/scan-query.md @@ -1,5 +1,7 @@ # Performing scan queries +{% include notitle [warning](../../_includes/deprecated_command_warning.md) %} + You can run a query using [Scan Queries](../../../../concepts/scan_query.md) via the {{ ydb-short-name }} CLI by adding the `-t scan` flag to the `{{ ydb-cli }} table query execute` command. Run the data query: diff --git a/ydb/docs/en/core/reference/ydb-cli/commands/scheme-permissions.md b/ydb/docs/en/core/reference/ydb-cli/commands/scheme-permissions.md index 848bd86f4b0..0cc2daf34e3 100644 --- a/ydb/docs/en/core/reference/ydb-cli/commands/scheme-permissions.md +++ b/ydb/docs/en/core/reference/ydb-cli/commands/scheme-permissions.md @@ -51,7 +51,7 @@ Additional parameters `[options...]`: Each right must be passed as a separate parameter, for example: ```bash -{{ ydb-cli }} scheme permissions grant -p "ydb.access.grant" -p "ydb.generic.read" '/Root/db1/MyApp/Orders' testuser +{{ ydb-cli }} scheme permissions grant -p "ydb.access.grant" -p "ydb.generic.read" '/Root/db1/MyApp/Orders' testuser ``` ## set @@ -129,7 +129,7 @@ Parameters: For example, if you execute the command over the database state from the previous example [`list`](#list): ```bash -{{ ydb-cli }} scheme permissions clear '/Root/db1/MyApp' +{{ ydb-cli }} scheme permissions clear '/Root/db1/MyApp' ``` And then execute the `list` command again on the object `/Root/db1/MyApp`, you will get the following result: diff --git a/ydb/docs/en/core/reference/ydb-cli/parameterized-queries-cli.md b/ydb/docs/en/core/reference/ydb-cli/parameterized-queries-cli.md index 73d33587272..bdde2eb2132 100644 --- a/ydb/docs/en/core/reference/ydb-cli/parameterized-queries-cli.md +++ b/ydb/docs/en/core/reference/ydb-cli/parameterized-queries-cli.md @@ -1,3 +1,10 @@ + +{% note warning %} + +This page is outdated. Please refer to [{#T}](parameterized-query-execution.md) for up-to-date information. + +{% endnote %} + # Running parametrized YQL queries and scripts ## Overview @@ -53,7 +60,7 @@ echo '{"a":10}' > p1.json {{ ydb-cli }} -p quickstart table query execute -q 'declare $a as Int64;select $a' --param-file p1.json ``` -Through `stdin`: +Via `stdin`: ```bash echo '{"a":10}' | {{ ydb-cli }} -p quickstart table query execute -q 'declare $a as Int64;select $a' @@ -293,7 +300,7 @@ Command output: This example demonstrates the adaptive batching triggered by a processing delay. In the first line of the command below, we generate 1,000 rows at a delay of 0.2 seconds on `stdout` and pipe them to `stdin` to the YQL query execution command. The YQL query execution command shows the parameter batches in each subsequent YQL query call. ```bash -for i in $(seq 1 1000);do echo "Line$i";sleep 0.2;done | \ +for i in $(seq 1 1000); do echo "Line$i"; sleep 0.2; done | \ {{ ydb-cli }} -p quickstart table query execute \ -q 'DECLARE $x AS List<Utf8>; SELECT ListLength($x), $x' \ @@ -335,7 +342,7 @@ This example demonstrates the adaptive batching triggered by a number of paramet In this example, we also demonstrate the option to join parameters from different sources and generate JSON at the output. ```bash -for i in $(seq 1 200);do echo "Line$i";done | \ +for i in $(seq 1 200); do echo "Line$i"; done | \ {{ ydb-cli }} -p quickstart table query execute \ -q 'DECLARE $x AS List<Utf8>; DECLARE $p2 AS Int64; @@ -372,7 +379,7 @@ Let's create a test table: Add 100,000 records to it: ```bash -for i in $(seq 1 100000);do echo "$i";done | \ +for i in $(seq 1 100000); do echo "$i"; done | \ {{ ydb-cli }} -p quickstart import file csv -p test_delete_1 ``` diff --git a/ydb/docs/en/core/reference/ydb-cli/parameterized-query-execution.md b/ydb/docs/en/core/reference/ydb-cli/parameterized-query-execution.md new file mode 100644 index 00000000000..b72d0435369 --- /dev/null +++ b/ydb/docs/en/core/reference/ydb-cli/parameterized-query-execution.md @@ -0,0 +1,596 @@ +# Running parameterized queries + +## Overview + +{{ ydb-short-name }} CLI can execute parameterized queries. To use parameters, you need to declare them using [the YQL `DECLARE` command](../../yql/reference/syntax/declare.md) in your query text. + +The preferred way to run parameterized queries in {{ ydb-short-name }} CLI is to use the [`ydb sql`](sql.md) command. + +Parameter values can be set via the command-line arguments, uploaded from [JSON](https://en.wikipedia.org/wiki/JSON) files, and read from `stdin` in binary or JSON format. Binary data can be encoded as base64 or UTF-8. While reading from `stdin` or a file, you can stream multiple parameter values, triggering multiple query executions with batching options. + +## Why use parameterized queries? + +Using parameterized queries offers several key advantages: + +* **Enhanced Performance:** Parameterized queries significantly boost performance when executing multiple similar queries that differ only in input parameters. This is achieved through the use of [prepared statements](https://en.wikipedia.org/wiki/Prepared_statement). The query is compiled once and then cached on the server. Subsequent requests with the same query text bypass the compilation phase, allowing for immediate execution. + +* **Protection Against SQL Injection:** Another critical benefit of using parameterized queries is the protection they offer against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. This security feature ensures that the input parameters are appropriately handled, mitigating the risk of malicious code execution. + +## Executing a single query {#one-request} + +To provide parameters for a single query execution, you can use the command-line arguments, JSON files, or `stdin`, using the following {{ ydb-short-name }} CLI options: + +| Name | Description | +| --- | --- | +| `-p, --param` | The value of a single query parameter in the `name=value` or `$name=value` format, where `name` is the parameter name and `value` is its value (a valid [JSON value](https://www.json.org/json-en.html)). This option can be specified multiple times.<br/><br/>All specified parameters must be declared in the query using the [DECLARE operator](../../yql/reference/syntax/declare.md). Otherwise, you will receive the "Query does not contain parameter" error. If you specify the same parameter multiple times, you will receive the "Parameter value found in more than one source" error.<br/><br/>Depending on your operating system, you might need to escape the `$` character or enclose your expression in single quotes (`'`). | +| `--input-file` | The name of a file in [JSON](https://en.wikipedia.org/wiki/JSON) format and [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoding that contains parameter values matched against the query parameters by key names. Only one input file can be used.<br/><br/>If values for the same parameter are found in multiple files or set by the `--param` command-line option, you will receive the "Parameter value found in more than one source" error.<br/><br/>Keys that are present in the file but not declared in the query will be ignored without an error message. | +| `--input-format` | The format of parameter values applied to all sources of parameters (command line, file, or `stdin`).<br/>Available options:<ul><li>`json` (default): JSON format.</li><li>`csv`: [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) format.</li><li>`tsv`: [TSV](https://en.wikipedia.org/wiki/Tab-separated_values) format.</li><li>`raw`: Input is read as parameter values with no transformation or parsing. The parameter name should be set with the `--input-param-name` option.</li></ul> | +| `--input-binary-strings` | The input binary string encoding format. Defines how binary strings in the input should be interpreted.<br/>Available options:<ul><li>`unicode`: Every byte in binary strings that is not a printable ASCII symbol (codes 32-126) should be encoded as UTF-8.</li><li>`base64`: Binary strings should be fully encoded with base64.</li></ul> | + +If values are specified for all non-optional (i.e., NOT NULL) parameters [in the `DECLARE` clause](../../yql/reference/syntax/declare.md), the query will be executed on the server. If a value is absent for even one such parameter, the command fails with the error message "Missing value for parameter". + +### More specific options for input parameters {#specific-param-options} + +The following options are not described in the `--help` output. To see their descriptions, use the `-hh` option instead. + +| Name | Description | +| --- | --- | +| `--input-framing` | The input framing format. Defines how parameter sets are delimited in the input.<br/>Available options:<br/><ul><li>`no-framing` (default): Data from the input is taken as a single set of parameters.</li><li>`newline-delimited`: A newline character delimits parameter sets in the input and triggers processing according to the `--input-batch` option.</li></ul> | +| `--input-param-name` | The parameter name in the input stream, required when the input format contains only values (that is, when `--input-format raw` is used). | +| `--input-columns` | A string with column names that replaces the CSV/TSV header. Relevant only when passing parameters in CSV/TSV format. It is assumed that the file does not contain a header. | +| `--input-skip-rows` | The number of CSV/TSV header rows to skip in the input data (excluding the row of column names if the `--header` option is used). Relevant only when passing parameters in CSV/TSV format. | +| `--input-batch` | The batch mode applied to parameter sets from `stdin` or `--input-file`.<br/>Available options:<br/><ul><li>`iterative` (default): Executes the query for each parameter set (exactly one execution when `no-framing` is specified for `--input-framing`).</li><li>`full`: A simplified batch mode where the query runs only once and all the parameter sets received from the input (`stdin` or `--input-file`) are wrapped into a `List<...>`.</li><li>`adaptive`: Executes the query with a JSON list of parameter sets when either the number of sets reaches `--input-batch-max-rows` or the waiting time reaches `--input-batch-max-delay`.</li></ul> | +| `--input-batch-max-rows` | The maximum size of the list for the input adaptive batching mode (default: 1000). | +| `--input-batch-max-delay` | The maximum delay before submitting a received parameter set for processing in the `adaptive` batch mode. The value is specified as a number with a time unit: `s` (seconds), `ms` (milliseconds), `m` (minutes), etc. Default value: `1s` (1 second).<br/><br/>The {{ ydb-short-name }} CLI starts a timer when it receives the first set of parameters for the batch from the input and sends the accumulated batch for execution once the timer expires. This parameter enables efficient batching when the arrival rate of new parameter sets is unpredictable. | + +### Examples {#examples-one-request} + +{% include [ydb-cli-profile](../../_includes/ydb-cli-profile.md) %} + +#### Passing the value of a single parameter {#example-simple} + +From the command line using `--param` option: + +```bash +{{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' --param '$a=10' +``` + +Using a file in JSON format (which is used by default): + +```bash +echo '{"a":10}' > p1.json +{{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' --input-file p1.json +``` + +Via `stdin` passing a JSON string as a set of one parameter: + +```bash +echo '{"a":10}' | {{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' +``` + +Via `stdin` passing only a parameter value and setting a parameter name via the `--input-param-name` option: + +```bash +echo '10' | {{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' --input-param-name a +``` + +#### Passing the values of parameters of different types from multiple sources {#example-multisource} + +```bash +# Create a JSON file with fields 'a', 'b', and 'x', where 'x' will be ignored in the query +echo '{ "a":10, "b":"Some text", "x":"Ignore me" }' > p1.json + +# Run the query using ydb-cli, passing in 'a' and 'b' from the input file, and 'c' as a direct parameter +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Utf8; + DECLARE $c AS Int64; + + SELECT $a, $b, $c' \ + --input-file p1.json \ + --param '$c=30' +``` + +Command output: + +```text +┌─────────┬─────────────┬─────────┐ +│ column0 │ column1 │ column2 │ +├─────────┼─────────────┼─────────┤ +│ 10 │ "Some text" │ 30 │ +└─────────┴─────────────┴─────────┘ +``` + +#### Passing Base64-encoded binary strings {#example-base64} + +```bash +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS String; + SELECT $a' \ + --input-format json \ + --input-binary-strings base64 \ + --param '$a="SGVsbG8sIHdvcmxkCg=="' +``` + +Command output: + +```text +┌──────────────────┐ +| column0 | +├──────────────────┤ +| "Hello, world\n" | +└──────────────────┘ +``` + +#### Passing raw binary content directly {#example-raw} + +```bash +curl -Ls http://ydb.tech/docs/en | {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS String; + SELECT LEN($a)' \ + --input-format raw \ + --input-param-name a +``` + +Command output (the exact number of bytes may vary): + +```text +┌─────────┐ +| column0 | +├─────────┤ +| 66426 | +└─────────┘ +``` + +#### Passing CSV data {#example-csv} + +```bash +echo '10,Some text' | {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int32; + DECLARE $b AS String; + SELECT $a, $b' \ + --input-format csv \ + --input-columns 'a,b' +``` + +Command output: + +```text +┌─────────┬─────────────┐ +| column0 | column1 | +├─────────┼─────────────┤ +| 10 | "Some text" | +└─────────┴─────────────┘ +``` + +## Iterative streaming processing {#streaming-iterate} + +{{ ydb-short-name }} CLI supports executing a query multiple times with different sets of parameter values provided via `stdin` **or** an input file (but not both). In this case, the database connection is established once, and the query execution plan is cached. This approach significantly improves performance compared to making separate CLI calls. + +To use this feature, stream different sets of values for the same parameters to the command input (`stdin` or `--input-file`) one after another, specifying a rule for the {{ ydb-short-name }} CLI to separate the sets. + +The query is executed as many times as there are parameter value sets received from the input. Each set is combined with the parameter values defined using the `--param` options. The command completes once the input stream is closed. Each query is executed within a dedicated transaction. + +A rule for separating parameter sets (framing) complements the `--input-format` option: + +| Name | Description | +---|--- +| `--input-framing` | Input framing format. Defines how parameter sets are delimited on the input.<br/>Available options:<br/><ul><li>`no-framing` (default): Data from the input is taken as a single set of parameters.</li><li>`newline-delimited`: A newline character delimits parameter sets in the input and triggers processing according to the `--input-batch` option.</li></ul> | + +{% note warning %} + +When using a newline character as a separator between parameter sets, ensure that newline characters are not used inside the parameter sets. Quoting a text value does not allow newlines within the text. Multiline JSON documents are also not allowed. + +{% endnote %} + +### Example {#example-streaming-iterate} + +#### Streaming processing of multiple parameter sets {#example-iterate} + +{% list tabs %} + +- JSON + + Suppose you need to run your query three times with the following sets of values for the `a` and `b` parameters: + + 1. `a` = 10, `b` = 20 + 2. `a` = 15, `b` = 25 + 3. `a` = 35, `b` = 48 + + Let's create a file that contains lines with JSON representations of these sets: + + ```bash + echo -e '{"a":10,"b":20}\n{"a":15,"b":25}\n{"a":35,"b":48}' | tee par1.txt + ``` + + Command output: + + ```text + {"a":10,"b":20} + {"a":15,"b":25} + {"a":35,"b":48} + ``` + + Let's execute the query by passing the content of this file to `stdin`, formatting the output as JSON: + + ```bash + cat par1.txt | \ + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-framing newline-delimited \ + --format json-unicode + ``` + + Command output: + + ```text + {"column0":30} + {"column0":40} + {"column0":83} + ``` + + Or just by passing the input file name to the `--input-file` option: + + ```bash + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-file par1.txt \ + --input-framing newline-delimited \ + --format json-unicode + ``` + + Command output: + + ```text + {"column0":30} + {"column0":40} + {"column0":83} + ``` + + This output can be passed as input to the next query command if it has a `column0` parameter. + +- CSV + + Suppose you need to run your query three times with the following sets of values for the `a` and `b` parameters: + + 1. `a` = 10, `b` = 20 + 2. `a` = 15, `b` = 25 + 3. `a` = 35, `b` = 48 + + Let's create a file that contains lines with CSV representations of these sets: + + ```bash + echo -e 'a,b\n10,20\n15,25\n35,48' | tee par1.txt + ``` + + Command output: + + ```text + a,b + 10,20 + 15,25 + 35,48 + ``` + + Let's execute the query by passing the content of this file to `stdin`, formatting the output as CSV: + + ```bash + cat par1.txt | \ + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-format csv \ + --input-framing newline-delimited \ + --format csv + ``` + + Command output: + + ```text + 30 + 40 + 83 + ``` + + Or just by passing the input file name to the `--input-file` option: + + ```bash + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-file par1.txt \ + --input-format csv \ + --input-framing newline-delimited \ + --format csv + ``` + + Command output: + + ```text + 30 + 40 + 83 + ``` + + This output can be passed as input to another command running a different parameterized query. + +- TSV + + Suppose you need to run your query three times, with the following sets of values for the `a` and `b` parameters: + + 1. `a` = 10, `b` = 20 + 2. `a` = 15, `b` = 25 + 3. `a` = 35, `b` = 48 + + Let's create a file that includes lines with TSV representations of these sets: + + ```bash + echo -e 'a\tb\n10\t20\n15\t25\n35\t48' | tee par1.txt + ``` + + Command output: + + ```text + a b + 10 20 + 15 25 + 35 48 + ``` + + Let's execute the query by passing the content of this file to `stdin`, formatting the output as TSV: + + ```bash + cat par1.txt | \ + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-format tsv \ + --input-framing newline-delimited \ + --format tsv + ``` + + Command output: + + ```text + 30 + 40 + 83 + ``` + + Or just by passing the input file name to the `--input-file` option: + + ```bash + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-file par1.txt \ + --input-format tsv \ + --input-framing newline-delimited \ + --format tsv + ``` + + Command output: + + ```text + 30 + 40 + 83 + ``` + + This output can be passed as input to the next query command. + +{% endlist %} + +#### Streaming processing with joining parameter values from different sources {#example-iterate-union} + +For example, you need to run your query three times with the following sets of values for the `a` and `b` parameters: + +1. `a` = 10, `b` = 100 +2. `a` = 15, `b` = 100 +3. `a` = 35, `b` = 100 + +```bash +echo -e '10\n15\n35' | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b AS sum1' \ + --param '$b=100' \ + --input-framing newline-delimited \ + --input-param-name a \ + --format json-unicode +``` + +Command output: + +```text +{"sum1":110} +{"sum1":115} +{"sum1":135} +``` + +## Batched streaming processing {#streaming-batch} + +The {{ ydb-short-name }} CLI supports automatic conversion of multiple consecutive parameter sets to a `List<...>`, enabling you to process them in a single request and transaction. As a result, you can achieve a substantial performance gain compared to one-by-one query processing. + +Two batch modes are supported: + +- Full +- Adaptive + +### Full batch mode {#batch-full} + +The `full` mode is a simplified batch mode where the query runs only once, and all the parameter sets received from the input (`stdin` or `--input-file`) are wrapped into a `List<...>`. If the request is too large, you will receive an error. + +Use this batch mode when you want to ensure transaction atomicity by applying all the parameters within a single transaction. + +### Adaptive batch mode {#batch-adaptive} + +In the `adaptive` mode, the input stream is split into multiple transactions, with the batch size automatically determined for each of them. + +In this mode, you can process a broad range of dynamic workloads with unpredictable or infinite amounts of data, as well as workloads with an unpredictable or significantly varying rate of new sets appearing in the input. For example, this scenario is common when sending the output of another command to `stdin` using the `|` operator. + +The adaptive mode solves two key issues of dynamic stream processing: + +1. Limiting the maximum batch size. +2. Limiting the maximum data processing delay. + +### Syntax {#batch-syntax} + +To use the batching capabilities, define the `List<...>` or `List<Struct<...>>` parameter in the query's `DECLARE` clause, and use the following options: + +| Name | Description | +| --- | --- | +| `--input-batch` | The batch mode applied to parameter sets on `stdin` or `--input-file`.<br/>Available options:<br/><ul><li>`iterative` (default): Executes the query for each parameter set (exactly one execution when `no-framing` is specified for `--input-framing`).</li><li>`full`: A simplified batch mode where the query runs only once and all the parameter sets received from the input (`stdin` or `--input-file`) are wrapped into a `List<...>`.</li><li>`adaptive`: Executes the query with a JSON list of parameter sets whenever the number of sets reaches `--input-batch-max-rows` or the waiting time reaches `--input-batch-max-delay`.</li></ul> | + +In the adaptive batch mode, you can use the following additional parameters: + +| Name | Description | +| --- | --- | +| `--input-batch-max-rows` | The maximum number of parameter sets per batch in the `adaptive` batch mode. The next batch will be sent with the query if the number of parameter sets reaches the specified limit. When set to `0`, there is no limit.<br/><br/>Default value: `1000`.<br/><br/>Parameter values are sent to each query execution without streaming, so the total size per gRPC request that includes the parameter values has an upper limit of about 5 MB. | +| `--input-batch-max-delay` | The maximum delay before submitting a received parameter set for processing in the `adaptive` batch mode. The value is specified as a number with a time unit: `s` (seconds), `ms` (milliseconds), `m` (minutes), etc. Default value: `1s` (1 second).<br/><br/>The {{ ydb-short-name }} CLI starts a timer when it receives the first set of parameters for the batch from the input and sends the accumulated batch for execution once the timer expires. This parameter enables efficient batching when the arrival rate of new parameter sets is unpredictable. | + +### Examples: Full batch processing {#example-batch-full} + +```bash +echo -e '{"a":10,"b":20}\n{"a":15,"b":25}\n{"a":35,"b":48}' | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $x AS List<Struct<a:Int64,b:Int64>>; + SELECT ListLength($x), $x' \ + --input-framing newline-delimited \ + --input-param-name x \ + --input-batch full +``` + +Command output: + +```text +┌─────────┬───────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼───────────────────────────────────────────────────┤ +| 3 | [{"a":10,"b":20},{"a":15,"b":25},{"a":35,"b":48}] | +└─────────┴───────────────────────────────────────────────────┘ +``` + +### Examples: Adaptive batch processing {#example-batch-adaptive} + +#### Limiting the maximum data processing delay {#example-adaptive-delay} + +This example demonstrates adaptive batching triggered by a processing delay. In the first line of the command below, we generate 1,000 rows with a delay of 0.2 seconds on `stdout` and pipe them to `stdin` for the `ydb sql` query execution command. The query execution command displays the parameter batches in each subsequent query call. + +```bash +for i in $(seq 1 1000); do echo "Line$i"; sleep 0.2; done | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $x AS List<Utf8>; + SELECT ListLength($x), $x' \ + --input-framing newline-delimited \ + --input-format raw \ + --input-param-name x \ + --input-batch adaptive +``` + +Command output (the actual values may differ): + +```text +┌─────────┬────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ +| 14 | ["Line1","Line2","Line3","Line4","Line5","Line6","Line7","Line8","Line9","Line10","Line11","Line12","Line13","Line14"] | +└─────────┴────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ +┌─────────┬─────────────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼─────────────────────────────────────────────────────────┤ +| 6 | ["Line15","Line16","Line17","Line18","Line19","Line20"] | +└─────────┴─────────────────────────────────────────────────────────┘ +┌─────────┬─────────────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼─────────────────────────────────────────────────────────┤ +| 6 | ["Line21","Line22","Line23","Line24","Line25","Line26"] | +└─────────┴─────────────────────────────────────────────────────────┘ +^C +``` + +The first batch includes all the rows accumulated at the input while the database connection was being established, which is why it is larger than the subsequent ones. + +You can terminate the command by pressing Ctrl+C or wait 200 seconds until the input generation is finished. + +#### Limit on the number of records {#example-adaptive-limit} + +This example demonstrates adaptive batching triggered by the number of parameter sets. In the first line of the command below, we generate 200 rows. The command displays parameter batches in each subsequent query call, applying the specified limit `--input-batch-max-rows` of 20 (the default limit is 1,000). + +This example also demonstrates the option to join parameters from different sources and generate JSON as output. + +```bash +for i in $(seq 1 200); do echo "Line$i"; done | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $x AS List<Utf8>; + DECLARE $p2 AS Int64; + SELECT ListLength($x) AS count, $p2 AS p2, $x AS items' \ + --input-framing newline-delimited \ + --input-format raw \ + --input-param-name x \ + --input-batch adaptive \ + --input-batch-max-rows 20 \ + --param '$p2=10' \ + --format json-unicode +``` + +Command output: + +```text +{"count":20,"p2":10,"items":["Line1","Line2","Line3","Line4","Line5","Line6","Line7","Line8","Line9","Line10","Line11","Line12","Line13","Line14","Line15","Line16","Line17","Line18","Line19","Line20"]} +{"count":20,"p2":10,"items":["Line21","Line22","Line23","Line24","Line25","Line26","Line27","Line28","Line29","Line30","Line31","Line32","Line33","Line34","Line35","Line36","Line37","Line38","Line39","Line40"]} +... +{"count":20,"p2":10,"items":["Line161","Line162","Line163","Line164","Line165","Line166","Line167","Line168","Line169","Line170","Line171","Line172","Line173","Line174","Line175","Line176","Line177","Line178","Line179","Line180"]} +{"count":20,"p2":10,"items":["Line181","Line182","Line183","Line184","Line185","Line186","Line187","Line188","Line189","Line190","Line191","Line192","Line193","Line194","Line195","Line196","Line197","Line198","Line199","Line200"]} +``` + +#### Deleting multiple records from a {{ ydb-short-name }} table based on primary keys {#example-adaptive-delete-pk} + +{% include [not_allow_for_olap_note](../../_includes/not_allow_for_olap_note.md) %} + +If you attempt to delete a large number of rows from a substantial table using a simple `DELETE FROM large_table WHERE id > 10;` statement, you may encounter an error due to exceeding the transaction record limit. This example shows how to delete an unlimited number of records from {{ ydb-short-name }} tables without breaching this limitation. + +Let's create a test table: + +```bash +{{ ydb-cli }} -p quickstart sql -s 'CREATE TABLE test_delete_1(id UInt64 NOT NULL, PRIMARY KEY (id))' +``` + +Add 100,000 records to it: + +```bash +for i in $(seq 1 100000); do echo "$i"; done | \ +{{ ydb-cli }} -p quickstart import file csv -p test_delete_1 +``` + +Delete all records with `id` greater than 10: + +```bash +{{ ydb-cli }} -p quickstart sql \ + -s 'SELECT t.id FROM test_delete_1 AS t WHERE t.id > 10' \ + --format json-unicode | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $lines AS List<Struct<id:UInt64>>; + DELETE FROM test_delete_1 WHERE id IN (SELECT tl.id FROM AS_TABLE($lines) AS tl)' \ + --input-framing newline-delimited \ + --input-param-name lines \ + --input-batch adaptive \ + --input-batch-max-rows 10000 +``` + +#### Processing messages read from a topic {#example-adaptive-pipeline-from-topic} + +Examples of processing messages read from a topic are provided in [{#T}](topic-pipeline.md#example-read-to-yql-param). + +## See also {#see-also} + +* [Parameterized queries in {{ ydb-short-name }} SDK](../ydb-sdk/parameterized_queries.md) diff --git a/ydb/docs/en/core/reference/ydb-cli/scripting-yql.md b/ydb/docs/en/core/reference/ydb-cli/scripting-yql.md index 50d022bfcf6..5b4812b216b 100644 --- a/ydb/docs/en/core/reference/ydb-cli/scripting-yql.md +++ b/ydb/docs/en/core/reference/ydb-cli/scripting-yql.md @@ -1,5 +1,8 @@ + # Running a script +{% include notitle [warning](./_includes/deprecated_command_warning.md) %} + You can use the `scripting yql` subcommand to run a YQL script. The script can include queries of different types. Unlike `yql`, the `scripting yql` command has a limit on the number of returned rows and accessed data. General format of the command: diff --git a/ydb/docs/en/core/reference/ydb-cli/sql.md b/ydb/docs/en/core/reference/ydb-cli/sql.md new file mode 100644 index 00000000000..87dea3e2da0 --- /dev/null +++ b/ydb/docs/en/core/reference/ydb-cli/sql.md @@ -0,0 +1,83 @@ +# Query execution + +You can use the `{{ ydb-cli }} sql` subcommand to execute an SQL query. The query can be of any type (DDL, DML, etc.) and can consist of several subqueries. The `{{ ydb-cli }} sql` subcommand establishes a streaming connection and retrieves data through it. With in-stream query execution, no limit is imposed on the amount of data read. Data can also be written using this command, which is more efficient when executing repeated queries with data passed through parameters. + +General format of the command: + +```bash +{{ ydb-cli }} [global options...] sql [options...] +``` + +* `global options`: [Global parameters](commands/global-options.md). +* `options`: [Subcommand parameters](#options). + +View the description of this command by calling it with `--help` option: + +```bash +{{ ydb-cli }} sql --help +``` + +## Parameters of the subcommand {#options} + +#| +|| Name | Description || +|| `-h`, `--help` | Print general usage help. || +|| `-hh` | Print complete usage help, including specific options not shown with `--help`. || +|| `-s`, `--script` | Script (query) text to execute. || +|| `-f`, `--file` | Path to a file with query text to execute. Path `-` means reading query text from `stdin` which disables passing parameters via `stdin`. || +|| `--stats` | Statistics mode.<br/>Available options:<br/><ul><li>`none` (default): Do not collect statistics.</li><li>`basic`: Collect aggregated statistics for updates and deletes per table.</li><li>`full`: Include execution statistics and plan in addition to `basic`.</li><li>`profile`: Collect detailed execution statistics, including statistics for individual tasks and channels.</li></ul> || +|| `--explain` | Execute an explain request for the query. Displays the query's logical plan. The query is not actually executed and does not affect database data. || +|| `--explain-ast` | Same as `--explain`, but in addition to the query's logical plan, an [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree) is printed. The AST section contains a representation in the internal [miniKQL](../../concepts/glossary.md#minikql) language. || +|| `--explain-analyze` | Execute the query in `EXPLAIN ANALYZE` mode. Displays the query execution plan. Query results are ignored.<br/>**Important note: The query is actually executed, so any changes will be applied to the database**. || +|| `--format` | Output format.<br/>Available options: + +{% include notitle [format](./_includes/result_format_common.md) %} + +{% include notitle [format](./_includes/result_format_csv_tsv.md) %} + +|| +|# + +### Working with parameterized queries {#parameterized-query} + +For a detailed description with examples on how to use parameterized queries, see [{#T}](parameterized-query-execution.md). + +## Examples {#examples} + +{% include [ydb-cli-profile](../../_includes/ydb-cli-profile.md) %} + +A script to create a table, populate it with data, and select data from the table: + +```bash +{{ ydb-cli }} -p quickstart sql -s ' + CREATE TABLE series (series_id Uint64, title Utf8, series_info Utf8, release_date Date, PRIMARY KEY (series_id)); + COMMIT; + UPSERT INTO series (series_id, title, series_info, release_date) values (1, "Title1", "Info1", Cast("2023-04-20" as Date)); + COMMIT; + SELECT * from series; + ' +``` + +Command output: + +```text +┌──────────────┬───────────┬─────────────┬──────────┐ +| release_date | series_id | series_info | title | +├──────────────┼───────────┼─────────────┼──────────┤ +| "2023-04-20" | 1 | "Info1" | "Title1" | +└──────────────┴───────────┴─────────────┴──────────┘ +``` + +Running a script from the example above saved as the `script1.yql` file, with results output in `JSON` format: + +```bash +{{ ydb-cli }} -p quickstart sql -f script1.yql --format json +``` + +Command output: + +```text +{"release_date":"2023-04-20","series_id":1,"series_info":"Info1","title":"Title1"} +``` + +You can find examples of passing parameters to queries in the [article on how to pass parameters to `{{ ydb-cli }} sql`](parameterized-query-execution.md). diff --git a/ydb/docs/en/core/reference/ydb-cli/table-query-execute.md b/ydb/docs/en/core/reference/ydb-cli/table-query-execute.md index 80bb91de877..ea9d80be3d4 100644 --- a/ydb/docs/en/core/reference/ydb-cli/table-query-execute.md +++ b/ydb/docs/en/core/reference/ydb-cli/table-query-execute.md @@ -1,5 +1,8 @@ + # Running a query +{% include notitle [warning](./_includes/deprecated_command_warning.md) %} + The `table query execute` subcommand is designed for reliable execution of YQL queries. With this sub-command, you can successfully execute your query when certain table partitions are unavailable for a short time (for example, due to being [split or merged](../../concepts/datamodel/table.md#partitioning)) by using built-in retry policies. General format of the command: diff --git a/ydb/docs/en/core/reference/ydb-cli/toc_i.yaml b/ydb/docs/en/core/reference/ydb-cli/toc_i.yaml index 3dc4805a98f..3bc6dcf8f80 100644 --- a/ydb/docs/en/core/reference/ydb-cli/toc_i.yaml +++ b/ydb/docs/en/core/reference/ydb-cli/toc_i.yaml @@ -69,20 +69,29 @@ items: href: topic-write.md - name: Message pipeline processing href: topic-pipeline.md - - name: YQL execution + - name: SQL query execution items: - name: Overview href: yql-query-overview.md + - name: Query execution + href: sql.md + - name: Parameterized query execution + href: parameterized-query-execution.md + - name: Interactive query execution mode + href: interactive-cli.md +# Deprecated commands: - name: Running a script (with streaming support) href: yql.md + hidden: true - name: Running a script href: scripting-yql.md + hidden: true - name: Running a query href: table-query-execute.md + hidden: true - name: Running parameterized queries href: parameterized-queries-cli.md - - name: Interactive query execution mode - href: interactive-cli.md + hidden: true # - name: Utilities # items: # - name: Backup diff --git a/ydb/docs/en/core/reference/ydb-cli/topic-pipeline.md b/ydb/docs/en/core/reference/ydb-cli/topic-pipeline.md index f43afa71a0a..159a9852e75 100644 --- a/ydb/docs/en/core/reference/ydb-cli/topic-pipeline.md +++ b/ydb/docs/en/core/reference/ydb-cli/topic-pipeline.md @@ -37,22 +37,22 @@ The use of the `topic read` and `topic write` commands with standard I/O devices {{ ydb-cli }} -p quickstart topic write topic1 --format newline-delimited ``` -## Running of an SQL query with the transmission of messages from the topic as parameters {#example-read-to-yql-param} +## Running an SQL query with the transmission of messages from the topic as parameters {#example-read-to-yql-param} * Running a YQL, passing each message read from `topic1` as a parameter ```bash {{ ydb-cli }} -p quickstart topic read topic1 -c c1 --format newline-delimited -w | \ - {{ ydb-cli }} -p quickstart table query execute -q 'declare $s as String;select Len($s) as Bytes' \ - --stdin-format newline-delimited --stdin-par s --stdin-format raw + {{ ydb-cli }} -p quickstart sql -s 'declare $s as String;select Len($s) as Bytes' \ + --input-framing newline-delimited --input-param-name s --input-format raw ``` * Running a YQL query involving adaptive batching of parameters from messages read from `topic1` ```bash {{ ydb-cli }} -p quickstart topic read topic1 -c c1 --format newline-delimited -w | \ - {{ ydb-cli }} -p quickstart table query execute \ - -q 'declare $s as List<String>;select ListLength($s) as Count, $s as Items' \ - --stdin-format newline-delimited --stdin-par s --stdin-format raw \ - --batch adaptive + {{ ydb-cli }} -p quickstart sql \ + -s 'declare $s as List<String>;select ListLength($s) as Count, $s as Items' \ + --input-framing newline-delimited --input-param-name s --input-format raw \ + --input-batch adaptive ``` diff --git a/ydb/docs/en/core/reference/ydb-cli/yql-query-overview.md b/ydb/docs/en/core/reference/ydb-cli/yql-query-overview.md index 66148c85c53..b23508417f9 100644 --- a/ydb/docs/en/core/reference/ydb-cli/yql-query-overview.md +++ b/ydb/docs/en/core/reference/ydb-cli/yql-query-overview.md @@ -1,10 +1,8 @@ # Overview -You can use the following {{ ydb-short-name }} CLI commands to run YQL queries: +You can use the following {{ ydb-short-name }} CLI commands to run queries: -1. [ydb yql](yql.md): Runs YQL queries and scripts with streaming enabled (without limiting the amount of returned data). -2. [ydb scripting yql](scripting-yql.md): Runs YQL queries and scripts, limiting the amount of data returned. You can also use this command to view the query execution plan and the response metadata. -3. [ydb table query execute](table-query-execute.md): Runs [DML queries](https://en.wikipedia.org/wiki/Data_manipulation_language#SQL) with a given level of transaction isolation and a standard retry policy. -4. [ydb](interactive-cli.md): Switches the console to interactive mode and executes YQL queries and scripts. +* [ydb sql](sql.md): A single command to execute any SQL query supported by YDB. +* [ydb](interactive-cli.md): Switches the console to interactive mode to execute queries. -Commands 1-3 support the same functionality for [query parameterization in YQL](parameterized-queries-cli.md). +[Query parameterization](parameterized-query-execution.md) is explained separately. diff --git a/ydb/docs/en/core/reference/ydb-cli/yql.md b/ydb/docs/en/core/reference/ydb-cli/yql.md index 0c26f101b8d..795be1713fd 100644 --- a/ydb/docs/en/core/reference/ydb-cli/yql.md +++ b/ydb/docs/en/core/reference/ydb-cli/yql.md @@ -1,5 +1,8 @@ + # Running a script (with streaming support) +{% include notitle [warning](./_includes/deprecated_command_warning.md) %} + You can use the `yql` subcommand to run a YQL script. The script can include queries of different types. Unlike `scripting yql`, the `yql` subcommand establishes a streaming connection and retrieves data through it. With the in-stream query execution, no limit is imposed on the amount of data read. General format of the command: @@ -87,4 +90,3 @@ Command output: ``` You can find examples of passing parameters to scripts in the [article on how to pass parameters to YQL execution commands](parameterized-queries-cli.md). - diff --git a/ydb/docs/ru/core/devops/ansible/initial-deployment.md b/ydb/docs/ru/core/devops/ansible/initial-deployment.md index bbd6c4aa92e..df8ad03b736 100644 --- a/ydb/docs/ru/core/devops/ansible/initial-deployment.md +++ b/ydb/docs/ru/core/devops/ansible/initial-deployment.md @@ -300,7 +300,7 @@ all: Проверить, создался ли профиль, можно командой `./ydb config profile list` – будет выведен список профилей. После создания профиля его нужно активировать командой `./ydb config profile activate <profile name>`. Проверить, что профиль был активирован, можно повторным выполнением команды `./ydb config profile list` – активный профиль будет иметь отметку (active). Теперь можно выполнить YQL запрос `./ydb yql -s 'select 1;'`, который вернёт в терминал результат выполнения команды `select 1` в табличной форме. После проверки соединения можно создать тестовую таблицу командой: -`./ydb workload kv init --init-upserts 1000 --cols 4`. Будет создана тестовая таблица `kv_test`, состоящая из 4 столбцов и 1000 строк. Проверить, что таблица `kv_test` создалась и заполнилась тестовыми данными, можно командой `./ydb yql -s 'select * from kv_test limit 10;'`. +`./ydb workload kv init --init-upserts 1000 --cols 4`. Будет создана тестовая таблица `kv_test`, состоящая из 4 столбцов и 1000 строк. Проверить, что таблица `kv_test` создалась и заполнилась тестовыми данными, можно командой `./ydb sql -s 'select * from kv_test limit 10;'`. В терминал будет выведена таблица из 10 строк. Теперь можно выполнять тестирование производительности кластера. В статье [{#T}](../../reference/ydb-cli/workload-kv.md) описаны 5 видов нагрузок (`upsert`, `insert`, `select`, `read-rows`, `mixed`) и параметры их выполнения. Пример выполнения тестовой нагрузки `upsert` с параметром вывода времени выполнения запроса `--print-timestamp` и стандартными параметрами исполнения: `./ydb workload kv run upsert --print-timestamp`. diff --git a/ydb/docs/ru/core/devops/kubernetes/initial-deployment.md b/ydb/docs/ru/core/devops/kubernetes/initial-deployment.md index 4062104f49f..d683bdc6fa7 100644 --- a/ydb/docs/ru/core/devops/kubernetes/initial-deployment.md +++ b/ydb/docs/ru/core/devops/kubernetes/initial-deployment.md @@ -262,7 +262,7 @@ Events: ydb \ --endpoint grpc://database-sample-grpc:2135 \ --database /root/database-sample \ - table query execute --query 'SELECT 2 + 2;' + sql -s 'SELECT 2 + 2;' ``` * `--endpoint` — эндпоинт базы данных; diff --git a/ydb/docs/ru/core/recipes/ydb-cli/ttl.md b/ydb/docs/ru/core/recipes/ydb-cli/ttl.md index 6ebf888e747..d41fdb5bbfe 100644 --- a/ydb/docs/ru/core/recipes/ydb-cli/ttl.md +++ b/ydb/docs/ru/core/recipes/ydb-cli/ttl.md @@ -25,7 +25,7 @@ $ {{ ydb-cli }} -e <endpoint> -d <database> table ttl set --column modified_at - Следующий пример демонстрирует включение вытеснения данных через вызов YQL-запроса из {{ ydb-short-name }} CLI. Строки таблицы `mytable` будут переноситься в бакет, описанный во внешнем источнике данных `/Root/s3_cold_data`, спустя час после наступления времени, записанного в колонке `created_at`, а спустя 24 часа будут удаляться. ```bash -$ {{ ydb-cli }} -e <endpoint> -d <database> table query execute -q ' +$ {{ ydb-cli }} -e <endpoint> -d <database> sql -s ' ALTER TABLE `mytable` SET ( TTL = Interval("PT1H") TO EXTERNAL DATA SOURCE `/Root/s3_cold_data`, diff --git a/ydb/docs/ru/core/reference/kafka-api/examples.md b/ydb/docs/ru/core/reference/kafka-api/examples.md index 1b70df9afd2..fe32a0e20d6 100644 --- a/ydb/docs/ru/core/reference/kafka-api/examples.md +++ b/ydb/docs/ru/core/reference/kafka-api/examples.md @@ -149,7 +149,7 @@ Unexpected error in join group response: This most likely occurs because of a re Для того, чтобы проверить работу с аутентификацией в локальной базе: -1. Создайте пользователя. [Как это сделать в YQL](../../yql/reference/syntax/create-user.md). [Как выполнить YQL из CLI](../ydb-cli/yql.md). +1. Создайте пользователя. [Как это сделать в YQL](../../yql/reference/syntax/create-user.md). [Как выполнить YQL из CLI](../ydb-cli/sql.md). 2. Подключитесь к Kafka API, как в примерах ниже. Во всех примерах предполагается, что: - YDB запущен локально с переменной окружения YDB_KAFKA_PROXY_PORT=9092 - то есть Kafka API доступен по адресу localhost:9092. Например можно поднять YDB в докере, как указано [здесь](../../quickstart.md#install). diff --git a/ydb/docs/ru/core/reference/ydb-cli/_includes/commands.md b/ydb/docs/ru/core/reference/ydb-cli/_includes/commands.md index ec8226b89ca..1558550c6af 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/_includes/commands.md +++ b/ydb/docs/ru/core/reference/ydb-cli/_includes/commands.md @@ -53,15 +53,16 @@ [scheme permissions clear-inheritance](../commands/scheme-permissions.md#clear-inheritance) | Запрет наследования разрешений [scheme permissions set-inheritance](../commands/scheme-permissions.md#set-inheritance) | Установка наследования разрешений [scheme rmdir](../commands/dir.md#rmdir) | Удаление директории -[scripting yql](../scripting-yql.md) | Выполнение YQL-скрипта +[scripting yql](../scripting-yql.md) | Выполнение YQL-скрипта (команда устарела, используйте [`ydb sql`](../sql.md)) +[sql](../sql.md) | Выполнение любого запроса table attribute add | Добавление атрибута для строкой или колоночной таблицы table attribute drop | Удаление атрибута у строковой или колоночной таблицы [table drop](../table-drop.md) | Удаление строковой или колоночной таблицы [table index add global-async](../commands/secondary_index.md#add) | Добавление асинхронного индекса для строковых таблиц [table index add global-sync](../commands/secondary_index.md#add) | Добавление синхронного индекса для строковых таблиц [table index drop](../commands/secondary_index.md#drop) | Удаление индекса у строковых таблиц -[table query execute](../table-query-execute.md) | Исполнение YQL-запроса -[table query explain](../commands/explain-plan.md) | План исполнения YQL-запроса +[table query execute](../table-query-execute.md) | Исполнение YQL-запроса (команда устарела, используйте [`ydb sql`](../sql.md)) +[table query explain](../commands/explain-plan.md) | Получение плана исполнения YQL-запроса (команда устарела, используйте [`ydb sql --explain`](../sql.md)) [table read](../commands/readtable.md) | Потоковое чтение строковой таблицы [table ttl set](../table-ttl-set.md) | Установка параметров TTL для строковых и колоночных таблиц [table ttl reset](../table-ttl-reset.md) | Сброс параметров TTL для строковых и колоночных таблиц @@ -85,4 +86,4 @@ table attribute drop | Удаление атрибута у строковой [version](../commands/service.md) | Вывод информации о версии {{ ydb-short-name }} CLI {% endif %} [workload](../commands/workload/index.md) | Генерация нагрузки -[yql](../yql.md) | Выполнение YQL-скрипта (с поддержкой стриминга) +[yql](../yql.md) | Выполнение YQL-скрипта с поддержкой стриминга (команда устарела, используйте [`ydb sql`](../sql.md)) diff --git a/ydb/docs/ru/core/reference/ydb-cli/_includes/deprecated_command_warning.md b/ydb/docs/ru/core/reference/ydb-cli/_includes/deprecated_command_warning.md new file mode 100644 index 00000000000..761b13ea98a --- /dev/null +++ b/ydb/docs/ru/core/reference/ydb-cli/_includes/deprecated_command_warning.md @@ -0,0 +1,6 @@ +{% note warning %} + +Данная команда устарела. +Рекомендуемый инструмент для выполнения запросов в {{ ydb-short-name }} CLI — это команда [{{ ydb-cli }} sql](../sql.md). + +{% endnote %}
\ No newline at end of file diff --git a/ydb/docs/ru/core/reference/ydb-cli/_includes/index.md b/ydb/docs/ru/core/reference/ydb-cli/_includes/index.md index 050f1e12095..28d7c6a52c0 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/_includes/index.md +++ b/ydb/docs/ru/core/reference/ydb-cli/_includes/index.md @@ -9,7 +9,7 @@ * [Список объектов](../commands/scheme-ls.md). * [Получение информации об объекте схемы](../commands/scheme-describe.md). * [Работа с директориями](../commands/dir.md). -* [Выполнение YQL](../yql-query-overview.md). +* [Выполнение запросов](../yql-query-overview.md). * [Потоковое чтение строковых таблиц](../commands/readtable.md). * [Работа со вторичными индексами](../commands/secondary_index.md). * [Получение списка эндпоинтов для базы данных](../commands/discovery-list.md). diff --git a/ydb/docs/ru/core/reference/ydb-cli/commands/_includes/scan-query.md b/ydb/docs/ru/core/reference/ydb-cli/commands/_includes/scan-query.md index 1183e820cf3..30aa775b204 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/commands/_includes/scan-query.md +++ b/ydb/docs/ru/core/reference/ydb-cli/commands/_includes/scan-query.md @@ -1,5 +1,7 @@ # Выполнение скан запросов +{% include notitle [warning](../../_includes/deprecated_command_warning.md) %} + Запуск запроса через [Scan Queries](../../../../concepts/scan_query.md) посредством {{ ydb-short-name }} CLI осуществляется добавлением флага `-t scan` в команду `{{ ydb-cli }} table query execute`. Выполните запрос к данным: diff --git a/ydb/docs/ru/core/reference/ydb-cli/commands/scheme-permissions.md b/ydb/docs/ru/core/reference/ydb-cli/commands/scheme-permissions.md index 0d11c72baa3..ee90dc0d63b 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/commands/scheme-permissions.md +++ b/ydb/docs/ru/core/reference/ydb-cli/commands/scheme-permissions.md @@ -51,7 +51,7 @@ permissions Modify permissions Каждое право нужно передавать отдельным параметром, например: ```bash -{{ ydb-cli }} scheme permissions grant -p "ydb.access.grant" -p "ydb.generic.read" '/Root/db1/MyApp/Orders' testuser +{{ ydb-cli }} scheme permissions grant -p "ydb.access.grant" -p "ydb.generic.read" '/Root/db1/MyApp/Orders' testuser ``` ## set @@ -111,8 +111,8 @@ user1:ydb.generic.read Структура результата состоит из трёх блоков: -- `Owner` — показывает владельца объекта схемы. -- `Permissions` — отображает список прав, выданных непосредственно на данный объект. +- `Owner` — показывает владельца объекта схемы. +- `Permissions` — отображает список прав, выданных непосредственно на данный объект. - `Effective permissions` — отображает список прав, фактически действующих на данный схемный объект с учётом правил наследования прав. Данный список также включает все права, отображаемые в секции `Permissions`. ## clear @@ -129,7 +129,7 @@ user1:ydb.generic.read Например, если над состоянием базы данных из предыдущего примера [`list`](#list) выполнить команду: ```bash -{{ ydb-cli }} scheme permissions clear '/Root/db1/MyApp' +{{ ydb-cli }} scheme permissions clear '/Root/db1/MyApp' ``` И затем заново выполнить команду `list` на объект `/Root/db1/MyApp`, то получим следующий результат: diff --git a/ydb/docs/ru/core/reference/ydb-cli/interactive-cli.md b/ydb/docs/ru/core/reference/ydb-cli/interactive-cli.md index e1745e7f4e3..bb67fdcc149 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/interactive-cli.md +++ b/ydb/docs/ru/core/reference/ydb-cli/interactive-cli.md @@ -27,8 +27,8 @@ Команда | Описание ---|--- `SET param = value` | Команда `SET` устанавливает значение [внутренней переменной](#internal-vars) `param` в `value`. -`EXPLAIN query-text` | Выводит план запроса `query-text`. Эквивалентна команде [ydb table query explain](commands/explain-plan.md#explain-plan). -`EXPLAIN AST query-text` | Выводит план запроса `query-text` вместе с [AST](commands/explain-plan.md). Эквивалентна команде [ydb table query explain --ast](commands/explain-plan.md#ast). +`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). ### Список внутренних переменных {#internal-vars} diff --git a/ydb/docs/ru/core/reference/ydb-cli/parameterized-queries-cli.md b/ydb/docs/ru/core/reference/ydb-cli/parameterized-queries-cli.md index 74567e0a49b..6d627f34b00 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/parameterized-queries-cli.md +++ b/ydb/docs/ru/core/reference/ydb-cli/parameterized-queries-cli.md @@ -1,3 +1,10 @@ + +{% note warning %} + +Данная страница устарела. Актуальная версия: [{#T}](parameterized-query-execution.md). + +{% endnote %} + # Выполнение параметризованных YQL-запросов и скриптов ## Обзор @@ -417,7 +424,7 @@ echo -e '{"a":10,"b":20}\n{"a":15,"b":25}\n{"a":35,"b":48}' | \ Для демонстрации работы адаптивного пакетирования со срабатыванием ограничения по задержке обработки в первой строке команды ниже производится генерация 1000 строк с задержкой в 0.2 секунды в `stdout`, которые передаются на `stdin` команде исполнения YQL-запроса. Команда исполнения YQL-запроса, в свою очередь, отображает пакеты параметров в каждом следующем вызове YQL-запроса. ```bash -for i in $(seq 1 1000);do echo "Line$i";sleep 0.2;done | \ +for i in $(seq 1 1000); do echo "Line$i"; sleep 0.2; done | \ {{ ydb-cli }} -p quickstart table query execute \ -q 'declare $x as List<Utf8>; select ListLength($x), $x' \ @@ -459,7 +466,7 @@ for i in $(seq 1 1000);do echo "Line$i";sleep 0.2;done | \ В данном примере также показана возможность объединения параметров из разных источников, и формирование JSON на выходе. ```bash -for i in $(seq 1 200);do echo "Line$i";done | \ +for i in $(seq 1 200); do echo "Line$i"; done | \ {{ ydb-cli }} -p quickstart table query execute \ -q 'declare $x as List<Utf8>; declare $p2 as Int64; @@ -498,7 +505,7 @@ for i in $(seq 1 200);do echo "Line$i";done | \ Занесем в неё 100000 записей: ```bash -for i in $(seq 1 100000);do echo "$i";done | \ +for i in $(seq 1 100000); do echo "$i"; done | \ {{ ydb-cli }} -p quickstart import file csv -p test_delete_1 ``` diff --git a/ydb/docs/ru/core/reference/ydb-cli/parameterized-query-execution.md b/ydb/docs/ru/core/reference/ydb-cli/parameterized-query-execution.md new file mode 100644 index 00000000000..f675c974389 --- /dev/null +++ b/ydb/docs/ru/core/reference/ydb-cli/parameterized-query-execution.md @@ -0,0 +1,593 @@ +# Выполнение параметризованных запросов + +## Обзор + +{{ ydb-short-name }} CLI поддерживает исполнение [параметризованных запросов](https://en.wikipedia.org/wiki/Prepared_statement). Для работы с параметрами в тексте запроса должны присутствовать их определения [командой YQL `DECLARE`](../../yql/reference/syntax/declare.md). + +Основной инструмент для выполнения параметризованных запросов в {{ ydb-short-name }} CLI — это команда [{{ ydb-cli }} sql](sql.md). + +## Зачем использовать параметризованные запросы? + +Использование параметризованных запросов предоставляет несколько важных преимуществ: + +* **Улучшенная производительность:** Параметризованные запросы значительно повышают производительность при выполнении множества схожих запросов, которые различаются только входными параметрами. Это достигается с помощью [подготовленных запросов](https://en.wikipedia.org/wiki/Prepared_statement). Запрос компилируется один раз и затем кешируется на сервере. Последующие запросы с тем же текстом минуют фазу компиляции и сразу начинают выполняться. + +* **Защита от SQL-инъекций:** Другим важным преимуществом использования параметризованных запросов является защита от [SQL-инъекций](https://en.wikipedia.org/wiki/SQL_injection). Эта функция безопасности гарантирует правильную обработку входных данных, что снижает риск выполнения вредоносного кода. + +## Единичное исполнение запроса {#one-request} + +Эта команда поддерживает передачу параметров через опции командной строки, файл, а также через `stdin`. При передаче параметров через `stdin` или файл поддерживается многократное поточное исполнение запроса с разными значениями параметров и возможностью пакетирования. Для этого в команде [{{ ydb-cli }} sql](sql.md) предназначены следующие параметры: + +| Имя | Описание | +---|--- +| `-p, --param` | Значение одного параметра запроса в формате `$name=value` или `name=value`, где `name` — имя параметра, а `value` — его значение (корректный [JSON value](https://www.json.org/json-ru.html)). | +| `--input-file` | Имя файла в формате [JSON](https://{{lang}}.wikipedia.org/wiki/JSON) в кодировке [UTF-8](https://{{lang}}.wikipedia.org/wiki/UTF-8), в котором заданы значения параметров, сопоставляемые с параметрами запроса по именам ключей. Может быть использован максимум один файл с параметрами. | +| `--input-format` | Формат представления значений параметров. Действует на все способы их передачи (через параметр команды, файл или `stdin`).<br/>Возможные значения:<ul><li>`json` (по умолчанию): Формат [JSON]{% if lang == "ru" %}(https://ru.wikipedia.org/wiki/JSON){% endif %}{% if lang == "en" %}(https://en.wikipedia.org/wiki/JSON){% endif %}.</li><li>`csv` — формат [CSV](https://{{lang}}.wikipedia.org/wiki/CSV). По умолчанию имена параметров должны находиться в header'е CSV файла. При единичном исполнении запроса допустима только одна строка в файле, не считая header'a.</li><li>`tsv` — формат [TSV](https://{{lang}}.wikipedia.org/wiki/TSV).</li><li>`raw`: Входной поток из `stdin` или `--input-file` содержит только значение параметра в виде бинарных данных. Имя параметра должно быть указано опцией `--input-param-name`.</li></ul> | +| `--input-binary-strings` | Формат кодировния значения параметров с типом «бинарная строка» (`DECLARE $par AS String`). Говорит о том, как должны интерпретироваться бинарные строки из входного потока.<br/>Возможные значения:<ul><li>`unicode`: Каждый байт в бинарной строке, не являющийся печатаемым ASCII-символом (codes 32-126), должен быть закодирован в кодировке [UTF-8]{% if lang == "ru" %}(https://ru.wikipedia.org/wiki/UTF-8){% endif %}{% if lang == "en" %}(https://en.wikipedia.org/wiki/UTF-8){% endif %}.</li><li>`base64`: Бинарные строки представлены в кодировке [Base64](https://{{lang}}.wikipedia.org/wiki/Base64). Такая возможность позволяет передавать бинарные данные, декодирование которых из Base64 выполнит {{ ydb-short-name }} CLI.</li></ul> | + +Если значения указаны для всех параметров, которые не допускают `NULL` (то есть с типом NOT NULL), [в составе оператора `DECLARE`](../../yql/reference/syntax/declare.md), запрос будет выполнен на сервере. Если отсутствует значение хотя бы для одного такого параметра, выполнение команды завершится с ошибкой и сообщением "Не задано значение для параметра". + +### Более специфичные опции для использования входных параметров {#specific-param-options} + +Следующие опции не представлены в выводе `--help`. Их описание можно увидеть только в выводе `-hh`. + +| Имя | Описание | +---|--- +| `--input-framing` | Задает фрейминг для входного потока (`stdin` или `--input-file`). Определяет как входной поток будет разделяться на отдельные наборы параметров.<br/>Возможные значения:<br/><ul><li>`no-framing` (по умолчанию): От входного потока ожидается один набор параметров, запрос исполняется однократно.</li><li>`newline-delimited`: Символ перевода строки отмечает во входном потоке окончание одного набора параметров, отделяя его от следующего. Набор параметров считается собранным каждый раз при получении во входном потоке символа перевода строки.</li></ul> | +| `--input-param-name` | Имя параметра, значение которого передано во входной поток. Указывается без символа `$`. Обязательно при использовании формата `raw` в `--input-format`.<br/><br/>При использовании с JSON-форматом входной поток интерпретируется не как JSON-документ, а как JSON value, с передачей значения в параметр с указанным именем. | +| `--input-columns` | Строка с именами колонок, заменяющими header CSV/TSV документа, читаемого из входного потока. При указании опции считается, что header отсутствует. Опция допустима только с форматами CSV и TSV.| +| `--input-skip-rows` | Число строк с начала данных, читаемых со stdin'a, которые нужно пропустить, не включая строку header'a, если она имеется. Опция допустима только с форматами stdin'a CSV и TSV. | +| `--input-batch` | Режим пакетирования значений наборов параметров, получаемых из входного потока (`stdin` или `--input-file`).<br/>Возможные значения:<br/><ul><li>`iterative` (по умолчанию): Пакетирование [выключено](#streaming-iterate). Запрос выполняется для каждого набора параметров (ровно один раз, если в опции `--input-framing` используется `no-framing`)</li><li>`full`: Полный пакет. Запрос выполнится один раз после завершения чтения входного потока, все полученные наборы параметров заворачиваются в `List<...>`, имя параметра задается опцией `--input-param-name`</li><li>`adaptive`: Адаптивное пакетирование. Запрос выполняется каждый раз, когда срабатывает ограничение на количество наборов параметров в одном запросе (`--input-batch-max-rows`) или на задержку обработки (`--input-batch-max-delay`). Все полученные к этому моменту наборы параметров заворачиваются в `List<...>`, имя параметра задается опцией `--input-param-name`.</li></ul> | +| `--input-batch-max-rows` | Максимальное количество наборов параметров в пакете для адаптивного режима пакетирования. Следующий пакет будет отправлен на исполнение вместе с запросом, если количество наборов данных в нем достигло указанного значения. Установка в `0` снимает ограничение.<br/><br/>Значение по умолчанию — `1000`.<br/><br/>Параметры передаются в запрос без стриминга и общий объем одного GRPC-запроса, в который включаются значения параметров, имеет верхнюю границу около 5 МБ. | +| `--input-batch-max-delay` | Максимальная задержка отправки на обработку полученного набора параметров для адаптивного режима пакетирования. Задается в виде числа с размерностью времени - `s` (секунды), `ms` (миллисекунды), `m` (минуты) и т.д. Значение по умолчанию — `1s` (1 секунда).<br/><br/>{{ ydb-short-name }} CLI будет отсчитывать время с момента получения первого набора параметров для пакета и отправит накопившийся пакет на исполнение, как только время превысит указанное значение. Параметр позволяет получить эффективное пакетирование в случае непредсказуемого темпа появления новых наборов параметров на `stdin`. | + +### Примеры {#examples-one-request} + +{% include [ydb-cli-profile](../../_includes/ydb-cli-profile.md) %} + +#### Передача значения одного параметра {#example-simple} + +В командной строке, через опцию `--param`: + +```bash +{{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' --param '$a=10' +``` + +Через файл в формате JSON (который используется по умолчанию): + +```bash +echo '{"a":10}' > p1.json +{{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' --input-file p1.json +``` + +Через `stdin`, передавая JSON-строку как набор из одного параметра: + +```bash +echo '{"a":10}' | {{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' +``` + +Через `stdin`, передавая только значение параметра и задавая имя параметра через опцию `--input-param-name`: + +```bash +echo '10' | {{ ydb-cli }} -p quickstart sql -s 'DECLARE $a AS Int64; SELECT $a' --input-param-name a +``` + +#### Передача значений параметров разных типов из нескольких источников {#example-multisource} + +```bash +# Create a JSON file with fields 'a', 'b', and 'x', where 'x' will be ignored in the query +echo '{ "a":10, "b":"Some text", "x":"Ignore me" }' > p1.json + +# Run the query using ydb-cli, passing in 'a' and 'b' from the input file, and 'c' as a direct parameter +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Utf8; + DECLARE $c AS Int64; + + SELECT $a, $b, $c' \ + --input-file p1.json \ + --param '$c=30' +``` + +Вывод команды: + +```text +┌─────────┬─────────────┬─────────┐ +│ column0 │ column1 │ column2 │ +├─────────┼─────────────┼─────────┤ +│ 10 │ "Some text" │ 30 │ +└─────────┴─────────────┴─────────┘ +``` + +#### Передача бинарных строк в кодировке Base64 {#example-base64} + +```bash +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS String; + SELECT $a' \ + --input-format json \ + --input-binary-strings base64 \ + --param '$a="SGVsbG8sIHdvcmxkCg=="' +``` + +Вывод команды: + +```text +┌──────────────────┐ +| column0 | +├──────────────────┤ +| "Hello, world\n" | +└──────────────────┘ +``` + +#### Прямая передача бинарного контента {#example-raw} + +```bash +curl -Ls http://ydb.tech/docs/en | {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS String; + SELECT LEN($a)' \ + --input-format raw \ + --input-param-name a +``` + +Вывод команды (точное количество байт может отличаться): + +```text +┌─────────┐ +| column0 | +├─────────┤ +| 66426 | +└─────────┘ +``` + +#### Передача файла в формате CSV {#example-csv} + +```bash +echo '10,Some text' | {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int32; + DECLARE $b AS String; + SELECT $a, $b' \ + --input-format csv \ + --input-columns 'a,b' +``` + +Вывод команды: + +```text +┌─────────┬─────────────┐ +| column0 | column1 | +├─────────┼─────────────┤ +| 10 | "Some text" | +└─────────┴─────────────┘ +``` + +## Итеративная потоковая обработка {#streaming-iterate} + +{{ ydb-short-name }} CLI поддерживает возможность многократного исполнения запроса с разными наборами значений параметров, при их передаче через `stdin` **или** входной файл (не одновременно). При этом соединение с базой данных устанавливается однократно, а план исполнения запроса кешируется, что существенно повышает производительность такого подхода по сравнению с отдельными вызовами CLI. + +Для того чтобы воспользоваться этой возможностью, необходимо на вход команды друг за другом передавать разные наборы значений одних и тех параметров, сообщив {{ ydb-short-name }} CLI правило, по которому будет возможно отделить эти наборы друг от друга. + +Запрос выполняется столько раз, сколько наборов значений параметров было получено. Каждый полученный через входной поток (`stdin` или `--input-file`) набор объединяется со значениями параметров, определенными через опции `--param`. Исполнение команды будет завершено после завершения входного потока. Каждый запрос исполняется в своей транзакции. + +Правило отделения наборов параметров друг от друга (фрейминг) дополняет описание формата представления параметров на входном потоке, задаваемое параметром `--input--framing`: + +Имя | Описание +---|--- +`--input-framing` | Задает фрейминг для входного потока (файл или `stdin`). <br/>Возможные значения:<ul><li>`no-framing` (по умолчанию) — на входе ожидается один набор параметров, запрос исполняется однократно после завершения чтения потока.</li><li>`newline-delimited` — символ перевода строки отмечает на входе окончание одного набора параметров, отделяя его от следующего. Запрос исполняется каждый раз при получении символа перевода строки.</li></ul> + +{% note warning %} + +При использовании символа перевода строки в качестве разделителя наборов параметров необходимо гарантировать его отсутствие внутри наборов параметров. Заключение текста в кавычки не делает допустимым перевод строки внутри такого текста. Многострочные JSON-документы не допускаются. + +{% endnote %} + +### Пример {#example-streaming-iterate} + +#### Потоковая обработка нескольких наборов параметров {#example-iterate} + +{% list tabs %} + +- JSON + + Допустим, нам необходимо выполнить запрос трижды, со следующими наборами значений параметров `a` и `b`: + + 1. `a` = 10, `b` = 20 + 2. `a` = 15, `b` = 25 + 3. `a` = 35, `b` = 48 + + Создадим файл, который будет содержать строки с JSON-представлением этих наборов: + + ```bash + echo -e '{"a":10,"b":20}\n{"a":15,"b":25}\n{"a":35,"b":48}' | tee par1.txt + ``` + + Вывод команды: + + ```text + {"a":10,"b":20} + {"a":15,"b":25} + {"a":35,"b":48} + ``` + + Исполним запрос, передав на `stdin` содержимое данного файла, с форматированием вывода в JSON: + + ```bash + cat par1.txt | \ + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a+$b' \ + --input-framing newline-delimited \ + --format json-unicode + ``` + + Вывод команды: + + ```text + {"column0":30} + {"column0":40} + {"column0":83} + ``` + + Или просто передав имя файла в опцию `--input-file`: + + ```bash + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-file par1.txt \ + --input-framing newline-delimited \ + --format json-unicode + ``` + + Вывод команды: + + ```text + {"column0":30} + {"column0":40} + {"column0":83} + ``` + + Полученный в таком формате результат можно использовать для передачи на вход команде исполнения следующего запроса. + +- CSV + + Допустим, нам необходимо выполнить запрос трижды, со следующими наборами значений параметров `a` и `b`: + + 1. `a` = 10, `b` = 20 + 2. `a` = 15, `b` = 25 + 3. `a` = 35, `b` = 48 + + Создадим файл c наборами значений параметров в формате CSV: + + ```bash + echo -e 'a,b\n10,20\n15,25\n35,48' | tee par1.txt + ``` + + Вывод команды: + + ```text + a,b + 10,20 + 15,25 + 35,48 + ``` + + Исполним запрос, передав на `stdin` содержимое данного файла, с форматированием вывода в CSV: + + ```bash + cat par1.txt | \ + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-format csv \ + --input-framing newline-delimited \ + --format csv + ``` + + Вывод команды: + + ```text + 30 + 40 + 83 + ``` + + Или просто передав имя файла в опцию `--input-file`: + + ```bash + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-file par1.txt \ + --input-format csv \ + --input-framing newline-delimited \ + --format csv + ``` + + Вывод команды: + + ```text + 30 + 40 + 83 + ``` + + Полученный в таком формате результат можно использовать для передачи на вход команде исполнения следующего запроса, задав header данным в CSV формате опцией `--input-columns`. + +- TSV + + Допустим, нам необходимо выполнить запрос трижды, со следующими наборами значений параметров `a` и `b`: + + 1. `a` = 10, `b` = row1 + 2. `a` = 15, `b` = row 2 + 3. `a` = 35, `b` = "row"\n3 + + Создадим файл c наборами значений параметров в формате TSV: + + ```bash + echo -e 'a\tb\n10\t20\n15\t25\n35\t48' | tee par1.txt + ``` + + Вывод команды: + + ```text + a b + 10 20 + 15 25 + 35 48 + ``` + + Исполним запрос, передав на `stdin` содержимое данного файла, с форматированием вывода в TSV: + + ```bash + cat par1.txt | \ + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Utf8; + SELECT $a, $b' \ + --input-framing newline-delimited \ + --input-format tsv \ + --format tsv + ``` + + Вывод команды: + + ```text + 30 + 40 + 83 + ``` + + Или просто передав имя файла в опцию `--input-file`: + + ```bash + {{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b' \ + --input-file par1.txt \ + --input-format tsv \ + --input-framing newline-delimited \ + --format tsv + ``` + + Вывод команды: + + ```text + 30 + 40 + 83 + ``` + + Полученный в таком формате результат можно использовать для передачи на вход команде исполнения следующего запроса, задав header данным в TSV формате опцией `--input-columns`. + +{% endlist %} + +#### Потоковая обработка с объединением значений параметров из разных источников {#example-iterate-union} + +Допустим, нам необходимо выполнить запрос трижды, со следующими наборами значений параметров `a` и `b`: + +1. `a` = 10, `b` = 100 +2. `a` = 15, `b` = 100 +3. `a` = 35, `b` = 100 + +```bash +echo -e '10\n15\n35' | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $a AS Int64; + DECLARE $b AS Int64; + SELECT $a + $b AS sum1' \ + --param '$b=100' \ + --input-framing newline-delimited \ + --input-param-name a \ + --format json-unicode +``` + +Вывод команды: + +```text +{"sum1":110} +{"sum1":115} +{"sum1":135} +``` + +## Пакетная потоковая обработка {#streaming-batch} + +{{ ydb-short-name }} CLI поддерживает автоматическую конвертацию наборов параметров в `List<...>`, позволяя одним запросом к серверу обработать множество наборов параметров в одной транзакции, что может дополнительно существенно повышать производительность по сравнению с выполнением запросов "по одному". + +Поддерживаются два режима пакетирования: + +- Полный (`full`); +- Адаптивный (`adaptive`). + +### Полный режим пакетирования {#batch-full} + +Полный (`full`) режим является упрощенным вариантом пакетирования, когда запрос выполняется один раз, с заворачиванием в `List<...>` всех полученных с входного потока наборов параметров. Если размер запроса окажется слишком большим, будет выдана ошибка. + +Данный вариант пакетирования необходим в случае, когда необходимо гарантировать атомарность за счет применения всех параметров в одной транзакции. + +### Адаптивный режим пакетирования {#batch-adaptive} + +При работе в адаптивном (`adaptive`) режиме обработка входного потока разбивается на множество транзакций, с автоматическим подбором размера пакета для каждой из них. + +Данный режим позволяет эффективно обрабатывать широкий спектр входной нагрузки, с непредсказуемым или бесконечным количеством данных, а также непредсказуемым или сильно меняющимся темпом их появления на входе. В частности, такой профиль характерен при подаче на `stdin` выхода другой команды через оператор `|`. + +Адаптивный режим решает две основные проблемы обработки динамического потока: + +1. Ограничение максимального размера пакета. +2. Ограничение максимальной задержки обработки данных. + +### Синтаксис {#batch-syntax} + +Для того чтобы воспользоваться возможностью пакетирования, необходимо описать параметр типа `List<...>` или `List<Struct<...>>` в секции DECLARE запроса, и выбрать режим следующим параметром: + +| Имя | Описание | +---|--- +| `--input-batch` | Режим пакетирования значений наборов параметров, получаемых из входного потока (`stdin` или `--input-file`).<br/>Возможные значения:<br/><ul><li>`iterative` (по умолчанию): Пакетирование [выключено](#streaming-iterate). Запрос выполняется для каждого набора параметров (ровно один раз, если в опции `--input-framing` используется `no-framing`)</li><li>`full`: Полный пакет. Запрос выполнится один раз после завершения чтения входного потока, все полученные наборы параметров заворачиваются в `List<...>`, имя параметра задается опцией `--input-param-name`</li><li>`adaptive`: Адаптивное пакетирование. Запрос выполняется каждый раз, когда срабатывает ограничение на количество наборов параметров в одном запросе (`--input-batch-max-rows`) или на задержку обработки (`--input-batch-max-delay`). Все полученные к этому моменту наборы параметров заворачиваются в `List<...>`, имя параметра задается опцией `--input-param-name`.</li></ul> | + +В адаптивном режиме пакетирования доступны дополнительные параметры: + +| Имя | Описание | +---|--- +| `--input-batch-max-rows` | Максимальное количество наборов параметров в пакете для адаптивного режима пакетирования. Следующий пакет будет отправлен на исполнение вместе с запросом, если количество наборов данных в нем достигло указанного значения. Установка в `0` снимает ограничение.<br/><br/>Значение по умолчанию — `1000`.<br/><br/>Параметры передаются в запрос без стриминга и общий объем одного GRPC-запроса, в который включаются значения параметров, имеет верхнюю границу около 5 МБ. | +| `--input-batch-max-delay` | Максимальная задержка отправки на обработку полученного набора параметров для адаптивного режима пакетирования. Задается в виде числа с размерностью времени - `s` (секунды), `ms` (миллисекунды), `m` (минуты) и т.д. Значение по умолчанию — `1s` (1 секунда).<br/><br/>{{ ydb-short-name }} CLI будет отсчитывать время с момента получения первого набора параметров для пакета и отправит накопившийся пакет на исполнение, как только время превысит указанное значение. Параметр позволяет получить эффективное пакетирование в случае непредсказуемого темпа появления новых наборов параметров на `stdin`. | + +### Примеры - полная пакетная обработка {#example-batch-full} + +```bash +echo -e '{"a":10,"b":20}\n{"a":15,"b":25}\n{"a":35,"b":48}' | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $x AS List<Struct<a:Int64,b:Int64>>; + SELECT ListLength($x), $x' \ + --input-framing newline-delimited \ + --input-param-name x \ + --input-batch full +``` + +Вывод команды: + +```text +┌─────────┬───────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼───────────────────────────────────────────────────┤ +| 3 | [{"a":10,"b":20},{"a":15,"b":25},{"a":35,"b":48}] | +└─────────┴───────────────────────────────────────────────────┘ +``` + +### Примеры - адаптивная пакетная обработка {#example-batch-adaptive} + +#### Ограничение максимальной задержки обработки {#example-adaptive-delay} + +Для демонстрации работы адаптивного пакетирования со срабатыванием ограничения по задержке обработки в первой строке команды ниже производится генерация 1000 строк с задержкой в 0.2 секунды в `stdout`, которые передаются на `stdin` команде исполнения запроса. Команда исполнения запроса, в свою очередь, отображает пакеты параметров в каждом следующем вызове запроса. + +```bash +for i in $(seq 1 1000); do echo "Line$i"; sleep 0.2; done | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $x AS List<Utf8>; + SELECT ListLength($x), $x' \ + --input-framing newline-delimited \ + --input-format raw \ + --input-param-name x \ + --input-batch adaptive +``` + +Вывод команды (точные значения могут отличаться): + +```text +┌─────────┬────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ +| 14 | ["Line1","Line2","Line3","Line4","Line5","Line6","Line7","Line8","Line9","Line10","Line11","Line12","Line13","Line14"] | +└─────────┴────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ +┌─────────┬─────────────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼─────────────────────────────────────────────────────────┤ +| 6 | ["Line15","Line16","Line17","Line18","Line19","Line20"] | +└─────────┴─────────────────────────────────────────────────────────┘ +┌─────────┬─────────────────────────────────────────────────────────┐ +| column0 | column1 | +├─────────┼─────────────────────────────────────────────────────────┤ +| 6 | ["Line21","Line22","Line23","Line24","Line25","Line26"] | +└─────────┴─────────────────────────────────────────────────────────┘ +^C +``` + +В первый пакет попадают все строки, накопившиеся на входе за время открытия соединения с БД, и поэтому он больше чем последующие. + +Выполнение команды можно прервать по Ctrl+C, или дождаться пока пройдут 200 секунд, в течение которых генерируется вход. + +#### Ограничение по количеству записей {#example-adaptive-limit} + +Для демонстрации работы адаптивного пакетирования со срабатыванием триггера по количеству наборов параметров в первой строке команды ниже производится генерация 200 строк. Команда будет отображать пакеты параметров в каждом следующем вызове запроса, учитывая заданное ограничение `--input-batch-max-rows` равное 20 (по умолчанию 1000). + +В данном примере также показана возможность объединения параметров из разных источников, и формирование JSON на выходе. + +```bash +for i in $(seq 1 200); do echo "Line$i"; done | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $x AS List<Utf8>; + DECLARE $p2 AS Int64; + SELECT ListLength($x) AS count, $p2 AS p2, $x AS items' \ + --input-framing newline-delimited \ + --input-format raw \ + --input-param-name x \ + --input-batch adaptive \ + --input-batch-max-rows 20 \ + --param '$p2=10' \ + --format json-unicode +``` + +Вывод команды: + +```text +{"count":20,"p2":10,"items":["Line1","Line2","Line3","Line4","Line5","Line6","Line7","Line8","Line9","Line10","Line11","Line12","Line13","Line14","Line15","Line16","Line17","Line18","Line19","Line20"]} +{"count":20,"p2":10,"items":["Line21","Line22","Line23","Line24","Line25","Line26","Line27","Line28","Line29","Line30","Line31","Line32","Line33","Line34","Line35","Line36","Line37","Line38","Line39","Line40"]} +... +{"count":20,"p2":10,"items":["Line161","Line162","Line163","Line164","Line165","Line166","Line167","Line168","Line169","Line170","Line171","Line172","Line173","Line174","Line175","Line176","Line177","Line178","Line179","Line180"]} +{"count":20,"p2":10,"items":["Line181","Line182","Line183","Line184","Line185","Line186","Line187","Line188","Line189","Line190","Line191","Line192","Line193","Line194","Line195","Line196","Line197","Line198","Line199","Line200"]} +``` + +#### Удаление множества записей из строковой таблицы {{ ydb-short-name }} по первичным ключам {#example-adaptive-delete-pk} + +{% include [not_allow_for_olap_note](../../_includes/not_allow_for_olap_note.md) %} + +Если вы попытаетесь удалить большое количество строк из крупной таблицы с помощью простого запроса `DELETE FROM large_table WHERE id > 10;`, вы можете столкнуться с ошибкой из-за превышения ограничения на количество записей в транзакции. Данный пример показывает, как можно удалять неограниченное количество записей из таблиц {{ ydb-short-name }} без нарушения этого ограничения. +Создадим тестовую строковую таблицу: + +```bash +{{ ydb-cli }} -p quickstart sql -s 'CREATE TABLE test_delete_1(id UInt64 NOT NULL, PRIMARY KEY (id))' +``` + +Занесем в неё 100,000 записей: + +```bash +for i in $(seq 1 100000); do echo "$i";done | \ +{{ ydb-cli }} -p quickstart import file csv -p test_delete_1 +``` + +Удалим все записи со значениями `id` больше 10: + +```bash +{{ ydb-cli }} -p quickstart sql \ + -s 'SELECT t.id FROM test_delete_1 AS t WHERE t.id > 10' \ + --format json-unicode | \ +{{ ydb-cli }} -p quickstart sql \ + -s 'DECLARE $lines AS List<Struct<id:UInt64>>; + DELETE FROM test_delete_1 WHERE id IN (SELECT tl.id FROM AS_TABLE($lines) AS tl)' \ + --input-framing newline-delimited \ + --input-param-name lines \ + --input-batch adaptive \ + --input-batch-max-rows 10000 +``` + +#### Обработка сообщений, считываемых из топика {#example-adaptive-pipeline-from-topic} + +Примеры обработки сообщений, считываемых из топика, приведены в статье [{#T}](topic-pipeline.md#example-read-to-yql-param). + +## См. также {#see-also} + +* [Параметризованные запросы в {{ ydb-short-name }} SDK](../ydb-sdk/parameterized_queries.md) diff --git a/ydb/docs/ru/core/reference/ydb-cli/profile/_includes/delete.md b/ydb/docs/ru/core/reference/ydb-cli/profile/_includes/delete.md index 8365a8593c3..0f41d254922 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/profile/_includes/delete.md +++ b/ydb/docs/ru/core/reference/ydb-cli/profile/_includes/delete.md @@ -46,5 +46,5 @@ Profile "mydb1" was removed. Хотя специальной команды удаления всех профилей нет в {{ ydb-short-name }} CLI, в Linux-совместимых операционных системах вы можете воспользоваться следующим рецептом для удаления всех существующих профилей: ``` bash -{{ ydb-cli }} config profile list | while read l;do {{ ydb-cli }} config profile delete $l;done; +{{ ydb-cli }} config profile list | while read l; do {{ ydb-cli }} config profile delete $l; done; ```
\ No newline at end of file diff --git a/ydb/docs/ru/core/reference/ydb-cli/scripting-yql.md b/ydb/docs/ru/core/reference/ydb-cli/scripting-yql.md index 84637712e61..2215975268f 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/scripting-yql.md +++ b/ydb/docs/ru/core/reference/ydb-cli/scripting-yql.md @@ -1,5 +1,8 @@ + # Выполнение скрипта +{% include notitle [warning](./_includes/deprecated_command_warning.md) %} + С помощью подкоманды `scripting yql` вы можете выполнить YQL-скрипт. Скрипт может содержать запросы разных типов. В отличие от `yql`, подкоманда `scripting yql` имеет ограничение на количество возвращаемых строк и объем затрагиваемых данных. Общий вид команды: diff --git a/ydb/docs/ru/core/reference/ydb-cli/sql.md b/ydb/docs/ru/core/reference/ydb-cli/sql.md new file mode 100644 index 00000000000..3cd2096364e --- /dev/null +++ b/ydb/docs/ru/core/reference/ydb-cli/sql.md @@ -0,0 +1,83 @@ +# Выполнение запросов + +С помощью подкоманды `{{ ydb-cli }} sql` вы можете выполнить SQL-запрос. Запрос может быть любого типа (DDL, DML и т.д.), а так же состоять из нескольких подзапросов. Подкоманда `{{ ydb-cli }} sql` устанавливает стрим и получает данные через него. Выполнение запроса в стриме позволяет снять ограничение на размер читаемых данных. Эта команда также позволяет записывать данные в YDB, что более эффективно при выполнении повторяющихся запросов с передачей данных через параметры. + +Общий вид команды: + +```bash +{{ ydb-cli }} [global options...] sql [options...] +``` + +* `global options` — [глобальные параметры](commands/global-options.md). +* `options` — [параметры подкоманды](#options). + +Посмотрите описание команды выполнения запроса: + +```bash +{{ ydb-cli }} sql --help +``` + +## Параметры подкоманды {#options} + +#| +|| Имя | Описание || +|| `-h`, `--help` | Выводит общую справку по использованию команды. || +|| `-hh` | Выводит полную справку по использованию команды. Вывод содержит некоторые специфичный команды, которых нет в выводе `--help`. || +|| `-s`, `--script` | Текст скрипта(запроса) для выполнения. || +|| `-f`, `--file` | Путь к файлу, содержащему текст запроса для выполнения. Путь `-` означает, что текст запроса будет прочитан из `stdin`, при этом передача параметров через `stdin` будет невозможна. || +|| `--stats` | Режим сбора статистики.<br/>Возможные значения:<br/><ul><li>`none` (по умолчанию) — не собирать;</li><li>`basic`: Собирать обобщенную статистику по обновлениям(update) и удалениям(delete) в таблицах.</li><li>`full`: К тому, что содержит режим `basic` добавляется статистика и план выполнения запроса.</li><li>`profile`: Собирать детальную статистику выполнения, содержащую статистику по каждому отдельному таску и каналу выолнения запроса.</li></ul> || +|| `--explain` | Выполнить explain-запрос, будет выведен логический план запроса. Сам запрос не будет выполнен, поэтому не затронет данные в базе. || +|| `--explain-ast` | То же, что и `--explain`, но вдобавок к логическому плану выводит [AST (abstract syntax tree)](https://ru.wikipedia.org/wiki/Абстрактное_синтаксическое_дерево). Раздел с AST содержит представление на внутреннем языке [miniKQL](../../concepts/glossary.md#minikql). || +|| `--explain-analyze` | Выполнить запрос в режиме `EXPLAIN ANALYZE`. Показывает план выполнения запроса. Возвращаемые в рамках запроса данные игнорируются.<br/>**Важное замечание: Запрос фактически выполняется, поэтому может внести изменения в базу**. || +|| `--format` | Формат вывода.<br/>Возможные значения: + +{% include notitle [format](./_includes/result_format_common.md) %} + +{% include notitle [format](./_includes/result_format_csv_tsv.md) %} + +|| +|# + +### Работа с параметризованными запросами {#parameterized-query} + +Подробное описание работы с параметрами с примерами смотрите в статье [{#T}](parameterized-query-execution.md). + +## Примеры {#examples} + +{% include [ydb-cli-profile](../../_includes/ydb-cli-profile.md) %} + +Запрос создания строковой таблицы, заполнения её данными, и получения выборки из этой таблицы: + +```bash +{{ ydb-cli }} -p quickstart sql -s ' + CREATE TABLE series (series_id Uint64, title Utf8, series_info Utf8, release_date Date, PRIMARY KEY (series_id)); + COMMIT; + UPSERT INTO series (series_id, title, series_info, release_date) values (1, "Title1", "Info1", Cast("2023-04-20" as Date)); + COMMIT; + SELECT * from series; + ' +``` + +Вывод команды: + +```text +┌──────────────┬───────────┬─────────────┬──────────┐ +| release_date | series_id | series_info | title | +├──────────────┼───────────┼─────────────┼──────────┤ +| "2023-04-20" | 1 | "Info1" | "Title1" | +└──────────────┴───────────┴─────────────┴──────────┘ +``` + +Выполнение запроса из примера выше, записанного в файле `script1.yql`, с выводом результатов в формате `JSON`: + +```bash +{{ ydb-cli }} -p quickstart sql -f script1.yql --format json-unicode +``` + +Вывод команды: + +```text +{"release_date":"2023-04-20","series_id":1,"series_info":"Info1","title":"Title1"} +``` + +Примеры передачи параметров в скрипты приведены в [статье о передаче параметров в команды исполнения запросов](parameterized-query-execution.md). diff --git a/ydb/docs/ru/core/reference/ydb-cli/table-query-execute.md b/ydb/docs/ru/core/reference/ydb-cli/table-query-execute.md index 81a5f73fc26..3eb8e013bca 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/table-query-execute.md +++ b/ydb/docs/ru/core/reference/ydb-cli/table-query-execute.md @@ -1,5 +1,8 @@ + # Выполнение запроса +{% include notitle [warning](./_includes/deprecated_command_warning.md) %} + Подкоманда `table query execute` предназначена для надежного исполнения YQL-запросов. Подкоманда обеспечивает успешное исполнение запроса при кратковременной недоступности отдельных партиций таблиц, например, связанной с [их разделением или слиянием](../../concepts/datamodel/table.md#partitioning), за счет применения встроенных политик повторных попыток (retry policies). Общий вид команды: diff --git a/ydb/docs/ru/core/reference/ydb-cli/toc_i.yaml b/ydb/docs/ru/core/reference/ydb-cli/toc_i.yaml index 47f8c51ccf5..e270a307a81 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/toc_i.yaml +++ b/ydb/docs/ru/core/reference/ydb-cli/toc_i.yaml @@ -70,21 +70,30 @@ items: - name: Запись в топик href: topic-write.md - name: Конвейерная обработка сообщений - href: topic-pipeline.md - - name: Выполнение YQL + href: topic-pipeline.md + - name: Выполнение SQL-запросов items: - name: Обзор href: yql-query-overview.md + - name: Выполнение запросов + href: sql.md + - name: Выполнение параметризованных запросов + href: parameterized-query-execution.md + - name: Интерактивный режим выполнения запросов + href: interactive-cli.md +# Справки по устаревшим командам: - name: Выполнение скрипта (с поддержкой стриминга) href: yql.md + hidden: true - name: Выполнение скрипта href: scripting-yql.md + hidden: true - name: Выполнение запроса href: table-query-execute.md - - name: Выполнение параметризованных запросов + hidden: true + - name: Выполнение запросов с параметрами href: parameterized-queries-cli.md - - name: Интерактивный режим выполнения запросов - href: interactive-cli.md + hidden: true # - name: Утилиты # items: # - name: Снятие бэкапа diff --git a/ydb/docs/ru/core/reference/ydb-cli/topic-pipeline.md b/ydb/docs/ru/core/reference/ydb-cli/topic-pipeline.md index 1ad4a8afc5c..4e47d5a96e7 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/topic-pipeline.md +++ b/ydb/docs/ru/core/reference/ydb-cli/topic-pipeline.md @@ -43,16 +43,16 @@ ```bash {{ ydb-cli }} -p quickstart topic read topic1 -c c1 --format newline-delimited -w | \ - {{ ydb-cli }} -p quickstart table query execute -q 'declare $s as String;select Len($s) as Bytes' \ - --stdin-format newline-delimited --stdin-par s --stdin-format raw + {{ ydb-cli }} -p quickstart sql -s 'declare $s as String;select Len($s) as Bytes' \ + --input-framing newline-delimited --input-param-name s --input-format raw ``` * Исполнение YQL-запроса с адаптивным пакетированием параметров из сообщений, считанных из топика `topic1` ```bash {{ ydb-cli }} -p quickstart topic read topic1 -c c1 --format newline-delimited -w | \ - {{ ydb-cli }} -p quickstart table query execute \ - -q 'declare $s as List<String>;select ListLength($s) as Count, $s as Items' \ - --stdin-format newline-delimited --stdin-par s --stdin-format raw \ - --batch adaptive + {{ ydb-cli }} -p quickstart sql \ + -s 'declare $s as List<String>;select ListLength($s) as Count, $s as Items' \ + --input-framing newline-delimited --input-param-name s --input-format raw \ + --input-batch adaptive ``` diff --git a/ydb/docs/ru/core/reference/ydb-cli/yql-query-overview.md b/ydb/docs/ru/core/reference/ydb-cli/yql-query-overview.md index 404911790a1..79beaafc6fa 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/yql-query-overview.md +++ b/ydb/docs/ru/core/reference/ydb-cli/yql-query-overview.md @@ -1,10 +1,8 @@ # Обзор -Для выполнения YQL-запросов вы можете использовать следующие команды {{ ydb-short-name }} CLI: +Для выполнения запросов в {{ ydb-short-name }} CLI рекомендуется использовать следующие команды: -1. [{{ ydb-cli }} yql](yql.md) — выполняет запросы и скрипты YQL с поддержкой стриминга (без ограничения на объем возвращаемых данных). -2. [{{ ydb-cli }} scripting yql](scripting-yql.md) — выполняет запросы и скрипты YQL, имеет ограничения на объем возвращаемых данных. Также с помощью этой команды вы можете просмотреть план выполнения запроса и метаданные ответа. -3. [{{ ydb-cli }} table query execute](table-query-execute.md) — выполняет [DML-запросы](https://en.wikipedia.org/wiki/Data_manipulation_language#SQL) с заданным уровнем изоляции транзакции и применением типовой политики повторных попыток. -4. [{{ ydb-cli }}](interactive-cli.md) — переключает консоль в интерактивный режим и выполняет запросы и скрипты YQL. +1. [{{ ydb-cli }} sql](sql.md) — единая команда для выполнения любого SQL запроса, поддерживаемого YDB. +2. [{{ ydb-cli }}](interactive-cli.md) — переключает консоль в интерактивный режим выполнения запросов. -Команды 1-3 поддерживают одинаковые возможности [параметризации запросов YQL](parameterized-queries-cli.md). +[Выполнение параметризованных запросов](parameterized-queries-cli.md) описано на отдельной странице. diff --git a/ydb/docs/ru/core/reference/ydb-cli/yql.md b/ydb/docs/ru/core/reference/ydb-cli/yql.md index 85c13cc9695..113bd627d62 100644 --- a/ydb/docs/ru/core/reference/ydb-cli/yql.md +++ b/ydb/docs/ru/core/reference/ydb-cli/yql.md @@ -1,5 +1,8 @@ + # Выполнение скрипта (с поддержкой стриминга) +{% include notitle [warning](./_includes/deprecated_command_warning.md) %} + С помощью подкоманды `yql` вы можете выполнить YQL-скрипт. Скрипт может содержать запросы разных типов. В отличие от `scripting yql`, подкоманда `yql` устанавливает стрим и получает данные через него. Выполнение запроса в стриме позволяет снять ограничение на размер читаемых данных. Общий вид команды: diff --git a/ydb/public/lib/ydb_cli/commands/ydb_sql.cpp b/ydb/public/lib/ydb_cli/commands/ydb_sql.cpp index b0081f8bbdd..aafef6cd5ed 100644 --- a/ydb/public/lib/ydb_cli/commands/ydb_sql.cpp +++ b/ydb/public/lib/ydb_cli/commands/ydb_sql.cpp @@ -28,8 +28,8 @@ void TCommandSql::Config(TConfig& config) { TYdbCommand::Config(config); config.Opts->AddLongOption('s', "script", "Script (query) text to execute").RequiredArgument("[String]") .StoreResult(&Query); - config.Opts->AddLongOption('f', "file", "Path to file with script (query) text." - " Path \"-\" means reading query text from stdin.").RequiredArgument("PATH") + config.Opts->AddLongOption('f', "file", "Path to a file containing the query text to execute. " + "The path '-' means reading the query text from stdin.").RequiredArgument("PATH") .StoreResult(&QueryFile); config.Opts->AddLongOption("explain", "Execute explain request for the query. Shows query logical plan. " "The query is not actually executed, thus does not affect the database.") |