Skip to content

Read the options of a COPY command on the PostgreSQL protocol - #119376

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-pg-copy-options-118322
Sep 20, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-pg-copy-options-118322

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix COPY options being silently ignored on the PostgreSQL wire protocol: WITH (FORMAT csv) and the legacy WITH CSV are now applied (and so are HEADER and 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 a COPY ... FROM STDIN.

Documentation entry for user-facing changes

...

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. It is refused together with FORMAT binary, where it has no meaning and where PostgreSQL refuses it as well.
  • 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.

Reading a HEADER the way PostgreSQL means it

HEADER on COPY ... FROM 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. The CSVWithNames / TSVWithNames formats that read it do more than that, so two things are taken care of on the read side:

  • input_format_with_names_use_header is 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, so COPY t (a, b) FROM STDIN WITH (FORMAT csv, HEADER) behind a header spelling b,a loaded the two columns the other way round, and a header naming columns the table does not have loaded no column at all.
  • The data of one COPY is read through a single ReadBufferFromCopyData spanning the stream, and so by a single input format. A client is free to split the data into COPY_DATA messages 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 before HEADER was 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 the COPY.

New tests (integration tests, since this is the wire protocol): test_postgresql_protocol/test.py::test_copy_options for the option list, and ::test_copy_from_header for 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_options and the option-list change were verified in both directions against a build from before the change, with the whole test_postgresql_protocol module 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') returns second, first with input_format_with_names_use_header at its default and first, second with it off, and the same input with an x,y header returns two empty strings by default — so test_copy_from_header itself is left to CI to run.

Closes: #118322
Related: #102483

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.262-master (included in 26.10 and later)

`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
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed9d097]

Summary: ✅


AI Review

Summary

This PR fixes the parser so PostgreSQL-style COPY option lists are no longer ignored, wires HEADER through both directions, and preserves one input stream across CopyData packets. The remaining problem is that the new FORMAT csv path still runs with ClickHouse CSV defaults in places where PostgreSQL CSV semantics differ, so standard PostgreSQL CSV can still round-trip the wrong values.

Findings

❌ Blockers

  • [src/Server/PostgreSQLHandler.cpp:901] COPY ... WITH (FORMAT csv) still uses ClickHouse CSV defaults for NULL and field parsing semantics. PostgreSQL CSV's default NULL marker is an unquoted empty field, and surrounding whitespace is significant; this code instead pins format_csv_null_representation to \N and leaves input_format_csv_empty_as_default = 1 / input_format_csv_trim_whitespaces = 1. As a result, a standard PostgreSQL CSV producer will still mis-round-trip through this protocol: NULL is emitted as \N, an unquoted empty field on COPY FROM becomes a default value or NULL depending on the target type, and an unquoted foo string is loaded as foo.
    Suggested fix: give the COPY CSV path PostgreSQL-specific settings in pinCopyFormatSettings (empty NULL, no whitespace trimming, no empty_as_default fallback), and update checkDataShapeOptions so CSV accepts NULL '' instead of only \N.
Final Verdict

Request changes. The option-list parsing and packet-boundary fixes look directionally right, but FORMAT csv is still semantically incompatible with PostgreSQL CSV in ways that can silently change data.

LLVM Coverage Report

Measured on commit ed9d097.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 187/212 (88.21%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ed9d097c4 with master 0b2e95c8f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7c6f66883; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+40.27 KiB total), 0 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserCopyQuery.cpp.o 58.56 KiB 90.13 KiB +31.57 KiB (+53.92%)

716 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

10 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.
The matched translation units cost +1.9 s (+10%) in total before that adjustment.

Job report

…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]>
Comment thread src/Parsers/ParserCopyQuery.cpp Resolved
Comment thread src/Parsers/ParserCopyQuery.cpp Resolved
alexey-milovidov and others added 3 commits September 19, 2026 08:38
…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]>
Comment on lines +901 to +906
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);

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.

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.

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.

We can address it separately.

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit 06a1db2 Sep 20, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-pg-copy-options-118322 branch September 20, 2026 03:50
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done
alexey-milovidov added a commit that referenced this pull request Oct 2, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

2 participants