Repository navigation
Add parseISO8601Duration - #116993
Add parseISO8601Duration#116993
parseISO8601Duration#116993Conversation
Parses an ISO 8601 duration string into a number of seconds, so that users do not have to assemble it from `extract` calls and a chain of regular expressions. The year designator and the month designator before `T` are rejected. Neither has a fixed length in seconds, so converting them needs either a reference date or an arbitrary average, and the averages already present in the codebase disagree with one another: `parseTimeDelta` uses 365 days and 30.5 days, while `IntervalKind::toAvgSeconds` uses 365.2425 days. Rejecting the two ambiguous designators keeps the function exact and follows `java.time.Duration`, which parses only `PnDTnHnMn.nS`, and `Temporal.Duration.total`, which refuses calendar units without a reference point. Closes: ClickHouse#116905
|
Workflow [PR], commit [535253c] Summary: ✅
AI ReviewSummaryThis PR adds Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 535253c.
Changed lines: Changed C/C++ lines covered: 177/180 (98.33%) · Uncovered code |
Components were accumulated straight into a `Float64`, so a long enough run of digits overflowed to infinity and was returned as a value rather than reported as an error. Two checks are needed, not one: a component can be finite on its own and still overflow once it is scaled to seconds, so the total is checked separately. `P` followed by 304 nines and `D` is finite as a component and infinite as a number of seconds. Found by the automatic review on the pull request.
|
Fixed in d7d7be7. Two checks were needed rather than one. A component can be finite on its own and still overflow once it is scaled to seconds — Small note on the repro in the review: |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes3 object files changed (+230.68 KiB total), 1 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 units7 translation units recompiled, 6 s compile time in total, 6 of them have a recent master baseline. |
The function deliberately departs from ISO 8601 in four ways, and only the rejection of `Y` and date-position `M` was written down. Accepting a fraction on any component rather than only the lowest-order one, allowing `W` alongside the other designators, and rejecting both comma decimals and signed durations are all user-visible, so they belong in the reference page the `FunctionDocumentation` generates. The stateless test also never exercised the comma or the sign, which are the two easiest to lose during a parser cleanup. Requested in the automatic review on the pull request.
|
Both addressed in b9aeb7a. Docs — the description now covers all four deliberate deviations rather than just the Tests — added Worth noting the two rejections arrive by different routes, which is why both spellings are tested: a sign fails the leading |
|
@yariks5s can we please merge this too? |
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds a new ClickHouse scalar function parseISO8601Duration that converts ISO 8601 duration strings into seconds (Float64), with explicit rejection of year/month designators.
Changes:
- Implements
parseISO8601Durationwith validation and detailed error reporting. - Adds stateless query tests for valid/invalid inputs, overflow handling, and argument validation.
- Documents function behavior and design constraints in the function registration docs.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
src/Functions/parseISO8601Duration.cpp |
Adds the new function implementation and user-facing documentation. |
tests/queries/0_stateless/05048_parse_iso8601_duration.sql |
Adds functional and negative tests covering parsing rules and errors. |
tests/queries/0_stateless/05048_parse_iso8601_duration.reference |
Adds expected outputs for the successful test cases. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
The bullet list said seconds may carry a fractional part, while a later paragraph said any component may. Only the second is true, so state it once, next to the list it qualifies. Requested in the Copilot review on the pull request.
|
Thanks — one of the three is a real inconsistency and is fixed in 14a6988. The other two I do not think apply here. Fractional part in the docs — fixed. The bullet list attached the fraction to
Explicit includes for |
yariks5s
left a comment
There was a problem hiding this comment.
Also, in the issue it was requested to have OrNull and OrZero variants. Do you plan to make them or we don't need them anymore?
There was a problem hiding this comment.
SELECT parseISO8601Duration(x)
FROM (SELECT CAST(arrayJoin(['PT1S', 'PT2S']) AS LowCardinality(String)) AS x);I think this will throw BAD_ARGUMENTS, because unused empty dictionary is parsed
There was a problem hiding this comment.
useDefaultImplementationForLowCardinalityColumns is not overridden here, so it defaults to true (IFunction.h:100) and the function is applied to the dictionary, which carries the unused empty default that my parser rejects.
I could not confirm that without a build, so I have added your query as a test case in 6e6f243 instead. If it throws, Fast test will now say so and the fix is to override that implementation and handle the column directly. Leaving this open until CI reports.
There was a problem hiding this comment.
Update: you were right, and CI reproduced it exactly on 6e6f243:
Code: 36. DB::Exception: Invalid argument of function parseISO8601Duration:
the duration is empty, str: "": while executing function parseISO8601Duration
on arguments __table1.x LowCardinality(String)
LowCardinality(size = 0, UInt8(size = 0), Unique(size = 1, String(size = 1)))
The dictionary always carries the default empty string whether or not any row references it, so the function was asked to parse "".
Fixed in 0ded5d8 by overriding canBeExecutedOnDefaultArguments, which is the same opt-out throwIf and digits use for this reason - the default LowCardinality implementation stays in place. Fast test passes on 0ded5d89.
There was a problem hiding this comment.
SELECT parseISO8601Duration(x)
FROM (SELECT arrayJoin(CAST([NULL, 'PT1S'] AS Array(Nullable(String)))) AS x);I think this example will throw as well.
There was a problem hiding this comment.
useDefaultImplementationForNulls defaults to true (IFunction.h:82), so the function runs over whatever sits under the null map. Added as a test case in the same commit, with sum so the expected value does not depend on arrayJoin ordering.
Worth noting parseTimeDelta and parseDateTime have the same shape with neither implementation overridden, so if this is a real bug it is not confined to this PR.
There was a problem hiding this comment.
Update: right as well, though the test aborted on the LowCardinality query before reaching this one, so rather than spend another CI round finding out I traced the mechanism.
defaultImplementationForNulls runs the function over createBlockWithNestedColumns, i.e. over the values sitting under the null map, and only filters those rows out when null_ratio >= short_circuit_function_evaluation_for_nulls_threshold. That threshold defaults to 1.0, so the skip only happens when every row is null - the single non-null row in your example is enough to reach the empty string under the null and throw.
Fixed in the same commit by taking useDefaultImplementationForNulls off and handling the null map directly, so only values the caller actually supplied are parsed. The test now also covers parseISO8601Duration(NULL), a Nullable(String) null, and the Nullable(Float64) return type.
…guments `introduced_in` said 26.10; the tree is at 26.9.1.1-testing, so a function merged now ships in 26.9. Both `LowCardinality` and `Nullable` reach the function through the default implementations, which apply it to the dictionary and to the values under the null map. Neither position holds a valid duration, so if the function throws on them the two new cases fail and say so, rather than the behaviour being argued about. Raised in review on the pull request.
|
Thanks — all three addressed in 6e6f243.
For what it's worth your reasoning looks sound to me: I used
|
…ongside the data Both default implementations hand the function values that no row asked about. The `LowCardinality` one applies it to the whole dictionary, which always contains the default empty string whether or not any row references it. The `Nullable` one applies it to the nested column under the null map, whose contents are that column's defaults. An empty string is not a duration, so in both cases the function threw and failed the whole query. Opt out of executing on default arguments, which is what keeps the dictionary's unused default out of the call, and handle the null map directly so that only rows the caller actually supplied are parsed. `short_circuit_function_evaluation_for_nulls_threshold` defaults to 1.0, so the `Nullable` path is only skipped when every row is null; a single non-null row was enough to reach the values under the null map. Co-Authored-By: Claude Opus 5 <[email protected]>
`sum` ignores nulls, so the mixed `Nullable(String)` case passed whether the null row came back as null or as zero, and it would have kept passing if the null map were dropped. Return the rows themselves, ordered with `NULLS LAST` so the expected output does not depend on `arrayJoin` ordering. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@yariks5s both of your cases were real - thank you for catching them. Neither was covered and both would have shipped. The Both fixed in 0ded5d8:
On One thing worth flagging beyond this PR: |
`useDefaultImplementationForDynamic` and `useDefaultImplementationForVariant` both default to `useDefaultImplementationForNulls`, so taking that off to handle the null map directly disabled them as a side effect. That left `getReturnTypeForDefaultImplementationForDynamic` unreachable and sent a `Dynamic` argument into `getReturnTypeImpl`, where `validateFunctionArguments` sees `Dynamic` rather than `String` and rejects it. Both adaptors dispatch on the concrete type held in the column and handle null rows themselves, so enable them explicitly, as `UTMToGeo` does for the same reason. The new cases compare against the plain `String` result so they do not depend on how the adaptors spell the return type. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@navneet83 please update your branch with master, docs check in CI has been fixed today |
2b87762
|
@navneet83 @yariks5s — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Adds
parseISO8601Duration, which parses an ISO 8601 duration string and returns the number of seconds asFloat64.There's currently no way to do this in ClickHouse, so people end up assembling it from
extractcalls and a chain of regular expressions, which quietly breaks on fractional seconds and week designators. The issue has a good example of one.Years and months are rejected. Neither has a fixed length in seconds, so converting them needs either a reference date or an arbitrary average — and the averages already in the tree disagree with each other:
parseTimeDeltauses 365 days and 30.5 days,IntervalKind::toAvgSecondsuses 365.2425 days. Adding a third would make that worse.java.time.Durationparses onlyPnDTnHnMn.nSfor the same reason, andTemporal.Duration.totalrefuses calendar units without arelativeToreference.P1YandP1MthrowBAD_ARGUMENTSnaming the designator and saying what to use instead. There's more detail in the issue comment.Design decisions
A few things ISO 8601 leaves open, or that the issue didn't pin down:
Wcan be combined withD. ISO 8601:2004 treats the week designator as exclusive, butjava.time.Periodallows combining and nothing breaks.PT1,5S. ClickHouse rejects comma decimals elsewhere and I kept that consistent.PT1M1HandPT1S1Sthrow.Happy to change any of these if you'd rather they went the other way.
Closes: #116905
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
New function
parseISO8601Durationfor parsing ISO 8601 duration strings such asPT1H30Minto a number of seconds.Workflow [PR]
Sync PR [sync-upstream/pr/116993]