Skip to content

Commit 0747713

Browse files
committed
Make psql handle EOF during COPY FROM STDIN properly on all platforms.
When stdin is a terminal, it's possible to end a COPY FROM STDIN with a keyboard EOF signal (typically control-D), and then keep on issuing SQL commands. One would expect another COPY FROM STDIN to work as well, but on some platforms it did not. This turns out to be because we were not resetting the stream's feof() flag, and BSD-ish versions of fread() and fgets() won't attempt to read more data if that's set. The misbehavior is observed on BSDen (including macOS), but not Linux, Windows, or SysV-ish Unixen, which makes this a portability bug not just a missing feature. Add a clearerr() call to fix the behavior, and improve the prompt that's issued when copying from a TTY to mention that EOF signals work. It's been like this forever, so back-patch to all supported branches. Thomas Munro Discussion: https://postgr.es/m/CAEepm=0MCGfYf=JAMiYhO6JPtv9-3ZfBo8fcGeCZ8oMzaw+Z+Q@mail.gmail.com
1 parent de973f6 commit 0747713

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/bin/psql/copy.c

+11-1
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ handleCopyIn(PGconn *conn, FILE *copystream, bool isbinary)
452452
{
453453
if (!pset.quiet)
454454
puts(_("Enter data to be copied followed by a newline.\n"
455-
"End with a backslash and a period on a line by itself."));
455+
"End with a backslash and a period on a line by itself, or an EOF signal."));
456456
prompt = get_prompt(PROMPT_COPY);
457457
}
458458
else
@@ -573,6 +573,16 @@ handleCopyIn(PGconn *conn, FILE *copystream, bool isbinary)
573573

574574
copyin_cleanup:
575575

576+
/*
577+
* Clear the EOF flag on the stream, in case copying ended due to an EOF
578+
* signal. This allows an interactive TTY session to perform another COPY
579+
* FROM STDIN later. (In non-STDIN cases, we're about to close the file
580+
* anyway, so it doesn't matter.) Although we don't ever test the flag
581+
* with feof(), some fread() implementations won't read more data if it's
582+
* set. This also clears the error flag, but we already checked that.
583+
*/
584+
clearerr(copystream);
585+
576586
/*
577587
* Check command status and return to normal libpq state.
578588
*

0 commit comments

Comments
 (0)