Update copyright for 2022
[pgsql.git] / src / bin / psql / t / 020_cancel.pl
blobf445fce67afe077dc8b15c3bd335d45d669315de
2 # Copyright (c) 2021-2022, PostgreSQL Global Development Group
4 use strict;
5 use warnings;
7 use PostgreSQL::Test::Cluster;
8 use PostgreSQL::Test::Utils;
9 use Test::More tests => 2;
10 use Time::HiRes qw(usleep);
12 my $tempdir = PostgreSQL::Test::Utils::tempdir;
14 my $node = PostgreSQL::Test::Cluster->new('main');
15 $node->init;
16 $node->start;
18 # Test query canceling by sending SIGINT to a running psql
20 # There is, as of this writing, no documented way to get the PID of
21 # the process from IPC::Run. As a workaround, we have psql print its
22 # own PID (which is the parent of the shell launched by psql) to a
23 # file.
24 SKIP: {
25 skip "cancel test requires a Unix shell", 2 if $windows_os;
27 local %ENV = $node->_get_env();
29 my ($stdin, $stdout, $stderr);
31 # Test whether shell supports $PPID. It's part of POSIX, but some
32 # pre-/non-POSIX shells don't support it (e.g., NetBSD).
33 $stdin = "\\! echo \$PPID";
34 IPC::Run::run(['psql', '-X', '-v', 'ON_ERROR_STOP=1'], '<', \$stdin, '>', \$stdout, '2>', \$stderr);
35 $stdout =~ /^\d+$/ or skip "shell apparently does not support \$PPID", 2;
37 # Now start the real test
38 my $h = IPC::Run::start(['psql', '-X', '-v', 'ON_ERROR_STOP=1'], \$stdin, \$stdout, \$stderr);
40 # Get the PID
41 $stdout = '';
42 $stderr = '';
43 $stdin = "\\! echo \$PPID >$tempdir/psql.pid\n";
44 pump $h while length $stdin;
45 my $count;
46 my $psql_pid;
47 until (-s "$tempdir/psql.pid" and ($psql_pid = PostgreSQL::Test::Utils::slurp_file("$tempdir/psql.pid")) =~ /^\d+\n/s)
49 ($count++ < 180 * 100) or die "pid file did not appear";
50 usleep(10_000)
53 # Send sleep command and wait until the server has registered it
54 $stdin = "select pg_sleep(180);\n";
55 pump $h while length $stdin;
56 $node->poll_query_until('postgres', q{SELECT (SELECT count(*) FROM pg_stat_activity WHERE query ~ '^select pg_sleep') > 0;})
57 or die "timed out";
59 # Send cancel request
60 kill 'INT', $psql_pid;
62 my $result = finish $h;
64 ok(!$result, 'query failed as expected');
65 like($stderr, qr/canceling statement due to user request/, 'query was canceled');