Skip to content

Support PostgreSQL regexp operators and make psql \d work over the PostgreSQL protocol - #115066

Merged
alexey-milovidov merged 12 commits into
masterfrom
pg-regexp-operators
Aug 22, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
pg-regexp-operators

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

Related: #25757

Disclaimer: I do not like Postgres operators! I think they are ugly. It makes the language similar to Bash and Perl. They use operators instead of functions only because of some design drawbacks related to the index analysis.

Changelog category (leave one):

  • Improvement

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

Support PostgreSQL-style regular expression match operators: ~ (an alias for the match function), ~* (case-insensitive match), !~ and !~* (negations). The \d, \dt, \dv commands of psql now work when connected to ClickHouse over the PostgreSQL compatibility protocol, and a failed query no longer terminates the connection.


psql could not run its \d command against ClickHouse over the PostgreSQL wire protocol:

alexey-milovidov=> \d
ERROR:  Query execution failed.
DB::Exception: Exclamation mark can only occur in != operator: Syntax error: failed at position 665 (!) (line 10, col 21): !~ '^pg_toast' ...
SSL connection has been closed unexpectedly
The connection to the server was lost. Attempting reset: Succeeded.

This fixes every layer of that incompatibility:

  • The lexer and the expression parser now understand the PostgreSQL regular expression match operators ~, ~*, !~, !~*, desugaring to match and the new functions matchCaseInsensitive, notMatch, notMatchCaseInsensitive (trivial MatchImpl variants). The KQL dialect, which previously consumed its own !~ operator as two error tokens, is adjusted to accept the new single token.
  • The PostgreSQL wire protocol handler removes the pg_catalog. schema qualifier from incoming queries at the token level, mapping references such as pg_catalog.pg_class onto the emulated per-session catalog views.
  • The emulated pg_class view now contains the actual tables of the current database (with relname, relnamespace, relowner, relam, relkind), pg_namespace contains the real databases, and a pg_am view is added (newer psql versions join it). The previous fixed rows are preserved for driver compatibility.
  • New compatibility functions pgGetUserById (alias pg_get_userbyid) and pgTableIsVisible (alias pg_table_is_visible) support the catalog query psql sends.
  • A failed query now keeps the connection alive: the server sends ErrorResponse and returns to the ReadyForQuery state, like PostgreSQL. The connection is still closed if some result bytes were already sent for the failed statement, since the output stream could be cut in the middle of a protocol message.

The result:

psql (18.4, server 26.7.1.1)
db_psql_test=> \d
              List of relations
    Schema    |    Name     | Type  | Owner
--------------+-------------+-------+--------
 db_psql_test | t_described | table | pguser
 db_psql_test | t_mt        | table | pguser
 db_psql_test | v_described | view  | pguser
(3 rows)

Known limitation: \d <name> (describing a specific table) sends follow-up queries using OPERATOR(pg_catalog.~) syntax, COLLATE pg_catalog.default and format_type, which are not supported yet; the error is now reported without dropping the connection.


Workflow [PR]
Sync PR [sync-upstream/pr/115066]

Version info

  • Merged into: 26.8.1.1919 (included in 26.8 and later)

robot-clickhouse and others added 3 commits August 17, 2026 02:04
Add the PostgreSQL-style regular expression match operators: `~`
(sugar for `match`), `~*` (`matchCaseInsensitive`), `!~`
(`notMatch`) and `!~*` (`notMatchCaseInsensitive`). The three new
functions are trivial variants of `match` via `MatchImpl` traits.

psql sends `!~` in the query behind the `\d` command, which
previously failed to lex: "Exclamation mark can only occur in !=
operator".

The KQL dialect matched its own `!~` operator as two tokens (the
formerly-invalid `!` followed by `~`); `genEqOpExprCis` now also
accepts the new single `!~` token.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Remove the `pg_catalog.` qualifier from incoming queries at the
  token level: the catalog tables are emulated with per-session
  temporary views, and ClickHouse has no `pg_catalog` database.
- Fill the `pg_class` view with the tables of the current database
  (the analog of the PostgreSQL search path) and the `pg_namespace`
  view with the real databases; keep the fixed rows for driver
  compatibility. Add the `pg_am` view: newer psql versions join it.
- Add the compatibility functions `pgGetUserById` (`pg_get_userbyid`)
  and `pgTableIsVisible` (`pg_table_is_visible`) used by the query
  behind `\d`.
