On 18/10/2026 13:01, Rui Zhao wrote:
1. Ctrl-C in a later \prompt can crash psql.

I used the prompt.sql case from t/042_singlestep.pl, containing one
line:

     SELECT 111; \prompt 'ANSWER: ' answer

Then, in an interactive psql session:

     \set SINGLESTEP on
     \i prompt.sql

I pressed Enter at the single-step confirmation to execute SELECT 111,
then Ctrl-C at the ANSWER: input requested by \prompt. With your
original patch, psql aborts with:

     double free or corruption (out)

Without your patch, the same sequence cancels the script and leaves the
interactive psql session ready for another command.

The reason is that MainLoop() calls singlestep_verify() through
SendQuery(). MainLoop() and singlestep_verify() both call
sigsetjmp(sigint_interrupt_jmp, 1), using the same global variable.
singlestep_verify() overwrites MainLoop()'s saved context and leaves its
own context in the buffer when it returns.

MainLoop() is still processing the same input line, so it has not
reached the next iteration's sigsetjmp(). The following \prompt calls
gets_fromFile(stdin), which sets sigint_interrupt_enabled to true. On
Ctrl-C, psql_cancel_callback() calls siglongjmp() using the context
saved by singlestep_verify(), but that function has already returned. In
GDB, psql aborts at pg_free(first_prompt) in singlestep_verify().

I initially fixed only singlestep_verify(), using a local sigjmp_buf
variable and a global pointer to select the sigjmp_buf for siglongjmp().
The function saves the previous pointer and restores it before
returning. That fixed this case. When reviewing the other calls to
sigsetjmp() in src/bin/psql/, I noticed that nested MainLoop() calls
also use the same global variable. To check this on unpatched master, I
used an interactive session with SINGLESTEP off. This is the nested-script
case in t/040_interrupt.pl: inner.sql contains SELECT 111;, and outer.sql
has this single line:

     \i inner.sql \prompt 'OUTER: ' answer

I ran \i outer.sql, then pressed Ctrl-C at OUTER:.

Both MainLoop() calls use sigsetjmp(sigint_interrupt_jmp, 1). The inner
call overwrites the outer call's saved context and then returns. Ctrl-C
at OUTER: makes siglongjmp() use the inner call's context after that
call has returned, and psql exits unexpectedly.

Good find; thanks for the analysis.

0001 replaces the global sigjmp_buf with local sigjmp_buf variables and
a global PG_exception_stack pointer, as with nested PG_TRY() blocks.
Each function saves the previous pointer, sets it to its local variable,
and restores it before returning. The SIGINT callback calls
siglongjmp(*PG_exception_stack, 1). A later Ctrl-C therefore uses the
calling function's saved context, not the context of a function that has
returned. This covers MainLoop(), handleCopyIn(), and the callers of
simple_prompt_extended(). 0003 applies the same change to
singlestep_verify().

Hmm, we're really only using longjmp to jump out of a few very specific function calls. It's not used as a generic error handling mechanism (like in the backend). I feel it would be more robust to push the sigsetjmp() calls as close to the function calls that we want to jump out of, instead of trying to ensure that the global stack is in the correct state at all times. Concretely, I suggest that we add a PromptInterruptContext argument to gets_interactive() and gets_fromFile(), so that they handle cancellation similar to simple_prompt_extended(). See attached.

The test feels a bit complicated, I think I'll leave that out of the version I'll commit. But thanks for a concrete repro. I didn't look at the other patches yet.

- Heikki
From 3ab464d71408eb221408815f03b049e96d89ecdf Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <[email protected]>
Date: Tue, 1 Dec 2026 17:28:02 +0200
Subject: [PATCH v2 1/1] psql: Fix crash on Ctrl-C in a prompt in a nested
 script

Ctrl-C at an included script's \prompt can make an interactive psql
session exit unexpectedly after returning from a nested MainLoop call.
For example, with inner.sql containing SELECT 111;, this line in an
outer script triggers the problem:

    \i inner.sql \prompt 'OUTER: ' answer

Run the outer script with \i from an interactive psql session, and hit
Ctrl-C at the OUTER: prompt.  psql exits or crashes.

