Skip to content

Add REGEXP_SUBSTR as alias of regexpExtract - #105122

Merged
alexey-milovidov merged 9 commits into
masterfrom
alias-regexp-substr
Jun 6, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
alias-regexp-substr

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 16, 2026 •

Copy link
Copy Markdown
Member

REGEXP_SUBSTR is the standard name used by Oracle, MySQL 8+, and Snowflake for the same operation that ClickHouse already exposes as regexpExtract (and as REGEXP_EXTRACT for Spark compatibility). Adding a case-insensitive alias spares those dialects a rewrite.

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added REGEXP_SUBSTR as a case-insensitive alias of regexpExtract for Oracle/MySQL/Snowflake compatibility.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Low Risk
Low risk: adds a new case-insensitive function alias and a stateless query test, without changing regexpExtract behavior or data handling.

Overview
Adds REGEXP_SUBSTR as a case-insensitive alias of regexpExtract for Oracle/MySQL/Snowflake SQL dialect compatibility.

Introduces a new stateless query test (04241_alias_regexp_substr) verifying the alias works with default and explicit capture group indexes and with lowercase regexp_substr.

Reviewed by Cursor Bugbot for commit 9c7198d. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.438

`REGEXP_SUBSTR` is the standard name used by Oracle, MySQL 8+, and
Snowflake for the same operation that ClickHouse already exposes as
`regexpExtract` (and as `REGEXP_EXTRACT` for Spark compatibility).
Expose `REGEXP_SUBSTR` as a case-insensitive alias to spare these
dialects a rewrite.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52d4c6e]

Summary: ✅


AI Review

Summary

This PR adds REGEXP_SUBSTR as a case-insensitive alias of regexpExtract plus a stateless test for the alias. The implementation is a mechanically safe alias, but the PR still advertises Oracle/MySQL/Snowflake compatibility while intentionally preserving regexpExtract capture-group semantics, which diverge from those dialects for common REGEXP_SUBSTR calls.

PR Metadata

The Improvement category is reasonable, and a changelog entry is required and present. The entry overstates dialect compatibility because this is not an Oracle/MySQL/Snowflake-compatible REGEXP_SUBSTR implementation. Suggested replacement:

Added REGEXP_SUBSTR as a case-insensitive alias of regexpExtract. It follows regexpExtract capture-group semantics rather than Oracle/MySQL/Snowflake REGEXP_SUBSTR signatures.

Missing Context / Blind Spots
  • ⚠️ Full CI for commit 52d4c6ee0a547529b29839e61da78f9806e7eb2f was still pending when checked; Config Workflow and Style check had passed, and the Praktika report showed no failed jobs yet. Required CI completion would close this gap.
Findings