- Keep the connection alive after a failed query: PostgreSQL sends
  `ErrorResponse` and returns to the `ReadyForQuery` state instead
  of closing the connection. The connection is still torn down if
  some result bytes have already been sent for the failed statement,
  because the output stream may be cut in the middle of a message.

Co-Authored-By: Claude Fable 5 <[email protected]>
The test asserted the old behavior in which a failed query tore the
PostgreSQL connection down ("SSL connection has been closed
unexpectedly"). The server now sends `ErrorResponse` and keeps the
connection alive, so psycopg2 raises `SqlRoutineException` and the
same connection stays usable.

Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 18, 2026, 12:02 AM

# Conflicts:
#	docs/en/sql-reference/operators/index.md
#	src/Server/PostgreSQLHandler.cpp
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cee95f4]

Summary: ✅


AI Review

Summary

This PR adds PostgreSQL-style regexp operators, expands the PostgreSQL-protocol compatibility catalog so psql \d/\dt/\dv work, and keeps PostgreSQL sessions alive after safe query failures. The overall direction is good, but there are still two catalog-compatibility gaps in PostgreSQLHandler: bare pg_catalog qualifiers are only rewritten in the exact lowercase spelling, and the synthetic OIDs used to wire pg_namespace and pg_class together are hash-based rather than unique.

Findings