Both MainLoop calls use sigsetjmp(sigint_interrupt_jmp, 1), with the
same global variable.  The inner call overwrites the outer call's
saved context and returns without restoring it.  The outer call is
still processing the same line, so it has not reached the next
iteration's sigsetjmp.  The following \prompt sets
sigint_interrupt_enabled to true.  On Ctrl-C, psql_cancel_callback
calls siglongjmp using the inner MainLoop's context after that call
has returned.

To fix, add a PromptInterruptContext argument to gets_interactive()
and gets_fromFile(), similar to simple_prompt_extended(), and make
them establish the longjmp destination themselves right before
enabling the interrupt.  Cancellation is reported to the caller in
prompt_ctx->canceled.  The rule now is that whoever sets
sigint_interrupt_enabled must establish sigint_interrupt_jmp locally
in the same function.  We're only using sigsetjmp() to jump out of
specific function calls, not as a generic error handling mechanism;
keeping the sigsetjmp() close to those function calls makes that more
clear.

MainLoop() no longer does sigsetjmp(), so its locals no longer need to
be volatile.

Note: Before this fix, there was one very long jump (no pun intended)
all the way up the following call stack, if there was a \prompt in a
script and it was interrupted with Ctrl-C:

  MainLoop()
    HandleSlashCmds()
      exec_command()
        exec_command_prompt()
          gets_fromFile()
	    fgets()

Aside from the crash issue at hand, that was error-prone, and could
e.g. leak some small allocations on the way.  With this patch, the
interrupt is caught by a local sigsetjmp() in gets_fromFile(), and we
return up the stack normally like on other errors or EOF, instead of
longjumping all the way up to MainLoop.

Ctrl-C at a \prompt in a script still aborts the whole script, but it
now happens through the cancel flag rather than the longjmp.  In
master, the SIGINT handler always sets CancelRequested; in the back
branches it doesn't set cancel_pressed when it longjmps, so
exec_command_prompt() must set it explicitly when gets_fromFile()
returns due to cancellation.  The flag stays set until the interactive
MainLoop clears it, so this now aborts all enclosing scripts too, as a
Ctrl-C during a query in a nested script already does.  Previously
only the innermost script was aborted.

Reported-by: Rui Zhao <[email protected]>
Discussion: https://www.postgresql.org/message-id/CAHWVJhF3_3V3v+YcrvB6rV3JRK_vGUpQKL3N5SFmZtQo=2n...@mail.gmail.com
Backpatch-through: 15
---
 src/bin/psql/command.c          |   6 +-
 src/bin/psql/input.c            |  58 ++++++---
 src/bin/psql/input.h            |   6 +-
 src/bin/psql/mainloop.c         | 103 ++++++++--------
 src/bin/psql/meson.build        |   1 +
 src/bin/psql/t/040_interrupt.pl | 204 ++++++++++++++++++++++++++++++++
 6 files changed, 302 insertions(+), 76 deletions(-)
 create mode 100644 src/bin/psql/t/040_interrupt.pl

diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 407d263fb20..dec83a3b460 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -2643,7 +2643,7 @@ exec_command_prompt(PsqlScanState scan_state, bool active_branch,
 			char	   *result;
 			PromptInterruptContext prompt_ctx;
 
-			/* Set up to let SIGINT cancel simple_prompt_extended() */
+			/* Set up to let SIGINT cancel waiting for input */
 			prompt_ctx.jmpbuf = sigint_interrupt_jmp;
 			prompt_ctx.enabled = &sigint_interrupt_enabled;
 			prompt_ctx.canceled = false;
@@ -2667,8 +2667,8 @@ exec_command_prompt(PsqlScanState scan_state, bool active_branch,
 					fputs(prompt_text, stdout);
 					fflush(stdout);
 				}
-				result = gets_fromFile(stdin);
-				if (!result)
+				result = gets_fromFile(stdin, &prompt_ctx);
+				if (!result && !prompt_ctx.canceled)
 				{
 					pg_log_error("\\%s: could not read value for variable",
 								 cmd);
diff --git a/src/bin/psql/input.c b/src/bin/psql/input.c
index 76b479387b1..0dcba865d08 100644
--- a/src/bin/psql/input.c
+++ b/src/bin/psql/input.c
@@ -59,12 +59,15 @@ static void finishInput(void);
  * query_buf: buffer containing lines already read in the current command
  * (query_buf is not modified here, but may be consulted for tab completion)
  *
- * The result is a malloc'd string.
+ * prompt_ctx can optionally be provided to allow the wait to be canceled by
+ * SIGINT, like in pg_get_line_append().  If canceled, the result is NULL and
+ * prompt_ctx->canceled is set to true.
  *
- * Caller *must* have set up sigint_interrupt_jmp before calling.
+ * The result is a malloc'd string, or NULL on EOF or cancellation.
  */
 char *
-gets_interactive(const char *prompt, PQExpBuffer query_buf)
+gets_interactive(const char *prompt, PQExpBuffer query_buf,
+				 PromptInterruptContext *prompt_ctx)
 {
 #ifdef USE_READLINE
 	if (useReadline)
@@ -85,13 +88,25 @@ gets_interactive(const char *prompt, PQExpBuffer query_buf)
 		/* Make current query_buf available to tab completion callback */
 		tab_completion_query_buf = query_buf;
 
-		/* Enable SIGINT to longjmp to sigint_interrupt_jmp */
-		sigint_interrupt_enabled = true;
+		/* Establish longjmp destination for Ctrl-C */
+		if (prompt_ctx &&
+			sigsetjmp(*((sigjmp_buf *) prompt_ctx->jmpbuf), 1) != 0)
+		{
+			/* got here with longjmp */
+			tab_completion_query_buf = NULL;
+			prompt_ctx->canceled = true;
+			return NULL;
+		}
+
+		/* Enable longjmp while waiting for input */
+		if (prompt_ctx)
+			*(prompt_ctx->enabled) = true;
 
 		result = readline(prompt);
 
-		/* Disable SIGINT again */
-		sigint_interrupt_enabled = false;
+		/* Disable longjmp again */
+		if (prompt_ctx)
+			*(prompt_ctx->enabled) = false;
 
 		/* Pure neatnik-ism */
 		tab_completion_query_buf = NULL;
@@ -102,7 +117,7 @@ gets_interactive(const char *prompt, PQExpBuffer query_buf)
 
 	fputs(prompt, stdout);
 	fflush(stdout);
-	return gets_fromFile(stdin);
+	return gets_fromFile(stdin, prompt_ctx);
 }
 
 
@@ -175,15 +190,18 @@ pg_send_history(PQExpBuffer history_buf)
  * gets_fromFile
  *
  * Gets a line of noninteractive input from a file (which could be stdin).
- * The result is a malloc'd string, or NULL on EOF or input error.
+ * The result is a malloc'd string, or NULL on EOF, input error, or
+ * cancellation.
  *
- * Caller *must* have set up sigint_interrupt_jmp before calling.
+ * prompt_ctx can optionally be provided to allow the wait to be canceled by
+ * SIGINT, like in pg_get_line_append().  If canceled, prompt_ctx->canceled is
+ * set to true.
  *
  * Note: we re-use a static PQExpBuffer for each call.  This is to avoid
  * leaking memory if interrupted by SIGINT.
  */
 char *
-gets_fromFile(FILE *source)
+gets_fromFile(FILE *source, PromptInterruptContext *prompt_ctx)
 {
 	static PQExpBuffer buffer = NULL;
 
@@ -194,18 +212,28 @@ gets_fromFile(FILE *source)
 	else
 		resetPQExpBuffer(buffer);
 
+	/* Establish longjmp destination for Ctrl-C */
+	if (prompt_ctx && sigsetjmp(*((sigjmp_buf *) prompt_ctx->jmpbuf), 1) != 0)
+	{
+		/* got here with longjmp */
+		prompt_ctx->canceled = true;
+		return NULL;
+	}
+
 	for (;;)
 	{
 		char	   *result;
 
-		/* Enable SIGINT to longjmp to sigint_interrupt_jmp */
-		sigint_interrupt_enabled = true;
+		/* Enable longjmp while waiting for input */
+		if (prompt_ctx)
+			*(prompt_ctx->enabled) = true;
 
 		/* Get some data */
 		result = fgets(line, sizeof(line), source);
 
-		/* Disable SIGINT again */
-		sigint_interrupt_enabled = false;
+		/* Disable longjmp again */
+		if (prompt_ctx)
+			*(prompt_ctx->enabled) = false;
 
 		/* EOF or error? */
 		if (result == NULL)
diff --git a/src/bin/psql/input.h b/src/bin/psql/input.h
index 2a47166347e..309e9e6e7c1 100644
--- a/src/bin/psql/input.h
+++ b/src/bin/psql/input.h
@@ -44,11 +44,13 @@
 #endif							/* HAVE_READLINE_READLINE_H, etc */
 #endif							/* HAVE_LIBREADLINE */
 
+#include "common/string.h"
 #include "pqexpbuffer.h"
 
 
-extern char *gets_interactive(const char *prompt, PQExpBuffer query_buf);
-extern char *gets_fromFile(FILE *source);
+extern char *gets_interactive(const char *prompt, PQExpBuffer query_buf,
+							  PromptInterruptContext *prompt_ctx);
+extern char *gets_fromFile(FILE *source, PromptInterruptContext *prompt_ctx);
 
 extern void initializeInput(int flags);
 
diff --git a/src/bin/psql/mainloop.c b/src/bin/psql/mainloop.c
index e8273779a04..f42abbb3389 100644
--- a/src/bin/psql/mainloop.c
+++ b/src/bin/psql/mainloop.c
@@ -35,22 +35,22 @@ MainLoop(FILE *source)
 {
 	PsqlScanState scan_state;	/* lexer working state */
 	ConditionalStack cond_stack;	/* \if status stack */
-	volatile PQExpBuffer query_buf; /* buffer for query being accumulated */
-	volatile PQExpBuffer previous_buf;	/* if there isn't anything in the new
-										 * buffer yet, use this one for \e,
-										 * etc. */
+	PQExpBuffer query_buf;		/* buffer for query being accumulated */
+	PQExpBuffer previous_buf;	/* if there isn't anything in the new buffer
+								 * yet, use this one for \e, etc. */
 	PQExpBuffer history_buf;	/* earlier lines of a multi-line command, not
 								 * yet saved to readline history */
 	char	   *line;			/* current line of input */
+	PromptInterruptContext prompt_ctx;	/* to let SIGINT cancel reading */
 	int			added_nl_pos;
 	bool		success;
 	bool		line_saved_in_history;
-	volatile int successResult = EXIT_SUCCESS;
-	volatile backslashResult slashCmdStatus = PSQL_CMD_UNKNOWN;
-	volatile promptStatus_t prompt_status = PROMPT_READY;
-	volatile bool need_redisplay = false;
-	volatile int count_eof = 0;
-	volatile bool die_on_error = false;
+	int			successResult = EXIT_SUCCESS;
+	backslashResult slashCmdStatus = PSQL_CMD_UNKNOWN;
+	promptStatus_t prompt_status = PROMPT_READY;
+	bool		need_redisplay = false;
+	int			count_eof = 0;
+	bool		die_on_error = false;
 	FILE	   *prev_cmd_source;
 	bool		prev_cmd_interactive;
 	uint64		prev_lineno;
@@ -100,15 +100,46 @@ MainLoop(FILE *source)
 			CancelRequested = false;
 		}
 
+		fflush(stdout);
+
+		/* Set up to let SIGINT cancel waiting for input */
+		prompt_ctx.jmpbuf = sigint_interrupt_jmp;
+		prompt_ctx.enabled = &sigint_interrupt_enabled;
+		prompt_ctx.canceled = false;
+
 		/*
-		 * Establish longjmp destination for exiting from wait-for-input. We
-		 * must re-do this each time through the loop for safety, since the
-		 * jmpbuf might get changed during command execution.
+		 * get another line
 		 */
-		if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
+		if (pset.cur_cmd_interactive)
+		{
+			/* May need to reset prompt, eg after \r command */
+			if (query_buf->len == 0)
+				prompt_status = PROMPT_READY;
+			/* If query buffer came from \e, redisplay it with a prompt */
+			if (need_redisplay)
+			{
+				if (query_buf->len > 0)
+				{
+					fputs(get_prompt(PROMPT_READY, cond_stack), stdout);
+					fputs(query_buf->data, stdout);
+					fflush(stdout);
+				}
+				need_redisplay = false;
+			}
+			/* Now we can fetch a line */
+			line = gets_interactive(get_prompt(prompt_status, cond_stack),
+									query_buf, &prompt_ctx);
+		}
+		else
 		{
-			/* got here with longjmp */
+			line = gets_fromFile(source, &prompt_ctx);
+			if (!line && !prompt_ctx.canceled && ferror(source))
+				successResult = EXIT_FAILURE;
+		}
 
+		/* Did the user hit Ctrl-C while we were waiting for input? */
+		if (prompt_ctx.canceled)
+		{
 			/* reset parsing state */
 			psql_scan_finish(scan_state);
 			psql_scan_reset(scan_state);
@@ -134,6 +165,7 @@ MainLoop(FILE *source)
 					pg_log_error("\\if: escaped");
 					conditional_stack_pop(cond_stack);
 				}
+				continue;
 			}
 			else
 			{
@@ -142,38 +174,6 @@ MainLoop(FILE *source)
 			}
 		}
 
-		fflush(stdout);
-
-		/*
-		 * get another line
-		 */
-		if (pset.cur_cmd_interactive)
-		{
-			/* May need to reset prompt, eg after \r command */
-			if (query_buf->len == 0)
-				prompt_status = PROMPT_READY;
-			/* If query buffer came from \e, redisplay it with a prompt */
-			if (need_redisplay)
-			{
-				if (query_buf->len > 0)
-				{
-					fputs(get_prompt(PROMPT_READY, cond_stack), stdout);
-					fputs(query_buf->data, stdout);
-					fflush(stdout);
-				}
-				need_redisplay = false;
-			}
-			/* Now we can fetch a line */
-			line = gets_interactive(get_prompt(prompt_status, cond_stack),
-									query_buf);
-		}
-		else
-		{
-			line = gets_fromFile(source);
-			if (!line && ferror(source))
-				successResult = EXIT_FAILURE;
-		}
-
 		/*
 		 * query_buf holds query already accumulated.  line is the malloc'd
 		 * new line of input (note it must be freed before looping around!)
@@ -642,15 +642,6 @@ MainLoop(FILE *source)
 			successResult = EXIT_USER;
 	}
 
-	/*
-	 * Let's just make real sure the SIGINT handler won't try to use
-	 * sigint_interrupt_jmp after we exit this routine.  If there is an outer
-	 * MainLoop instance, it will reset sigint_interrupt_jmp to point to
-	 * itself at the top of its loop, before any further interactive input
-	 * happens.
-	 */
-	sigint_interrupt_enabled = false;
-
 	destroyPQExpBuffer(query_buf);
 	destroyPQExpBuffer(previous_buf);
 	destroyPQExpBuffer(history_buf);
diff --git a/src/bin/psql/meson.build b/src/bin/psql/meson.build
index 922b2845267..debdaf8294c 100644
--- a/src/bin/psql/meson.build
+++ b/src/bin/psql/meson.build
@@ -78,6 +78,7 @@ tests += {
       't/010_tab_completion.pl',
       't/020_cancel.pl',
       't/030_pager.pl',
+      't/040_interrupt.pl',
     ],
   },
 }
