Repository navigation
Reapply "Make postgresql and PostgreSQL engine work against a ClickHouse instance", with a fix for the cancel-request logical error - #112940
Conversation
…ckHouse instance" This reverts commit ea54b3c. The reason for the revert was a `Query context must be created after authentication` logical error in the `Stress test` jobs on master. It is not introduced by this change: `PostgreSQLHandler::cancelRequest` has needed an authenticated session that a PostgreSQL cancel request never has since sessions were introduced. This change only made the path reachable in CI, because it makes ClickHouse a libpq client against itself and `PostgreSQLSource` cancels the remote statement through `PQcancel`. The next commit fixes that bug.
A PostgreSQL client cancels a running statement by opening a second connection and sending a `CancelRequest` on it, carrying the `(process id, secret key)` pair the server handed out in `BackendKeyData`. By the protocol that connection never authenticates - the secret key is the credential - so `PostgreSQLHandler::cancelRequest` had no authenticated session, and `Session::makeQueryContext` threw `Query context must be created after authentication` (`LOGICAL_ERROR`). Cancel the query through the process list directly instead, which needs no session; the raw `KILL QUERY` output the old code wrote straight into the client socket, where the protocol expects no answer at all, is gone with it. The secret key never matched anything either: `BackendKeyData` was sent while `secret_key` was still zero, and every statement then re-randomized it, so the query id a cancel request resolved to was never the id of a running query. The key now belongs to the connection, as in PostgreSQL, where it identifies the backend rather than one statement, and every statement of the connection runs under `postgres:<connection id>:<secret key>`. Statements of one connection run one after another, so reusing the id is safe. Reachable by any PostgreSQL client that cancels a statement - `psql` on Ctrl-C, or the `pgx` driver in the issue below.
|
Workflow [PR], commit [4b3d39c] Summary: ✅
AI ReviewSummaryThis PR adds a lot of PostgreSQL-compatibility surface area — self-connect for the Findings
Final Verdict |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1116/1285 (86.85%) · Uncovered code |
`fetchPostgreSQLTableStructureImpl` looks the physical columns up in `current_schema()` when no schema is given, but the `with_replica_identity_index` query at the end of the same helper still fell back to a hardcoded `public`, so a caller asking for `replica_identity_columns` described the columns of one relation and the replica identity of another whenever the connected schema is not `public` - which, against a ClickHouse server, is every database other than one named `public`. On real PostgreSQL with the default search path `current_schema()` is `public`, so nothing changes there.
…s enough The flaky check failed `04665_postgresql_self_connect` with "Test runs too long (> 180s)": every self-connect opens a second connection and runs a handful of catalog queries on it, and the test spent eleven `clickhouse-client` invocations and six self-connects doing that, which is slow enough under a sanitizer on a loaded server to cross the limit (196 runs of that job passed, averaging 99s). The test now runs as a single client invocation, drops the `count()` read that the row-by-row read already covers, and the `PostgreSQL` engine, the explicit schema and the search path move to `04692_postgresql_self_connect_engine`. Both take about a second here. The blanket `GRANT SELECT ON system.*` is gone with it: `system.databases`, `system.tables` and `system.columns`, which the emulated `pg_namespace`, `pg_class` and `pg_attribute` are views over, are readable by every user - their rows are filtered by the user's own grants - so a grant on the table to read is all a self-connect needs. The one remaining `GRANT SELECT ON system.one` is for the table the first query reads, not for the catalog.
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/postgresCatalog.cpp.o |
new | 361.03 KiB | +361.03 KiB |
src/CMakeFiles/dbms.dir/Server/PostgreSQLHandler.cpp.o |
628.89 KiB | 841.02 KiB | +212.12 KiB (+33.73%) |
src/CMakeFiles/dbms.dir/Processors/Formats/PostgreSQLArrayText.cpp.o |
new | 89.39 KiB | +89.39 KiB |
src/CMakeFiles/dbms.dir/Core/PostgreSQLProtocol.cpp.o |
9.53 KiB | 35.22 KiB | +25.69 KiB (+269.51%) |
719 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
29 translation units recompiled, 146 s compile time in total, 27 of them have a recent master baseline.
|
Acknowledged. This failure is not caused by this PR: the PR does not touch |
|
Fixing PR: #119264 (mine, open). My "no fix is in progress" above was wrong: this is the release-build form of the race that PR fixes. On the attach path, a |
…nect The conflict in `ParserCopyQuery.cpp` is resolved by keeping this branch's non-throwing `COPY` option parser and applying master's acceptance of the terminating `;` (`isEndOfStatement`) to its option loop. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `COPY (query)` The option scan of `ParserCopyQuery::parseOptions` treated `WITH`, `AS`, standalone booleans and stray punctuation as inert, so e.g. `COPY t TO STDOUT WITH (FORMAT csv, false)` ran as `WITH (FORMAT csv)`. A boolean is now accepted only as the value of `HEADER`, `AS` only after `DELIMITER` / `NULL` / `QUOTE`, `WITH` only at the start of the options, and punctuation other than balanced parentheses and commas is rejected; the command is answered with "malformed option syntax". `COPY (SELECT 1) AS junk TO STDOUT` dropped the alias of the subquery and ran as `COPY (SELECT 1) TO STDOUT`; an alias is now a syntax error. The endpoint after `TO` / `FROM` is now required: the handler splits the statements on `;` before parsing, so `COPY t TO;` reached the parser as `COPY t TO` and ran as `COPY t TO STDOUT`, which the test `05331_postgresql_copy_trailing_semicolon` from master rejects. Its reference also loses the empty line after each `COPY ... TO STDOUT`: that came from the `CopyCompletionResponse` sent on master, while this branch ends the copy with `CopyDone` and `CommandComplete`, after which `psql` prints nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`rewritePgTableIsVisible` rewrote any `pg_table_is_visible(...)`, so `SELECT other.pg_table_is_visible(oid)` became `other.((oid) IN (...))`. The `pg_catalog.` qualifier is already removed by `removePgCatalogQualifier`, so a call that is still qualified belongs to another schema and is left alone. Co-Authored-By: Claude Opus 5.5 <[email protected]>
In PostgreSQL `format_type` is not strict, and a `NULL` type modifier means that no modifier is known, so introspection queries use `format_type(t.oid, NULL)`. The function now takes a `NULL` or `Nullable` type modifier and treats `NULL` as `-1`; only a `NULL` type OID gives `NULL`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le` and `format_type` with `NULL` Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 I merged master and resolved the conflict in |
…py-out, limits of the catalog refresh - `normalizeDecimal` checked the precision after padding the digits with the display-only leading zero, so a valid `Decimal256(76)` value like `0.0...01` (76 fractional digits) was rejected as a `numeric` or `numeric[]` prepared-statement parameter. Check the precision before padding. - A `COPY ... TO STDOUT` cancelled by `CancelRequest` / `KILL QUERY` is reported with SQLSTATE `57014` (as `COPY FROM STDIN` already is), not with the generic `2F000`. - `refreshCatalogOids` runs before any statement that mentions `pg_` and inherited the scan and complexity limits of the session, so e.g. `max_rows_in_set` could make an unrelated statement fail. Reset those limits in the internal context. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| /// to move them: a session that did `SET format_csv_delimiter = ';'` would otherwise get its | ||
| /// `COPY ... WITH (FORMAT csv, DELIMITER ',')` accepted and then served with `;`, which is the silent | ||
| /// shape mismatch the option list is there to prevent. The NULL marker of the CSV format is set | ||
| /// afterwards from `ASTCopyQuery::csv_null_marker`. | ||
| void pinCopyFormatSettings(const ContextMutablePtr & query_context) | ||
| { | ||
| query_context->setSetting("format_csv_delimiter", String(",")); |
There was a problem hiding this comment.
Because pinCopyFormatSettings leaves the CSV tuple settings at their defaults, COPY ... WITH (FORMAT csv) still inherits ClickHouse's bare-Tuple flattening on the PostgreSQL path. A column like Tuple(UInt8, UInt8) is advertised as one text column (convertDataTypeToPostgresColumnTypeSpec falls back to VARCHAR), but CSV / CSVWithNames will emit two CSV fields by default, and COPY FROM STDIN will symmetrically accept two fields into one column.
That breaks the PostgreSQL COPY contract for every bare Tuple column: CopyOutResponse still reports one column, while the payload/header carry two fields (x.1,x.2 / 1,2). Please pin output_format_csv_serialize_tuple_into_separate_columns, output_format_csv_header_serialize_tuple_into_separate_columns, and input_format_csv_deserialize_separate_columns_into_tuple to false here (or otherwise force tuple values through a single text field, the way arrays are handled).
|
@groeneai is there a check if the number of columns returned by the function doesn't match the alias? I think I found an issue like this before in a similar place. |
|
No. The alias list is checked only after a subquery: SELECT * FROM postgresql('127.0.0.1:21550', 'default', 't', 'u', 'p') AS x(p, q, r); -- columns a, b, no error
SELECT * FROM numbers(2) AS x(a, b, c); -- column number, no error
SELECT a FROM t AS x(b, a); -- t.a (1, 2); (SELECT * FROM t) AS x(b, a) gives t.b ('x', 'y')The last one is a silent wrong result. It is not specific to this PR and is already reported as #124803 (open, no fixing PR yet). It also shows up through this PR's self-connect: a PostgreSQL-valid The lists the I can send the fix for #124803 if nobody else is on it. |
In a simple-query message holding several statements, every statement must report its own row count in `CommandComplete`. On releases 26.3 to 26.9 statement N reported N times its count, because `processQuery` reused one query context for every statement and `executeQueryWithTracking` chained a progress callback onto the previous statement's callback, writing into counters of a returned stack frame. Master is fixed by ClickHouse#112940 (per-statement query context, callback-owned counters restored on exit), but nothing asserted the counts: the same fix first landed with ClickHouse#110760 and was reverted along with it (ClickHouse#112935) without any test noticing. The test speaks the PostgreSQL wire protocol over a raw socket and prints every `CommandComplete` tag of two multi-statement queries (SELECT and INSERT, which use the `result_rows` and `written_rows` counters). It prints `SELECT 9, SELECT 18, SELECT 12` / `INSERT 0 7, INSERT 0 4` on v26.3.57.12-lts, v26.8.32.14-lts and v26.9.23.15, and matches the reference on master. Closes ClickHouse#117805 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reapply #110760, reverted in #112935, together with a fix for the bug that motivated the revert.
Related: #110760
Related: #112935
Related: #84085
Why it was reverted, and why the bug is not in the reverted change
Every
Stress testjob on master started failing withCI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=cd6fd72e2b29fa607cffe0595e347452f8dcba9b&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29
A PostgreSQL client cancels a running statement by opening a second connection and sending a
CancelRequeston it, carrying the(process id, secret key)pair the server handed out inBackendKeyData. By the protocol that connection never authenticates - the secret key is thecredential - so
PostgreSQLHandler::cancelRequesthas no authenticated session, and thesession->makeQueryContext()it called throwsLOGICAL_ERROR. That has been true since sessionswere introduced (
51ffc334573), and it is reachable by any PostgreSQL client that cancels astatement:
psqlon Ctrl-C, or thepgxdriver in issue #84085, which reports this very error.#110760 did not introduce it, it only made CI reach it: with ClickHouse acting as a libpq/pqxx
client against itself,
PostgreSQLSourcecancels the remote statement throughPQcancel, so astress run that cancels a query now sends a cancel request to the server's own PostgreSQL port.
The fix (second commit)
cancelRequestcancels the query through the process list directly, which needs no session, viaa new
ProcessList::sendCancelToQueryOfAnyUser. Only queries whose id has thepostgres:<connection id>:<secret key>shape the server itself assigns can be named this way, andthe secret key is what makes such an id unguessable - the same credential PostgreSQL relies on.
KILL QUERYresult the old code wrote straight into the client socket is gone with it.The protocol expects no answer at all to a cancel request, so that was protocol garbage.
BackendKeyDatawas sent whilesecret_keywasstill zero, and every statement then re-randomized it, so the query id a cancel request resolved
to was never the id of a running query - cancellation over the PostgreSQL protocol has never
worked. The key now belongs to the connection, as in PostgreSQL, where it identifies the backend
rather than one statement, and every statement of the connection runs under
postgres:<connection id>:<secret key>. Statements of one connection run one after another, soreusing the id is safe.
04669_postgresql_protocol_cancel_request, which drives a realpsqland cancels itwith
SIGINT- that is what makespsqlsend aCancelRequest.The
-- pinghalf of issue #84085 (a comment-only statement is not recognized as an empty query) isnot addressed here.
Privileges
A self-connect needs nothing beyond access to the table being read.
system.databases,system.tablesandsystem.columns, which the emulatedpg_namespace,pg_classandpg_attributeare views over, are readable by every user even withaccess_control_improvements.select_from_system_db_requires_grantenabled, and their rows arefiltered by the reader's own grants - so the catalog shows a user exactly the relations that user
may read, as
pg_catalogdoes in PostgreSQL.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
postgresqltable function andPostgreSQLtable engine can now be used to connect to another ClickHouse server over the PostgreSQL protocol (inferring the structure of thequery(...)variant is not supported yet, so it needs an explicit column list). Added the PostgreSQL-compatibility functionsformat_typeandcurrent_setting. Fixed cancellation over the PostgreSQL protocol: a cancel request used to log a logical error and never cancelled anything.Workflow [PR]
Sync PR [sync-upstream/pr/112940]
Version info
26.10.1.2103-master(included in26.10and later)