⚠️ Majors

  • src/Server/PostgreSQLHandler.cpp:609 The pg_catalog qualifier rewrite violates PostgreSQL's case-insensitive bare-identifier contract. PG_CATALOG.pg_class and similar spellings bypass the rewrite because both the fast path and the token check only match lowercase pg_catalog, so the query still fails with a real-database lookup instead of using the emulated catalog objects.
  • src/Server/PostgreSQLHandler.cpp:1354 The emulated catalog now treats pg_namespace.oid and pg_class.relnamespace as relational keys, but both are only 32-bit hashes. That breaks the uniqueness invariant of PostgreSQL OIDs: a collision between two visible database names makes the join ambiguous, so \d/\dt can duplicate or mislabel tables under the wrong schema.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Make bare pg_catalog stripping case-insensitive for unquoted identifiers.
  • Replace the hash-based synthetic OID mapping with a collision-free one for the emulated catalog keys.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 328/355 (92.39%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 18, 2026
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cee95f4b1 with master 577afb433 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.54 MiB 701.62 MiB -2.92 MiB (-0.42%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

58 object files changed (+1.52 MiB total), 5 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/notMatchCaseInsensitive.cpp.o new 347.59 KiB +347.59 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/matchCaseInsensitive.cpp.o new 346.70 KiB +346.70 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/notMatch.cpp.o new 331.34 KiB +331.34 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/pgGetUserById.cpp.o new 262.80 KiB +262.80 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/pgTableIsVisible.cpp.o new 252.36 KiB +252.36 KiB

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1373 translation units recompiled, 7628 s compile time in total, 1368 of them have a recent master baseline.

Job report

Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
An extended-protocol `Execute` failure now keeps the session alive only
while nothing has been sent for the failed statement, mirroring the
`out_bytes_before_statement` check of `processQuery`. Once result bytes
were emitted, the output stream may be cut in the middle of a protocol
message, so the connection is torn down instead of returning to the
`ReadyForQuery` state.

The `pg_namespace` and `pg_class` compatibility views are switched from
`SQL SECURITY DEFINER` to `SQL SECURITY INVOKER`, so `system.databases`
and `system.tables` apply the session user's visibility filtering: both
tables are implicitly `SELECT`able by every user and hide rows the user
has no `SHOW` privilege for. Definer rights allowed a user with narrow
grants to enumerate databases and tables they are not allowed to see.
Comment on lines +609 to +621
if (!query.contains("pg_catalog"))
return query;

std::vector<Token> tokens;
Lexer lexer(query.data(), query.data() + query.size());
for (Token token = lexer.nextToken(); !token.isEnd(); token = lexer.nextToken())
tokens.push_back(token);

auto is_pg_catalog = [](const Token & token)
{
std::string_view text(token.begin, token.size());
return (token.type == TokenType::BareWord && text == "pg_catalog")
|| (token.type == TokenType::QuotedIdentifier && text == "\"pg_catalog\"");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The pg_catalog-qualifier rewrite is still case-sensitive for unquoted identifiers. PostgreSQL folds bare identifiers to lower case, so queries such as SELECT * FROM PG_CATALOG.pg_class or SELECT PG_CATALOG.pg_table_is_visible(1) should hit the emulated objects too. Today both the fast path query.contains("pg_catalog") and the bareword check text == "pg_catalog" miss those spellings, so the request falls through to a real database lookup and fails instead of behaving like PostgreSQL.

Please make the bareword match ASCII-case-insensitive, and either make the substring fast path case-insensitive too or drop it.

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.

🕵 Addressed in the follow-up #115960 (this PR was already merged). The bareword match now uses equalsCaseInsensitive, and the substring fast path is a case-insensitive std::search, so PG_CATALOG.pg_class and PG_CATALOG.pg_table_is_visible(1) are rewritten too. The quoted spelling stays case-sensitive, matching PostgreSQL, so "PG_CATALOG" is still a different (non-existent) schema. Covered by the new test_catalog_qualifier_is_case_insensitive.

SELECT
toUInt32(16384 + sipHash64(database, name) % 4294900000) AS oid,
name AS relname,
toUInt32(16384 + sipHash64(database) % 4294900000) AS relnamespace,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

pg_namespace.oid and pg_class.relnamespace are now being used as a key/foreign-key pair, but this mapping is not unique: both values are just sipHash64(...) reduced into a 32-bit space. Once two visible database names collide, every pg_class row for the current database joins to both pg_namespace rows, so \d / \dt can duplicate tables or show them under the wrong schema. The same issue exists for pg_class.oid itself if a later catalog query uses it as a key.

Because the contract here is “synthetic PostgreSQL OIDs”, these IDs still need to be unique within the emulated catalog. Please derive a collision-free session-local numbering (for example by enumerating visible databases/tables in a stable order and reusing that mapping inside pg_class) instead of hashing into 32 bits.

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.

🕵 Addressed in the follow-up #115960 (this PR was already merged). The hashes are replaced by a collision-free enumeration: databases and the tables of the current database are numbered in the stable order of their names, with namespaces taking the even oids above 16384 and relations the odd ones, so the two enumerations cannot collide with each other either. Covered by the new test_catalog_oids_are_unique.

@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.

Overall LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 22, 2026
Merged via the queue into master with commit 12cc4bd Aug 22, 2026
349 of 350 checks passed
@alexey-milovidov
alexey-milovidov deleted the pg-regexp-operators branch August 22, 2026 21:18
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 5, 2026
…que synthetic oids

Two findings from the review of ClickHouse#115066 that landed unaddressed.

1. The `pg_catalog` qualifier rewrite was case-sensitive. PostgreSQL folds
   unquoted identifiers to lower case, so `SELECT * FROM PG_CATALOG.pg_class`
   and `SELECT PG_CATALOG.pg_table_is_visible(1)` name the same objects as the
   lower-case spelling, but both the substring fast path and the bareword
   comparison missed them, and the query fell through to a real database lookup
   and failed. The bareword match and the fast path are now ASCII
   case-insensitive. A quoted identifier keeps its case in PostgreSQL, so
   `"PG_CATALOG"` is deliberately still a different (non-existent) schema.

2. `pg_namespace.oid` and `pg_class.oid` / `pg_class.relnamespace` were
   `sipHash64` values reduced into a 32-bit space. They are used by clients as a
   key/foreign-key pair, so a collision between two visible database names would
   join every `pg_class` row of the current database to both `pg_namespace`
   rows, making `\d` / `\dt` duplicate tables or show them under the wrong
   schema. The oids are now synthesized by enumerating the visible databases and
   tables in the stable order of their names, which is collision-free within the
   emulated catalog; namespaces take the even oids above 16384 and relations the
   odd ones, so the two enumerations cannot collide with each other either.

Adds `test_catalog_qualifier_is_case_insensitive` and
`test_catalog_oids_are_unique` to `test_postgresql_protocol`.

Related: ClickHouse#115066
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 5, 2026
…niqueness-and-case

Follow-up to ClickHouse#115066: case-insensitive `pg_catalog` qualifier and unique synthetic oids

This branch was successfully deployed

1 active deployment
staging - docs — cee95f4b Deployed Aug 22, 2026 by mintlify[bot]
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.

3 participants