Repository navigation
Read the options of a COPY command on the PostgreSQL protocol - #119376
Conversation
`COPY t FROM STDIN WITH (FORMAT csv)` - the spelling every modern PostgreSQL client and `psql` emit -
was parsed as far as the `WITH`, and the rest of the command was skipped token by token without being
applied or rejected. The transfer then ran in the default TSV format: `COPY FROM` acknowledged and
stored wrongly parsed rows, `COPY TO` handed TSV bytes to a client that had asked for CSV, and no
error was reported either way. The legacy `WITH CSV` spelling was ignored the same way, so the only
form that applied a format at all was `WITH FORMAT csv`, which PostgreSQL itself does not accept.
Parse the option list, in both the parenthesized and the legacy form:
* `FORMAT`, with PostgreSQL's own names (`text`, `csv`, `binary`) as well as `tsv`, and in any
spelling - previously `WITH FORMAT CSV` threw, because the lowercased name was computed and then
never used, and `tsv` selected the CSV format.
* `HEADER`, which now writes the column names on the way out and reads them as a header on the way
in, instead of being dropped.
* `DELIMITER`, `NULL` and `QUOTE`, accepted when they ask for what the chosen format writes anyway
(the `psycopg2` helpers spell those defaults out on every `copy_to` and `copy_from`) and refused
otherwise, because transferring a different shape than the client asked for is the very thing
this option list used to do silently.
* Anything else is refused with its name, rather than ignored.
`COPY ... TO` also asked for a format named `Binary`, which does not exist, while `COPY ... FROM`
read `RowBinary`; both use `RowBinary` now.
Separately, the wire data was fed through the TSV input format with the session defaults, where
`input_format_tsv_detect_header` is on: a first data row that happens to look like the column names
was taken for a header and dropped. PostgreSQL `COPY` data has a header only when `HEADER` was asked
for, which the format name above accounts for, so header detection is turned off for this path.
Closes: #118322
Related: #102483
|
Workflow [PR], commit [ed9d097] Summary: ✅
AI ReviewSummaryThis PR fixes the parser so PostgreSQL-style Findings❌ Blockers
Final VerdictRequest changes. The option-list parsing and packet-boundary fixes look directionally right, but LLVM Coverage ReportMeasured on commit ed9d097.
Changed lines: Changed C/C++ lines covered: 187/212 (88.21%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+40.27 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units10 translation units recompiled, 20 s compile time in total, 10 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
…ine of the whole stream
`HEADER` was implemented by reading the data with `CSVWithNames` / `TSVWithNames`, and the input
format was built anew for every `COPY_DATA` message. Both do more than PostgreSQL's `HEADER`, which
says that the first line of the data is the column names and says nothing else: the fields are still
bound to the columns of the command by position, and that line stands at the beginning of the whole
stream and nowhere else.
* With `input_format_with_names_use_header` left at its default, the `*WithNames` formats match the
fields of every row to columns by the names on that line, and default the columns no name was
given for. `COPY t (a, b) FROM STDIN WITH (FORMAT csv, HEADER)` behind a header spelling `b,a`
therefore loaded the two columns the other way round, and a header naming columns the table does
not have loaded no column at all. The setting is turned off for this path, which leaves the line
read and discarded, and the rows bound by position.
* A client is free to split the data into `COPY_DATA` messages at any byte. One format per message
therefore took the first row of every message for a header - dropping a row per message after
the first - and cut in half every row that spans a message boundary, which it already did before
`HEADER` was read here at all. The data of one `COPY` is now read through a single
`ReadBufferFromCopyData` spanning the stream, and so by a single input format.
The stream is parsed on the thread that owns the connection: handed to the parsing pool, a pool
thread would be blocked on the socket for as long as the client takes to send the rest of the `COPY`,
which it may do at any pace.
`HEADER` is also refused now together with `FORMAT binary`, where it has no meaning and where
PostgreSQL refuses it as well, rather than being accepted and then ignored.
New test: `test_postgresql_protocol/test.py::test_copy_from_header` - a header naming the target
columns in the other order and a header naming columns that do not exist, both bound by position; a
hundred rows sent 100 bytes at a time, with and without a header; and the binary case.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…n errors reach the client Two gaps found by review: - The option list of a `COPY` is accepted only when it asks for the shape this protocol transfers anyway, but `FormatFactory` still read `format_csv_delimiter`, `format_csv_null_representation` and `format_tsv_null_representation` from the session, so a session that did `SET format_csv_delimiter = ';'` got its `COPY ... WITH (FORMAT csv, DELIMITER ',')` accepted and then served with `;`. `pinCopyFormatSettings` now pins those settings on the query context of both `COPY ... FROM` and `COPY ... TO`. `DELIMITER` and `NULL` are also refused outright for `FORMAT binary`, which honours neither. - `processCopyQuery` swallowed every exception from `parseQuery`, so the targeted `BAD_ARGUMENTS` diagnostics were replaced by a plain syntax error from the generic SQL parser. `ParserCopyQuery` raises `BAD_ARGUMENTS` only after it has recognized a `COPY` command and got as far as its options, so that code now distinguishes "this `COPY` asks for something unsupported" from "this was not a `COPY` command" and is rethrown. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`test_copy_option_defaults_are_pinned` runs a `COPY` in a session that has moved `format_csv_delimiter` and `format_tsv_null_representation` away from the PostgreSQL defaults, and checks that the data is still transferred in the shape the option list asked for, both in and out. `test_copy_option_errors_reach_the_client` asserts the targeted messages themselves rather than a substring the echoed query text would also match, so a generic syntax error from the fallback parser no longer passes for a diagnostic. It also covers `DELIMITER` and `NULL` on `FORMAT binary`, and checks that a refused `COPY` stored nothing and left the session usable. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| query_context->setSetting("format_csv_delimiter", String(",")); | ||
| query_context->setSetting("format_csv_null_representation", String("\\N")); | ||
| query_context->setSetting("format_tsv_null_representation", String("\\N")); | ||
| query_context->setSetting("format_csv_allow_single_quotes", false); | ||
| query_context->setSetting("format_csv_allow_double_quotes", true); | ||
| query_context->setSetting("input_format_csv_allow_whitespace_or_tab_as_delimiter", false); |
There was a problem hiding this comment.
COPY ... WITH (FORMAT csv) is now supposed to follow PostgreSQL's CSV syntax, but this block still leaves the query context on ClickHouse's CSV dialect in a few places that change the actual bytes on the wire. PostgreSQL CSV uses an unquoted empty field as the default NULL marker and treats surrounding spaces as data; here we pin format_csv_null_representation to \N and leave input_format_csv_empty_as_default = 1 / input_format_csv_trim_whitespaces = 1.
That means a standard PostgreSQL producer still round-trips incorrectly through this path: COPY TO ... CSV will write \N for NULL, COPY FROM ... CSV will treat an unquoted empty field as a column default/NULL instead of PostgreSQL's CSV null semantics, and an unquoted foo string is loaded as foo. I think the COPY context needs PostgreSQL-specific CSV settings here (empty NULL, no whitespace trimming, no empty_as_default fallback), and checkDataShapeOptions needs the matching NULL '' support for CSV instead of only \N.
There was a problem hiding this comment.
We can address it separately.
…nect Conflicts resolved: - `ParserCopyQuery.cpp` / `ASTCopyQuery.h`: master (#119376) reworked the `COPY` option parsing with a parser that throws; this branch has its own non-throwing parser that records the reason in `unsupported_option` (so the handler answers with an `ErrorResponse` and keeps the connection). Kept the branch's parser and ported master's features into it: `HEADER` (now honoured through the `*WithNames` formats via `getFormatName`) and `QUOTE` (accepted when it is the CSV default). - `PostgreSQLHandler.cpp`: kept the branch's staged, cancellable `COPY FROM` reader instead of master's `ReadBufferFromCopyData`, and ported master's `pinCopyFormatSettings` (the CSV NULL marker is still applied afterwards from `csv_null_marker`) and the header settings. Master's handshake-timeout and startup-size changes merged cleanly. - `PostgreSQLSource.cpp`: took master's (#118995) cancellation, which interrupts a streaming read via a duplicated socket and arbitrates the clean finish and the interrupt through `teardown_started`; it supersedes the branch's narrower change to the same code. - Tests: master's `COPY` option tests now expect this branch's error messages (and the rejection of the PostgreSQL binary format), and the branch's test that `HEADER` is rejected now checks its output.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fix
COPYoptions being silently ignored on the PostgreSQL wire protocol:WITH (FORMAT csv)and the legacyWITH CSVare now applied (and so areHEADERand a format name in any spelling), unsupported options are reported instead of skipped, and TSV header auto-detection no longer drops the first data row of aCOPY ... FROM STDIN.Documentation entry for user-facing changes
...
COPY t FROM STDIN WITH (FORMAT csv)— the spelling every modern PostgreSQL client andpsqlemit — was parsed as far as theWITH, and the rest of the command was skipped token by token without being applied or rejected. The transfer then ran in the default TSV format:COPY FROMacknowledged and stored wrongly parsed rows,COPY TOhanded TSV bytes to a client that had asked for CSV, and no error was reported either way. The legacyWITH CSVspelling was ignored the same way, so the only form that applied a format at all wasWITH FORMAT csv, which PostgreSQL itself does not accept.Parse the option list, in both the parenthesized and the legacy form:
FORMAT, with PostgreSQL's own names (text,csv,binary) as well astsv, and in any spelling — previouslyWITH FORMAT CSVthrew, because the lowercased name was computed and then never used, andtsvselected the CSV format.HEADER, which now writes the column names on the way out and reads them as a header on the way in, instead of being dropped. It is refused together withFORMAT binary, where it has no meaning and where PostgreSQL refuses it as well.DELIMITER,NULLandQUOTE, accepted when they ask for what the chosen format writes anyway (thepsycopg2helpers spell those defaults out on everycopy_toandcopy_from) and refused otherwise, because transferring a different shape than the client asked for is the very thing this option list used to do silently.COPY ... TOalso asked for a format namedBinary, which does not exist, whileCOPY ... FROMreadRowBinary; both useRowBinarynow.Separately, the wire data was fed through the TSV input format with the session defaults, where
input_format_tsv_detect_headeris on: a first data row that happens to look like the column names was taken for a header and dropped. PostgreSQLCOPYdata has a header only whenHEADERwas asked for, which the format name above accounts for, so header detection is turned off for this path.Reading a
HEADERthe way PostgreSQL means itHEADERonCOPY ... FROMsays that the first line of the data is the column names, and says nothing else: the fields are still bound to the columns of the command by position, and that line stands at the beginning of the whole stream and nowhere else. TheCSVWithNames/TSVWithNamesformats that read it do more than that, so two things are taken care of on the read side:input_format_with_names_use_headeris turned off, which leaves the line read and discarded. With it at its default, the fields of every row are matched to columns by the names on that line and the columns no name was given for are defaulted, soCOPY t (a, b) FROM STDIN WITH (FORMAT csv, HEADER)behind a header spellingb,aloaded the two columns the other way round, and a header naming columns the table does not have loaded no column at all.COPYis read through a singleReadBufferFromCopyDataspanning the stream, and so by a single input format. A client is free to split the data intoCOPY_DATAmessages at any byte; one format per message took the first row of every message for a header — dropping a row per message after the first — and cut in half every row spanning a message boundary, which it already did beforeHEADERwas read here at all. The stream is parsed on the thread that owns the connection, because a parsing pool thread would otherwise be blocked on the socket for as long as the client takes to send the rest of theCOPY.New tests (integration tests, since this is the wire protocol):
test_postgresql_protocol/test.py::test_copy_optionsfor the option list, and::test_copy_from_headerfor the header — a header naming the target columns in the other order and a header naming columns that do not exist, both bound by position; a hundred rows sent 100 bytes at a time, with and without a header; and the binary case.test_copy_optionsand the option-list change were verified in both directions against a build from before the change, with the wholetest_postgresql_protocolmodule passing. The header change is verified so far by compiling the two translation units and by reproducing the two read-side behaviours it turns on directly at the format level against a released binary —format(CSVWithNames, 'a String, b String', 'b,a\nfirst,second\n')returnssecond,firstwithinput_format_with_names_use_headerat its default andfirst,secondwith it off, and the same input with anx,yheader returns two empty strings by default — sotest_copy_from_headeritself is left to CI to run.Closes: #118322
Related: #102483
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/119376]
Version info
26.10.1.262-master(included in26.10and later)