Repository navigation
Support C# client in postgres protocol - #80785
Conversation
|
Workflow [PR], commit [94dd541c] |
|
@scanhex12, I really like this! Could you please resolve the conflicts? |
|
However, I'm ok keeping this ad-hoc translation. |
|
Workflow [PR], commit [2650965] Summary: ❌
AI ReviewSummaryThis PR improves PostgreSQL wire handling for Npgsql/C# by fixing extended-protocol state transitions ( PR Metadata
Findings
Final Verdict
|
Create temporary views for `pg_type`, `pg_namespace`, `pg_class`, `pg_proc`, `pg_range`, `pg_attribute`, and `pg_enum` system tables when a PostgreSQL protocol session starts. This allows C# Npgsql client queries to run as-is without ad-hoc query translation. Also fix `deleteStatement` and `resetBindQuery` to properly handle the close protocol message. ClickHouse#80785 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
d5bf864 to
9feba4a
Compare
…et client test Instead of creating a separate `clickhouse/postgresql-dotnet-client` Docker image, add the PostgreSQL test app to the existing `clickhouse/mysql_dotnet_client` image since both share the same base (ubuntu:22.04 + dotnet-sdk-8.0). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The PostgreSQL system table views (pg_type, pg_namespace, etc.) are created as temporary views during session initialization. Use the global context (which has full access) instead of the user's query context, so that the CREATE TEMPORARY VIEW statements bypass grant checks. The session context is shared so the views remain visible to subsequent user queries. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Verify that a user with only SELECT privileges can connect via PostgreSQL protocol (internal pg_type views are created successfully) but cannot perform privileged operations like CREATE TABLE. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix three issues causing test failures:
1. `initializeSystemTables` called `executeQuery` without marking queries
as internal, causing "Query id cannot be empty" fatal error in
`ProcessList::insert`. Use the `String`-based `executeQuery` overload
with `QueryFlags{.internal = true}` and generate unique query IDs via
`setCurrentQueryId`.
2. `processCloseQuery` unconditionally called `deleteStatement` which
throws if the statement doesn't exist. Now only delete statements
when the PostgreSQL Close message type is 'S' (statement), not 'P'
(portal).
3. `CloseQuery` discarded the close target type byte. Store it and
expose `isStatement`/`isPortal` helpers.
#80785
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix two issues in the PostgreSQL wire protocol handler:
1. Set a query ID on the internal context in `initializeSystemTables`
to avoid "Query id cannot be empty" exception when creating
temporary pg_* views on connection startup.
2. Parse and store the close target type ('S' for statement, 'P' for
portal) in `CloseQuery`. Only call `deleteStatement` when the target
is a prepared statement. Closing a portal should not deallocate the
prepared statement, otherwise a later Bind/Execute on the same
statement would fail.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ndler - Rename `spl_query` variable to `sql_query` (typo fix) - Call `initializeSystemTables` from extended protocol path (`processExecuteQuery`) in addition to simple-query path, so clients using Parse/Bind/Execute can access `pg_type` and other system views from the first query - Fix `test_restricted_user_cannot_bypass_grants`: add explicit `dbname="default"` to psycopg connection for the restricted user (psycopg defaults to using the username as database name, causing "Database pg_restricted does not exist") - Fix `test_dotnet_client`: initialize C# string properties with defaults to suppress CS8618 nullable warnings that polluted test output Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
* `test_dotnet_client` failed because Npgsql 9 issues a complex `pg_catalog` introspection query on connect (joining `pg_type`, `pg_class`, `pg_proc`, `pg_range`, `pg_namespace`) that ClickHouse's analyzer cannot resolve due to unqualified column references in JOIN ON clauses. Use `Server Compatibility Mode=NoTypeLoading` so Npgsql skips that query while still allowing the explicit `SELECT oid, typname FROM pg_type` the test verifies. * `test_restricted_user_cannot_bypass_grants` failed with a `TypeError` comparing `str` to `int`: ClickHouse sends scalar values over the PostgreSQL protocol in text mode, so `result[0]` arrives as a string. Cast to `int` before comparison. Failing CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=80785&sha=adcd2d963f652bc671743fb22ba5fca1defd1f13&name_0=PR
…ocol C# Npgsql client issues multiple Parse/Bind/Execute/Sync cycles per connection. The second cycle's `Bind` was rejected with `UNEXPECTED_PACKET_FROM_CLIENT: Query is already binded` because `bind_query` was never cleared at the end of a cycle. Per PostgreSQL extended-query protocol, `Bind` replaces any portal of the same name, and the unnamed portal is destroyed at the next `Sync`. This change: * Makes `attachBindQuery` overwrite the bind slot instead of failing. * Resets `bind_query` in `processSyncQuery` so each cycle starts from a clean state. * Adds a null check in `getStatmentFromBind` so an out-of-order `Execute` (without prior `Bind`) raises a proper exception instead of dereferencing a null pointer. Failing CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=80785&sha=41f6306421771a6981fbaea309724474bfd25fbf&name_0=PR Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e tag The extended-protocol `Close` request must be acknowledged with a `CloseComplete` message; otherwise clients tracking the protocol state machine block waiting for the acknowledgement. Two related fixes: * `processCloseQuery` now sends `CloseQueryComplete` after processing the close target. * The `CloseQueryComplete` message previously wrote tag `'C'`, which is the `CommandComplete` tag in the PostgreSQL message protocol. `CloseComplete` is `'3'`. Fix the tag so clients can actually distinguish the message. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Continuing the PR:
The remaining failure @groeneai, please investigate the AST fuzzer regression: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=80785&sha=41f6306421771a6981fbaea309724474bfd25fbf&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 and provide a fix in a separate PR if one isn't already in progress. |
|
Thanks for the heads-up @alexey-milovidov — confirming your attribution. This is an existing chronic master bug, not introduced by this PR. CIDB cross-PR analysis (90 days)Two hits total in 90 days, zero in 30. The master hit and the PR hit are independent. PR #80785 does not touch Where it's thrown
Pattern in both failuresBoth fuzzer queries use
WITH RECURSIVE x AS (
SELECT 1 AS id ...
UNION ALL
SELECT ..., minus(toDateOrNull(NULL, -1), x.*), ... -- x.* references x while x is being defined
FROM x WHERE id < 5
), y AS (...)
SELECT ... FROM y__fuzz_39 LEFT JOIN x USING (id) ...Master hit (2026-04-13, qualified matcher WITH RECURSIVE x AS (
SELECT -9223372036854775808 AS id GROUP BY 1, 1, if(divide(...), y.*) AS alias384, ...
UNION ALL SELECT toLowCardinality(65537) / id FROM x WHERE 65537 <= id
), y AS (SELECT DISTINCT -2147483647 AS id ... UNION ALL ... FROM x ...)
SELECT DISTINCT x.* FROM y LEFT JOIN x USING (id) ...The CTE name is registered in HistoryThis shape is older than the current fuzzer hits:
So the engine has rejected related shapes cleanly for a while, but qualified-matcher self/mutual references inside the CTE body still bypass the early checks and fall into the PlanI will file a follow-up issue with both reproducers and a separate fix PR. The fix direction is to detect this state in I'll link the issue and fix PR back here once filed. CI report this PR: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=80785&sha=41f6306421771a6981fbaea309724474bfd25fbf&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 |
The PR refactored `attachBindQuery` to silently overwrite the single `bind_query` slot. With the previous strict check removed, a sequence `Bind(p1, $1=1); Bind(p2, $1=2); Execute(p1)` would have executed the `p2` bind instead of `p1` without raising an exception, because the server keeps a single bind slot and `Execute` ignores `ExecuteQuery::portal_name`. Reject non-empty `portal_name` explicitly in `attachBindQuery`, `processExecuteQuery`, and `processCloseQuery`. Clients of the simple extended-query flow (unnamed portal — Npgsql, psycopg, etc.) are unaffected; clients that need named portals get a clear `NOT_IMPLEMENTED` error instead of silently wrong results. Also clarify the `Sync` comment to note that resetting the single bind slot is equivalent to destroying the unnamed portal here, because the unnamed portal is the only kind we accept. Addresses two `clickhouse-gh` review threads on PR ClickHouse#80785.
…tement
`processCloseQuery` cleared `bind_query` unconditionally, so a valid
sequence — `Parse s1; Parse s2; Bind(s1); Close('S', 's2'); Execute` —
would fail with `Execute without prior Bind` even though the bind for
`s1` should still be valid.
Now clear bind state only when:
* the bind currently references the statement being deallocated
(`Close('S', name)`), or
* the unnamed portal is closed (`Close('P', '')`), since `attachBindQuery`
only accepts the unnamed portal.
Add `PreparedStatemetsManager::bindReferencesStatement` to drive the
first condition.
ClickHouse#80785 (review)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| // Server Compatibility Mode=NoTypeLoading: Npgsql 9+ otherwise issues a | ||
| // complex `pg_catalog` introspection query on connect (joining pg_type, | ||
| // pg_class, pg_proc, pg_range, pg_namespace) that ClickHouse cannot run. | ||
| var connectionString = $"Host={options.Host};Port={options.Port};Username={options.Username};Password={options.Password};Database=default;Server Compatibility Mode=NoTypeLoading;"; |
There was a problem hiding this comment.
This test hard-codes Server Compatibility Mode=NoTypeLoading, which disables Npgsql's default catalog/type-loading introspection on connect.
So the PR's contract (Support C# client in postgres protocol) is not actually validated for the default Npgsql connection path; it only validates an opt-in compatibility mode.
Please either make the default path work and test it without this flag, or explicitly narrow/document the feature contract to require NoTypeLoading.
There was a problem hiding this comment.
Scope decision. The PR makes the C# client connect with NoTypeLoading (a single opt-in connection-string flag), which is the documented and tested contract — the inline code comment captures why: Npgsql 9+ otherwise issues a multi-way pg_catalog join (pg_type/pg_class/pg_proc/pg_range/pg_namespace) that we cannot fully execute even with the temporary views in place. Making the default connection path work would require additional pg_catalog views and join-shape support that are out of scope for this PR. The C# integration test exists precisely to pin down the NoTypeLoading contract and prevent regressions; widening Npgsql default-mode support can be a follow-up.
There was a problem hiding this comment.
Thanks for the scope clarification. I still see a contract mismatch: the PR title/changelog say Support C# client in postgres protocol and the body says this closes #18611, but the implementation and test only support the NoTypeLoading mode (Server Compatibility Mode=NoTypeLoading) while the default Npgsql connection path remains unsupported.
Please either:
- narrow the PR contract explicitly (including changelog text) to
NoTypeLoading, and avoid closing#18611, or - add support/tests for the default Npgsql connect path.
The previous `processCloseQuery` handler only acted on `'S'` (prepared statement) and `'P'` (portal) targets, but any other byte fell through and was silently acknowledged with `CloseComplete`. That violates the protocol contract for malformed packets and hides client/server state bugs. Throw `UNEXPECTED_PACKET_FROM_CLIENT` for unknown `Close` targets so that protocol violations surface as errors instead of being acked. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous diagnostic used `{:02X}` against a `char8_t` argument,
which trips fmtlib's consteval format-string check ("mixing character
types is disallowed" / "unknown format specifier"). Cast the target
byte to `int` (via `unsigned char` for the correct numeric value) and
drop the hex spec — the resulting decimal byte value is enough to
identify a malformed packet.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: 80.42% (152/189) · Uncovered code |
|
Need to revert this PR, it broke the CI ( This is what Claude thinks: |
PR #80785 added a second app under /pg_testapp to the `clickhouse/mysql_dotnet_client` image, making /pg_testapp the last WORKDIR. `dotnet run` (no project arg) then launched the Npgsql client against the MySQL port, producing "Received unknown response X for SSLRequest (expecting S or N)". The PR was reverted (#105615) but the cached `:latest` image on integration runners still has /pg_testapp as the last WORKDIR. Anchor the command to /testapp so the test passes regardless of the image's working directory, matching what test_dotnet_client in test_postgresql_protocol/test.py already does. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PR ClickHouse#80785 added a second app under /pg_testapp to the `clickhouse/mysql_dotnet_client` image, making /pg_testapp the last WORKDIR. `dotnet run` (no project arg) then launched the Npgsql client against the MySQL port, producing "Received unknown response X for SSLRequest (expecting S or N)". The PR was reverted (ClickHouse#105615) but the cached `:latest` image on integration runners still has /pg_testapp as the last WORKDIR. Anchor the command to /testapp so the test passes regardless of the image's working directory, matching what test_dotnet_client in test_postgresql_protocol/test.py already does. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Support C# client in postgres protocol
PR ClickHouse#80785 added a second app under /pg_testapp to the `clickhouse/mysql_dotnet_client` image, making /pg_testapp the last WORKDIR. `dotnet run` (no project arg) then launched the Npgsql client against the MySQL port, producing "Received unknown response X for SSLRequest (expecting S or N)". The PR was reverted (ClickHouse#105615) but the cached `:latest` image on integration runners still has /pg_testapp as the last WORKDIR. Anchor the command to /testapp so the test passes regardless of the image's working directory, matching what test_dotnet_client in test_postgresql_protocol/test.py already does. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PR ClickHouse#80785 added a second app under /pg_testapp to the `clickhouse/mysql_dotnet_client` image, making /pg_testapp the last WORKDIR. `dotnet run` (no project arg) then launched the Npgsql client against the MySQL port, producing "Received unknown response X for SSLRequest (expecting S or N)". The PR was reverted (ClickHouse#105615) but the cached `:latest` image on integration runners still has /pg_testapp as the last WORKDIR. Anchor the command to /testapp so the test passes regardless of the image's working directory, matching what test_dotnet_client in test_postgresql_protocol/test.py already does. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Problems:
Initial error from issue is not reproducible
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Support C# client in postgres protocol. This closes #18611
Documentation entry for user-facing changes
Version info
26.5.1.924