diff --git a/src/bin/psql/t/040_interrupt.pl b/src/bin/psql/t/040_interrupt.pl
new file mode 100644
index 00000000000..71b0738efab
--- /dev/null
+++ b/src/bin/psql/t/040_interrupt.pl
@@ -0,0 +1,204 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+use Time::HiRes qw(time usleep);
+
+plan skip_all => 'sending SIGINT on Windows terminates the test itself'
+  if $windows_os;
+plan skip_all => 'IO::Pty is needed to run this test'
+  unless eval { require IO::Pty; 1 };
+
+my $node = PostgreSQL::Test::Cluster->new('main');
+$node->init;
+
+my $hba = $node->data_dir . '/pg_hba.conf';
+my $old_hba = slurp_file($hba);
+open(my $hba_fh, '>', $hba) or die "open $hba: $!";
+print $hba_fh "local all interrupt_user scram-sha-256\n";
+print $hba_fh $old_hba;
+close($hba_fh) or die "close $hba: $!";
+
+$node->start;
+$node->safe_psql('postgres',
+	'CREATE TABLE copy_log (id int); CREATE ROLE interrupt_user LOGIN');
+
+my $inner = $node->basedir . '/inner.sql';
+my $outer = $node->basedir . '/outer.sql';
+append_to_file($inner, "SELECT 111;\n");
+append_to_file($outer, "\\i $inner \\prompt 'OUTER: ' answer\n");
+my $password_script = $node->basedir . '/password_then_prompt.sql';
+append_to_file($password_script,
+	"\\password interrupt_user \\prompt 'AFTER: ' answer\n");
+
+# simple_prompt_extended() can write to /dev/tty or stderr.  Accept either
+# stream, and discard the matched output before issuing the next command.
+sub query_until
+{
+	my ($h, $until, $query) = @_;
+	$h->{timeout}->start();
+	$h->{stdin} .= $query;
+	$h->{run}->pump() until ($h->{stdout} . $h->{stderr}) =~ $until;
+	my $output = $h->{stdout} . $h->{stderr};
+	$h->{stdout} = '';
+	$h->{stderr} = '';
+	return $output;
+}
+
+# psql prints a prompt before it starts waiting for input, and SIGINT only
+# interrupts the wait once it has started.  A SIGINT sent as soon as the prompt
+# appears can therefore arrive too early, merely setting CancelRequested.
+# Keep sending SIGINT until the expected output appears.
+sub interrupt_until
+{
+	my ($h, $until) = @_;
+	$h->{timeout}->start();
+	while (1)
+	{
+		$h->{run}->signal('INT');
+		my $retry_at = time() + 0.5;
+		while (time() < $retry_at)
+		{
+			$h->{run}->pump_nb();
+			if (($h->{stdout} . $h->{stderr}) =~ $until)
+			{
+				$h->{stdout} = '';
+				$h->{stderr} = '';
+				return;
+			}
+			die "timed out waiting for $until" if $h->{timeout}->is_expired;
+			usleep(10_000);
+		}
+	}
+}
+
+my $ready = qr/ready> /;
+
+for my $no_readline (1, 0)
+{
+	next
+	  if !$no_readline
+	  && ((!defined($ENV{with_readline}) || $ENV{with_readline} ne 'yes')
+		|| defined($ENV{SKIP_READLINE_TESTS}));
+
+	my $mode = $no_readline ? 'without readline' : 'with readline';
+	my $h = $node->interactive_psql('postgres',
+		extra_params => [ '--pset' => 'pager=off', $no_readline ? ('-n') : () ]);
+	query_until(
+		$h,
+		qr/interrupt-ready\r?\nready> /,
+		"\\set PROMPT1 'ready> '\n\\echo interrupt-ready\n");
+
+	# After the inner MainLoop returns, Ctrl-C during \prompt on the same
+	# line must use the context saved by sigsetjmp in the outer MainLoop.
+	query_until($h, qr/OUTER: /, "\\i $outer\n");
+	interrupt_until($h, $ready);
+	like(query_until($h, $ready, "SELECT 222;\n"),
+		qr/\r?\n222\r?\n/,
+		"canceling a prompt after nested \\i preserves the session, $mode");
+
+	# Password input must not overwrite MainLoop's sigjmp_buf either.  A
+	# later \prompt on the same line can set sigint_interrupt_enabled to true
+	# before MainLoop calls sigsetjmp again.
+	query_until(
+		$h,
+		qr/Enter new password for user "interrupt_user": /,
+		"\\i $password_script\n");
+	query_until($h, qr/Enter it again: /, "test-password\n");
+	query_until($h, qr/AFTER: /, "test-password\n");
+	interrupt_until($h, $ready);
+	like(
+		query_until($h, $ready, "SELECT 223;\n"),
+		qr/\r?\n223\r?\n/,
+		"canceling a prompt after password input preserves the session, $mode"
+	);
+
+	# COPY must handle the interrupt itself and finish the COPY protocol,
+	# rather than jumping directly to MainLoop.
+	$node->safe_psql('postgres', 'TRUNCATE copy_log');
+	query_until($h, qr/>> /, "COPY copy_log FROM STDIN;\n");
+	query_until($h, qr/>> /, "1\n");
+	interrupt_until($h, $ready);
+	is($node->safe_psql('postgres', 'SELECT count(*) FROM copy_log'),
+		'0', "canceling COPY rolls back its rows, $mode");
+	like(query_until($h, $ready, "SELECT 333;\n"),
+		qr/\r?\n333\r?\n/,
+		"connection remains usable after canceling COPY, $mode");
+
+	query_until($h, qr/>> /, "COPY copy_log FROM STDIN (FORMAT binary);\n");
+	interrupt_until($h, $ready);
+	like(query_until($h, $ready, "SELECT 444;\n"),
+		qr/\r?\n444\r?\n/,
+		"connection remains usable after canceling binary COPY, $mode");
+
+	query_until($h, qr/>> /, "COPY copy_log FROM STDIN;\n");
+	query_until($h, $ready, "2\n\\.\n");
+	is($node->safe_psql('postgres', 'SELECT id FROM copy_log'),
+		'2', "COPY can subsequently complete, $mode");
+
+	query_until($h, qr/VALUE: /, "\\prompt 'VALUE: ' answer\n");
+	interrupt_until($h, $ready);
+	query_until($h, qr/VALUE: /, "\\prompt 'VALUE: ' answer\n");
+	query_until($h, $ready, "prompt-ok\n");
+	like(query_until($h, $ready, "\\echo :answer\n"),
+		qr/prompt-ok/,
+		"interactive prompt can be retried after cancellation, $mode");
+
+	$node->safe_psql('postgres', 'ALTER ROLE interrupt_user PASSWORD NULL');
+	for my $second_prompt (0, 1)
+	{
+		query_until(
+			$h,
+			qr/Enter new password for user "interrupt_user": /,
+			"\\password interrupt_user\n");
+		query_until($h, qr/Enter it again: /, "test-password\n")
+		  if $second_prompt;
+		interrupt_until($h, $ready);
+		is( $node->safe_psql(
+				'postgres',
+				q{SELECT rolpassword IS NULL FROM pg_authid WHERE rolname = 'interrupt_user'}
+			),
+			't',
+			"canceling password prompt $second_prompt leaves password unchanged, $mode"
+		);
+	}
+	query_until(
+		$h,
+		qr/Enter new password for user "interrupt_user": /,
+		"\\password interrupt_user\n");
+	query_until($h, qr/Enter it again: /, "test-password\n");
+	query_until($h, $ready, "test-password\n");
+	is( $node->safe_psql(
+			'postgres',
+			q{SELECT rolpassword IS NOT NULL FROM pg_authid WHERE rolname = 'interrupt_user'}
+		),
+		't',
+		"password change succeeds after cancellation, $mode");
+
+	query_until(
+		$h,
+		qr/Password for user interrupt_user: /,
+		"\\connect postgres interrupt_user\n");
+	interrupt_until($h, $ready);
+	like(query_until($h, $ready, "SELECT 555;\n"),
+		qr/\r?\n555\r?\n/,
+		"canceling connection password preserves the old connection, $mode");
+	query_until(
+		$h,
+		qr/Password for user interrupt_user: /,
+		"\\connect postgres interrupt_user\n");
+	query_until($h, $ready, "test-password\n");
+	like(
+		query_until($h, $ready, "SELECT current_user;\n"),
+		qr/\r?\ninterrupt_user\r?\n/,
+		"password connection succeeds after cancellation, $mode");
+
+	ok($h->quit, "psql exits normally, $mode");
+}
+
+$node->stop;
+done_testing();
-- 
2.47.3

Reply via email to