emad60 opened a new pull request, #77506:
URL: https://github.com/apache/airflow/pull/77506
With psycopg 3, `PostgresHook.copy_expert` decided whether to load or dump
by searching the statement for the literal text `" from stdin"`. A statement
with a newline or a tab before `FROM`, or two spaces before `STDIN`, was
treated as `COPY TO STDOUT`. The input file was opened for writing and emptied,
the server then rejected the copy, and nothing was loaded. So the data file was
lost.
For example, this emptied `data.csv`:
hook.copy_expert("COPY my_table\nFROM STDIN", "data.csv")
The opposite also happened: a `COPY ... TO STDOUT` statement that only
mentioned those words, in a string literal or a comment, was treated as a load
and failed.
**Fix**
The hook now starts the copy first and reads the direction from the server's
reply (`COPY_IN` or `COPY_OUT` in `cur.pgresult.status`), then opens the file
to match. The SQL text is no longer parsed. Only the psycopg 3 path changes;
the psycopg2 path is untouched.
**Tests**
Added to `TestPostgresHookPPG3`, running against a real database:
- three variants of `COPY ... FROM STDIN` (newline before `FROM`, tab before
`FROM`, two spaces before `STDIN`) load the rows and leave the input file
intact;
- `COPY (SELECT 'read from stdin') TO STDOUT` writes the file.
All four fail without the fix. The two existing mocked tests now set the
server status explicitly.
I ran the Postgres hook tests locally against Postgres 17 (25 passed) and
the provider's unit tests on the default backend.
---
##### Was generative AI tooling used to co-author this PR?
- [X] Yes — Claude Code (Fable 5.2)
Generated-by: Claude Code (Fable 5.2) following [the
guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]