Debian Codegraph @

src/test/perl/PostgreSQL/Test/BackgroundPsql.pm

raw
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 =pod
5
6 =head1 NAME
7
8 PostgreSQL::Test::BackgroundPsql - class for controlling background psql processes
9
10 =head1 SYNOPSIS
11
12 use PostgreSQL::Test::Cluster;
13
14 my $node = PostgreSQL::Test::Cluster->new('mynode');
15
16 # Create a data directory with initdb
17 $node->init();
18
19 # Start the PostgreSQL server
20 $node->start();
21
22 # Create and start an interactive psql session
23 my $isession = $node->interactive_psql('postgres');
24 # Apply timeout per query rather than per session
25 $isession->set_query_timer_restart();
26 # Run a query and get the output as seen by psql
27 my $ret = $isession->query("SELECT 1");
28 # Run a backslash command and wait until the prompt returns
29 $isession->query_until(qr/postgres #/, "\\d foo\n");
30 # Close the session and exit psql
31 $isession->quit;
32
33 # Create and start a background psql session
34 my $bsession = $node->background_psql('postgres');
35
36 # Run a query which is guaranteed to not return in case it fails
37 $bsession->query_safe("SELECT 1");
38 # Initiate a command which can be expected to terminate at a later stage
39 $bsession->query_until(qr/start/, q(
40 \echo start
41 CREATE INDEX CONCURRENTLY idx ON t(a);
42 ));
43 # Close the session and exit psql
44 $bsession->quit;
45
46 =head1 DESCRIPTION
47
48 PostgreSQL::Test::BackgroundPsql contains functionality for controlling
49 a background or interactive psql session operating on a PostgreSQL node
50 initiated by PostgreSQL::Test::Cluster.
51
52 =cut
53
54 package PostgreSQL::Test::BackgroundPsql;
55
56 use strict;
57 use warnings FATAL => 'all';
58
59 use Carp;
60 use Config;
61 use IPC::Run;
62 use PostgreSQL::Test::Utils qw(pump_until);
63 use Test::More;
64
65 =pod
66
67 =head1 METHODS
68
69 =over
70
71 =item PostgreSQL::Test::BackgroundPsql->new(interactive, @psql_params, timeout, wait)
72
73 Builds a new object of class C<PostgreSQL::Test::BackgroundPsql> for either
74 an interactive or background session and starts it. If C<interactive> is
75 true then a PTY will be attached. C<psql_params> should contain the full
76 command to run psql with all desired parameters and a complete connection
77 string. For C<interactive> sessions, IO::Pty is required.
78
79 This routine will not return until psql has started up and is ready to
80 consume input. Set B<wait> to 0 to return immediately instead.
81
82 =cut
83
84 sub new
85 {
86 my $class = shift;
87 my ($interactive, $psql_params, $timeout, $wait) = @_;
88 my $psql = {
89 'stdin' => '',
90 'stdout' => '',
91 'stderr' => '',
92 'query_timer_restart' => undef,
93 'query_cnt' => 1,
94 };
95 my $run;
96
97 # This constructor should only be called from PostgreSQL::Test::Cluster
98 my ($package, $file, $line) = caller;
99 die
100 "Forbidden caller of constructor: package: $package, file: $file:$line"
101 unless $package->isa('PostgreSQL::Test::Cluster');
102
103 $psql->{timeout} = IPC::Run::timeout(
104 defined($timeout)
105 ? $timeout
106 : $PostgreSQL::Test::Utils::timeout_default);
107
108 if ($interactive)
109 {
110 $run = IPC::Run::start $psql_params,
111 '<pty<' => \$psql->{stdin},
112 '>pty>' => \$psql->{stdout},
113 '2>' => \$psql->{stderr},
114 $psql->{timeout};
115 }
116 else
117 {
118 $run = IPC::Run::start $psql_params,
119 '<' => \$psql->{stdin},
120 '>' => \$psql->{stdout},
121 '2>' => \$psql->{stderr},
122 $psql->{timeout};
123 }
124
125 $psql->{run} = $run;
126
127 my $self = bless $psql, $class;
128
129 $wait = 1 unless defined($wait);
130 if ($wait)
131 {
132 $self->wait_connect();
133 }
134
135 return $self;
136 }
137
138 =pod
139
140 =item $session->wait_connect
141
142 Returns once psql has started up and is ready to consume input. This is called
143 automatically for clients unless requested otherwise in the constructor.
144
145 =cut
146
147 sub wait_connect
148 {
149 my ($self) = @_;
150
151 # Request some output, and pump until we see it. This means that psql
152 # connection failures are caught here, relieving callers of the need to
153 # handle those. (Right now, we have no particularly good handling for
154 # errors anyway, but that might be added later.)
155 #
156 # See query() for details about why/how the banner is used.
157 my $banner = "background_psql: ready";
158 my $banner_match = qr/$banner\r?\n/;
159 $self->{stdin} .= "\\echo '$banner'\n\\warn '$banner'\n";
160 $self->{run}->pump()
161 until ($self->{stdout} =~ /$banner_match/
162 && $self->{stderr} =~ /$banner_match/)
163 || $self->{timeout}->is_expired;
164
165 note "connect output:\n",
166 explain {
167 stdout => $self->{stdout},
168 stderr => $self->{stderr},
169 };
170
171 # clear out banners
172 $self->{stdout} = '';
173 $self->{stderr} = '';
174
175 die "psql startup timed out" if $self->{timeout}->is_expired;
176 }
177
178 =pod
179
180 =item $session->quit
181
182 Close the session and clean up resources. Each test run must be closed with
183 C<quit>.
184
185 =cut
186
187 sub quit
188 {
189 my ($self) = @_;
190
191 $self->{stdin} .= "\\q\n";
192
193 return $self->{run}->finish;
194 }
195
196 =pod
197
198 =item $session->reconnect_and_clear
199
200 Terminate the current session and connect again.
201
202 =cut
203
204 sub reconnect_and_clear
205 {
206 my ($self) = @_;
207
208 # If psql isn't dead already, tell it to quit as \q, when already dead,
209 # causes IPC::Run to unhelpfully error out with "ack Broken pipe:".
210 $self->{run}->pump_nb();
211 if ($self->{run}->pumpable())
212 {
213 $self->{stdin} .= "\\q\n";
214 }
215 $self->{run}->finish;
216
217 # restart
218 $self->{run}->run();
219 $self->{stdin} = '';
220 $self->{stdout} = '';
221
222 $self->wait_connect();
223 }
224
225 =pod
226
227 =item $session->query()
228
229 Executes a query in the current session and returns the output in scalar
230 context and (output, error) in list context where error is 1 in case there
231 was output generated on stderr when executing the query.
232
233 =cut
234
235 sub query
236 {
237 my ($self, $query) = @_;
238 my $ret;
239 my $output;
240 my $query_cnt = $self->{query_cnt}++;
241
242 local $Test::Builder::Level = $Test::Builder::Level + 1;
243
244 note "issuing query $query_cnt via background psql: $query";
245
246 $self->{timeout}->start() if (defined($self->{query_timer_restart}));
247
248 # Feed the query to psql's stdin, followed by \n (so psql processes the
249 # line), by a ; (so that psql issues the query, if it doesn't include a ;
250 # itself), and a separator echoed both with \echo and \warn, that we can
251 # wait on.
252 #
253 # To avoid somehow confusing the separator from separately issued queries,
254 # and to make it easier to debug, we include a per-psql query counter in
255 # the separator.
256 #
257 # We need both \echo (printing to stdout) and \warn (printing to stderr),
258 # because on windows we can get data on stdout before seeing data on
259 # stderr (or vice versa), even if psql printed them in the opposite
260 # order. We therefore wait on both.
261 #
262 # In interactive psql we emit \r\n, so we need to allow for that.
263 # Also, include quotes around the banner string in the \echo and \warn
264 # commands, not because the string needs quoting but so that $banner_match
265 # can't match readline's echoing of these commands.
266 my $banner = "background_psql: QUERY_SEPARATOR $query_cnt:";
267 my $banner_match = qr/$banner\r?\n/;
268 $self->{stdin} .= "$query\n;\n\\echo '$banner'\n\\warn '$banner'\n";
269 $self->{run}->pump()
270 until ($self->{stdout} =~ /$banner_match/
271 && $self->{stderr} =~ /$banner_match/)
272 || $self->{timeout}->is_expired;
273
274 note "results query $query_cnt:\n",
275 explain {
276 stdout => $self->{stdout},
277 stderr => $self->{stderr},
278 };
279
280 die "psql query timed out" if $self->{timeout}->is_expired;
281
282 # Remove banner from stdout and stderr, our caller doesn't want it.
283 # Also remove the query output's trailing newline, if present (there
284 # would not be one if consuming an empty query result).
285 $banner_match = qr/\r?\n?$banner\r?\n/;
286 $output = $self->{stdout};
287 $output =~ s/$banner_match//;
288 $self->{stderr} =~ s/$banner_match//;
289
290 # clear out output for the next query
291 $self->{stdout} = '';
292
293 $ret = $self->{stderr} eq "" ? 0 : 1;
294
295 return wantarray ? ($output, $ret) : $output;
296 }
297
298 =pod
299
300 =item $session->query_safe()
301
302 Wrapper around C<query> which errors out if the query failed to execute.
303 Query failure is determined by it producing output on stderr.
304
305 =cut
306
307 sub query_safe
308 {
309 my ($self, $query) = @_;
310
311 my $ret = $self->query($query);
312
313 if ($self->{stderr} ne "")
314 {
315 die "query failed: $self->{stderr}";
316 }
317
318 return $ret;
319 }
320
321 =pod
322
323 =item $session->query_until(until, query)
324
325 Issue C<query> and wait for C<until> appearing in the query output rather than
326 waiting for query completion. C<query> needs to end with newline and semicolon
327 (if applicable, interactive psql input may not require it) for psql to process
328 the input.
329
330 =cut
331
332 sub query_until
333 {
334 my ($self, $until, $query) = @_;
335 my $ret;
336 local $Test::Builder::Level = $Test::Builder::Level + 1;
337
338 $self->{timeout}->start() if (defined($self->{query_timer_restart}));
339 $self->{stdin} .= $query;
340
341 pump_until($self->{run}, $self->{timeout}, \$self->{stdout}, $until);
342
343 die "psql query timed out" if $self->{timeout}->is_expired;
344
345 $ret = $self->{stdout};
346
347 # clear out output for the next query
348 $self->{stdout} = '';
349
350 return $ret;
351 }
352
353 =pod
354
355 =item $session->set_query_timer_restart()
356
357 Configures the timer to be restarted before each query such that the defined
358 timeout is valid per query rather than per test run.
359
360 =back
361
362 =cut
363
364 sub set_query_timer_restart
365 {
366 my $self = shift;
367
368 $self->{query_timer_restart} = 1;
369 return $self->{query_timer_restart};
370 }
371
372 1;