Repository navigation
Support PostgreSQL-compatible ARRAY[...] syntax as sugar for [...] - #106028
lvzhipin03 wants to merge 12 commits into
Conversation
The PostgreSQL array constructor `ARRAY[1, 2, 3]` is a widespread spelling used by many query generators and BI tools. ClickHouse already supports the equivalent `[1, 2, 3]` bracket form and the `array()` function, but previously rejected `ARRAY[...]` at parse time with a syntax error. This change makes the parser recognize the optional `ARRAY` keyword before `[...]` and treat it as pure syntactic sugar for the existing bracket constructor — the two forms produce identical ASTs. No new AST nodes, no runtime overhead. Closes ClickHouse#105951
|
Workflow [PR], commit [f8084ae] Summary: ❌
AI ReviewSummary
Missing context / blind spots
Final Verdict
|
|
There's an ambiguity in queries like: SELECT ARRAY[1] FROM (SELECT [10, 20] AS ARRAY) With the current implementation, this silently changes meaning — previously it returned 10 (subscript access on column ARRAY), now it returns [1] (array constructor). Should we instead make ARRAY a reserved keyword in expression position when followed by [, so that using it as a column name in this context produces a parse error rather than silently changing behavior? That would match PostgreSQL's semantics and be less surprising than a silent result change. |
I think it is not a problem, if someone uses ARRAY as a column name they can easily change the column name to not trigger this ambiguity. Same issue with multiple columns that have the same name - there is precedence and user should know what is happening. Interesting does this |
Verifies that the result of ARRAY[...] constructor can be directly subscripted, e.g. ARRAY[1,2,3][2] returns 2.
Agreed — the precedence is intentional and consistent with how PostgreSQL treats ARRAY as a constructor keyword. Users with a column named ARRAY can use arrayElement() explicitly. As for SELECT ARRAY[1,2,3][2] — yes, it returns 2. After ARRAY[1,2,3] is parsed as the array literal [1,2,3], the trailing [2] is handled as a normal subscript (arrayElement([1,2,3], 2)). Good idea, I'll add it as a test case. |
Previously ARRAY[...] was only recognized by ParserExpressionImpl. ParserArray (used by BACKUP ... SETTINGS cluster_host_ids) and ParserArrayOfLiterals (used by dictionary attribute DEFAULT) still rejected the ARRAY keyword, making ARRAY[...] and [...] not truly equivalent everywhere. Now all three array parsers optionally skip a leading ARRAY keyword, so ARRAY[...] is syntactic sugar for [...] wherever [...] is accepted. Tests added for all three paths: - Expression context (SELECT, INSERT VALUES, WHERE) - Dictionary attribute DEFAULT (ParserArrayOfLiterals) - BACKUP SETTINGS cluster_host_ids (ParserArray, verified via formatQuery)
Three remaining gaps where ARRAY[...] was still rejected: 1. Nested ARRAY[ARRAY[...]] inside ParserCollectionOfLiterals: the per-element branch only checked for a bare [ token. Now also accepts an optional ARRAY keyword before [. 2. Top-level and nested ARRAY[...] in ParserAllCollectionsOfLiterals (used by SET param_x = ...): parseAllCollectionsStart now accepts an optional ARRAY keyword before [, fixing both the entry point and any recursively nested collections via CommonCollection::parse. 3. SET param_x = ARRAY[...]: ParserCompoundIdentifier was consuming the ARRAY token before ParserAllCollectionsOfLiterals got a chance to see it. Reorder parseParameterValueIntoString to try collections before identifier. Tests added for all three paths.
The original placement of the ARRAY[...] check in tryParseOperand was before array_literal_parser.parse, causing ARRAY[1, 2, 3] to be routed through ArrayLayer::getResultImpl instead of ParserArrayOfLiterals. ArrayLayer does not call recordLiteralTokens, which ValuesBlockInputFormat relies on to build ConstantExpressionTemplates for bulk INSERT ... VALUES optimizations. This broke the "no runtime overhead" contract for the primary motivated use case. Fix: remove the early ARRAY[...] check. ParserArrayOfLiterals already handles ARRAY[literal...] (via the earlier fix to parseAllCollectionsStart and ParserArrayOfLiterals::parseImpl), so the fast literal path with recordLiteralTokens is preserved automatically. The ARRAY[...] check is moved into the else-branch after the literal parsers, before identifier_parser, to handle non-literal ARRAY[expr...] arrays via ArrayLayer as before.
The PostgreSQL-compatible `ARRAY[...]` constructor (added in earlier commits) introduced a round-trip inconsistency: the expression `ARRAY[n]` where `ARRAY` is a column name was parsed as `arrayElement(ARRAY, n)`, but the formatter output the bare identifier `ARRAY` so the formatted text re-parsed as the literal array `[n]`. In a debug build this tripped the AST-consistency check in `executeQueryImpl` with "Inconsistent AST formatting" and aborted the server. Two changes fix this: 1. `src/Parsers/CommonParsers.h` — register `ARRAY` as a keyword (`Keyword::ARRAY`) so it appears in the keyword set returned by `getKeyWordSet`. 2. `src/Parsers/IAST.cpp` — extend `writeIdentifier` to consult the keyword set not only in `UserDisplay` mode but also in `WhenNecessary` mode (the mode used by the round-trip check). An identifier named `ARRAY` is now back-quoted in the formatted output, so `arrayElement(\`ARRAY\`, n)` round- trips correctly. The precedence rule itself is intentional and matches PostgreSQL: unquoted `ARRAY[...]` is always an array constructor; to subscript a column named `ARRAY` the identifier must be quoted as `` `ARRAY`[n] ``. Two regression tests are added to `04278_array_bracket_syntax.sql` to pin this boundary: one showing that `ARRAY[1]` returns `[1]` (constructor), and one showing that `` `ARRAY`[1] `` returns the first element of the column (10).
The PostgreSQL-compatible ARRAY[...] constructor (added in earlier commits) introduced a round-trip inconsistency: `ARRAY[n]` where `ARRAY` is a column name was parsed as `arrayElement(ARRAY, n)`, but the formatter output the bare identifier `ARRAY`, so the formatted text re-parsed as the literal array `[n]`. In a debug build this tripped the AST-consistency check in `executeQueryImpl` with "Inconsistent AST formatting" and aborted the server. Fix: in `ASTIdentifier::formatImplWithoutAlias`, mark the identifier as ambiguous when its name is `ARRAY` (case-insensitive). This causes `writeIdentifier` to back-quote it in `WhenNecessary` mode, so `arrayElement(`ARRAY`, n)` round-trips correctly. `ARRAY` is also registered as a keyword in `CommonParsers.h` so that `UserDisplay` mode (used in SHOW CREATE TABLE output and similar) quotes it consistently. The precedence rule itself is intentional and matches PostgreSQL: unquoted `ARRAY[...]` is always an array constructor; to subscript a column named `ARRAY` the identifier must be quoted as `` `ARRAY`[n] ``. Two regression tests are added to `04278_array_bracket_syntax.sql` to pin this boundary: one showing that `ARRAY[1]` returns `[1]` (constructor), and one showing that `` `ARRAY`[1] `` returns the first element of the column (10).
…pellings in INSERT VALUES `ParserArrayOfLiterals` consumed the `ARRAY` keyword before delegating to the bracket-array parser, but the `literal_token_map` span recorded by `recordLiteralTokens` started at the `[` rather than at `ARRAY`. When `ConstantExpressionTemplate` cached the first row's template using `ARRAY[...]`, it saw `ARRAY` as a fixed token followed by a literal span `[...]`. A subsequent row written as `[...]` (without the keyword) produced a different fixed-token sequence, causing a template-key mismatch. With `input_format_values_interpret_expressions = 0` the row was rejected; with it enabled the row fell back to the slow expression-evaluation path. Fix: save the position before keyword consumption and, if a keyword was consumed and the literal was registered in `literal_token_map`, extend the recorded span's `begin` pointer back to cover the `ARRAY` keyword. Both spellings now produce an identical, fixed-token-free template and the fast path works regardless of which spelling appears first. Test: added a mixed-spelling `INSERT VALUES` case to `04278_array_bracket_syntax`.
Add a mention of the PostgreSQL-compatible `ARRAY[...]` array constructor in the "Compound" section of `docs/en/sql-reference/syntax.md`, alongside the existing `[...]` description. Also add a note explaining that `ARRAY` followed by `[` is treated as a reserved constructor keyword, and that an identifier named `ARRAY` must be back-quoted (`` `ARRAY` ``) to be subscripted rather than parsed as the constructor.
…s_interpret_expressions = 0 Disable the slow expression-evaluation fallback for the mixed-spelling INSERT VALUES test so it exercises only the `ConstantExpressionTemplate` fast path. Without this, the per-row fallback could silently mask a template-key mismatch and the test would pass even if the fix were reverted.
The sentence "An array must consist of at least one item" contradicted both the existing `[]` syntax and the new `ARRAY[]` form tested in this PR. Replace it with "Arrays may be empty; tuples must have at least two items."
…prevent ARRAY[...] vs [...] cache collision
ARRAY[...] and [...] produce identical ASTs, so getTemplateHash previously
assigned them the same cache key. When ARRAY[1+1] was cached first, a later
[2+2] row retrieved the same template, failed checkString("ARRAY", istr),
and caused a parse error with input_format_values_interpret_expressions = 0.
Fix by hashing the non-literal fixed tokens (skipping replaced literal ranges)
in addition to the AST tree hash and literal types. This also resolves the
long-standing TODO for CAST(x, 'T') vs CAST(x AS T) and similar cases.
Regression tests for empty arrays (ARRAY[] vs []), expression arrays
(ARRAY[1+1] vs [2+2]), and all-NULL arrays (ARRAY[NULL] vs [NULL]) added
to 04278_array_bracket_syntax.sql with interpret_expressions = 0.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 99/106 (93.40%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 8 line(s) · Uncovered code |
The PostgreSQL array constructor
ARRAY[1, 2, 3]is a widespread spelling used by many query generators and BI tools. ClickHouse already supports the equivalent[1, 2, 3]bracket form and thearray()function, but previously rejectedARRAY[...]at parse time with a syntax error.This change makes the parser recognize the optional
ARRAYkeyword before[...]and treat it as pure syntactic sugar for the existing bracket constructor — the two forms produce identical ASTs. No new AST nodes, no runtime overhead.Closes #105951
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Support PostgreSQL-compatible
ARRAY[...]array constructor syntax as syntactic sugar for[...].