Skip to content

Support PostgreSQL-compatible ARRAY[...] syntax as sugar for [...] - #106028

Open
lvzhipin03 wants to merge 12 commits into
ClickHouse:masterfrom
lvzhipin03:array-bracket-syntax
Open

lvzhipin03 wants to merge 12 commits into
ClickHouse:masterfrom
lvzhipin03:array-bracket-syntax

Conversation

@lvzhipin03

Copy link
Copy Markdown
Contributor

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 #105951

Changelog category (leave one):

  • New Feature

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 [...].

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
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f8084ae]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Hung check failed, possible deadlock found FAIL cidb
Stress test (arm_msan) FAIL
Segmentation fault (STID: 4348-2010) FAIL cidb

AI Review

Summary
  • The PR adds PostgreSQL-compatible ARRAY[...] syntax as sugar for existing [...] array construction, wires it through full expression parsing, literal-only parser contexts, SET query parameters, formatting of identifiers named ARRAY, documentation, and focused stateless tests. I verified the prior parser-context and ConstantExpressionTemplate cache issues against the current code and resolved the remaining bot-authored thread; I do not have new blocking or major findings.
Missing context / blind spots
  • ⚠️ I could not run the stateless test locally because this checkout has no build* directory or clickhouse binary. The Praktika helper worked only against the S3 report URL from the robot comment, which returned the PR report shell but no test rows; a passing CI/stateless run closes this gap.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 28, 2026
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@lvzhipin03

lvzhipin03 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@qoega

qoega commented May 29, 2026

Copy link
Copy Markdown
Member

There's an ambiguity in queries like

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 SELECT ARRAY[1,2,3][2] return 2?

Verifies that the result of ARRAY[...] constructor can be directly
subscripted, e.g. ARRAY[1,2,3][2] returns 2.
@lvzhipin03

Copy link
Copy Markdown
Contributor Author

There's an ambiguity in queries like

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 SELECT ARRAY[1,2,3][2] return 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.

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
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.
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
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.
Comment thread docs/en/sql-reference/syntax.md Resolved
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."
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
…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.
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.50% +0.00%

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

Full report · Diff report

@abashkeev abashkeev added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 4, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Accept ARRAY[…] array constructor as alias for […]

5 participants