⚠️ Majors

  • src/Functions/regexpExtract.cpp:293 [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/105122#discussion_r3252967209] The PR promises an Oracle/MySQL/Snowflake-compatible REGEXP_SUBSTR name, but the alias resolves directly to regexpExtract: two-argument calls default to capture group 1 rather than the whole match, patterns without capture groups can throw INDEX_OF_POSITIONAL_ARGUMENT_IS_OUT_OF_RANGE, and the third argument is a capture-group index rather than a start position. This can silently change migrated query results or turn valid dialect queries into exceptions. I still consider this real because the current source comment, PR body, and changelog continue to describe dialect compatibility while the implementation intentionally does not emulate those dialect signatures. Suggested fix: implement a dedicated REGEXP_SUBSTR function with the compatible default/signature, or drop/rename the compatibility claim and document that this is only a regexpExtract alias with regexpExtract semantics.
Tests
  • ⚠️ The new stateless test validates the alias behavior that diverges from the advertised dialects, including REGEXP_SUBSTR(..., 2) as capture-group selection. If the compatibility claim remains, add focused coverage for the dialect boundary: two-argument whole-match behavior and the third argument as start position/occurrence semantics as applicable.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: either make REGEXP_SUBSTR match the advertised Oracle/MySQL/Snowflake behavior, or make the source comment, test wording, and changelog explicit that this is only a regexpExtract alias and not dialect-compatible REGEXP_SUBSTR.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 16, 2026
Comment thread src/Functions/regexpExtract.cpp Resolved
alexey-milovidov added a commit that referenced this pull request May 16, 2026
Recent compatibility PRs added case-insensitive aliases and parser sugar
that make several of the SQLStorm rewrites unnecessary:

  - `STDDEV`            -> `stddevPop`            (#105120)
  - `array_to_string`   -> `arrayStringConcat`    (#105121)
  - `REGEXP_SUBSTR`     -> `regexpExtract`        (#105122)
  - `CARDINALITY`       -> `length`               (#105123)
  - `unnest()` function -> `arrayJoin()`          (#105124)
  - `STRING_AGG`        -> `groupConcat`          (#105125)
  - `date_part(unit,e)` -> `EXTRACT(unit FROM e)` (#105127)
  - `expr OP ANY/ALL(array_literal)`              (#105129)

`ARRAY_AGG`, `TRANSLATE`, and `EXTRACT(EPOCH|DOW|... FROM ...)` were
already supported by ClickHouse before these PRs.

Removed the corresponding rewrite calls and helper functions
(`rewrite_string_agg`, `rewrite_array_agg`, `rewrite_date_part`,
`rewrite_stddev`, `rewrite_extract_epoch`, the EXTRACT(DOW) inline
rewrite, `rewrite_any_comparison`, and the trailing
`unnest(...) -> arrayJoin(...)` substitution). Also dropped the
unreferenced no-op helpers (`rewrite_extract_unit`, `rewrite_fetch_offset`,
`rewrite_interval`, `rewrite_cast_timestamp`, `rewrite_current_timestamp`,
`rewrite_bool_literals`, `rewrite_ilike`, `rewrite_no_supertype`).

The PostgreSQL `LATERAL` / `CROSS JOIN UNNEST(...)` table-source forms,
`arrayJoin(...)` in JOIN position, PG-specific casts, `AT TIME ZONE`,
`STRING_AGGDistinct` (a mangled-name artifact), and the still-unsupported
function rewrites (`string_to_array`, `regexp_split_to_array`, `RANDOM`,
`TO_TIMESTAMP`, `ARRAY_LENGTH`, `SPLIT_PART`, `age`) are still rewritten.

Net change: -329 lines from rewrite_queries.py and -75 lines from the
tests (the `TestRewriteAnyComparison` class is removed since the rewrite
it covered no longer exists).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This was fixed by #105146. Let's update the branch.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, fix "Logical error: 'Inconsistent AST formatting between 'ExpressionList' and 'ExpressionList' in the query: (STID: 1941-1bfa)" or provide a link to the fix here.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov The failing AST fuzzer query on commit b1d08109 is the STATISTICS subvariant of STID 1941-1bfa, fixed by #104991 (merged 2026-05-31T08:41:21Z, commit 5670bbaaf1d). The CI here ran 2026-05-29, two days before the fix landed. A rebase onto current master should clear it.

The trigger shape is not(a, b) (variadic-2 call on a unary function) inside a STATISTICS(...) argument list:

STATISTICS(toUInt64OrNull(not(toNullable(materialize(*, 1048575), alias868), isZeroOrNull(...)), 1048575), tdigest)

Inside CODEC / STATISTICS / BACKUP_NAME arguments, ASTFunction::formatImpl forces frame.allow_operators = false, so the multi-arg Function_tuple synthesised from not(a, b) falls back to the function-call form tuple(a, b). Re-parsing the formatted output sees tuple(...) wrapped in (...) from the outer not(...) argument list, so RoundBracketsLayer::getResultImpl sets parenthesized = true on the inner Function_tuple. The next format pass adds an extra (...) around it via IAST::decideParensEmission, breaking the round-trip:

  • First format: not(tuple(a, b))
  • Re-parsed, re-formatted: not((tuple(a, b)))

#104991 suppresses the redundant outer paren on multi-arg Function_tuple when frame.allow_operators == false. The fix is in src/Parsers/IAST.cpp decideParensEmission and is gated on func->name == "tuple", args.size() > 1, and !frame.allow_operators. Regression coverage for the STATISTICS shape is in tests/queries/0_stateless/04241_inconsistent_ast_codec_tuple_paren_round_trip_1941_1bfa.sql.

Remaining uncovered subvariants of STID 1941-1bfa (DESCRIBE TABLE (SELECT ... COLUMNS(multiIf(...)) ...) and qualifier-chained db.t.COLUMNS(*)) live in different parser/formatter paths and are still being tracked separately.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, let's update the branch, so that we will be able to merge this PR.

@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

The fix for STID 1941-1bfa (#104991) is now on master (merged 2026-05-31T08:41:21Z, commit 5670bbaaf1d), so rebasing this branch onto master or merging master in will clear the AST fuzzer failure.

I don't have push access to this branch (it lives on the ClickHouse org repo, ClickHouse:alias-regexp-substr, not a fork), so the branch update needs to come from you or a maintainer.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged.

Please update your branch to pick up the revert; the tests should pass again.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Updated the branch by merging current master (c45c299d344..52d4c6ee0a5, 526 commits, 0 conflicts). This picks up the fixes for all three previously-failing checks:

Built locally on ARM (clean) and verified 04241_alias_regexp_substr matches its reference (100 / 100 / 200 / 123). The change itself is just the two-line case-insensitive alias registration; no regexpExtract behavior is altered.

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.50% +0.10%
Functions 92.40% 92.30% -0.10%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 2/2 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Jun 6, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 6, 2026
Merged via the queue into master with commit 76307a6 Jun 6, 2026
166 checks passed
@alexey-milovidov
alexey-milovidov deleted the alias-regexp-substr branch June 6, 2026 00:26
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 6, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body claims the alias 'spares those dialects a rewrite', but the default-group semantics differ: MySQL/Oracle/Snowflake REGEXP_SUBSTR(str, pattern) returns the whole match, whereas ClickHouse regexpExtract (and thus this alias) defaults to capture-group index 1. For REGEXP_SUBSTR('100-200', '(\d+)-(\d+)') MySQL returns '100-200' but ClickHouse returns '100'. A user migrating queries verbatim may get different results unless they pass index 0. Worth a one-line caveat in the description.

  • Suggested addition:

    Note: ClickHouse regexpExtract defaults to capture-group index 1, while MySQL/Oracle/Snowflake REGEXP_SUBSTR returns the entire match. For whole-match semantics use index 0, e.g. REGEXP_SUBSTR('100-200', '(\d+)-(\d+)', 0).

Ignore this if the current title/body is intentional.

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

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants