Repository navigation
Support PostgreSQL regexp operators and make psql \d work over the PostgreSQL protocol - #115066
Conversation
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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
# Conflicts: # docs/en/sql-reference/operators/index.md # src/Server/PostgreSQLHandler.cpp
|
Workflow [PR], commit [cee95f4] Summary: ✅
AI ReviewSummaryThis PR adds PostgreSQL-style regexp operators, expands the PostgreSQL-protocol compatibility catalog so Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 328/355 (92.39%) · Uncovered code |
Build profile diff (arm_release)Comparing Binary sizes
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
|
| 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.
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.
| 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\""); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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
left a comment
There was a problem hiding this comment.
Overall LGTM.
…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
…niqueness-and-case Follow-up to ClickHouse#115066: case-insensitive `pg_catalog` qualifier and unique synthetic oids
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):
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 thematchfunction),~*(case-insensitive match),!~and!~*(negations). The\d,\dt,\dvcommands ofpsqlnow work when connected to ClickHouse over the PostgreSQL compatibility protocol, and a failed query no longer terminates the connection.psqlcould not run its\dcommand against ClickHouse over the PostgreSQL wire protocol:This fixes every layer of that incompatibility:
~,~*,!~,!~*, desugaring tomatchand the new functionsmatchCaseInsensitive,notMatch,notMatchCaseInsensitive(trivialMatchImplvariants). The KQL dialect, which previously consumed its own!~operator as two error tokens, is adjusted to accept the new single token.pg_catalog.schema qualifier from incoming queries at the token level, mapping references such aspg_catalog.pg_classonto the emulated per-session catalog views.pg_classview now contains the actual tables of the current database (withrelname,relnamespace,relowner,relam,relkind),pg_namespacecontains the real databases, and apg_amview is added (newerpsqlversions join it). The previous fixed rows are preserved for driver compatibility.pgGetUserById(aliaspg_get_userbyid) andpgTableIsVisible(aliaspg_table_is_visible) support the catalog query psql sends.ErrorResponseand returns to theReadyForQuerystate, 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:
Known limitation:
\d <name>(describing a specific table) sends follow-up queries usingOPERATOR(pg_catalog.~)syntax,COLLATE pg_catalog.defaultandformat_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
26.8.1.1919(included in26.8and later)