diff options
author | robot-piglet <[email protected]> | 2025-06-25 16:22:36 +0300 |
---|---|---|
committer | robot-piglet <[email protected]> | 2025-06-25 16:39:17 +0300 |
commit | 3be8ad92d079fd7c22a7bb9978eb71bed8ea3348 (patch) | |
tree | e459a4bb6e9b0080116cd10d7cd6182cf0d43a31 | |
parent | 59fa891737bd017e3c73b3ee4320333d8f57611c (diff) |
Intermediate changes
commit_hash:8d0c00185a2284990cdc8168d34b4cd0d87e09ae
33 files changed, 937 insertions, 927 deletions
diff --git a/yql/essentials/docs/.yfmlint b/yql/essentials/docs/.yfmlint index 0c54658d91b..2327d24c3f8 100644 --- a/yql/essentials/docs/.yfmlint +++ b/yql/essentials/docs/.yfmlint @@ -2,7 +2,6 @@ log-levels: YFM001: 'error' # Inline code length MD009: 'error' # Trailing spaces MD023: 'error' # Headings must start at the beginning of the line - MD024: 'error' # Multiple headings with the same content MD026: 'error' # Trailing punctuation in heading # Inline code length diff --git a/yql/essentials/docs/en/builtins/basic.md b/yql/essentials/docs/en/builtins/basic.md index 59c52a65dbc..b7b109797d7 100644 --- a/yql/essentials/docs/en/builtins/basic.md +++ b/yql/essentials/docs/en/builtins/basic.md @@ -751,7 +751,7 @@ Getting the path to the root of a directory with several "attached" files with t The argument is a string with a prefix among aliases. -See also [PRAGMA File](../syntax/pragma.md#file) and [PRAGMA Folder](../syntax/pragma.md#folder). +See also [PRAGMA File](../syntax/pragma/file.md#file) and [PRAGMA Folder](../syntax/pragma/file.md#folder). #### Examples @@ -842,7 +842,7 @@ Evaluate an expression before the start of the main calculation and input its re EvaluateExpr can be used where the grammar already expects an expression. For example, you can use it to: -* Round the current time to days, weeks, or months and insert it into the query to ensure correct [query caching](../syntax/pragma.md#yt.querycachemode), although usually when [functions are used to get the current time](#current-utc), query caching is completely disabled. +* Round the current time to days, weeks, or months and insert it into the query to ensure correct query caching, although usually when [functions are used to get the current time](#current-utc), query caching is completely disabled. * Run a heavy calculation with a small result once per query instead of once per job. EvaluateAtom lets you dynamically create an [atom](../types/special.md), but since atoms are mainly controlled from a lower [s-expressions](/docs/s_expressions/functions) level, it's generally not recommended to use this function directly. diff --git a/yql/essentials/docs/en/syntax/export_import.md b/yql/essentials/docs/en/syntax/export_import.md index 1e70fa2457f..0af803466e7 100644 --- a/yql/essentials/docs/en/syntax/export_import.md +++ b/yql/essentials/docs/en/syntax/export_import.md @@ -2,7 +2,7 @@ A mechanism for putting part of the query into a separate attached file. To use the mechanism, you need to set the following pragma in the query: -* [PRAGMA Library](pragma.md#library) — marks the attached file as available for import. +* [PRAGMA Library](pragma/file.md#library) — marks the attached file as available for import. ## EXPORT @@ -20,7 +20,7 @@ A mechanism for putting part of the query into a separate attached file. To use {% note warning %} -The file linked by the [PRAGMA Library](pragma.md#library) must be attached to the query. __You can't use [PRAGMA File](pragma.md#file) for this purpose__. +The file linked by the [PRAGMA Library](pragma/file.md#library) must be attached to the query. __You can't use [PRAGMA File](pragma/file.md#file) for this purpose__. {% endnote %} diff --git a/yql/essentials/docs/en/syntax/index.md b/yql/essentials/docs/en/syntax/index.md index cd9ca6d592a..165ae19311a 100644 --- a/yql/essentials/docs/en/syntax/index.md +++ b/yql/essentials/docs/en/syntax/index.md @@ -12,7 +12,7 @@ * [INSERT](insert_into.md) * [INTO RESULT](into_result.md) * [JOIN](join.md) -* [PRAGMA](pragma.md) +* [PRAGMA](pragma/index.md) * [PROCESS](process.md) * [REDUCE](reduce.md) * [SELECT](select/index.md) diff --git a/yql/essentials/docs/en/syntax/lexer.md b/yql/essentials/docs/en/syntax/lexer.md index c63ad8e745e..792c719051b 100644 --- a/yql/essentials/docs/en/syntax/lexer.md +++ b/yql/essentials/docs/en/syntax/lexer.md @@ -84,7 +84,7 @@ SELECT 1 as "column with "" double quote"; -- column name will be: column with " ## SQL hints {#sql-hints} -SQL hints are special settings with which a user can modify a query execution plan (for example, enable/disable specific optimizations or force the JOIN execution strategy). Unlike [PRAGMA](pragma.md), SQL hints act locally – they are linked to a specific point in the YQL query (normally, after the keyword) and affect only the corresponding statement or even a part of it. +SQL hints are special settings with which a user can modify a query execution plan (for example, enable/disable specific optimizations or force the JOIN execution strategy). Unlike [PRAGMA](pragma/index.md), SQL hints act locally – they are linked to a specific point in the YQL query (normally, after the keyword) and affect only the corresponding statement or even a part of it. SQL hints are a set of settings "name-value list" and defined inside special comments — comments with SQL hints must have `+` as the first character: @@ -186,7 +186,7 @@ SELECT $text; ### Typed string literals {#typed-string-literals} -* For string literals, including [multi-string](#multiline-string-literals) ones, the `String` type is used by default (see also [PRAGMA UnicodeLiterals](pragma.md#UnicodeLiterals)). +* For string literals, including [multi-string](#multiline-string-literals) ones, the `String` type is used by default (see also [PRAGMA UnicodeLiterals](pragma/global.md#UnicodeLiterals)). * You can use the following suffixes to explicitly control the literal type: * `s` — `String` diff --git a/yql/essentials/docs/en/syntax/pragma.md b/yql/essentials/docs/en/syntax/pragma.md deleted file mode 100644 index 64403deabd4..00000000000 --- a/yql/essentials/docs/en/syntax/pragma.md +++ /dev/null @@ -1,429 +0,0 @@ -# PRAGMA - -## Definition - -Redefinition of settings. - -#### Syntax - -`PRAGMA x.y = "z";` or `PRAGMA x.y("z", "z2", "z3");`: - -* `x`: (optional) The category of the setting. -* `y`: The name of the setting. -* `z`: (optional for flags) The value of the setting. The following suffixes are acceptable: - - * `Kb`, `Mb`, `Gb`: For the data amounts. - * `sec`, `min`, `h`, `d`: For the time values. - -#### Examples - -```yql -PRAGMA AutoCommit; -``` - -```yql -PRAGMA TablePathPrefix = "home/yql"; -``` - -```yql -PRAGMA Warning("disable", "1101"); -``` - -With some exceptions, you can return the settings values to their default states using `PRAGMA my_pragma = default;`. - -For the full list of available settings, [see the table below](pragma.md#pragmas). - -### Scope {#pragmascope} - -Unless otherwise specified, a pragma affects all the subsequent expressions up to the end of the module where it's used. If necessary and logically possible, you can change the value of this setting several times within a given query to make it different at different execution steps. - -There are also special scoped pragmas with the scope defined by the same rules as the scope of [named expressions](expressions.md#named-nodes). Unlike scoped pragmas, regular pragmas can only be used in the global scope (not inside lambda functions, `ACTION`, `SUBQUERY`, etc.). - - - -## Global {#pragmas} - -### AutoCommit {#autocommit} - -| Value type | Default | -| --- | --- | -| Flag | false | - -Automatically run [COMMIT](commit.md) after every statement. - -### RuntimeLogLevel {#runtime-log-level} - -| Value type | Default | -| --- | --- | -| String, one of `Trace`, `Debug`, `Info`, `Notice`, `Warn`, `Error`, `Fatal` | `Info` | - -Allows you to change the logging level of calculations (for example, for UDFs) during query execution or at the stage of declaring the UDF signature. - -### TablePathPrefix {#table-path-prefix} - -| Value type | Default | -| --- | --- | -| String | — | - -Add the specified prefix to the cluster table paths. It uses standard file system path concatenation, supporting parent folder `..` referencing and requiring no trailing slash. For example, - -`PRAGMA TablePathPrefix = "home/yql"; -SELECT * FROM test;` - -The prefix is not added if the table name is an absolute path (starts with /). - -### UseTablePrefixForEach {#use-table-prefix-for-each} - -| Value type | Default | -| --- | --- | -| Flag | false | - -EACH uses [TablePathPrefix](#table-path-prefix) for each list item. - -### Warning {#warning} - -| Value type | Default | -| --- | --- | -| 1. Action<br/>2. Warning code or "*" | — | - -Action: - -* `disable`: Disable. -* `error`: Treat as an error. -* `default`: Revert to the default behavior. - -The warning code is returned with the text itself (it's displayed on the right side of the web interface). - -#### Example - -`PRAGMA Warning("error", "*");` -`PRAGMA Warning("disable", "1101");` -`PRAGMA Warning("default", "4503");` - -In this case, all the warnings are treated as errors, except for the warning `1101` (that will be disabled) and `4503` (that will be processed by default, that is, remain a warning). Since warnings may be added in new YQL releases, use `PRAGMA Warning("error", "*");` with caution (at least cover such queries with autotests). - -### SimpleColumns {#simplecolumns} - -`SimpleColumns` / `DisableSimpleColumns` - -| Value type | Default | -| --- | --- | -| Flag | true | - -When you use `SELECT foo.* FROM ... AS foo`, remove the `foo.` prefix from the names of the result columns. - -It can be also used with a [JOIN](join.md), but in this case it may fail in the case of a name conflict (that can be resolved by using [WITHOUT](select/without.md) and renaming columns). For JOIN in SimpleColumns mode, an implicit Coalesce is made for key columns: the query `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` in the SimpleColumns mode works same as `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)`. - -### CoalesceJoinKeysOnQualifiedAll - -`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` - -| Value type | Default | -| --- | --- | -| Flag | true | - -Controls implicit Coalesce for the key `JOIN` columns in the SimpleColumns mode. If the flag is set, the Coalesce is made for key columns if there is at least one expression in the format `foo.*` or `*` in SELECT: for example, `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. If the flag is not set, then Coalesce for JOIN keys is made only if there is an asterisk '*' after `SELECT` - -### StrictJoinKeyTypes - -`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` - -| Value type | Default | -| --- | --- | -| Flag | false | - -If the flag is set, then [JOIN](join.md) will require strict matching of key types. -By default, JOIN preconverts keys to a shared type, which might result in performance degradation. -StrictJoinKeyTypes is a [scoped](pragma.md#pragmascope) setting. - -### AnsiInForEmptyOrNullableItemsCollections - -| Value type | Default | -| --- | --- | -| Flag | false | - -This pragma brings the behavior of the `IN` operator in accordance with the standard when there's `NULL` in the left or right side of `IN`. The behavior of `IN` when on the right side there is a Tuple with elements of different types also changed. Examples: - -`1 IN (2, 3, NULL) = NULL (was Just(False))` -`NULL IN () = Just(False) (was NULL)` -`(1, null) IN ((2, 2), (3, 3)) = Just(False) (was NULL)` - -For more information about the `IN` behavior when operands include `NULL`s, see [here](expressions.md#in). You can explicitly select the old behavior by specifying the pragma `DisableAnsiInForEmptyOrNullableItemsCollections`. If no pragma is set, then a warning is issued and the old version works. - -### AnsiRankForNullableKeys - -| Value type | Default | -| --- | --- | -| Flag | false | - -Aligns the RANK/DENSE_RANK behavior with the standard if there are optional types in the window sort keys or in the argument of such window functions. It means that: - -* The result type is always Uint64 rather than Uint64?. -* NULLs in keys are treated as equal to each other (the current implementation returns NULL). - -You can explicitly select the old behavior by using the `DisableAnsiRankForNullableKeys` pragma. If no pragma is set, then a warning is issued and the old version works. - -### AnsiCurrentRow - -| Value type | Default | -| --- | --- | -| Flag | false | - -Aligns the implicit setting of a window frame with the standard if there is ORDER BY. -If AnsiCurrentRow is not set, then the `(ORDER BY key)` window is equivalent to `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. -The standard also requires that this window behave as `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. -The difference is in how `CURRENT ROW` is interpreted. In `ROWS` mode `CURRENT ROW` is interpreted literally: the current row in a partition. -In `RANGE` mode, the end of the `CURRENT ROW` frame means "the last row in a partition with a sort key equal to the current row". - -### AnsiOrderByLimitInUnionAll - -| Value type | Default | -| --- | --- | -| Flag | false | - -Aligns the UNION ALL behavior with the standard if there is `ORDER BY/LIMIT/DISCARD/INSERT INTO` in the combined subqueries. It means that: - -* `ORDER BY/LIMIT/INSERT INTO` are allowed only after the last subquery. -* `DISCARD` is allowed only before the first subquery. -* The specified operators apply to the `UNION ALL` result (unlike the current behavior when they apply only to the subquery). -* To apply an operator to a subquery, enclose the subquery in parentheses. - -You can explicitly select the old behavior by using the `DisableAnsiOrderByLimitInUnionAll` pragma. If no pragma is set, then a warning is issued and the old version works. - -### OrderedColumns {#orderedcolumns} - -`OrderedColumns`/`DisableOrderedColumns` - -Output the [column order](select/order_by.md) in SELECT/JOIN/UNION ALL and preserve it when writing the results. The order of columns is undefined by default. - -### PositionalUnionAll {#positionalunionall} - -Enable the standard column-by-column execution for [UNION ALL](select/union.md#unionall). This automatically enables -[ordered columns](#orderedcolumns). - -### RegexUseRe2 - -| Value type | Default | -| --- | --- | -| Flag | false | - -Use Re2 UDF instead of Pcre to execute SQL the `REGEX`,`MATCH`,`RLIKE` statements. Re2 UDF can properly handle Unicode characters, unlike the default Pcre UDF. - -### ClassicDivision - -| Value type | Default | -| --- | --- | -| Flag | true | - -In the classical version, the result of integer division remains integer (by default). -If disabled, the result is always Double. -ClassicDivision is a [scoped](pragma.md#pragmascope) setting. - -### UnicodeLiterals - -`UnicodeLiterals`/`DisableUnicodeLiterals` - -| Value type | Default | -| --- | --- | -| Flag | false | - -When this mode is enabled, string literals without suffixes like "foo"/'bar'/@@multiline@@ will be of type `Utf8`, when disabled - `String`. -UnicodeLiterals is a [scoped](pragma.md#pragmascope) setting. - -### WarnUntypedStringLiterals - -`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` - -| Value type | Default | -| --- | --- | -| Flag | false | - -When this mode is enabled, a warning will be generated for string literals without suffixes like "foo"/'bar'/@@multiline@@. It can be suppressed by explicitly choosing the suffix `s` for the `String` type, or `u` for the `Utf8` type. -WarnUntypedStringLiterals is a [scoped](pragma.md#pragmascope) setting. - -### AllowDotInAlias - -| Value type | Default | -| --- | --- | -| Flag | false | - -Enable dot in names of result columns. This behavior is disabled by default, since the further use of such columns in JOIN is not fully implemented. - -### WarnUnnamedColumns - -| Value type | Default | -| --- | --- | -| Flag | false | - -Generate a warning if a column name was automatically generated for an unnamed expression in `SELECT` (in the format `column[0-9]+`). - -### GroupByLimit - -| Value type | Default | -| --- | --- | -| Positive number | 32 | - -Increasing the limit on the number of dimensions in [GROUP BY](group_by.md). - -### GroupByCubeLimit - -| Value type | Default | -| --- | --- | -| Positive number | 5 | - -Increasing the limit on the number of dimensions in [GROUP BY](group_by.md#rollup-cube-group-sets). - -Use this option with care, because the computational complexity of the query grows exponentially with the number of dimensions. - - -## Yson - -Managing the default behavior of Yson UDF, for more information, see the [documentation](../udf/list/yson.md) and, in particular, [Yson::Options](../udf/list/yson.md#ysonoptions). - -### `yson.AutoConvert` - -| Value type | Default | -| --- | --- | -| Flag | false | - -Automatic conversion of values to the required data type in all Yson UDF calls, including implicit calls. - -### `yson.Strict` - -| Value type | Default | -| --- | --- | -| Flag | true | - -Strict mode control in all Yson UDF calls, including implicit calls. If the value is omitted or is `"true"`, it enables the strict mode. If the value is `"false"`, it disables the strict mode. - -### `yson.DisableStrict` - -| Value type | Default | -| --- | --- | -| Flag | false | - -An inverted version of `yson.Strict`. If the value is omitted or is `"true"`, it disables the strict mode. If the value is `"false"`, it enables the strict mode. - - -## Working with files - -### File - -| Value type | Default | Static/<br/>dynamic | -| --- | --- | --- | -| Two string arguments: alias and URL | — | Static | - -Attach a file to the query by URL. For attaching files you can use the built-in functions [FilePath and FileContent](../builtins/basic.md#filecontent). - -### Folder - -| Value type | Default | Static/<br/>dynamic | -| --- | --- | --- | -| Two string arguments: prefix and URL | — | Static | - -Attach a set of files to the query by URL. Works similarly to adding multiple files via [`PRAGMA File`](#file) by direct links to files with aliases obtained by combining a prefix with a file name using `/`. - -### Library - -| Value type | Default | Static/<br/>dynamic | -| --- | --- | --- | -| One or two arguments: the file name and an optional URL | — | Static | - -Treat the specified attached file as a library from which you can do [IMPORT](export_import.md). The syntax type for the library is determined from the file extension: - -* `.sql`: For the YQL dialect of SQL <span style="color: green;">(recommended)</span>. -* `.yqls`: For [s-expressions](/docs/s_expressions). - -Example with a file attached to the query: - -```yql -PRAGMA library("a.sql"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -If the URL is specified, the library is downloaded from the URL rather than from the pre-attached file as in the following example: - -```yql -PRAGMA library("a.sql","http://intranet.site/5618566/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -In this case, you can use text parameter value substitution in the URL: - -```yql -DECLARE $_ver AS STRING; -- "5618566" -PRAGMA library("a.sql","http://intranet.site/{$_ver}/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -### Package - -| Value type | Default | Static /<br/>dynamic | -| --- | --- | --- | -| Two or three arguments: package name, URL and optional token | — | Static | - -Attach a hierarchical set of files to the query by URL, treating them as a package with a given name - an interconnected set of libraries. - -Package name is expected to be given as ``project_name.package_name``; from package's libraries you can do [IMPORT](export_import.md) with a module name like ``pkg.project_name.package_name.maybe.nested.module.name``. - -Example for a package with flat hierarchy which consists of two libraries - foo.sql and bar.sql: - -```yql -PRAGMA package("project.package", "http://intranet.site/path/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -You can also use text parameter value substitution in the URL: - -```yql -DECLARE $_path AS STRING; -- "path" -PRAGMA package("project.package","http://intranet.site/{$_path}/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -### OverrideLibrary - -| Value type | Default | Static/<br/>dynamic | -| --- | --- | --- | -| One argument: the file name | — | Static | - -Treat the specified attached file as a library and override with it one of package's libraries. - -File name is expected to be given as ``project_name/package_name/maybe/nested/module/name.EXTENSION``, extensions analagous to [PRAGMA Library](#library) are supported. - -Example: - -```yql -PRAGMA package("project.package", "http://intranet.site/path/to/package"); -PRAGMA override_library("project/package/maybe/nested/module/name.sql"); - -IMPORT pkg.project.package.foo SYMBOLS $foo; -SELECT $foo; -``` - -## Debugging and auxiliary settings {#debug} - - -### `config.flags("ValidateUdf", "Lazy")` - -| Value type | Default | -| --- | --- | -| String: None/Lazy/Greedy | None | - -Validating whether UDF results match the declared signature. The Greedy mode enforces materialization of lazy containers, although the Lazy mode doesn't. - -### `config.flags("Diagnostics")` - -| Value type | Default | -| --- | --- | -| Flag | false | - -Getting diagnostic information from YQL as an additional result of a query. - diff --git a/yql/essentials/docs/en/syntax/pragma/debug.md b/yql/essentials/docs/en/syntax/pragma/debug.md new file mode 100644 index 00000000000..0378f459916 --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/debug.md @@ -0,0 +1,18 @@ +# Debugging and service settings {#debug} + +## `config.flags("ValidateUdf", "Lazy")` + +| Value type | Default | +| --- | --- | +| String: None/Lazy/Greedy | None | + +Validating whether UDF results match the declared signature. The Greedy mode enforces materialization of lazy containers, although the Lazy mode doesn't. + +## `config.flags("Diagnostics")` + +| Value type | Default | +| --- | --- | +| Flag | false | + +Getting diagnostic information from YQL as an additional result of a query. + diff --git a/yql/essentials/docs/en/syntax/pragma/file.md b/yql/essentials/docs/en/syntax/pragma/file.md new file mode 100644 index 00000000000..776e7ce0878 --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/file.md @@ -0,0 +1,106 @@ +# Working with files + +## File {#file} + +| Value type | Default | Static/<br/>dynamic | +| --- | --- | --- | +| Two or three string arguments: alias, URL, and optional token name | — | Static | + +Attach a file to the query by URL. For attaching files you can use the built-in functions [FilePath and FileContent](../../builtins/basic.md#filecontent). + +When specifying the token name, its value will be used to access the target system. + +## Folder {#folder} + +| Value type | Default | Static/<br/>dynamic | +| --- | --- | --- | +| Two or three string arguments: alias, URL, and optional token name | — | Static | + +Attach a set of files to the query by URL. Works similarly to adding multiple files via [`PRAGMA File`](#file) by direct links to files with aliases obtained by combining a prefix with a file name using `/`. + +When specifying the token name, its value will be used to access the target system. + +## Library {#library} + +| Value type | Default | Static/<br/>dynamic | +| --- | --- | --- | +| One or two arguments: the file name and an optional URL | — | Static | + +Treat the specified attached file as a library from which you can do [IMPORT](../export_import.md). The syntax type for the library is determined from the file extension: + +* `.sql`: For the YQL dialect of SQL <span style="color: green;">(recommended)</span>. +* `.yqls`: For [s-expressions](/docs/s_expressions). + +Example with a file attached to the query: + +```yql +PRAGMA library("a.sql"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +If the URL is specified, the library is downloaded from the URL rather than from the pre-attached file as in the following example: + +```yql +PRAGMA library("a.sql","http://intranet.site/5618566/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +In this case, you can use text parameter value substitution in the URL: + +```yql +DECLARE $_ver AS STRING; -- "5618566" +PRAGMA library("a.sql","http://intranet.site/{$_ver}/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +## Package + +| Value type | Default | Static /<br/>dynamic | +| --- | --- | --- | +| Two or three arguments: package name, URL and optional token | — | Static | + +Attach a hierarchical set of files to the query by URL, treating them as a package with a given name - an interconnected set of libraries. + +Package name is expected to be given as ``project_name.package_name``; from package's libraries you can do [IMPORT](../export_import.md) with a module name like ``pkg.project_name.package_name.maybe.nested.module.name``. + +Example for a package with flat hierarchy which consists of two libraries - foo.sql and bar.sql: + +```yql +PRAGMA package("project.package", "http://intranet.site/path/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +You can also use text parameter value substitution in the URL: + +```yql +DECLARE $_path AS STRING; -- "path" +PRAGMA package("project.package","http://intranet.site/{$_path}/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +## OverrideLibrary + +| Value type | Default | Static/<br/>dynamic | +| --- | --- | --- | +| One argument: the file name | — | Static | + +Treat the specified attached file as a library and override with it one of package's libraries. + +File name is expected to be given as ``project_name/package_name/maybe/nested/module/name.EXTENSION``, extensions analogous to [PRAGMA Library](#library) are supported. + +Example: + +```yql +PRAGMA package("project.package", "http://intranet.site/path/to/package"); +PRAGMA override_library("project/package/maybe/nested/module/name.sql"); + +IMPORT pkg.project.package.foo SYMBOLS $foo; +SELECT $foo; +``` diff --git a/yql/essentials/docs/en/syntax/pragma/global.md b/yql/essentials/docs/en/syntax/pragma/global.md new file mode 100644 index 00000000000..464f6ebaabd --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/global.md @@ -0,0 +1,227 @@ +# Global + + +## Scope {#pragmascope} + +Unless otherwise specified, a pragma affects all the subsequent expressions up to the end of the module where it's used. If necessary and logically possible, you can change the value of this setting several times within a given query to make it different at different execution steps. + +There are also special scoped pragmas with the scope defined by the same rules as the scope of [named expressions](../expressions.md#named-nodes). Unlike scoped pragmas, regular pragmas can only be used in the global scope (not inside lambda functions, `ACTION`, `SUBQUERY`, etc.). + +## AutoCommit {#autocommit} + +| Value type | Default | +| --- | --- | +| Flag | false | + +Automatically run [COMMIT](../commit.md) after every statement. + +## RuntimeLogLevel {#runtime-log-level} + +| Value type | Default | +| --- | --- | +| String, one of `Trace`, `Debug`, `Info`, `Notice`, `Warn`, `Error`, `Fatal` | `Info` | + +Allows you to change the logging level of calculations (for example, for UDFs) during query execution or at the stage of declaring the UDF signature. + +## TablePathPrefix {#table-path-prefix} + +| Value type | Default | +| --- | --- | +| String | — | + +Add the specified prefix to the cluster table paths. It uses standard file system path concatenation, supporting parent folder `..` referencing and requiring no trailing slash. For example, + +```yql +PRAGMA TablePathPrefix = "home/yql"; +SELECT * FROM test; +``` + +The prefix is not added if the table name is an absolute path (starts with /). + +## UseTablePrefixForEach {#use-table-prefix-for-each} + +| Value type | Default | +| --- | --- | +| Flag | false | + +`EACH` uses [TablePathPrefix](#table-path-prefix) for each list item. + +## Warning {#warning} + +| Value type | Default | +| --- | --- | +| 1. Action<br/>2. Warning code or "*" | — | + +Action: + +* `disable`: Disable. +* `error`: Treat as an error. +* `default`: Revert to the default behavior. + +The warning code is returned with the text itself (it's displayed on the right side of the web interface). + +### Example + +`PRAGMA Warning("error", "*");` +`PRAGMA Warning("disable", "1101");` +`PRAGMA Warning("default", "4503");` + +In this case, all the warnings are treated as errors, except for the warning `1101` (that will be disabled) and `4503` (that will be processed by default, that is, remain a warning). Since warnings may be added in new YQL releases, use `PRAGMA Warning("error", "*");` with caution (at least cover such queries with autotests). + +## SimpleColumns {#simplecolumns} + +`SimpleColumns` / `DisableSimpleColumns` + +| Value type | Default | +| --- | --- | +| Flag | true | + +When you use `SELECT foo.* FROM ... AS foo`, remove the `foo.` prefix from the names of the result columns. + +It can be also used with a [JOIN](../join.md), but in this case it may fail in the case of a name conflict (that can be resolved by using [WITHOUT](../select/without.md) and renaming columns). For `JOIN` in SimpleColumns mode, an implicit Coalesce is made for key columns: the query `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` in the SimpleColumns mode works same as `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)`. + +## CoalesceJoinKeysOnQualifiedAll + +`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` + +| Value type | Default | +| --- | --- | +| Flag | true | + +Controls implicit Coalesce for the key `JOIN` columns in the `SimpleColumns` mode. If the flag is set, the Coalesce is made for key columns if there is at least one expression in the format `foo.*` or `*` in `SELECT`: for example, `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. If the flag is not set, then Coalesce for JOIN keys is made only if there is an asterisk '*' after `SELECT` + +## StrictJoinKeyTypes + +`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` + +| Value type | Default | +| --- | --- | +| Flag | false | + +If the flag is set, then [JOIN](../join.md) will require strict matching of key types. +By default, `JOIN` preconverts keys to a shared type, which might result in performance degradation. +`StrictJoinKeyTypes` is a [scoped](#pragmascope) setting. + +## AnsiInForEmptyOrNullableItemsCollections + +| Value type | Default | +| --- | --- | +| Flag | false | + +This pragma brings the behavior of the `IN` operator in accordance with the standard when there's `NULL` in the left or right side of `IN`. The behavior of `IN` when on the right side there is a Tuple with elements of different types also changed. Examples: + +`1 IN (2, 3, NULL) = NULL (was Just(False))` +`NULL IN () = Just(False) (was NULL)` +`(1, null) IN ((2, 2), (3, 3)) = Just(False) (was NULL)` + +For more information about the `IN` behavior when operands include `NULL`s, see [here](../expressions.md#in). You can explicitly select the old behavior by specifying the pragma `DisableAnsiInForEmptyOrNullableItemsCollections`. If no pragma is set, then a warning is issued and the old version works. + +## AnsiRankForNullableKeys + +| Value type | Default | +| --- | --- | +| Flag | false | + +Aligns the `RANK`/`DENSE_RANK` behavior with the standard if there are optional types in the window sort keys or in the argument of such window functions. It means that: + +* The result type is always Uint64 rather than Uint64?. +* NULLs in keys are treated as equal to each other (the current implementation returns NULL). + +You can explicitly select the old behavior by using the `DisableAnsiRankForNullableKeys` pragma. If no pragma is set, then a warning is issued and the old version works. + +## AnsiCurrentRow + +| Value type | Default | +| --- | --- | +| Flag | false | + +Aligns the implicit setting of a window frame with the standard if there is `ORDER BY`. +If `AnsiCurrentRow` is not set, then the `(ORDER BY key)` window is equivalent to `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. +The standard also requires that this window behave as `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. +The difference is in how `CURRENT ROW` is interpreted. In `ROWS` mode `CURRENT ROW` is interpreted literally: the current row in a partition. +In `RANGE` mode, the end of the `CURRENT ROW` frame means "the last row in a partition with a sort key equal to the current row". + +## OrderedColumns {#orderedcolumns} + +`OrderedColumns`/`DisableOrderedColumns` + +Output the [column order](../select/order_by.md) in `SELECT`/`JOIN`/`UNION ALL` and preserve it when writing the results. The order of columns is undefined by default. + +## PositionalUnionAll {#positionalunionall} + +Enable the standard column-by-column execution for [UNION ALL](../select/union.md#unionall). This automatically enables +[ordered columns](#orderedcolumns). + +## RegexUseRe2 + +| Value type | Default | +| --- | --- | +| Flag | false | + +Use Re2 UDF instead of Pcre to execute SQL the `REGEX`,`MATCH`,`RLIKE` statements. Re2 UDF can properly handle Unicode characters, unlike the default Pcre UDF. + +## ClassicDivision + +| Value type | Default | +| --- | --- | +| Flag | true | + +In the classical version, the result of integer division remains integer (by default). +If disabled, the result is always Double. +`ClassicDivision` is a [scoped](#pragmascope) setting. + +## UnicodeLiterals + +`UnicodeLiterals`/`DisableUnicodeLiterals` + +| Value type | Default | +| --- | --- | +| Flag | false | + +When this mode is enabled, string literals without suffixes like "foo"/'bar'/@@multiline@@ will be of type `Utf8`, when disabled - `String`. +`UnicodeLiterals` is a [scoped](#pragmascope) setting. + +## WarnUntypedStringLiterals + +`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` + +| Value type | Default | +| --- | --- | +| Flag | false | + +When this mode is enabled, a warning will be generated for string literals without suffixes like "foo"/'bar'/@@multiline@@. It can be suppressed by explicitly choosing the suffix `s` for the `String` type, or `u` for the `Utf8` type. +`WarnUntypedStringLiterals` is a [scoped](#pragmascope) setting. + +## AllowDotInAlias + +| Value type | Default | +| --- | --- | +| Flag | false | + +Enable dot in names of result columns. This behavior is disabled by default, since the further use of such columns in `JOIN` is not fully implemented. + +## WarnUnnamedColumns + +| Value type | Default | +| --- | --- | +| Flag | false | + +Generate a warning if a column name was automatically generated for an unnamed expression in `SELECT` (in the format `column[0-9]+`). + +## GroupByLimit + +| Value type | Default | +| --- | --- | +| Positive number | 32 | + +Increasing the limit on the number of dimensions in [GROUP BY](../group_by.md). + +## GroupByCubeLimit + +| Value type | Default | +| --- | --- | +| Positive number | 5 | + +Increasing the limit on the number of dimensions in [GROUP BY](../group_by.md#rollup-cube-group-sets). + +Use this option with care, because the computational complexity of the query grows exponentially with the number of dimensions. diff --git a/yql/essentials/docs/en/syntax/pragma/index.md b/yql/essentials/docs/en/syntax/pragma/index.md new file mode 100644 index 00000000000..7492b217800 --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/index.md @@ -0,0 +1,44 @@ +# PRAGMA + +## Definition + +Pragmas are special directives that override the query execution settings. For example, they can be used to select a strategy for joining tables, configure the error logging level, or specify which pool to perform query operations in. Pragmas can affect query execution speed, resource allocation, and semantics. + +The pragmas apply only within the current query. For more information, see the [pragma scope](global.md#pragmascope). + +#### Syntax + +`PRAGMA x.y = "z";` or `PRAGMA x.y("z", "z2", "z3");`: + +* `x`: (optional) The category of the setting. +* `y`: The name of the setting. +* `z`: (optional for flags) The value of the setting. The following suffixes are acceptable: + + * `Kb`, `Mb`, `Gb`: For the data amounts. + * `sec`, `min`, `h`, `d`: For the time values. + +#### Examples + +```yql +PRAGMA AutoCommit; +``` + +```yql +PRAGMA TablePathPrefix = "home/yql"; +``` + +```yql +PRAGMA Warning("disable", "1101"); +``` + +With some exceptions, you can return the settings values to their default states using `PRAGMA my_pragma = default;`. + +For the full list of available settings, [see below](#pragmas). + +### Available pragmas {#pragmas} + +* [Global](global.md) +* [Yson](yson.md) +* [Working with files](file.md) +* [Debug and service](debug.md) + diff --git a/yql/essentials/docs/en/syntax/pragma/toc_i.yaml b/yql/essentials/docs/en/syntax/pragma/toc_i.yaml new file mode 100644 index 00000000000..74c6bd0c4f9 --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/toc_i.yaml @@ -0,0 +1,7 @@ +items: +- { name: Overview, href: index.md } +- { name: Global, href: global.md } +- { name: Yson, href: yson.md } +- { name: Working with files, href: file.md } +- { name: Debug and service, href: debug.md } + diff --git a/yql/essentials/docs/en/syntax/pragma/toc_p.yaml b/yql/essentials/docs/en/syntax/pragma/toc_p.yaml new file mode 100644 index 00000000000..82343f6140f --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/toc_p.yaml @@ -0,0 +1,2 @@ +items: +- include: { mode: link, path: toc_i.yaml } diff --git a/yql/essentials/docs/en/syntax/pragma/yson.md b/yql/essentials/docs/en/syntax/pragma/yson.md new file mode 100644 index 00000000000..090cf30052e --- /dev/null +++ b/yql/essentials/docs/en/syntax/pragma/yson.md @@ -0,0 +1,28 @@ +# Yson + +Managing the default behavior of Yson UDF, for more information, see the [documentation](../../udf/list/yson.md) and, in particular, [Yson::Options](../../udf/list/yson.md#ysonoptions). + +## `yson.AutoConvert` {#autoconvert} + +| Value type | Default | +| --- | --- | +| Flag | false | + +Automatic conversion of values to the required data type in all Yson UDF calls, including implicit calls. + +## `yson.Strict` {#strict} + +| Value type | Default | +| --- | --- | +| Flag | true | + +Strict mode control in all Yson UDF calls, including implicit calls. If the value is omitted or is `"true"`, it enables the strict mode. If the value is `"false"`, it disables the strict mode. + +## `yson.DisableStrict` + +| Value type | Default | +| --- | --- | +| Flag | false | + +An inverted version of `yson.Strict`. If the value is omitted or is `"true"`, it disables the strict mode. If the value is `"false"`, it enables the strict mode. + diff --git a/yql/essentials/docs/en/syntax/select/index.md b/yql/essentials/docs/en/syntax/select/index.md index 47b61a68d84..449c7e80020 100644 --- a/yql/essentials/docs/en/syntax/select/index.md +++ b/yql/essentials/docs/en/syntax/select/index.md @@ -32,7 +32,7 @@ The `SELECT` query result is calculated as follows: * Evaluate expressions in `SELECT`. * Assign names set by aliases to expressions in `SELECT`. * Apply top-level [DISTINCT](distinct.md) to the resulting columns. -* Execute similarly every subquery inside [UNION ALL](union.md#union-all), combine them (see [PRAGMA AnsiOrderByLimitInUnionAll](../pragma.md#pragmas)). +* Execute similarly every subquery inside [UNION ALL](union.md#union-all). * Perform sorting with [ORDER BY](order_by.md). * Apply [OFFSET and LIMIT](limit_offset.md) to the result. diff --git a/yql/essentials/docs/en/syntax/select/union.md b/yql/essentials/docs/en/syntax/select/union.md index 4b6097dc301..a0b7e9155f9 100644 --- a/yql/essentials/docs/en/syntax/select/union.md +++ b/yql/essentials/docs/en/syntax/select/union.md @@ -19,7 +19,7 @@ SELECT key FROM T2 -- returns the set of distinct keys in the tables Concatenating results of multiple `SELECT` statements (or subqueries). -Two `UNION ALL` modes are supported: by column names (the default mode) and by column positions (corresponds to the ANSI SQL standard and is enabled by the [PRAGMA](../pragma.md#positionalunionall)). +Two `UNION ALL` modes are supported: by column names (the default mode) and by column positions (corresponds to the ANSI SQL standard and is enabled by the [PRAGMA](../pragma/global.md#positionalunionall)). In the "by name" mode, the output of the resulting data schema uses the following rules: diff --git a/yql/essentials/docs/en/syntax/toc_i.yaml b/yql/essentials/docs/en/syntax/toc_i.yaml index f91c0f3e1eb..b756ffa29f2 100644 --- a/yql/essentials/docs/en/syntax/toc_i.yaml +++ b/yql/essentials/docs/en/syntax/toc_i.yaml @@ -12,7 +12,7 @@ items: - { name: INSERT, href: insert_into.md } - { name: INTO RESULT, href: into_result.md } - { name: JOIN, href: join.md } -- { name: PRAGMA, href: pragma.md } +- { name: PRAGMA, include: { mode: link, path: pragma/toc_p.yaml } } - { name: PROCESS, href: process.md } - { name: REDUCE, href: reduce.md } - { name: SELECT, include: { mode: link, path: select/toc_p.yaml } } diff --git a/yql/essentials/docs/en/udf/list/yson.md b/yql/essentials/docs/en/udf/list/yson.md index 756ea377800..d21ce3544de 100644 --- a/yql/essentials/docs/en/udf/list/yson.md +++ b/yql/essentials/docs/en/udf/list/yson.md @@ -300,7 +300,7 @@ SELECT Yson::ConvertToBoolDict($yson, Yson::Options(false as Strict)); --- { "y" SELECT Yson::ConvertToDoubleDict($yson, Yson::Options(false as Strict)); --- { "x": 5.5 } ``` -If you need to use the same Yson library settings throughout the query, it's more convenient to use [PRAGMA yson.AutoConvert;](../../syntax/pragma.md#yson.autoconvert) and/or [PRAGMA yson.Strict;](../../syntax/pragma.md#yson.strict). Only with these `PRAGMA` you can affect implicit calls to the Yson library occurring when you work with Yson/Json data types. +If you need to use the same Yson library settings throughout the query, it's more convenient to use [PRAGMA yson.AutoConvert;](../../syntax/pragma/yson.md#autoconvert) and/or [PRAGMA yson.Strict;](../../syntax/pragma/yson.md#strict). Only with these `PRAGMA` you can affect implicit calls to the Yson library occurring when you work with Yson/Json data types. ## See also diff --git a/yql/essentials/docs/ru/builtins/basic.md b/yql/essentials/docs/ru/builtins/basic.md index 0dae688bd3e..b7379e1b6c1 100644 --- a/yql/essentials/docs/ru/builtins/basic.md +++ b/yql/essentials/docs/ru/builtins/basic.md @@ -961,7 +961,7 @@ FolderPath(String)->String Аргумент — строка с префиксом среди алиасов. -Также см. [PRAGMA File](../syntax/pragma.md#file) и [PRAGMA Folder](../syntax/pragma.md#folder). +Также см. [PRAGMA File](../syntax/pragma/file.md#file) и [PRAGMA Folder](../syntax/pragma/file.md#folder). #### Примеры @@ -1115,7 +1115,7 @@ WHERE Likely(a.amount > 0) -- почти всегда верно EvaluateExpr может использоваться в тех местах, где грамматикой уже ожидается выражение. Например, с его помощью можно: -* округлить текущее время до дней, недель или месяцев и подставить в запрос, что затем позволит корректно работать [кешированию запросов](../syntax/pragma.md#yt.querycachemode), хотя обычно использование [функций для получения текущего времени](#current-utc) его полностью отключает; +* округлить текущее время до дней, недель или месяцев и подставить в запрос, что затем позволит корректно работать кешированию запросов, хотя обычно использование [функций для получения текущего времени](#current-utc) его полностью отключает; * сделать тяжелое вычисление с небольшим результатом один раз на запрос вместо одного раза на каждую джобу. EvaluateAtom позволяет динамически создать [атом](../types/special.md), но т.к. ими в основном оперирует более низкий уровень [s-expressions](/docs/s_expressions/functions), то использовать эту функцию напрямую как правило не рекомендуется. diff --git a/yql/essentials/docs/ru/syntax/export_import.md b/yql/essentials/docs/ru/syntax/export_import.md index e613a54305a..b25eb67d7a8 100644 --- a/yql/essentials/docs/ru/syntax/export_import.md +++ b/yql/essentials/docs/ru/syntax/export_import.md @@ -2,7 +2,7 @@ Механизм для выноса части запроса в отдельный приложенный файл. Чтобы воспользоваться механизмом, необходимо выставить прагму: -* [PRAGMA Library](pragma.md#library) — помечает приложенный файл как доступный для импорта. +* [PRAGMA Library](pragma/file.md#library) — помечает приложенный файл как доступный для импорта. ## EXPORT @@ -20,7 +20,7 @@ {% note warning %} -Файл, на который ссылается [PRAGMA Library](pragma.md#library), должен быть приложен к запросу. __Использовать для этой цели [PRAGMA File](pragma.md#file) нельзя__. +Файл, на который ссылается [PRAGMA Library](pragma/file.md#library), должен быть приложен к запросу. __Использовать для этой цели [PRAGMA File](pragma/file.md#file) нельзя__. {% endnote %} diff --git a/yql/essentials/docs/ru/syntax/index.md b/yql/essentials/docs/ru/syntax/index.md index 2fbea1dd772..8beb75d5701 100644 --- a/yql/essentials/docs/ru/syntax/index.md +++ b/yql/essentials/docs/ru/syntax/index.md @@ -12,7 +12,7 @@ * [INSERT](insert_into.md) * [INTO RESULT](into_result.md) * [JOIN](join.md) -* [PRAGMA](pragma.md) +* [PRAGMA](pragma/index.md) * [PROCESS](process.md) * [REDUCE](reduce.md) * [SELECT](select/index.md) diff --git a/yql/essentials/docs/ru/syntax/lexer.md b/yql/essentials/docs/ru/syntax/lexer.md index 6c9eb9e2de4..42959357707 100644 --- a/yql/essentials/docs/ru/syntax/lexer.md +++ b/yql/essentials/docs/ru/syntax/lexer.md @@ -88,7 +88,7 @@ SELECT 1 as "column with "" double quoute"; -- имя колонки будет: ## SQL хинты {#sql-hints} -SQL хинты – это специальные настройки, которые позволяют пользователю влиять на план выполнения запроса (например, включать/выключать определенные оптимизации, форсировать стратегию JOIN-а и т. п.). В отличие от [PRAGMA](pragma.md), SQL хинты обладают локальным действием – они привязаны к определенной точке YQL запроса (обычно следуют после ключевого слова) и влияют только на соответствующий statement или даже его часть. +SQL хинты – это специальные настройки, которые позволяют пользователю влиять на план выполнения запроса (например, включать/выключать определенные оптимизации, форсировать стратегию JOIN-а и т. п.). В отличие от [PRAGMA](pragma/index.md), SQL хинты обладают локальным действием – они привязаны к определенной точке YQL запроса (обычно следуют после ключевого слова) и влияют только на соответствующий statement или даже его часть. SQL хинты представляют собой набор настроек "имя-список значений" и задаются внутри комментариев специального вида – первым символом комментария с SQL хинтами должен быть `+`: @@ -193,7 +193,7 @@ SELECT $text; ### Типизированные строковые литералы {#typed-string-literals} -* Для строкового литерала, включая [многострочный](#multiline-string-literals), по умолчанию используется тип `String` (см. также [PRAGMA UnicodeLiterals](pragma.md#UnicodeLiterals)). +* Для строкового литерала, включая [многострочный](#multiline-string-literals), по умолчанию используется тип `String` (см. также [PRAGMA UnicodeLiterals](pragma/global.md#UnicodeLiterals)). * С помощью следующих суффиксов можно явно управлять типом литерала: * `s` — `String`; diff --git a/yql/essentials/docs/ru/syntax/pragma.md b/yql/essentials/docs/ru/syntax/pragma.md deleted file mode 100644 index 4b380de4a1a..00000000000 --- a/yql/essentials/docs/ru/syntax/pragma.md +++ /dev/null @@ -1,475 +0,0 @@ -# PRAGMA - -## Определение - -Переопределение настроек. - -### Синтаксис - -`PRAGMA x.y = "z";` или `PRAGMA x.y("z", "z2", "z3");`: - -* `x` — (опционально) категория настройки. -* `y` — название настройки. -* `z` — (опционально для флагов) значение настройки. Допустимо использование следующих суффиксов: - - * `Kb`, `Mb`, `Gb` — для объема информации. - * `sec`, `min`, `h`, `d` — для временных значений. - -За некоторым исключением, значение настроек можно вернуть в состояние по умолчанию с помощью `PRAGMA my_pragma = default;`. - -### Примеры - -```yql -PRAGMA AutoCommit; -``` - -```yql -PRAGMA TablePathPrefix = "home/yql"; -``` - -```yql -PRAGMA Warning("disable", "1101"); -``` - -Полный список доступных настроек [см. в таблице ниже](#pragmas). - -### Область действия {#pragmascope} - -Если не указано иное, прагма влияет на все идущие следом выражения вплоть до конца модуля, в котором она встречается. При необходимости и логической возможности можно менять значение настройки несколько раз в одном запросе, чтобы оно было разным на разных этапах выполнения. - -Существуют также специальные scoped прагмы, область действия которых определяется по тем же правилам, что и область видимости [именованных выражений](expressions.md#named-nodes). - -В отличие от scoped прагм, обычные прагмы могут использоваться только в глобальной области видимости (не внутри [DEFINE ACTION](action.md#define-action) и [DEFINE SUBQUERY](subquery.md#define-subquery)). - -## Глобальные {#pragmas} - -### AutoCommit {#autocommit} - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Автоматически выполнять [COMMIT](select/index.md#commit) после каждого выражения. - -### TablePathPrefix {#table-path-prefix} - -| Тип значения | По умолчанию | -| --- | --- | -| Строка | — | - -Добавить указанный префикс к путям таблиц внутри кластеров. Работает по принципу объединения путей в файловой системе: поддерживает ссылки на родительский каталог `..` и не требует добавления слеша справа. Например, - -```yql -PRAGMA TablePathPrefix = "home/yql"; -SELECT * FROM test; -``` - -Префикс не добавляется, если имя таблицы указано как абсолютный путь (начинается с /). - -### UDF {#udf} - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Строка | — | Статическая | -| Строка — имя префикса, добавляемого ко всем модулям | "" | Статическая | - -Импорт всех UDF из указанной библиотеки. Чтобы прагма сработала, библиотеку необходимо приложить к запросу. Обратите внимание: библиотека должна быть разделяемой (.so) и она должна быть скомпилирована под Linux x64. - -При указании префикса, он добавляется перед названием всех загруженных модулей, например, CustomPrefixIp::IsIPv4 вместо Ip::IsIPv4. Указание префикса позволяет подгрузить одну и ту же UDF разных версий. - -### RuntimeLogLevel {#runtime-log-level} - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Строка, одно из `Trace`, `Debug`, `Info`, `Notice`, `Warn`, `Error`, `Fatal` | `Info` | Статическая | - -Позволяет поменять уровень логирования вычислений (например, для UDF) во время выполнения запроса или на этапе декларации сигнатуры UDF. - -### UseTablePrefixForEach {#use-table-prefix-for-each} - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -`EACH` использует [TablePathPrefix](#table-path-prefix) для каждого элемента списка. - -### Warning {#warning} - -| Тип значения | По умолчанию | -| --- | --- | -| 1. Действие<br/>2. Код предупреждения либо символ "*"| — | - -Действие: - -* `disable` — отключить; -* `error` — приравнять к ошибке; -* `default` — вернуть поведение по умолчанию. - -Код предупреждения возвращается вместе с самим текстом (в веб-интерфейсе отображается справа). - -Примеры: - -`PRAGMA Warning("error", "*");` -`PRAGMA Warning("disable", "1101");` -`PRAGMA Warning("default", "4503");` - -В данном случае все предупреждения будут считаться ошибками, за исключением предупреждения с кодом `1101`, которое будет отключено, и `4503`, которое будет обрабатываться по умолчанию (то есть останется предупреждением). Поскольку предупреждения могут добавляться в новых релизах YQL, следует с осторожностью пользоваться конструкцией `PRAGMA Warning("error", "*");` (как минимум покрывать такие запросы автотестами). - -### Greetings {#greetings} - -| Тип значения | По умолчанию | -| --- | --- | -| Текст | — | - -Выдать указанный текст в качестве Info сообщения запроса. - -Пример: `PRAGMA Greetings("It's a good day!");` - -### WarningMsg {#warningmsg} - -| Тип значения | По умолчанию | -| --- | --- | -| Текст | — | - -Выдать указанный текст в качестве Warning сообщения запроса. - -Пример: -`PRAGMA WarningMsg("Attention!");` - -### SimpleColumns {#simplecolumns} - -`SimpleColumns` / `DisableSimpleColumns` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -При использовании `SELECT foo.* FROM ... AS foo` убрать префикс `foo.` у имен результирующих колонок. - -Работает в том числе и для [JOIN](join.md), но в этом случае имеет право упасть в случае конфликта имен (который можно разрешить с помощью [WITHOUT](select/without.md) и переименования колонок). Для JOIN в режиме SimpleColumns производится неявный Coalesce для ключевых колонок: запрос `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` в режиме SimpleColumns работает как `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)` - -### CoalesceJoinKeysOnQualifiedAll - -`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -Управляет неявным Coalesce для ключевых колонок `JOIN` в режиме SimpleColumns. Если флаг установлен, то Coalesce ключевых колонок происходит при наличии хотя бы одного выражения вида `foo.*` или `*` в SELECT — например `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. Если флаг сброшен, то Coalesce ключей JOIN происходит только при наличии '*' после `SELECT`. - -### StrictJoinKeyTypes - -`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Если флаг установлен, то [JOIN](join.md) будет требовать строгого совпадения типов ключей. -По умолчанию JOIN предварительно конвертирует ключи к общему типу, что может быть нежелательно с точки зрения производительности. - -StrictJoinKeyTypes является [scoped](#pragmascope) настройкой. - - -### AnsiInForEmptyOrNullableItemsCollections - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Наличие этой прагмы приводит поведение оператора `IN` в соответствие со стандартом в случае наличия `NULL` в левой или правой части оператора `IN`. Также изменено поведение `IN` в случае, когда справа был Tuple с элементами разных типов. Примеры: - -`1 IN (2, 3, NULL) = NULL (было Just(False))` -`NULL IN () = Just(False) (было NULL)` -`(1, null) IN ((2, 2), (3, 3)) = Just(False) (было NULL)` - -Подробнее про поведение `IN` при наличии NULL-ов в операндах можно почитать [здесь](expressions.md#in). Явным образом выбрать старое поведение можно, указав прагму `DisableAnsiInForEmptyOrNullableItemsCollections`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. - -### AnsiRankForNullableKeys - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Приводит поведение RANK/DENSE_RANK в соответствие со стандартом при наличии опциональных типов в ключах сортировки окна или в аргументе этих оконных функций. А именно: - -* типом результата всегда является Uint64, а не Uint64?; -* null-ы в ключах считаются равными друг другу (текущая реализация возвращает NULL). - -Явным образом выбрать старое поведение можно, указав прагму `DisableAnsiRankForNullableKeys`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. - -### AnsiCurrentRow - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Приводит неявное задание рамки окна при наличии [ORDER BY](select/order_by.md) в соответствие со стандартом. - -Если AnsiCurrentRow не установлен, то окно `(ORDER BY key)` эквивалентно `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. Стандарт же требует, чтобы такое окно вело себя как `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. - -Разница состоит в трактовке `CURRENT ROW`. В режиме `ROWS` `CURRENT ROW` трактуется буквально – текущая строка в партиции. -А в режиме `RANGE` конец рамки `CURRENT ROW` означает "последняя строка в партиции с ключом сортировки, равным текущей строке". - -### OrderedColumns {#orderedcolumns} - -`OrderedColumns` / `DisableOrderedColumns` - -Выводить [порядок колонок](select/index.md#orderedcolumns) в SELECT/JOIN/UNION ALL и сохранять его при записи результатов. По умолчанию порядок колонок не определен. - -### PositionalUnionAll {#positionalunionall} - -Включить соответствующий стандарту поколоночный режим выполнения [UNION ALL](select/index.md#unionall). При этом автоматически включается [упорядоченность колонок](#orderedcolumns). - -### RegexUseRe2 - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Использовать Re2 UDF вместо Pcre для выполнения SQL операторов `REGEX`,`MATCH`,`RLIKE`. Re2 UDF поддерживает корректную обработку Unicode-символов в отличие от используемой по умолчанию Pcre UDF. - -### ClassicDivision - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -В классическом варианте результат целочисленного деления остается целочисленным (по умолчанию). Если отключить — результат всегда становится Double. - -`ClassicDivision` является [scoped](#pragmascope) настройкой. - -### CheckedOps - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -При включенном режиме: если в результате выполнения агрегационных функций SUM/SUM_IF, бинарных операций `+`,`-`,`*`,`/`,`%` или унарной операции `-` над целыми числами происходит выход за границы целевого типа аргументов или результата, то возвращается `NULL`. Если отключить — переполнение не проверяется. - -Не влияет на операции с числами с плавающей точкой или `Decimal`. - -`CheckedOps` является [scoped](#pragmascope) настройкой. - -### UnicodeLiterals - -`UnicodeLiterals`/`DisableUnicodeLiterals` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -При включенном режиме строковые литералы без суффиксов вида "foo"/'bar'/@@multiline@@ будут иметь тип `Utf8`, при выключенном — `String`. - -`UnicodeLiterals` является [scoped](#pragmascope) настройкой. - -### WarnUntypedStringLiterals - -`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -При включенном режиме для строковых литералов без суффиксов вида "foo"/'bar'/@@multiline@@ будет генерироваться предупреждение. Его можно подавить, если явно выбрать суффикс `s` для типа `String`, либо `u` для типа `Utf8`. - -`WarnUntypedStringLiterals` является [scoped](#pragmascope) настройкой. - -### AllowDotInAlias - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Разрешить использовать точку в именах результирующих колонок. По умолчанию отключено, т. к. дальнейшее использование таких колонок в JOIN полностью не реализовано. - -### WarnUnnamedColumns - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Генерировать предупреждение, если для безымянного выражения в `SELECT` было автоматически сгенерировано имя колонки (вида `column[0-9]+`). - -### GroupByLimit - -| Тип значения | По умолчанию | -| --- | --- | -| Положительное число | 32 | - -Увеличение лимита на число группировок в [GROUP BY](group_by.md). - -### GroupByCubeLimit - -| Тип значения | По умолчанию | -| --- | --- | -| Положительное число | 5 | - -Увеличение лимита на число размерностей [GROUP BY](group_by.md#rollup-cube-group-sets). - -Использовать нужно аккуратно, так как вычислительная сложность запроса растет экспоненциально по отношению к числу размерностей. - - -## Yson - -Управление поведением Yson UDF по умолчанию, подробнее см. в [документации](../udf/list/yson.md) и в частности [Yson::Options](../udf/list/yson.md#ysonoptions). - -### `yson.AutoConvert` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Автоматическая конвертация значений в требуемый тип данных во всех вызовах Yson UDF, в том числе и неявных. - -### `yson.Strict` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -Управление строгим режимом во всех вызовах Yson UDF, в том числе и неявных. Без значения или при значении `"true"` — включает строгий режим. Со значением `"false"` — отключает. - -### `yson.DisableStrict` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Инвертированная версия `yson.Strict`. Без значения или при значении `"true"` — отключает строгий режим. Со значением `"false"` — включает. - - -## Работа с файлами - -### File - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Два или три строковых аргумента — алиас, URL и опциональное имя токена | — | Статическая | - -Приложить файл к запросу по URL. Использовать приложенные файлы можно с помощью встроенных функций [FilePath и FileContent](../builtins/basic.md#filecontent). - -При указании имени токена, его значение будет использоваться для обращения к целевой системе. - -### FileOption - -| Тип значения | По умолчанию | Статическая /<br/> динамическая | -|-------------------------------------------------|--------------|--------------------------------| -| Три строковых аргумента — алиас, ключ, значение | — | Статическая | - -Установить для указанного файла опцию по заданному ключу в заданное значение. Файл с этим алиасом уже должен быть объявлен через [PRAGMA File](#file) или приложен к запросу. - - - -### Folder - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Два или три строковых аргумента — префикс, URL и опциональное имя токена | — | Статическая | - -Приложить набор файлов к запросу по URL. Работает аналогично добавлению множества файлов через [PRAGMA File](#file) по прямым ссылкам на файлы с алиасами, полученными объединением префикса с именем файла через `/`. - -При указании имени токена, его значение будет использоваться для обращения к целевой системе. - -### Library - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Один или два аргумента — имя файла и опциональный URL | — | Статическая | - -Интерпретировать указанный приложенный файл как библиотеку, из которой можно делать [IMPORT](export_import.md). Тип синтаксиса библиотеки определяется по расширению файла: -* `.sql` для YQL диалекта SQL <span style="color: green;">(рекомендуется)</span>; -* `.yqls` для [s-expressions](/docs/s_expressions). - -Пример с приложенным файлом к запросу: - -```yql -PRAGMA library("a.sql"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -В случае указания URL библиотека скачивается с него, а не с предварительного приложенного файла, как в следующем примере: - -```yql -PRAGMA library("a.sql","http://intranet.site/5618566/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -При этом можно использовать подстановку текстовых параметров в URL: - -```yql -DECLARE $_ver AS STRING; -- "5618566" -PRAGMA library("a.sql","http://intranet.site/{$_ver}/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -### Package - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Два или три аргумента — имя пакета, URL и опциональный токен | — | Статическая | - -Приложить иерархический набор файлов к запросу по URL, интерпретируя их в качестве пакета с указанным именем — взаимосвязанного набора библиотек. - -Имя пакета ожидается в формате ``project_name.package_name``; из библиотек пакета в дальнейшем можно делать [IMPORT](export_import.md) с именем модуля вида ``pkg.project_name.package_name.maybe.nested.module.name``. - -Пример для пакета с плоской иерархией, состоящего из двух библиотек — foo.sql и bar.sql: - -```yql -PRAGMA package("project.package", "http://intranet.site/path/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -При этом можно использовать подстановку текстовых параметров в URL: - -```yql -DECLARE $_path AS STRING; -- "path" -PRAGMA package("project.package","http://intranet.site/{$_path}/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -### OverrideLibrary - -| Тип значения | По умолчанию | Статическая /<br/>динамическая | -| --- | --- | --- | -| Один аргумент — имя файла | — | Статическая | - -Интерпретировать указанный приложенный файл как библиотеку и перекрыть ей одну из библиотек пакета. - -Имя файла ожидается в формате ``project_name/package_name/maybe/nested/module/name.EXTENSION``, поддерживаются аналогичные [PRAGMA Library](#library) расширения. - -Пример: - -```yql -PRAGMA package("project.package", "http://intranet.site/path/to/package"); -PRAGMA override_library("project/package/maybe/nested/module/name.sql"); - -IMPORT pkg.project.package.foo SYMBOLS $foo; -SELECT $foo; -``` - -## Отладочные и служебные {#debug} - -### `config.flags("ValidateUdf", "Lazy")` - -| Тип значения | По умолчанию | -| --- | --- | -| Строка: None / Lazy / Greedy | None | - -Валидация результатов UDF на соответствие объявленной сигнатуре. Greedy режим форсирует материализацию «ленивых» контейнеров, а Lazy — нет. - -### `config.flags("Diagnostics")` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Получение диагностической информации от YQL в виде дополнительного результата запроса. diff --git a/yql/essentials/docs/ru/syntax/pragma/debug.md b/yql/essentials/docs/ru/syntax/pragma/debug.md new file mode 100644 index 00000000000..cffcb1ba7b4 --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/debug.md @@ -0,0 +1,17 @@ +# Отладочные и служебные {#debug} + +## `config.flags("ValidateUdf", "Lazy")` + +| Тип значения | По умолчанию | +| --- | --- | +| Строка: None / Lazy / Greedy | None | + +Валидация результатов UDF на соответствие объявленной сигнатуре. Greedy режим форсирует материализацию «ленивых» контейнеров, а Lazy — нет. + +## `config.flags("Diagnostics")` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Получение диагностической информации от YQL в виде дополнительного результата запроса. diff --git a/yql/essentials/docs/ru/syntax/pragma/file.md b/yql/essentials/docs/ru/syntax/pragma/file.md new file mode 100644 index 00000000000..c3dae62dce0 --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/file.md @@ -0,0 +1,113 @@ +# Работа с файлами + +## File {#file} + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Два или три строковых аргумента — алиас, URL и опциональное имя токена | — | Статическая | + +Приложить файл к запросу по URL. Использовать приложенные файлы можно с помощью встроенных функций [FilePath и FileContent](../../builtins/basic.md#filecontent). + +При указании имени токена, его значение будет использоваться для обращения к целевой системе. + +## FileOption + +| Тип значения | По умолчанию | Статическая /<br/> динамическая | +|-------------------------------------------------|--------------|--------------------------------| +| Три строковых аргумента — алиас, ключ, значение | — | Статическая | + +Установить для указанного файла опцию по заданному ключу в заданное значение. Файл с этим алиасом уже должен быть объявлен через [PRAGMA File](#file) или приложен к запросу. + +## Folder {#folder} + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Два или три строковых аргумента — префикс, URL и опциональное имя токена | — | Статическая | + +Приложить набор файлов к запросу по URL. Работает аналогично добавлению множества файлов через [PRAGMA File](#file) по прямым ссылкам на файлы с алиасами, полученными объединением префикса с именем файла через `/`. + +При указании имени токена, его значение будет использоваться для обращения к целевой системе. + +## Library {#library} + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Один или два аргумента — имя файла и опциональный URL | — | Статическая | + +Интерпретировать указанный приложенный файл как библиотеку, из которой можно делать [IMPORT](../export_import.md). Тип синтаксиса библиотеки определяется по расширению файла: +* `.sql` для YQL диалекта SQL <span style="color: green;">(рекомендуется)</span>; +* `.yqls` для [s-expressions](/docs/s_expressions). + +Пример с приложенным файлом к запросу: + +```yql +PRAGMA library("a.sql"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +В случае указания URL библиотека скачивается с него, а не с предварительного приложенного файла, как в следующем примере: + +```yql +PRAGMA library("a.sql","http://intranet.site/5618566/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +При этом можно использовать подстановку текстовых параметров в URL: + +```yql +DECLARE $_ver AS STRING; -- "5618566" +PRAGMA library("a.sql","http://intranet.site/{$_ver}/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +## Package + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Два или три аргумента — имя пакета, URL и опциональный токен | — | Статическая | + +Приложить иерархический набор файлов к запросу по URL, интерпретируя их в качестве пакета с указанным именем — взаимосвязанного набора библиотек. + +Имя пакета ожидается в формате ``project_name.package_name``; из библиотек пакета в дальнейшем можно делать [IMPORT](../export_import.md) с именем модуля вида ``pkg.project_name.package_name.maybe.nested.module.name``. + +Пример для пакета с плоской иерархией, состоящего из двух библиотек — foo.sql и bar.sql: + +```yql +PRAGMA package("project.package", "http://intranet.site/path/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +При этом можно использовать подстановку текстовых параметров в URL: + +```yql +DECLARE $_path AS STRING; -- "path" +PRAGMA package("project.package","http://intranet.site/{$_path}/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +## OverrideLibrary + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Один аргумент — имя файла | — | Статическая | + +Интерпретировать указанный приложенный файл как библиотеку и перекрыть ей одну из библиотек пакета. + +Имя файла ожидается в формате ``project_name/package_name/maybe/nested/module/name.EXTENSION``, поддерживаются аналогичные [PRAGMA Library](#library) расширения. + +Пример: + +```yql +PRAGMA package("project.package", "http://intranet.site/path/to/package"); +PRAGMA override_library("project/package/maybe/nested/module/name.sql"); + +IMPORT pkg.project.package.foo SYMBOLS $foo; +SELECT $foo; +``` diff --git a/yql/essentials/docs/ru/syntax/pragma/global.md b/yql/essentials/docs/ru/syntax/pragma/global.md new file mode 100644 index 00000000000..5a36dc9b068 --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/global.md @@ -0,0 +1,276 @@ +# Глобальные + +## Область действия {#pragmascope} + +Если не указано иное, глобальная прагма влияет на все идущие следом выражения вплоть до конца модуля, в котором она встречается. При необходимости и логической возможности можно менять значение настройки несколько раз в одном запросе, чтобы оно было разным на разных этапах выполнения. + +Существуют также специальные scoped прагмы, область действия которых определяется по тем же правилам, что и область видимости [именованных выражений](../expressions.md#named-nodes). + +В отличие от scoped прагм, обычные прагмы могут использоваться только в глобальной области видимости (не внутри [DEFINE ACTION](../action.md#define-action) и [DEFINE SUBQUERY](../subquery.md#define-subquery)). + + +## AutoCommit {#autocommit} + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Автоматически выполнять [COMMIT](../select/index.md#commit) после каждого выражения. + +## TablePathPrefix {#table-path-prefix} + +| Тип значения | По умолчанию | +| --- | --- | +| Строка | — | + +Добавить указанный префикс к путям таблиц внутри кластеров. Работает по принципу объединения путей в файловой системе: поддерживает ссылки на родительский каталог `..` и не требует добавления слеша справа. Например, + +```yql +PRAGMA TablePathPrefix = "home/yql"; +SELECT * FROM test; +``` + +Префикс не добавляется, если имя таблицы указано как абсолютный путь (начинается с /). + +## UDF {#udf} + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Строка | — | Статическая | +| Строка — имя префикса, добавляемого ко всем модулям | "" | Статическая | + +Импорт всех UDF из указанной библиотеки. Чтобы прагма сработала, библиотеку необходимо приложить к запросу. Обратите внимание: библиотека должна быть разделяемой (.so) и она должна быть скомпилирована под Linux x64. + +При указании префикса, он добавляется перед названием всех загруженных модулей, например, CustomPrefixIp::IsIPv4 вместо Ip::IsIPv4. Указание префикса позволяет подгрузить одну и ту же UDF разных версий. + +## RuntimeLogLevel {#runtime-log-level} + +| Тип значения | По умолчанию | Статическая /<br/>динамическая | +| --- | --- | --- | +| Строка, одно из `Trace`, `Debug`, `Info`, `Notice`, `Warn`, `Error`, `Fatal` | `Info` | Статическая | + +Позволяет поменять уровень логирования вычислений (например, для UDF) во время выполнения запроса или на этапе декларации сигнатуры UDF. + +## UseTablePrefixForEach {#use-table-prefix-for-each} + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +`EACH` использует [TablePathPrefix](#table-path-prefix) для каждого элемента списка. + +## Warning {#warning} + +| Тип значения | По умолчанию | +| --- | --- | +| 1. Действие<br/>2. Код предупреждения либо символ "*"| — | + +Действие: + +* `disable` — отключить; +* `error` — приравнять к ошибке; +* `default` — вернуть поведение по умолчанию. + +Код предупреждения возвращается вместе с самим текстом (в веб-интерфейсе отображается справа). + +Примеры: + +`PRAGMA Warning("error", "*");` +`PRAGMA Warning("disable", "1101");` +`PRAGMA Warning("default", "4503");` + +В данном случае все предупреждения будут считаться ошибками, за исключением предупреждения с кодом `1101`, которое будет отключено, и `4503`, которое будет обрабатываться по умолчанию (то есть останется предупреждением). Поскольку предупреждения могут добавляться в новых релизах YQL, следует с осторожностью пользоваться конструкцией `PRAGMA Warning("error", "*");` (как минимум покрывать такие запросы автотестами). + +## Greetings {#greetings} + +| Тип значения | По умолчанию | +| --- | --- | +| Текст | — | + +Выдать указанный текст в качестве Info сообщения запроса. + +Пример: `PRAGMA Greetings("It's a good day!");` + +## WarningMsg {#warningmsg} + +| Тип значения | По умолчанию | +| --- | --- | +| Текст | — | + +Выдать указанный текст в качестве Warning сообщения запроса. + +Пример: +`PRAGMA WarningMsg("Attention!");` + +## SimpleColumns {#simplecolumns} + +`SimpleColumns` / `DisableSimpleColumns` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +При использовании `SELECT foo.* FROM ... AS foo` убрать префикс `foo.` у имен результирующих колонок. + +Работает в том числе и для [JOIN](../join.md), но в этом случае имеет право упасть в случае конфликта имен (который можно разрешить с помощью [WITHOUT](../select/without.md) и переименования колонок). Для `JOIN` в режиме SimpleColumns производится неявный Coalesce для ключевых колонок: запрос `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` в режиме SimpleColumns работает как `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)` + +## CoalesceJoinKeysOnQualifiedAll + +`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +Управляет неявным Coalesce для ключевых колонок `JOIN` в режиме SimpleColumns. Если флаг установлен, то Coalesce ключевых колонок происходит при наличии хотя бы одного выражения вида `foo.*` или `*` в SELECT — например `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. Если флаг сброшен, то Coalesce ключей JOIN происходит только при наличии '*' после `SELECT`. + +## StrictJoinKeyTypes + +`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Если флаг установлен, то [JOIN](../join.md) будет требовать строгого совпадения типов ключей. +По умолчанию `JOIN` предварительно конвертирует ключи к общему типу, что может быть нежелательно с точки зрения производительности. + +`StrictJoinKeyTypes` является [scoped](#pragmascope) настройкой. + +## AnsiInForEmptyOrNullableItemsCollections + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Наличие этой прагмы приводит поведение оператора `IN` в соответствие со стандартом в случае наличия `NULL` в левой или правой части оператора `IN`. Также изменено поведение `IN` в случае, когда справа был Tuple с элементами разных типов. Примеры: + +`1 IN (2, 3, NULL) = NULL (было Just(False))` +`NULL IN () = Just(False) (было NULL)` +`(1, null) IN ((2, 2), (3, 3)) = Just(False) (было NULL)` + +Подробнее про поведение `IN` при наличии NULL-ов в операндах можно почитать [здесь](../expressions.md#in). Явным образом выбрать старое поведение можно, указав прагму `DisableAnsiInForEmptyOrNullableItemsCollections`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. + +## AnsiRankForNullableKeys + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Приводит поведение `RANK`/`DENSE_RANK` в соответствие со стандартом при наличии опциональных типов в ключах сортировки окна или в аргументе этих оконных функций. А именно: + +* типом результата всегда является Uint64, а не Uint64?; +* null-ы в ключах считаются равными друг другу (текущая реализация возвращает NULL). + +Явным образом выбрать старое поведение можно, указав прагму `DisableAnsiRankForNullableKeys`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. + +## AnsiCurrentRow + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Приводит неявное задание рамки окна при наличии [ORDER BY](../select/order_by.md) в соответствие со стандартом. + +Если `AnsiCurrentRow` не установлен, то окно `(ORDER BY key)` эквивалентно `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. Стандарт же требует, чтобы такое окно вело себя как `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. + +Разница состоит в трактовке `CURRENT ROW`. В режиме `ROWS` `CURRENT ROW` трактуется буквально – текущая строка в партиции. +А в режиме `RANGE` конец рамки `CURRENT ROW` означает "последняя строка в партиции с ключом сортировки, равным текущей строке". + +## OrderedColumns {#orderedcolumns} + +`OrderedColumns` / `DisableOrderedColumns` + +Выводить [порядок колонок](../select/index.md#orderedcolumns) в `SELECT`/`JOIN`/`UNION ALL` и сохранять его при записи результатов. По умолчанию порядок колонок не определен. + +## PositionalUnionAll {#positionalunionall} + +Включить соответствующий стандарту поколоночный режим выполнения [UNION ALL](../select/index.md#unionall). При этом автоматически включается [упорядоченность колонок](#orderedcolumns). + +## RegexUseRe2 + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Использовать Re2 UDF вместо Pcre для выполнения SQL операторов `REGEX`,`MATCH`,`RLIKE`. Re2 UDF поддерживает корректную обработку Unicode-символов в отличие от используемой по умолчанию Pcre UDF. + +## ClassicDivision + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +В классическом варианте результат целочисленного деления остается целочисленным (по умолчанию). Если отключить — результат всегда становится Double. + +`ClassicDivision` является [scoped](#pragmascope) настройкой. + +## CheckedOps + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +При включенном режиме: если в результате выполнения агрегационных функций SUM/SUM_IF, бинарных операций `+`,`-`,`*`,`/`,`%` или унарной операции `-` над целыми числами происходит выход за границы целевого типа аргументов или результата, то возвращается `NULL`. Если отключить — переполнение не проверяется. + +Не влияет на операции с числами с плавающей точкой или `Decimal`. + +`CheckedOps` является [scoped](#pragmascope) настройкой. + +## UnicodeLiterals + +`UnicodeLiterals`/`DisableUnicodeLiterals` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +При включенном режиме строковые литералы без суффиксов вида "foo"/'bar'/@@multiline@@ будут иметь тип `Utf8`, при выключенном — `String`. + +`UnicodeLiterals` является [scoped](#pragmascope) настройкой. + +## WarnUntypedStringLiterals + +`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +При включенном режиме для строковых литералов без суффиксов вида "foo"/'bar'/@@multiline@@ будет генерироваться предупреждение. Его можно подавить, если явно выбрать суффикс `s` для типа `String`, либо `u` для типа `Utf8`. + +`WarnUntypedStringLiterals` является [scoped](#pragmascope) настройкой. + +## AllowDotInAlias + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Разрешить использовать точку в именах результирующих колонок. По умолчанию отключено, т. к. дальнейшее использование таких колонок в `JOIN` полностью не реализовано. + +## WarnUnnamedColumns + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Генерировать предупреждение, если для безымянного выражения в `SELECT` было автоматически сгенерировано имя колонки (вида `column[0-9]+`). + +## GroupByLimit + +| Тип значения | По умолчанию | +| --- | --- | +| Положительное число | 32 | + +Увеличение лимита на число группировок в [GROUP BY](../group_by.md). + +## GroupByCubeLimit + +| Тип значения | По умолчанию | +| --- | --- | +| Положительное число | 5 | + +Увеличение лимита на число размерностей [GROUP BY](../group_by.md#rollup-cube-group-sets). + +Использовать нужно аккуратно, так как вычислительная сложность запроса растет экспоненциально по отношению к числу размерностей. diff --git a/yql/essentials/docs/ru/syntax/pragma/index.md b/yql/essentials/docs/ru/syntax/pragma/index.md new file mode 100644 index 00000000000..7fd48116dcc --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/index.md @@ -0,0 +1,40 @@ +# PRAGMA + +## Определение + +Прагмы — это специальные директивы, которые переопределяют настройки выполнения запроса. Например, с их помощью можно выбрать стратегию объединения таблиц, настроить уровень логирования ошибок или указать, в каком пуле выполнять операции запроса. Прагмы могут влиять на скорость выполнения запроса, на распределение ресурсов и семантику. + +Действие прагм распространяется только в рамках текущего запроса. Подробнее смотри в разделе [область действия прагм](global.md#pragmascope). + +### Синтаксис + +`PRAGMA x.y = "z";` или `PRAGMA x.y("z", "z2", "z3");`: + +* `x` — (опционально) категория настройки. +* `y` — название настройки. +* `z` — (опционально для флагов) значение настройки + +За некоторым исключением, значение настроек можно вернуть в состояние по умолчанию с помощью `PRAGMA my_pragma = default;`. + +### Примеры + +```yql +PRAGMA AutoCommit; +``` + +```yql +PRAGMA TablePathPrefix = "home/yql"; +``` + +```yql +PRAGMA Warning("disable", "1101"); +``` + +Полный список доступных настроек [см. ниже](#pragmas). + +### Доступные прагмы {#pragmas} + +* [Глобальные](global.md) +* [Yson](yson.md) +* [Работа с файлами](file.md) +* [Отладочные и служебные](debug.md) diff --git a/yql/essentials/docs/ru/syntax/pragma/toc_i.yaml b/yql/essentials/docs/ru/syntax/pragma/toc_i.yaml new file mode 100644 index 00000000000..232bd8bafcf --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/toc_i.yaml @@ -0,0 +1,7 @@ +items: +- { name: Обзор, href: index.md } +- { name: Глобальные, href: global.md } +- { name: Yson, href: yson.md } +- { name: Работа с файлами, href: file.md } +- { name: Отладочные и служебные, href: debug.md } + diff --git a/yql/essentials/docs/ru/syntax/pragma/toc_p.yaml b/yql/essentials/docs/ru/syntax/pragma/toc_p.yaml new file mode 100644 index 00000000000..82343f6140f --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/toc_p.yaml @@ -0,0 +1,2 @@ +items: +- include: { mode: link, path: toc_i.yaml } diff --git a/yql/essentials/docs/ru/syntax/pragma/yson.md b/yql/essentials/docs/ru/syntax/pragma/yson.md new file mode 100644 index 00000000000..d695c6f4407 --- /dev/null +++ b/yql/essentials/docs/ru/syntax/pragma/yson.md @@ -0,0 +1,28 @@ +# Yson + +Yson-прагма влияет на все идущие следом выражения вплоть до конца модуля, в котором она встречается. + +## `yson.AutoConvert` {#autoconvert} + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Автоматическая конвертация значений в требуемый тип данных во всех вызовах Yson UDF, в том числе и неявных. + +## `yson.Strict` {#strict} + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +Управление строгим режимом во всех вызовах Yson UDF, в том числе и неявных. Без значения или при значении `"true"` — включает строгий режим. Со значением `"false"` — отключает. + +## `yson.DisableStrict` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Инвертированная версия `yson.Strict`. Без значения или при значении `"true"` — отключает строгий режим. Со значением `"false"` — включает. + diff --git a/yql/essentials/docs/ru/syntax/select/index.md b/yql/essentials/docs/ru/syntax/select/index.md index f0d3814907c..602b0d3f65f 100644 --- a/yql/essentials/docs/ru/syntax/select/index.md +++ b/yql/essentials/docs/ru/syntax/select/index.md @@ -31,7 +31,7 @@ SELECT 2 + 2; * вычисляются выражения в `SELECT`; * выражениям в `SELECT` назначаются имена заданные алиасами; * к полученным таким образом колонкам применяется top-level [DISTINCT](distinct.md); -* таким же образом вычисляются все подзапросы в [UNION ALL](union.md#union-all), выполняется их объединение (см. [PRAGMA AnsiOrderByLimitInUnionAll](../pragma.md#pragmas)); +* таким же образом вычисляются все подзапросы в [UNION ALL](union.md#union-all), выполняется их объединение; * выполняется сортировка согласно [ORDER BY](order_by.md); * к полученному результату применяются [OFFSET и LIMIT](limit_offset.md). diff --git a/yql/essentials/docs/ru/syntax/select/union.md b/yql/essentials/docs/ru/syntax/select/union.md index 037a71ed749..4b1770bfa8e 100644 --- a/yql/essentials/docs/ru/syntax/select/union.md +++ b/yql/essentials/docs/ru/syntax/select/union.md @@ -19,7 +19,7 @@ SELECT key FROM T2 -- возвращает таблицу различных к� Конкатенация результатов нескольких `SELECT` (или подзапросов). -Поддерживаются два режима выполнения `UNION ALL` – по именам колонок (режим по умолчанию) и по позициям колонок (соответствует стандарту ANSI SQL и включается через соответствующую [PRAGMA](../pragma.md#positionalunionall)). +Поддерживаются два режима выполнения `UNION ALL` – по именам колонок (режим по умолчанию) и по позициям колонок (соответствует стандарту ANSI SQL и включается через соответствующую [PRAGMA](../pragma/global.md#positionalunionall)). В режиме "по именам" результирующая схема данных выводится по следующим правилам: diff --git a/yql/essentials/docs/ru/syntax/toc_i.yaml b/yql/essentials/docs/ru/syntax/toc_i.yaml index 524351d1326..ec223a352a9 100644 --- a/yql/essentials/docs/ru/syntax/toc_i.yaml +++ b/yql/essentials/docs/ru/syntax/toc_i.yaml @@ -12,7 +12,7 @@ items: - { name: INSERT, href: insert_into.md } - { name: INTO RESULT, href: into_result.md } - { name: JOIN, href: join.md } -- { name: PRAGMA, href: pragma.md } +- { name: PRAGMA, include: { mode: link, path: pragma/toc_p.yaml } } - { name: PROCESS, href: process.md } - { name: REDUCE, href: reduce.md } - { name: SELECT, include: { mode: link, path: select/toc_p.yaml } } diff --git a/yql/essentials/docs/ru/udf/list/yson.md b/yql/essentials/docs/ru/udf/list/yson.md index 2b5f86d9864..cfa9c67511a 100644 --- a/yql/essentials/docs/ru/udf/list/yson.md +++ b/yql/essentials/docs/ru/udf/list/yson.md @@ -301,7 +301,7 @@ SELECT Yson::ConvertToBoolDict($yson, Yson::Options(false as Strict)); --- { "y" SELECT Yson::ConvertToDoubleDict($yson, Yson::Options(false as Strict)); --- { "x": 5.5 } ``` -Если во всём запросе требуется применять одинаковые значения настроек библиотеки Yson, то удобнее воспользоваться [PRAGMA yson.AutoConvert;](../../syntax/pragma.md#yson.autoconvert) и/или [PRAGMA yson.Strict;](../../syntax/pragma.md#yson.strict). Также эти `PRAGMA` являются единственным способом повлиять на неявные вызовы библиотеки Yson, которые возникают при работе с типами данных Yson/Json. +Если во всём запросе требуется применять одинаковые значения настроек библиотеки Yson, то удобнее воспользоваться [PRAGMA yson.AutoConvert;](../../syntax/pragma/yson.md#autoconvert) и/или [PRAGMA yson.Strict;](../../syntax/pragma/yson.md#strict). Также эти `PRAGMA` являются единственным способом повлиять на неявные вызовы библиотеки Yson, которые возникают при работе с типами данных Yson/Json. ## Смотрите также |