Repository navigation
Support bracket syntax json['key'] for JSON type - #107039
Conversation
Add support for accessing JSON subcolumns using bracket syntax, e.g. `json['key1']['key2']`, which the parser translates to nested `arrayElement` calls. Changes: - `arrayElement` function: add `getReturnTypeImpl(ColumnsWithTypeAndName)` overload that resolves the exact return type for JSON typed paths (e.g. `UInt32` instead of `Dynamic`), and `executeJSON` that extracts the combined subcolumn via `IDataType::getSubcolumn`. - `FunctionToSubcolumnsPass`: add a unified `optimizeJSONArrayElementChain` transformer registered in both `node_transformers` (single key) and `chained_node_transformers` (chains). Single `json['key']` is rewritten to a direct subcolumn read `json.@`key``. Chains like `json['a']['b']['c']` are collapsed into `json.@`a`.b.c`. - Fix `chained_pattern_inner_nodes` check ordering in the first pass: move it before the single-level match to prevent double-counting when an inner function also matches a single-level transformer. - Extract `DataTypeObject::getCombinedSubcolumnName` static method that uses `backQuote` for proper escaping of special characters in key names. Replace all manual combined subcolumn name formations in `tupleElement`, `FunctionsJSON`, `arrayElement`, and `FunctionToSubcolumnsPass`. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Workflow [PR], commit [23bb178] Summary: ✅
AI ReviewSummaryThis PR adds Findings❌ Blockers
Final VerdictChanges requested: the chained bracket optimization is not semantics-preserving once an intermediate hop yields a typed LLVM Coverage Report |
… JSON type When `json_type_escape_dots_in_keys` is enabled, dots in JSON keys are stored escaped as `%2E`. This commit makes `arrayElement` (bracket syntax `json['key.with.dots']`) and the `FunctionToSubcolumnsPass` rewrite aware of this setting, so that dotted keys are properly escaped before subcolumn lookup. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…:ClickHouse/ClickHouse into json-array-element-syntax
Document the `json['key']` bracket syntax in the JSON type documentation page and in the `arrayElement` FunctionDocumentation. Fix `arrayElement` for JSON when both arguments are constant: `useDefaultImplementationForConstants` unwraps them into plain 1-row columns, so `executeJSON` must also accept a non-const `ColumnString` with 1 row. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…:ClickHouse/ClickHouse into json-array-element-syntax
…ntChain`
The `optimizeJSONArrayElementChain` function in `FunctionToSubcolumnsPass`
was missing the `sourceHasColumn` check that all neighbouring subcolumn
optimizers use. Without it, if a table contains a physical column whose
name happens to equal the generated JSON subcolumn name (e.g. `json.@`a``
for `json['a']`), the optimizer would silently rewrite `json['a']` to a
`ColumnNode` pointing at that physical column instead of at the JSON
subcolumn, returning wrong results when `optimize_functions_to_subcolumns`
is enabled.
Fix: apply the same two-condition guard used everywhere else:
if (sourceHasColumn(ctx.column_source, full_name) || !canOptimizeToSubcolumn(...))
return;
A regression test is added that creates a table with a physical column
`\`json.@\`a\`\`` alongside a `json JSON` column, inserts rows with
`{"a": 42}` / `{"a": 100}`, and verifies that `json['a']` returns the
JSON values (not the physical column values 999/888) regardless of the
`optimize_functions_to_subcolumns` setting.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
`arrayElementOrNull` shares the same `FunctionArrayElement` template as `arrayElement`, but the JSON code path ignores `is_null_mode` — a missing typed key returns the default value (e.g. 0) instead of NULL. Rather than adding Nullable wrapping to the JSON subcolumn accessor, reject JSON arguments in `arrayElementOrNull` with a clear error pointing users to `arrayElement`. Guards are added in both `getReturnTypeImpl` and `executeImpl` so the error is raised regardless of how the function is invoked. Co-Authored-By: Claude Opus 4.6 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 113/136 (83.09%) · Uncovered code |
…rray-element-syntax
Resolve conflicts: - src/Functions/array/arrayElement.cpp: drop obsolete out-of-line create(); FunctionWithLowCardinalityFastPath now forwards context to the constructor. Keep both getReturnTypeImpl(ColumnsWithTypeAndName) and tryExecuteLowCardinality. - docs: newjson.md was removed on master (docs are source-generated); move the json['key'] bracket-syntax section into the embedded documentation in src/DataTypes/DataTypeObject.cpp. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes30 object files changed (+107.94 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units940 translation units recompiled, 6909 s compile time in total, 940 of them have a recent master baseline. |
| FunctionDocumentation::Arguments arguments = { | ||
| {"arr", "The array to search. [`Array(T)`](/sql-reference/data-types/array)."}, | ||
| {"n", "Position of the element to get. [`(U)Int*`](/sql-reference/data-types/int-uint)."} | ||
| {"arr", "The array to search. [`Array(T)`](/sql-reference/data-types/array). Or a [`JSON`](/sql-reference/data-types/newjson) column."}, |
There was a problem hiding this comment.
By the way Map also already supported arrayElement, but not mentioned here
There was a problem hiding this comment.
🕵 Good catch — addressed: the arrayElement documentation now lists Map alongside Array, QBit and JSON in the description, the argument descriptions and the returned value, with a SELECT map('a', 1, 'b', 2)['b'] example. arrayElementOrNull documents the Map behaviour too (an absent key gives NULL instead of the value type's default).
…rray-element-syntax
The `QBit` and `JSON` first-argument forms were described in two differently shaped paragraphs, and `Map` was not documented at all even though `m['key']` is `arrayElement`. List all non-`Array` first arguments in one parallel structure and extend the argument, returned value and example sections accordingly, for both `arrayElement` and `arrayElementOrNull`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rray-element-syntax
Master replaced `canOptimizeToSubcolumn` with `canOptimizeToExpectedSubcolumn`, which additionally checks the substreams path of the resolved subcolumn, so the JSON bracket rewrite in `FunctionToSubcolumnsPass` no longer compiled after the merge. The rewrite means the JSON combined (`@`) subcolumn of the accessed path, so it now asks for exactly that substream via a new `SerializationObjectCombinedPath::isCombinedPathSubcolumn` predicate. As a side effect, a `Tuple` element or a typed path that happens to claim the same flat subcolumn name no longer diverts the rewrite. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address review: `arrayElement` recognized only a bare `DataTypeObject`, so `nullable_json['a']` fell through to the legacy array path and failed with "First argument ... must be array", even though `nullable_json.a` and `tupleElement(nullable_json, 'a')` already work. Schema inference and existing tables commonly produce `Nullable(JSON)`, so the bracket syntax disappeared as soon as the carrier became nullable. `getReturnTypeImpl` now unwraps `Nullable(JSON)` and promotes the extracted path with `makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe`, and `executeJSON` unwraps `ColumnNullable(ColumnObject)` and folds the outer null map into the extracted path with the same rules as `tupleElement`: a path that can represent NULL (`Dynamic`, `Variant`, `Nullable`, `LowCardinality(Nullable)` or a type wrappable into `Nullable`) gets the mask OR-ed in, a typed path that has no NULL representation (`Array`, `Map`) is default-filled. The result is identical in value and in type to reading the subcolumn directly. `arrayElementOrNull` keeps rejecting JSON. The analyzer rewrite needs no change: `FunctionToSubcolumnsPass` keys its transformers on the column's type id, which is `Nullable` and not `Object` for such a column, so bracket access on a `Nullable(JSON)` column is simply not rewritten and behaves the same with and without `optimize_functions_to_subcolumns`. The new test also pins the semantics of chained bracket access over a path that holds a scalar in one row and an object in another, which a review raised as well: under `optimize_functions_to_subcolumns` the chain is flattened into the JSON path and matches the dot syntax `json.c.d` (`NULL` for the scalar row), and without it the outer access goes through the `Dynamic` type mismatch rules. This divergence is the author's deliberate trade-off for the subcolumn optimization; the test makes it explicit instead of leaving it undocumented. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…syntax # Conflicts: # src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp
…are the real subcolumn type for chained JSON bracket access Master now passes the whole `ColumnContext` and the type the rewrite is declared to produce. The `json['c']['d']` rewrite declared `Dynamic` for every chain, but a typed path such as `JSON(c.d UInt32)` resolves in storage to `UInt32`, so the stricter check refused the rewrite. Declare the type storage really produces and cast back to the type of the original expression, as the single-key case already does. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…`arrayElement`
The JSON-specific `getReturnTypeImpl` required a constant `String` key and rejected
`json[CAST('a', 'Nullable(String)')]` and `json[CAST(NULL, 'Nullable(String)')]` at analysis, while the
`Array` and `Map` overloads and `executeImpl` already follow the nullable-key convention. Resolve the key
through its nested column, return `Nullable(Nothing)` for a `NULL` key and promote the result for a nullable
key the way a `Nullable(JSON)` carrier does.
Also reword the `Nullable(JSON)` documentation: bracket access follows the nullability rules of `json.key`,
so a non-nullable typed path such as `Array` keeps its default value for a `NULL` row.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
@Avogar @vdimir @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add support for accessing JSON subcolumns using bracket syntax, e.g.
json['key1']['key2'], which the parser translates to nestedarrayElementcalls.Workflow [PR]
Sync PR [sync-upstream/pr/107039]
Version info
26.9.1.1413(included in26.9and later)