Debian Codegraph @

src/bin/pgbench/t/001_pgbench_with_server.pl

raw
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 use strict;
5 use warnings FATAL => 'all';
6
7 use PostgreSQL::Test::Cluster;
8 use PostgreSQL::Test::Utils;
9 use Test::More;
10
11 # Check the initial state of the data generated. Tables for tellers and
12 # branches use NULL for their filler attribute. The table accounts uses
13 # a non-NULL filler. The history table should have no data.
14 sub check_data_state
15 {
16 local $Test::Builder::Level = $Test::Builder::Level + 1;
17 my $node = shift;
18 my $type = shift;
19
20 my $sql_result = $node->safe_psql('postgres',
21 'SELECT count(*) AS null_count FROM pgbench_accounts WHERE filler IS NULL LIMIT 10;'
22 );
23 is($sql_result, '0',
24 "$type: filler column of pgbench_accounts has no NULL data");
25 $sql_result = $node->safe_psql('postgres',
26 'SELECT count(*) AS null_count FROM pgbench_branches WHERE filler IS NULL;'
27 );
28 is($sql_result, '1',
29 "$type: filler column of pgbench_branches has only NULL data");
30 $sql_result = $node->safe_psql('postgres',
31 'SELECT count(*) AS null_count FROM pgbench_tellers WHERE filler IS NULL;'
32 );
33 is($sql_result, '10',
34 "$type: filler column of pgbench_tellers has only NULL data");
35 $sql_result = $node->safe_psql('postgres',
36 'SELECT count(*) AS data_count FROM pgbench_history;');
37 is($sql_result, '0', "$type: pgbench_history has no data");
38 }
39
40 # start a pgbench specific server
41 my $node = PostgreSQL::Test::Cluster->new('main');
42 # Set to untranslated messages, to be able to compare program output with
43 # expected strings.
44 $node->init(extra => [ '--locale', 'C' ]);
45 $node->start;
46
47 # tablespace for testing, because partitioned tables cannot use pg_default
48 # explicitly and we want to test that table creation with tablespace works
49 # for partitioned tables.
50 my $ts = $node->basedir . '/regress_pgbench_tap_1_ts_dir';
51 mkdir $ts or die "cannot create directory $ts";
52
53 # the next commands will issue a syntax error if the path contains a "'"
54 $node->safe_psql('postgres',
55 "CREATE TABLESPACE regress_pgbench_tap_1_ts LOCATION '$ts';");
56
57 # Test concurrent OID generation via pg_enum_oid_index. This indirectly
58 # exercises LWLock and spinlock concurrency.
59 my $labels = join ',', map { "'l$_'" } 1 .. 1000;
60 $node->pgbench(
61 '--no-vacuum --client=5 --protocol=prepared --transactions=25',
62 0,
63 [qr{processed: 125/125}],
64 [qr{^$}],
65 'concurrent OID generation',
66 {
67 '001_pgbench_concurrent_insert' =>
68 "CREATE TYPE pg_temp.e AS ENUM ($labels); DROP TYPE pg_temp.e;"
69 });
70
71 # Test inplace updates from VACUUM concurrent with heap_update from GRANT.
72 # The PROC_IN_VACUUM environment can't finish MVCC table scans consistently,
73 # so this fails rarely. To reproduce consistently, add a sleep after
74 # GetCatalogSnapshot(non-catalog-rel).
75 Test::More->builder->todo_start('PROC_IN_VACUUM scan breakage');
76 $node->safe_psql('postgres', 'CREATE TABLE ddl_target ()');
77 $node->pgbench(
78 '--no-vacuum --client=5 --protocol=prepared --transactions=50',
79 0,
80 [qr{processed: 250/250}],
81 [qr{^$}],
82 'concurrent GRANT/VACUUM',
83 {
84 '001_pgbench_grant@9' => q(
85 DO $$
86 BEGIN
87 PERFORM pg_advisory_xact_lock(42);
88 FOR i IN 1 .. 10 LOOP
89 GRANT SELECT ON ddl_target TO PUBLIC;
90 REVOKE SELECT ON ddl_target FROM PUBLIC;
91 END LOOP;
92 END
93 $$;
94 ),
95 '001_pgbench_vacuum_ddl_target@1' => "VACUUM ddl_target;",
96 });
97 Test::More->builder->todo_end;
98
99 # Trigger various connection errors
100 $node->pgbench(
101 'no-such-database',
102 1,
103 [qr{^$}],
104 [
105 qr{connection to server .* failed},
106 qr{FATAL: database "no-such-database" does not exist}
107 ],
108 'no such database');
109
110 $node->pgbench(
111 '-S -t 1', 1, [],
112 [qr{Perhaps you need to do initialization}],
113 'run without init');
114
115 # Initialize pgbench tables scale 1
116 $node->pgbench(
117 '-i', 0,
118 [qr{^$}],
119 [
120 qr{creating tables},
121 qr{vacuuming},
122 qr{creating primary keys},
123 qr{done in \d+\.\d\d s }
124 ],
125 'pgbench scale 1 initialization',);
126
127 # Check data state, after client-side data generation.
128 check_data_state($node, 'client-side');
129
130 # Again, with all possible options
131 $node->pgbench(
132 '--initialize --init-steps=dtpvg --scale=1 --unlogged-tables --fillfactor=98 --foreign-keys --quiet --tablespace=regress_pgbench_tap_1_ts --index-tablespace=regress_pgbench_tap_1_ts --partitions=2 --partition-method=hash',
133 0,
134 [qr{^$}i],
135 [
136 qr{dropping old tables},
137 qr{creating tables},
138 qr{creating 2 partitions},
139 qr{vacuuming},
140 qr{creating primary keys},
141 qr{creating foreign keys},
142 qr{(?!vacuuming)}, # no vacuum
143 qr{done in \d+\.\d\d s }
144 ],
145 'pgbench scale 1 initialization');
146
147 # Test interaction of --init-steps with legacy step-selection options
148 $node->pgbench(
149 '--initialize --init-steps=dtpvGvv --no-vacuum --foreign-keys --unlogged-tables --partitions=3',
150 0,
151 [qr{^$}],
152 [
153 qr{dropping old tables},
154 qr{creating tables},
155 qr{creating 3 partitions},
156 qr{creating primary keys},
157 qr{generating data \(server-side\)},
158 qr{creating foreign keys},
159 qr{(?!vacuuming)}, # no vacuum
160 qr{done in \d+\.\d\d s }
161 ],
162 'pgbench --init-steps');
163
164 # Check data state, after server-side data generation.
165 check_data_state($node, 'server-side');
166
167 # Run all builtin scripts, for a few transactions each
168 $node->pgbench(
169 '--transactions=5 -Dfoo=bla --client=2 --protocol=simple --builtin=t'
170 . ' --connect -n -v -n',
171 0,
172 [
173 qr{builtin: TPC-B},
174 qr{clients: 2\b},
175 qr{processed: 10/10},
176 qr{mode: simple},
177 qr{maximum number of tries: 1}
178 ],
179 [qr{^$}],
180 'pgbench tpcb-like');
181
182 $node->pgbench(
183 '--transactions=20 --client=5 -M extended --builtin=si -C --no-vacuum -s 1',
184 0,
185 [
186 qr{builtin: simple update},
187 qr{clients: 5\b},
188 qr{threads: 1\b},
189 qr{processed: 100/100},
190 qr{mode: extended}
191 ],
192 [qr{scale option ignored}],
193 'pgbench simple update');
194
195 $node->pgbench(
196 '-t 100 -c 7 -M prepared -b se --debug',
197 0,
198 [
199 qr{builtin: select only},
200 qr{clients: 7\b},
201 qr{threads: 1\b},
202 qr{processed: 700/700},
203 qr{mode: prepared}
204 ],
205 [
206 qr{vacuum}, qr{client 0}, qr{client 1}, qr{sending},
207 qr{receiving}, qr{executing}
208 ],
209 'pgbench select only');
210
211 # check if threads are supported
212 my $nthreads = 2;
213
214 {
215 my ($stderr);
216 run_log([ 'pgbench', '--jobs' => '2', '--bad-option' ], '2>' => \$stderr);
217 $nthreads = 1 if $stderr =~ m/threads are not supported on this platform/;
218 }
219
220 # run custom scripts
221 $node->pgbench(
222 "-t 100 -c 1 -j $nthreads -M prepared -n",
223 0,
224 [
225 qr{type: multiple scripts},
226 qr{mode: prepared},
227 qr{script 1: .*/001_pgbench_custom_script_1},
228 qr{weight: 2},
229 qr{script 2: .*/001_pgbench_custom_script_2},
230 qr{weight: 1},
231 qr{processed: 100/100}
232 ],
233 [qr{^$}],
234 'pgbench custom scripts',
235 {
236 '001_pgbench_custom_script_1@1' => q{-- select only
237 \set aid random(1, :scale * 100000)
238 SELECT abalance::INTEGER AS balance
239 FROM pgbench_accounts
240 WHERE aid=:aid;
241 },
242 '001_pgbench_custom_script_2@2' => q{-- special variables
243 BEGIN;
244 \set foo 1
245 -- cast are needed for typing under -M prepared
246 SELECT :foo::INT + :scale::INT * :client_id::INT AS bla;
247 COMMIT;
248 }
249 });
250
251 $node->pgbench(
252 '-n -t 10 -c 1 -M simple',
253 0,
254 [
255 qr{type: .*/001_pgbench_custom_script_3},
256 qr{processed: 10/10},
257 qr{mode: simple}
258 ],
259 [qr{^$}],
260 'pgbench custom script',
261 {
262 '001_pgbench_custom_script_3' => q{-- select only variant
263 \set aid random(1, :scale * 100000)
264 BEGIN;
265 SELECT abalance::INTEGER AS balance
266 FROM pgbench_accounts
267 WHERE aid=:aid;
268 COMMIT;
269 }
270 });
271
272 $node->pgbench(
273 '-n -t 10 -c 2 -M extended',
274 0,
275 [
276 qr{type: .*/001_pgbench_custom_script_4},
277 qr{processed: 20/20},
278 qr{mode: extended}
279 ],
280 [qr{^$}],
281 'pgbench custom script',
282 {
283 '001_pgbench_custom_script_4' => q{-- select only variant
284 \set aid random(1, :scale * 100000)
285 BEGIN;
286 SELECT abalance::INTEGER AS balance
287 FROM pgbench_accounts
288 WHERE aid=:aid;
289 COMMIT;
290 }
291 });
292
293 # Verify server logging of query parameters.
294 # (This doesn't really belong here, but pgbench is a convenient way
295 # to issue commands using extended query mode with parameters.)
296
297 # 1. Logging neither with errors nor with statements
298 $node->append_conf('postgresql.conf',
299 "log_min_duration_statement = 0\n"
300 . "log_parameter_max_length = 0\n"
301 . "log_parameter_max_length_on_error = 0");
302 $node->reload;
303 $node->pgbench(
304 '-n -t1 -c1 -M prepared',
305 2,
306 [],
307 [
308 qr{ERROR: invalid input syntax for type json},
309 qr{(?!unnamed portal with parameters)}
310 ],
311 'server parameter logging',
312 {
313 '001_param_1' => q[select '{ invalid ' as value \gset
314 select $$'Valame Dios!' dijo Sancho; 'no le dije yo a vuestra merced que mirase bien lo que hacia?'$$ as long \gset
315 select column1::jsonb from (values (:value), (:long)) as q;
316 ]
317 });
318 my $log = PostgreSQL::Test::Utils::slurp_file($node->logfile);
319 unlike(
320 $log,
321 qr[DETAIL: Parameters: \$1 = '\{ invalid ',],
322 "no parameters logged");
323 $log = undef;
324
325 # 2. Logging truncated parameters on error, full with statements
326 $node->append_conf('postgresql.conf',
327 "log_parameter_max_length = -1\n"
328 . "log_parameter_max_length_on_error = 64");
329 $node->reload;
330 $node->pgbench(
331 '-n -t1 -c1 -M prepared',
332 2,
333 [],
334 [
335 qr{ERROR: division by zero},
336 qr{CONTEXT: unnamed portal with parameters: \$1 = '1', \$2 = NULL}
337 ],
338 'server parameter logging',
339 {
340 '001_param_2' => q{select '1' as one \gset
341 SELECT 1 / (random() / 2)::int, :one::int, :two::int;
342 }
343 });
344 $node->pgbench(
345 '-n -t1 -c1 -M prepared',
346 2,
347 [],
348 [
349 qr{ERROR: invalid input syntax for type json},
350 qr[CONTEXT: JSON data, line 1: \{ invalid\.\.\.[\r\n]+unnamed portal with parameters: \$1 = '\{ invalid ', \$2 = '''Valame Dios!'' dijo Sancho; ''no le dije yo a vuestra merced que \.\.\.']m
351 ],
352 'server parameter logging',
353 {
354 '001_param_3' => q[select '{ invalid ' as value \gset
355 select $$'Valame Dios!' dijo Sancho; 'no le dije yo a vuestra merced que mirase bien lo que hacia?'$$ as long \gset
356 select column1::jsonb from (values (:value), (:long)) as q;
357 ]
358 });
359 $log = PostgreSQL::Test::Utils::slurp_file($node->logfile);
360 like(
361 $log,
362 qr[DETAIL: Parameters: \$1 = '\{ invalid ', \$2 = '''Valame Dios!'' dijo Sancho; ''no le dije yo a vuestra merced que mirase bien lo que hacia\?'''],
363 "parameter report does not truncate");
364 $log = undef;
365
366 # 3. Logging full parameters on error, truncated with statements
367 $node->append_conf('postgresql.conf',
368 "log_min_duration_statement = -1\n"
369 . "log_parameter_max_length = 7\n"
370 . "log_parameter_max_length_on_error = -1");
371 $node->reload;
372 $node->pgbench(
373 '-n -t1 -c1 -M prepared',
374 2,
375 [],
376 [
377 qr{ERROR: division by zero},
378 qr{CONTEXT: unnamed portal with parameters: \$1 = '1', \$2 = NULL}
379 ],
380 'server parameter logging',
381 {
382 '001_param_4' => q{select '1' as one \gset
383 SELECT 1 / (random() / 2)::int, :one::int, :two::int;
384 }
385 });
386
387 $node->append_conf('postgresql.conf', "log_min_duration_statement = 0");
388 $node->reload;
389 $node->pgbench(
390 '-n -t1 -c1 -M prepared',
391 2,
392 [],
393 [
394 qr{ERROR: invalid input syntax for type json},
395 qr[CONTEXT: JSON data, line 1: \{ invalid\.\.\.[\r\n]+unnamed portal with parameters: \$1 = '\{ invalid ', \$2 = '''Valame Dios!'' dijo Sancho; ''no le dije yo a vuestra merced que mirase bien lo que hacia\?']m
396 ],
397 'server parameter logging',
398 {
399 '001_param_5' => q[select '{ invalid ' as value \gset
400 select $$'Valame Dios!' dijo Sancho; 'no le dije yo a vuestra merced que mirase bien lo que hacia?'$$ as long \gset
401 select column1::jsonb from (values (:value), (:long)) as q;
402 ]
403 });
404 $log = PostgreSQL::Test::Utils::slurp_file($node->logfile);
405 like(
406 $log,
407 qr[DETAIL: Parameters: \$1 = '\{ inval\.\.\.', \$2 = '''Valame\.\.\.'],
408 "parameter report truncates");
409 $log = undef;
410
411 # Check that bad parameters are reported during typinput phase of BIND
412 $node->pgbench(
413 '-n -t1 -c1 -M prepared',
414 2,
415 [],
416 [
417 qr{ERROR: invalid input syntax for type smallint: "1a"},
418 qr{CONTEXT: unnamed portal parameter \$2 = '1a'}
419 ],
420 'server parameter logging',
421 {
422 '001_param_6' => q{select 42 as value1, '1a' as value2 \gset
423 select :value1::smallint, :value2::smallint;
424 }
425 });
426
427 # Restore default logging config
428 $node->append_conf('postgresql.conf',
429 "log_min_duration_statement = -1\n"
430 . "log_parameter_max_length_on_error = 0\n"
431 . "log_parameter_max_length = -1");
432 $node->reload;
433
434 # test expressions
435 $node->pgbench(
436 '--random-seed=5432 -t 1 -Dfoo=-10.1 -Dbla=false -Di=+3 -Dn=null -Dt=t -Df=of -Dd=1.0',
437 0,
438 [ qr{type: .*/001_pgbench_expressions}, qr{processed: 1/1} ],
439 [
440 qr{setting random seed to 5432\b},
441
442 # After explicit seeding, the four random checks (1-3,20) are
443 # deterministic; but see also magic values in checks 111,113.
444 qr{command=1.: int 17\b}, # uniform random
445 qr{command=2.: int 104\b}, # exponential random
446 qr{command=3.: int 1498\b}, # gaussian random
447 qr{command=4.: int 4\b},
448 qr{command=5.: int 5\b},
449 qr{command=6.: int 6\b},
450 qr{command=7.: int 7\b},
451 qr{command=8.: int 8\b},
452 qr{command=9.: int 9\b},
453 qr{command=10.: int 10\b},
454 qr{command=11.: int 11\b},
455 qr{command=12.: int 12\b},
456 qr{command=15.: double 15\b},
457 qr{command=16.: double 16\b},
458 qr{command=17.: double 17\b},
459 qr{command=20.: int 3\b}, # zipfian random
460 qr{command=21.: double -27\b},
461 qr{command=22.: double 1024\b},
462 qr{command=23.: double 1\b},
463 qr{command=24.: double 1\b},
464 qr{command=25.: double -0.125\b},
465 qr{command=26.: double -0.125\b},
466 qr{command=27.: double -0.00032\b},
467 qr{command=28.: double 8.50705917302346e\+0?37\b},
468 qr{command=29.: double 1e\+0?30\b},
469 qr{command=30.: boolean false\b},
470 qr{command=31.: boolean true\b},
471 qr{command=32.: int 32\b},
472 qr{command=33.: int 33\b},
473 qr{command=34.: double 34\b},
474 qr{command=35.: int 35\b},
475 qr{command=36.: int 36\b},
476 qr{command=37.: double 37\b},
477 qr{command=38.: int 38\b},
478 qr{command=39.: int 39\b},
479 qr{command=40.: boolean true\b},
480 qr{command=41.: null\b},
481 qr{command=42.: null\b},
482 qr{command=43.: boolean true\b},
483 qr{command=44.: boolean true\b},
484 qr{command=45.: boolean true\b},
485 qr{command=46.: int 46\b},
486 qr{command=47.: boolean true\b},
487 qr{command=48.: boolean true\b},
488 qr{command=49.: int -5817877081768721676\b},
489 qr{command=50.: boolean true\b},
490 qr{command=51.: int -7793829335365542153\b},
491 qr{command=52.: int -?\d+\b},
492 qr{command=53.: boolean true\b},
493 qr{command=65.: int 65\b},
494 qr{command=74.: int 74\b},
495 qr{command=83.: int 83\b},
496 qr{command=86.: int 86\b},
497 qr{command=93.: int 93\b},
498 qr{command=95.: int 0\b},
499 qr{command=96.: int 1\b}, # :scale
500 qr{command=97.: int 0\b}, # :client_id
501 qr{command=98.: int 5432\b}, # :random_seed
502 qr{command=99.: int -9223372036854775808\b}, # min int
503 qr{command=100.: int 9223372036854775807\b}, # max int
504 # pseudorandom permutation tests
505 qr{command=101.: boolean true\b},
506 qr{command=102.: boolean true\b},
507 qr{command=103.: boolean true\b},
508 qr{command=104.: boolean true\b},
509 qr{command=105.: boolean true\b},
510 qr{command=109.: boolean true\b},
511 qr{command=110.: boolean true\b},
512 qr{command=111.: boolean true\b},
513 qr{command=113.: boolean true\b},
514 ],
515 'pgbench expressions',
516 {
517 '001_pgbench_expressions' => q{-- integer functions
518 \set i1 debug(random(10, 19))
519 \set i2 debug(random_exponential(100, 199, 10.0))
520 \set i3 debug(random_gaussian(1000, 1999, 10.0))
521 \set i4 debug(abs(-4))
522 \set i5 debug(greatest(5, 4, 3, 2))
523 \set i6 debug(11 + least(-5, -4, -3, -2))
524 \set i7 debug(int(7.3))
525 -- integer arithmetic and bit-wise operators
526 \set i8 debug(17 / (4|1) + ( 4 + (7 >> 2)))
527 \set i9 debug(- (3 * 4 - (-(~ 1) + -(~ 0))) / -1 + 3 % -1)
528 \set ia debug(10 + (0 + 0 * 0 - 0 / 1))
529 \set ib debug(:ia + :scale)
530 \set ic debug(64 % (((2 + 1 * 2 + (1 # 2) | 4 * (2 & 11)) - (1 << 2)) + 2))
531 -- double functions and operators
532 \set d1 debug(sqrt(+1.5 * 2.0) * abs(-0.8E1))
533 \set d2 debug(double(1 + 1) * (-75.0 / :foo))
534 \set pi debug(pi() * 4.9)
535 \set d4 debug(greatest(4, 2, -1.17) * 4.0 * Ln(Exp(1.0)))
536 \set d5 debug(least(-5.18, .0E0, 1.0/0) * -3.3)
537 -- reset variables
538 \set i1 0
539 \set d1 false
540 -- yet another integer function
541 \set id debug(random_zipfian(1, 9, 1.3))
542 --- pow and power
543 \set poweri debug(pow(-3,3))
544 \set powerd debug(pow(2.0,10))
545 \set poweriz debug(pow(0,0))
546 \set powerdz debug(pow(0.0,0.0))
547 \set powernegi debug(pow(-2,-3))
548 \set powernegd debug(pow(-2.0,-3.0))
549 \set powernegd2 debug(power(-5.0,-5.0))
550 \set powerov debug(pow(9223372036854775807, 2))
551 \set powerov2 debug(pow(10,30))
552 -- comparisons and logical operations
553 \set c0 debug(1.0 = 0.0 and 1.0 != 0.0)
554 \set c1 debug(0 = 1 Or 1.0 = 1)
555 \set c4 debug(case when 0 < 1 then 32 else 0 end)
556 \set c5 debug(case when true then 33 else 0 end)
557 \set c6 debug(case when false THEN -1 when 1 = 1 then 13 + 19 + 2.0 end )
558 \set c7 debug(case when (1 > 0) and (1 >= 0) and (0 < 1) and (0 <= 1) and (0 != 1) and (0 = 0) and (0 <> 1) then 35 else 0 end)
559 \set c8 debug(CASE \
560 WHEN (1.0 > 0.0) AND (1.0 >= 0.0) AND (0.0 < 1.0) AND (0.0 <= 1.0) AND \
561 (0.0 != 1.0) AND (0.0 = 0.0) AND (0.0 <> 1.0) AND (0.0 = 0.0) \
562 THEN 36 \
563 ELSE 0 \
564 END)
565 \set c9 debug(CASE WHEN NOT FALSE THEN 3 * 12.3333334 END)
566 \set ca debug(case when false then 0 when 1-1 <> 0 then 1 else 38 end)
567 \set cb debug(10 + mod(13 * 7 + 12, 13) - mod(-19 * 11 - 17, 19))
568 \set cc debug(NOT (0 > 1) AND (1 <= 1) AND NOT (0 >= 1) AND (0 < 1) AND \
569 NOT (false and true) AND (false OR TRUE) AND (NOT :f) AND (NOT FALSE) AND \
570 NOT (NOT TRUE))
571 -- NULL value and associated operators
572 \set n0 debug(NULL + NULL * exp(NULL))
573 \set n1 debug(:n0)
574 \set n2 debug(NOT (:n0 IS NOT NULL OR :d1 IS NULL))
575 \set n3 debug(:n0 IS NULL AND :d1 IS NOT NULL AND :d1 NOTNULL)
576 \set n4 debug(:n0 ISNULL AND NOT :n0 IS TRUE AND :n0 IS NOT FALSE)
577 \set n5 debug(CASE WHEN :n IS NULL THEN 46 ELSE NULL END)
578 -- use a variables of all types
579 \set n6 debug(:n IS NULL AND NOT :f AND :t)
580 -- conditional truth
581 \set cs debug(CASE WHEN 1 THEN TRUE END AND CASE WHEN 1.0 THEN TRUE END AND CASE WHEN :n THEN NULL ELSE TRUE END)
582 -- hash functions
583 \set h0 debug(hash(10, 5432))
584 \set h1 debug(:h0 = hash_murmur2(10, 5432))
585 \set h3 debug(hash_fnv1a(10, 5432))
586 \set h4 debug(hash(10))
587 \set h5 debug(hash(10) = hash(10, :default_seed))
588 -- lazy evaluation
589 \set zy 0
590 \set yz debug(case when :zy = 0 then -1 else (1 / :zy) end)
591 \set yz debug(case when :zy = 0 or (1 / :zy) < 0 then -1 else (1 / :zy) end)
592 \set yz debug(case when :zy > 0 and (1 / :zy) < 0 then (1 / :zy) else 1 end)
593 -- substitute variables of all possible types
594 \set v0 NULL
595 \set v1 TRUE
596 \set v2 5432
597 \set v3 -54.21E-2
598 SELECT :v0, :v1, :v2, :v3;
599 -- if tests
600 \set nope 0
601 \if 1 > 0
602 \set id debug(65)
603 \elif 0
604 \set nope 1
605 \else
606 \set nope 1
607 \endif
608 \if 1 < 0
609 \set nope 1
610 \elif 1 > 0
611 \set ie debug(74)
612 \else
613 \set nope 1
614 \endif
615 \if 1 < 0
616 \set nope 1
617 \elif 1 < 0
618 \set nope 1
619 \else
620 \set if debug(83)
621 \endif
622 \if 1 = 1
623 \set ig debug(86)
624 \elif 0
625 \set nope 1
626 \endif
627 \if 1 = 0
628 \set nope 1
629 \elif 1 <> 0
630 \set ih debug(93)
631 \endif
632 -- must be zero if false branches where skipped
633 \set nope debug(:nope)
634 -- check automatic variables
635 \set sc debug(:scale)
636 \set ci debug(:client_id)
637 \set rs debug(:random_seed)
638 -- minint constant parsing
639 \set min debug(-9223372036854775808)
640 \set max debug(-(:min + 1))
641 -- parametric pseudorandom permutation function
642 \set t debug(permute(0, 2) + permute(1, 2) = 1)
643 \set t debug(permute(0, 3) + permute(1, 3) + permute(2, 3) = 3)
644 \set t debug(permute(0, 4) + permute(1, 4) + permute(2, 4) + permute(3, 4) = 6)
645 \set t debug(permute(0, 5) + permute(1, 5) + permute(2, 5) + permute(3, 5) + permute(4, 5) = 10)
646 \set t debug(permute(0, 16) + permute(1, 16) + permute(2, 16) + permute(3, 16) + \
647 permute(4, 16) + permute(5, 16) + permute(6, 16) + permute(7, 16) + \
648 permute(8, 16) + permute(9, 16) + permute(10, 16) + permute(11, 16) + \
649 permute(12, 16) + permute(13, 16) + permute(14, 16) + permute(15, 16) = 120)
650 -- random sanity checks
651 \set size random(2, 1000)
652 \set v random(0, :size - 1)
653 \set p permute(:v, :size)
654 \set t debug(0 <= :p and :p < :size and :p = permute(:v + :size, :size) and :p <> permute(:v + 1, :size))
655 -- actual values
656 \set t debug(permute(:v, 1) = 0)
657 \set t debug(permute(0, 2, 5431) = 0 and permute(1, 2, 5431) = 1 and \
658 permute(0, 2, 5433) = 1 and permute(1, 2, 5433) = 0)
659 -- check permute's portability across architectures
660 \set size debug(:max - 10)
661 \set t debug(permute(:size-1, :size, 5432) = 520382784483822430 and \
662 permute(:size-2, :size, 5432) = 1143715004660802862 and \
663 permute(:size-3, :size, 5432) = 447293596416496998 and \
664 permute(:size-4, :size, 5432) = 916527772266572956 and \
665 permute(:size-5, :size, 5432) = 2763809008686028849 and \
666 permute(:size-6, :size, 5432) = 8648551549198294572 and \
667 permute(:size-7, :size, 5432) = 4542876852200565125)
668 }
669 });
670
671 # test nested \if constructs
672 $node->pgbench(
673 '--no-vacuum --client=1 --exit-on-abort --transactions=1',
674 0,
675 [qr{actually processed}],
676 [qr{^$}],
677 'nested ifs',
678 {
679 'pgbench_nested_if' => q(
680 \if false
681 SELECT 1 / 0;
682 \if true
683 SELECT 1 / 0;
684 \elif true
685 SELECT 1 / 0;
686 \else
687 SELECT 1 / 0;
688 \endif
689 SELECT 1 / 0;
690 \elif false
691 \if true
692 SELECT 1 / 0;
693 \elif true
694 SELECT 1 / 0;
695 \else
696 SELECT 1 / 0;
697 \endif
698 \else
699 \if false
700 SELECT 1 / 0;
701 \elif false
702 SELECT 1 / 0;
703 \else
704 SELECT 'correct';
705 \endif
706 \endif
707 \if true
708 SELECT 'correct';
709 \else
710 \if true
711 SELECT 1 / 0;
712 \elif true
713 SELECT 1 / 0;
714 \else
715 SELECT 1 / 0;
716 \endif
717 \endif
718 )
719 });
720
721 # random determinism when seeded
722 $node->safe_psql('postgres',
723 'CREATE UNLOGGED TABLE seeded_random(seed INT8 NOT NULL, rand TEXT NOT NULL, val INTEGER NOT NULL);'
724 );
725
726 # same value to check for determinism
727 my $seed = int(rand(1000000000));
728 for my $i (1, 2)
729 {
730 $node->pgbench(
731 "--random-seed=$seed -t 1",
732 0,
733 [qr{processed: 1/1}],
734 [qr{setting random seed to $seed\b}],
735 "random seeded with $seed",
736 {
737 "001_pgbench_random_seed_$i" => q{-- test random functions
738 \set ur random(1000, 1999)
739 \set er random_exponential(2000, 2999, 2.0)
740 \set gr random_gaussian(3000, 3999, 3.0)
741 \set zr random_zipfian(4000, 4999, 1.5)
742 INSERT INTO seeded_random(seed, rand, val) VALUES
743 (:random_seed, 'uniform', :ur),
744 (:random_seed, 'exponential', :er),
745 (:random_seed, 'gaussian', :gr),
746 (:random_seed, 'zipfian', :zr);
747 }
748 });
749 }
750
751 # check that all runs generated the same 4 values
752 my ($ret, $out, $err) = $node->psql('postgres',
753 'SELECT seed, rand, val, COUNT(*) FROM seeded_random GROUP BY seed, rand, val'
754 );
755
756 ok($ret == 0, "psql seeded_random count ok");
757 ok($err eq '', "psql seeded_random count stderr is empty");
758 ok($out =~ /\b$seed\|uniform\|1\d\d\d\|2/,
759 "psql seeded_random count uniform");
760 ok( $out =~ /\b$seed\|exponential\|2\d\d\d\|2/,
761 "psql seeded_random count exponential");
762 ok( $out =~ /\b$seed\|gaussian\|3\d\d\d\|2/,
763 "psql seeded_random count gaussian");
764 ok($out =~ /\b$seed\|zipfian\|4\d\d\d\|2/,
765 "psql seeded_random count zipfian");
766
767 $node->safe_psql('postgres', 'DROP TABLE seeded_random;');
768
769 # backslash commands
770 $node->pgbench(
771 '-t 1', 0,
772 [
773 qr{type: .*/001_pgbench_backslash_commands},
774 qr{processed: 1/1},
775 qr{shell-echo-output}
776 ],
777 [qr{command=8.: int 1\b}],
778 'pgbench backslash commands',
779 {
780 '001_pgbench_backslash_commands' => q{-- run set
781 \set zero 0
782 \set one 1.0
783 -- sleep
784 \sleep :one ms
785 \sleep 100 us
786 \sleep 0 s
787 \sleep :zero
788 -- setshell and continuation
789 \setshell another_one\
790 echo \
791 :one
792 \set n debug(:another_one)
793 -- shell
794 \shell echo shell-echo-output
795 }
796 });
797
798 # working \gset
799 $node->pgbench(
800 '-t 1', 0,
801 [ qr{type: .*/001_pgbench_gset}, qr{processed: 1/1} ],
802 [
803 qr{command=3.: int 0\b},
804 qr{command=5.: int 1\b},
805 qr{command=6.: int 2\b},
806 qr{command=8.: int 3\b},
807 qr{command=10.: int 4\b},
808 qr{command=12.: int 5\b}
809 ],
810 'pgbench gset command',
811 {
812 '001_pgbench_gset' => q{-- test gset
813 -- no columns
814 SELECT \gset
815 -- one value
816 SELECT 0 AS i0 \gset
817 \set i debug(:i0)
818 -- two values
819 SELECT 1 AS i1, 2 AS i2 \gset
820 \set i debug(:i1)
821 \set i debug(:i2)
822 -- with prefix
823 SELECT 3 AS i3 \gset x_
824 \set i debug(:x_i3)
825 -- overwrite existing variable
826 SELECT 0 AS i4, 4 AS i4 \gset
827 \set i debug(:i4)
828 -- work on the last SQL command under \;
829 \; \; SELECT 0 AS i5 \; SELECT 5 AS i5 \; \; \gset
830 \set i debug(:i5)
831 }
832 });
833 # \gset cannot accept more than one row, causing command to fail.
834 $node->pgbench(
835 '-t 1', 2,
836 [ qr{type: .*/001_pgbench_gset_two_rows}, qr{processed: 0/1} ],
837 [qr{expected one row, got 2\b}],
838 'pgbench gset command with two rows',
839 {
840 '001_pgbench_gset_two_rows' => q{
841 SELECT 5432 AS fail UNION SELECT 5433 ORDER BY 1 \gset
842 }
843 });
844
845 # working \aset
846 # Valid cases.
847 $node->pgbench(
848 '-t 1', 0,
849 [ qr{type: .*/001_pgbench_aset}, qr{processed: 1/1} ],
850 [ qr{command=3.: int 8\b}, qr{command=4.: int 7\b} ],
851 'pgbench aset command',
852 {
853 '001_pgbench_aset' => q{
854 -- test aset, which applies to a combined query
855 \; SELECT 6 AS i6 \; SELECT 7 AS i7 \; \aset
856 -- unless it returns more than one row, last is kept
857 SELECT 8 AS i6 UNION SELECT 9 ORDER BY 1 DESC \aset
858 \set i debug(:i6)
859 \set i debug(:i7)
860 }
861 });
862 # Empty result set with \aset, causing command to fail.
863 $node->pgbench(
864 '-t 1', 2,
865 [ qr{type: .*/001_pgbench_aset_empty}, qr{processed: 0/1} ],
866 [
867 qr{undefined variable \"i8\"},
868 qr{evaluation of meta-command failed\b}
869 ],
870 'pgbench aset command with empty result',
871 {
872 '001_pgbench_aset_empty' => q{
873 -- empty result
874 \; SELECT 5432 AS i8 WHERE FALSE \; \aset
875 \set i debug(:i8)
876 }
877 });
878
879 # Working \startpipeline
880 $node->pgbench(
881 '-t 1 -n -M extended',
882 0,
883 [ qr{type: .*/001_pgbench_pipeline}, qr{actually processed: 1/1} ],
884 [],
885 'working \startpipeline',
886 {
887 '001_pgbench_pipeline' => q{
888 -- test startpipeline
889 \startpipeline
890 } . "select 1;\n" x 10 . q{
891 \endpipeline
892 }
893 });
894
895 # Working \startpipeline with \syncpipeline
896 $node->pgbench(
897 '-t 1 -n -M extended',
898 0,
899 [ qr{type: .*/001_pgbench_pipeline_sync}, qr{actually processed: 1/1} ],
900 [],
901 'working \startpipeline with \syncpipeline',
902 {
903 '001_pgbench_pipeline_sync' => q{
904 -- test startpipeline
905 \startpipeline
906 select 1;
907 \syncpipeline
908 \syncpipeline
909 select 2;
910 \syncpipeline
911 select 3;
912 \endpipeline
913 }
914 });
915
916 # Working \startpipeline in prepared query mode
917 $node->pgbench(
918 '-t 1 -n -M prepared',
919 0,
920 [ qr{type: .*/001_pgbench_pipeline_prep}, qr{actually processed: 1/1} ],
921 [],
922 'working \startpipeline',
923 {
924 '001_pgbench_pipeline_prep' => q{
925 -- test startpipeline
926 \startpipeline
927 \endpipeline
928 \startpipeline
929 } . "select 1;\n" x 10 . q{
930 \endpipeline
931 }
932 });
933
934 # Try \startpipeline twice
935 $node->pgbench(
936 '-t 1 -n -M extended',
937 2,
938 [],
939 [qr{already in pipeline mode}],
940 'error: call \startpipeline twice',
941 {
942 '001_pgbench_pipeline_2' => q{
943 -- startpipeline twice
944 \startpipeline
945 \startpipeline
946 }
947 });
948
949 # Try to end a pipeline that hasn't started
950 $node->pgbench(
951 '-t 1 -n -M extended',
952 2,
953 [],
954 [qr{not in pipeline mode}],
955 'error: \endpipeline with no start',
956 {
957 '001_pgbench_pipeline_3' => q{
958 -- pipeline not started
959 \endpipeline
960 }
961 });
962
963 # Try \gset in pipeline mode
964 $node->pgbench(
965 '-t 1 -n -M extended',
966 2,
967 [],
968 [qr{gset is not allowed in pipeline mode}],
969 'error: \gset not allowed in pipeline mode',
970 {
971 '001_pgbench_pipeline_4' => q{
972 \startpipeline
973 select 1 \gset f
974 \endpipeline
975 }
976 });
977
978 # Try \startpipeline without \endpipeline in a single transaction
979 $node->pgbench(
980 '-t 1 -n -M extended',
981 2,
982 [],
983 [qr{end of script reached with pipeline open}],
984 'error: call \startpipeline without \endpipeline in a single transaction',
985 {
986 '001_pgbench_pipeline_5' => q{
987 -- startpipeline only with single transaction
988 \startpipeline
989 }
990 });
991
992 # Try \startpipeline without \endpipeline
993 $node->pgbench(
994 '-t 2 -n -M extended',
995 2,
996 [],
997 [qr{end of script reached with pipeline open}],
998 'error: call \startpipeline without \endpipeline',
999 {
1000 '001_pgbench_pipeline_6' => q{
1001 -- startpipeline only
1002 \startpipeline
1003 }
1004 });
1005
1006 # Try \startpipeline with \syncpipeline without \endpipeline
1007 $node->pgbench(
1008 '-t 2 -n -M extended',
1009 2,
1010 [],
1011 [qr{end of script reached with pipeline open}],
1012 'error: call \startpipeline and \syncpipeline without \endpipeline',
1013 {
1014 '001_pgbench_pipeline_7' => q{
1015 -- startpipeline with \syncpipeline only
1016 \startpipeline
1017 \syncpipeline
1018 }
1019 });
1020
1021 # Try SET LOCAL as first pipeline command. This succeeds and the first
1022 # command is not executed inside an implicit transaction block, causing
1023 # a WARNING.
1024 $node->pgbench(
1025 '-t 1 -n -M extended',
1026 0,
1027 [],
1028 [qr{WARNING: SET LOCAL can only be used in transaction blocks}],
1029 'SET LOCAL outside implicit transaction block of pipeline',
1030 {
1031 '001_pgbench_pipeline_set_local_1' => q{
1032 \startpipeline
1033 SET LOCAL statement_timeout='1h';
1034 \endpipeline
1035 }
1036 });
1037
1038 # Try SET LOCAL as second pipeline command. This succeeds and the second
1039 # command does not cause a WARNING to be generated.
1040 $node->pgbench(
1041 '-t 1 -n -M extended',
1042 0,
1043 [],
1044 [qr{^$}],
1045 'SET LOCAL inside implicit transaction block of pipeline',
1046 {
1047 '001_pgbench_pipeline_set_local_2' => q{
1048 \startpipeline
1049 SELECT 1;
1050 SET LOCAL statement_timeout='1h';
1051 \endpipeline
1052 }
1053 });
1054
1055 # Try SET LOCAL with \syncpipeline. This succeeds and the command
1056 # launched after the sync is outside the implicit transaction block
1057 # of the pipeline, causing a WARNING.
1058 $node->pgbench(
1059 '-t 1 -n -M extended',
1060 0,
1061 [],
1062 [qr{WARNING: SET LOCAL can only be used in transaction blocks}],
1063 'SET LOCAL and \syncpipeline',
1064 {
1065 '001_pgbench_pipeline_set_local_3' => q{
1066 \startpipeline
1067 SELECT 1;
1068 \syncpipeline
1069 SET LOCAL statement_timeout='1h';
1070 \endpipeline
1071 }
1072 });
1073
1074 # Try REINDEX CONCURRENTLY as first pipeline command. This succeeds
1075 # as the first command is outside the implicit transaction block of
1076 # a pipeline.
1077 $node->pgbench(
1078 '-t 1 -n -M extended',
1079 0,
1080 [],
1081 [],
1082 'REINDEX CONCURRENTLY outside implicit transaction block of pipeline',
1083 {
1084 '001_pgbench_pipeline_reindex_1' => q{
1085 \startpipeline
1086 REINDEX TABLE CONCURRENTLY pgbench_accounts;
1087 SELECT 1;
1088 \endpipeline
1089 }
1090 });
1091
1092 # Try REINDEX CONCURRENTLY as second pipeline command. This fails
1093 # as the second command is inside an implicit transaction block.
1094 $node->pgbench(
1095 '-t 1 -n -M extended',
1096 2,
1097 [],
1098 [],
1099 'error: REINDEX CONCURRENTLY inside implicit transaction block of pipeline',
1100 {
1101 '001_pgbench_pipeline_reindex_2' => q{
1102 \startpipeline
1103 SELECT 1;
1104 REINDEX TABLE CONCURRENTLY pgbench_accounts;
1105 \endpipeline
1106 }
1107 });
1108
1109 # Try VACUUM as first pipeline command. Like REINDEX CONCURRENTLY, this
1110 # succeeds as this is outside the implicit transaction block of a pipeline.
1111 $node->pgbench(
1112 '-t 1 -n -M extended',
1113 0,
1114 [],
1115 [],
1116 'VACUUM outside implicit transaction block of pipeline',
1117 {
1118 '001_pgbench_pipeline_vacuum_1' => q{
1119 \startpipeline
1120 VACUUM pgbench_accounts;
1121 \endpipeline
1122 }
1123 });
1124
1125 # Try VACUUM as second pipeline command. This fails, as the second command
1126 # of a pipeline is inside an implicit transaction block.
1127 $node->pgbench(
1128 '-t 1 -n -M extended',
1129 2,
1130 [],
1131 [],
1132 'error: VACUUM inside implicit transaction block of pipeline',
1133 {
1134 '001_pgbench_pipeline_vacuum_2' => q{
1135 \startpipeline
1136 SELECT 1;
1137 VACUUM pgbench_accounts;
1138 \endpipeline
1139 }
1140 });
1141
1142 # Try subtransactions in a pipeline. These are forbidden in implicit
1143 # transaction blocks.
1144 $node->pgbench(
1145 '-t 1 -n -M extended',
1146 2,
1147 [],
1148 [],
1149 'error: subtransactions not allowed in pipeline',
1150 {
1151 '001_pgbench_pipeline_subtrans' => q{
1152 \startpipeline
1153 SAVEPOINT a;
1154 SELECT 1;
1155 ROLLBACK TO SAVEPOINT a;
1156 SELECT 2;
1157 \endpipeline
1158 }
1159 });
1160
1161 # Try LOCK TABLE as first pipeline command. This fails as LOCK is outside
1162 # an implicit transaction block.
1163 $node->pgbench(
1164 '-t 1 -n -M extended',
1165 2,
1166 [],
1167 [],
1168 'error: LOCK TABLE outside implicit transaction block of pipeline',
1169 {
1170 '001_pgbench_pipeline_lock_1' => q{
1171 \startpipeline
1172 LOCK pgbench_accounts;
1173 SELECT 1;
1174 \endpipeline
1175 }
1176 });
1177
1178 # Try LOCK TABLE as second pipeline command. This succeeds as LOCK is inside
1179 # an implicit transaction block.
1180 $node->pgbench(
1181 '-t 1 -n -M extended',
1182 0,
1183 [],
1184 [],
1185 'LOCK TABLE inside implicit transaction block of pipeline',
1186 {
1187 '001_pgbench_pipeline_lock_2' => q{
1188 \startpipeline
1189 SELECT 1;
1190 LOCK pgbench_accounts;
1191 \endpipeline
1192 }
1193 });
1194
1195 # Working \startpipeline in prepared query mode with serializable
1196 $node->pgbench(
1197 '-c4 -t 10 -n -M prepared',
1198 0,
1199 [
1200 qr{type: .*/001_pgbench_pipeline_serializable},
1201 qr{actually processed: (\d+)/\1}
1202 ],
1203 [],
1204 'working \startpipeline with serializable',
1205 {
1206 '001_pgbench_pipeline_serializable' => q{
1207 -- test startpipeline with serializable
1208 \startpipeline
1209 BEGIN ISOLATION LEVEL SERIALIZABLE;
1210 } . "select 1;\n" x 10 . q{
1211 END;
1212 \endpipeline
1213 }
1214 });
1215
1216 # trigger many expression errors
1217 my @errors = (
1218
1219 # [ test name, expected status, expected stderr, script ]
1220 # SQL
1221 [
1222 'sql syntax error',
1223 2,
1224 [
1225 qr{ERROR: syntax error},
1226 qr{prepared statement .* does not exist}
1227 ],
1228 q{-- SQL syntax error
1229 SELECT 1 + ;
1230 }
1231 ],
1232 [
1233 'sql too many args', 1,
1234 [qr{statement has too many arguments.*\b255\b}],
1235 q{-- MAX_ARGS=256 for prepared
1236 \set i 0
1237 SELECT LEAST(} . join(', ', (':i') x 256) . q{)}
1238 ],
1239
1240 # SHELL
1241 [
1242 'shell bad command', 2,
1243 [qr{\(shell\) .* meta-command failed}], q{\shell no-such-command}
1244 ],
1245 [
1246 'shell undefined variable', 2,
1247 [qr{undefined variable ":nosuchvariable"}],
1248 q{-- undefined variable in shell
1249 \shell echo ::foo :nosuchvariable
1250 }
1251 ],
1252 [ 'shell missing command', 1, [qr{missing command }], q{\shell} ],
1253 [
1254 'shell too many args', 1, [qr{too many arguments in command "shell"}],
1255 q{-- 256 arguments to \shell
1256 \shell echo } . join(' ', ('arg') x 255)
1257 ],
1258
1259 # SET
1260 [
1261 'set syntax error', 1,
1262 [qr{syntax error in command "set"}], q{\set i 1 +}
1263 ],
1264 [
1265 'set no such function', 1,
1266 [qr{unexpected function name}], q{\set i noSuchFunction()}
1267 ],
1268 [
1269 'set invalid variable name', 2,
1270 [qr{invalid variable name}], q{\set . 1}
1271 ],
1272 [ 'set division by zero', 2, [qr{division by zero}], q{\set i 1/0} ],
1273 [
1274 'set undefined variable',
1275 2,
1276 [qr{undefined variable "nosuchvariable"}],
1277 q{\set i :nosuchvariable}
1278 ],
1279 [ 'set unexpected char', 1, [qr{unexpected character .;.}], q{\set i ;} ],
1280 [
1281 'set too many args',
1282 2,
1283 [qr{too many function arguments}],
1284 q{\set i least(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)}
1285 ],
1286 [
1287 'set empty random range', 2,
1288 [qr{empty range given to random}], q{\set i random(5,3)}
1289 ],
1290 [
1291 'set random range too large', 2,
1292 [qr{random range is too large}], q{\set i random(:minint, :maxint)}
1293 ],
1294 [
1295 'set gaussian param too small',
1296 2,
1297 [qr{gaussian param.* at least 2}],
1298 q{\set i random_gaussian(0, 10, 1.0)}
1299 ],
1300 [
1301 'set exponential param greater 0',
1302 2,
1303 [qr{exponential parameter must be greater }],
1304 q{\set i random_exponential(0, 10, 0.0)}
1305 ],
1306 [
1307 'set zipfian param to 1',
1308 2,
1309 [qr{zipfian parameter must be in range \[1\.001, 1000\]}],
1310 q{\set i random_zipfian(0, 10, 1)}
1311 ],
1312 [
1313 'set zipfian param too large',
1314 2,
1315 [qr{zipfian parameter must be in range \[1\.001, 1000\]}],
1316 q{\set i random_zipfian(0, 10, 1000000)}
1317 ],
1318 [
1319 'set non numeric value', 2,
1320 [qr{malformed variable "foo" value: "bla"}], q{\set i :foo + 1}
1321 ],
1322 [ 'set no expression', 1, [qr{syntax error}], q{\set i} ],
1323 [ 'set missing argument', 1, [qr{missing argument}i], q{\set} ],
1324 [
1325 'set not a bool', 2,
1326 [qr{cannot coerce double to boolean}], q{\set b NOT 0.0}
1327 ],
1328 [
1329 'set not an int', 2,
1330 [qr{cannot coerce boolean to int}], q{\set i TRUE + 2}
1331 ],
1332 [
1333 'set not a double', 2,
1334 [qr{cannot coerce boolean to double}], q{\set d ln(TRUE)}
1335 ],
1336 [
1337 'set case error',
1338 1,
1339 [qr{syntax error in command "set"}],
1340 q{\set i CASE TRUE THEN 1 ELSE 0 END}
1341 ],
1342 [
1343 'set random error', 2,
1344 [qr{cannot coerce boolean to int}], q{\set b random(FALSE, TRUE)}
1345 ],
1346 [
1347 'set number of args mismatch', 1,
1348 [qr{unexpected number of arguments}], q{\set d ln(1.0, 2.0))}
1349 ],
1350 [
1351 'set at least one arg', 1,
1352 [qr{at least one argument expected}], q{\set i greatest())}
1353 ],
1354
1355 # SET: ARITHMETIC OVERFLOW DETECTION
1356 [
1357 'set double to int overflow', 2,
1358 [qr{double to int overflow for 100}], q{\set i int(1E32)}
1359 ],
1360 [
1361 'set bigint add overflow', 2,
1362 [qr{int add out}], q{\set i (1<<62) + (1<<62)}
1363 ],
1364 [
1365 'set bigint sub overflow',
1366 2, [qr{int sub out}], q{\set i 0 - (1<<62) - (1<<62) - (1<<62)}
1367 ],
1368 [
1369 'set bigint mul overflow', 2,
1370 [qr{int mul out}], q{\set i 2 * (1<<62)}
1371 ],
1372 [
1373 'set bigint div out of range', 2,
1374 [qr{bigint div out of range}], q{\set i :minint / -1}
1375 ],
1376
1377 # SETSHELL
1378 [
1379 'setshell not an int', 2,
1380 [qr{command must return an integer}], q{\setshell i echo -n one}
1381 ],
1382 [ 'setshell missing arg', 1, [qr{missing argument }], q{\setshell var} ],
1383 [
1384 'setshell no such command', 2,
1385 [qr{could not read result }], q{\setshell var no-such-command}
1386 ],
1387
1388 # SLEEP
1389 [
1390 'sleep undefined variable', 2,
1391 [qr{sleep: undefined variable}], q{\sleep :nosuchvariable}
1392 ],
1393 [
1394 'sleep too many args', 1,
1395 [qr{too many arguments}], q{\sleep too many args}
1396 ],
1397 [
1398 'sleep missing arg', 1,
1399 [ qr{missing argument}, qr{\\sleep} ], q{\sleep}
1400 ],
1401 [
1402 'sleep unknown unit', 1,
1403 [qr{unrecognized time unit}], q{\sleep 1 week}
1404 ],
1405
1406 # MISC
1407 [
1408 'misc invalid backslash command', 1,
1409 [qr{invalid command .* "nosuchcommand"}], q{\nosuchcommand}
1410 ],
1411 [ 'misc empty script', 1, [qr{empty command list for script}], q{} ],
1412 [
1413 'bad boolean', 2,
1414 [qr{malformed variable.*trueXXX}], q{\set b :badtrue or true}
1415 ],
1416 [
1417 'invalid permute size',
1418 2,
1419 [qr{permute size parameter must be greater than zero}],
1420 q{\set i permute(0, 0)}
1421 ],
1422
1423 # GSET
1424 [
1425 'gset no row', 2,
1426 [qr{expected one row, got 0\b}], q{SELECT WHERE FALSE \gset}
1427 ],
1428 [ 'gset alone', 1, [qr{gset must follow an SQL command}], q{\gset} ],
1429 [
1430 'gset no SQL', 1,
1431 [qr{gset must follow an SQL command}], q{\set i +1
1432 \gset}
1433 ],
1434 [
1435 'gset too many arguments', 1,
1436 [qr{too many arguments}], q{SELECT 1 \gset a b}
1437 ],
1438 [
1439 'gset after gset', 1,
1440 [qr{gset must follow an SQL command}], q{SELECT 1 AS i \gset
1441 \gset}
1442 ],
1443 [
1444 'gset non SELECT',
1445 2,
1446 [qr{expected one row, got 0}],
1447 q{DROP TABLE IF EXISTS no_such_table \gset}
1448 ],
1449 [
1450 'gset bad default name', 2,
1451 [qr{error storing into variable \?column\?}], q{SELECT 1 \gset}
1452 ],
1453 [
1454 'gset bad name',
1455 2,
1456 [qr{error storing into variable bad name!}],
1457 q{SELECT 1 AS "bad name!" \gset}
1458 ],);
1459
1460 for my $e (@errors)
1461 {
1462 my ($name, $status, $re, $script, $no_prepare) = @$e;
1463 $status != 0 or die "invalid expected status for test \"$name\"";
1464 my $n = '001_pgbench_error_' . $name;
1465 $n =~ s/ /_/g;
1466 $node->pgbench(
1467 '-n -t 1 -Dfoo=bla -Dnull=null -Dtrue=true -Done=1 -Dzero=0.0 -Dbadtrue=trueXXX'
1468 . ' -Dmaxint=9223372036854775807 -Dminint=-9223372036854775808'
1469 . ($no_prepare ? '' : ' -M prepared'),
1470 $status,
1471 [ $status == 1 ? qr{^$} : qr{processed: 0/1} ],
1472 $re,
1473 'pgbench script error: ' . $name,
1474 { $n => $script });
1475 }
1476
1477 # throttling
1478 $node->pgbench(
1479 '-t 100 -S --rate=100000 --latency-limit=1000000 -c 2 -n -r',
1480 0,
1481 [ qr{processed: 200/200}, qr{builtin: select only} ],
1482 [qr{^$}],
1483 'pgbench throttling');
1484
1485 $node->pgbench(
1486
1487 # given the expected rate and the 2 ms tx duration, at most one is executed
1488 '-t 10 --rate=100000 --latency-limit=1 -n -r',
1489 0,
1490 [
1491 qr{processed: [01]/10},
1492 qr{type: .*/001_pgbench_sleep},
1493 qr{above the 1.0 ms latency limit: [01]/}
1494 ],
1495 [qr{^$}],
1496 'pgbench late throttling',
1497 { '001_pgbench_sleep' => q{\sleep 2ms} });
1498
1499 # return a list of files from directory $dir matching regexpr $re
1500 # this works around glob portability and escaping issues
1501 sub list_files
1502 {
1503 my ($dir, $re) = @_;
1504 opendir my $dh, $dir or die "cannot opendir $dir: $!";
1505 my @files = grep /$re/, readdir $dh;
1506 closedir $dh or die "cannot closedir $dir: $!";
1507 return map { $dir . '/' . $_ } @files;
1508 }
1509
1510 # Check log contents and clean them up:
1511 # $dir: directory holding logs
1512 # $prefix: file prefix for per-thread logs
1513 # $nb: number of expected files
1514 # $min/$max: minimum and maximum number of lines in log files
1515 # $re: regular expression each log line has to match
1516 sub check_pgbench_logs
1517 {
1518 local $Test::Builder::Level = $Test::Builder::Level + 1;
1519
1520 my ($dir, $prefix, $nb, $min, $max, $re) = @_;
1521
1522 # $prefix is simple enough, thus does not need escaping
1523 my @logs = list_files($dir, qr{^$prefix\..*$});
1524 ok(@logs == $nb, "number of log files");
1525 ok(grep(/\/$prefix\.\d+(\.\d+)?$/, @logs) == $nb, "file name format");
1526
1527 my $log_number = 0;
1528 for my $log (sort @logs)
1529 {
1530 # Check the contents of each log file.
1531 my $contents_raw = slurp_file($log);
1532
1533 my @contents = split(/\n/, $contents_raw);
1534 my $clen = @contents;
1535 ok( $min <= $clen && $clen <= $max,
1536 "transaction count for $log ($clen)");
1537 my $clen_match = grep(/$re/, @contents);
1538 ok($clen_match == $clen, "transaction format for $prefix");
1539
1540 # Show more information if some logs don't match
1541 # to help with debugging.
1542 if ($clen_match != $clen)
1543 {
1544 foreach my $log (@contents)
1545 {
1546 print "# Log entry not matching: $log\n"
1547 unless $log =~ /$re/;
1548 }
1549 }
1550 }
1551 return;
1552 }
1553
1554 my $bdir = $node->basedir;
1555
1556 # Run with sampling rate, 2 clients with 50 transactions each.
1557 $node->pgbench(
1558 "-n -S -t 50 -c 2 --log --sampling-rate=0.5", 0,
1559 [ qr{select only}, qr{processed: 100/100} ], [qr{^$}],
1560 'pgbench logs', undef,
1561 "--log-prefix=$bdir/001_pgbench_log_2");
1562 # The IDs of the clients (1st field) in the logs should be either 0 or 1.
1563 check_pgbench_logs($bdir, '001_pgbench_log_2', 1, 8, 92,
1564 qr{^[01] \d{1,2} \d+ \d \d+ \d+$});
1565
1566 # Run with different read-only option pattern, 1 client with 10 transactions.
1567 $node->pgbench(
1568 "-n -b select-only -t 10 -l", 0,
1569 [ qr{select only}, qr{processed: 10/10} ], [qr{^$}],
1570 'pgbench logs contents', undef,
1571 "--log-prefix=$bdir/001_pgbench_log_3");
1572 # The ID of a single client (1st field) should match 0.
1573 check_pgbench_logs($bdir, '001_pgbench_log_3', 1, 10, 10,
1574 qr{^0 \d{1,2} \d+ \d \d+ \d+$});
1575
1576 # abortion of the client if the script contains an incomplete transaction block
1577 $node->pgbench(
1578 '--no-vacuum',
1579 2,
1580 [qr{processed: 1/10}],
1581 [
1582 qr{client 0 aborted: end of script reached without completing the last transaction}
1583 ],
1584 'incomplete transaction block',
1585 { '001_pgbench_incomplete_transaction_block' => q{BEGIN;SELECT 1;} });
1586
1587 # Test the concurrent update in the table row and deadlocks.
1588
1589 $node->safe_psql('postgres',
1590 'CREATE UNLOGGED TABLE first_client_table (value integer); '
1591 . 'CREATE UNLOGGED TABLE xy (x integer, y integer); '
1592 . 'INSERT INTO xy VALUES (1, 2);');
1593
1594 # Serialization error and retry
1595
1596 local $ENV{PGOPTIONS} = "-c default_transaction_isolation=repeatable\\ read";
1597
1598 # Check that we have a serialization error and the same random value of the
1599 # delta variable in the next try
1600 my $err_pattern =
1601 "(client (0|1) sending UPDATE xy SET y = y \\+ -?\\d+\\b).*"
1602 . "client \\2 got an error in command 3 \\(SQL\\) of script 0; "
1603 . "ERROR: could not serialize access due to concurrent update\\b.*"
1604 . "\\1";
1605
1606 $node->pgbench(
1607 "-n -c 2 -t 1 --debug --verbose-errors --max-tries 2",
1608 0,
1609 [
1610 qr{processed: 2/2\b},
1611 qr{number of transactions retried: 1\b},
1612 qr{total number of retries: 1\b}
1613 ],
1614 [qr/$err_pattern/s],
1615 'concurrent update with retrying',
1616 {
1617 '001_pgbench_serialization' => q{
1618 -- What's happening:
1619 -- The first client starts the transaction with the isolation level Repeatable
1620 -- Read:
1621 --
1622 -- BEGIN;
1623 -- UPDATE xy SET y = ... WHERE x = 1;
1624 --
1625 -- The second client starts a similar transaction with the same isolation level:
1626 --
1627 -- BEGIN;
1628 -- UPDATE xy SET y = ... WHERE x = 1;
1629 -- <waiting for the first client>
1630 --
1631 -- The first client commits its transaction, and the second client gets a
1632 -- serialization error.
1633
1634 \set delta random(-5000, 5000)
1635
1636 -- The second client will stop here
1637 SELECT pg_advisory_lock(0);
1638
1639 -- Start transaction with concurrent update
1640 BEGIN;
1641 UPDATE xy SET y = y + :delta WHERE x = 1 AND pg_advisory_lock(1) IS NOT NULL;
1642
1643 -- Wait for the second client
1644 DO $$
1645 DECLARE
1646 exists boolean;
1647 waiters integer;
1648 BEGIN
1649 -- The second client always comes in second, and the number of rows in the
1650 -- table first_client_table reflect this. Here the first client inserts a row,
1651 -- so the second client will see a non-empty table when repeating the
1652 -- transaction after the serialization error.
1653 SELECT EXISTS (SELECT * FROM first_client_table) INTO STRICT exists;
1654 IF NOT exists THEN
1655 -- Let the second client begin
1656 PERFORM pg_advisory_unlock(0);
1657 -- And wait until the second client tries to get the same lock
1658 LOOP
1659 SELECT COUNT(*) INTO STRICT waiters FROM pg_locks WHERE
1660 locktype = 'advisory' AND objsubid = 1 AND
1661 ((classid::bigint << 32) | objid::bigint = 1::bigint) AND NOT granted;
1662 IF waiters = 1 THEN
1663 INSERT INTO first_client_table VALUES (1);
1664
1665 -- Exit loop
1666 EXIT;
1667 END IF;
1668 END LOOP;
1669 END IF;
1670 END$$;
1671
1672 COMMIT;
1673 SELECT pg_advisory_unlock_all();
1674 }
1675 });
1676
1677 # Clean up
1678
1679 $node->safe_psql('postgres', 'DELETE FROM first_client_table;');
1680
1681 local $ENV{PGOPTIONS} = "-c default_transaction_isolation=read\\ committed";
1682
1683 # Deadlock error and retry
1684
1685 # Check that we have a deadlock error
1686 $err_pattern =
1687 "client (0|1) got an error in command (3|5) \\(SQL\\) of script 0; "
1688 . "ERROR: deadlock detected\\b";
1689
1690 $node->pgbench(
1691 "-n -c 2 -t 1 --max-tries 2 --verbose-errors",
1692 0,
1693 [
1694 qr{processed: 2/2\b},
1695 qr{number of transactions retried: 1\b},
1696 qr{total number of retries: 1\b}
1697 ],
1698 [qr{$err_pattern}],
1699 'deadlock with retrying',
1700 {
1701 '001_pgbench_deadlock' => q{
1702 -- What's happening:
1703 -- The first client gets the lock 2.
1704 -- The second client gets the lock 3 and tries to get the lock 2.
1705 -- The first client tries to get the lock 3 and one of them gets a deadlock
1706 -- error.
1707 --
1708 -- A client that does not get a deadlock error must hold a lock at the
1709 -- transaction start. Thus in the end it releases all of its locks before the
1710 -- client with the deadlock error starts a retry (we do not want any errors
1711 -- again).
1712
1713 -- Since the client with the deadlock error has not released the blocking locks,
1714 -- let's do this here.
1715 SELECT pg_advisory_unlock_all();
1716
1717 -- The second client and the client with the deadlock error stop here
1718 SELECT pg_advisory_lock(0);
1719 SELECT pg_advisory_lock(1);
1720
1721 -- The second client and the client with the deadlock error always come after
1722 -- the first and the number of rows in the table first_client_table reflects
1723 -- this. Here the first client inserts a row, so in the future the table is
1724 -- always non-empty.
1725 DO $$
1726 DECLARE
1727 exists boolean;
1728 BEGIN
1729 SELECT EXISTS (SELECT * FROM first_client_table) INTO STRICT exists;
1730 IF exists THEN
1731 -- We are the second client or the client with the deadlock error
1732
1733 -- The first client will take care by itself of this lock (see below)
1734 PERFORM pg_advisory_unlock(0);
1735
1736 PERFORM pg_advisory_lock(3);
1737
1738 -- The second client can get a deadlock here
1739 PERFORM pg_advisory_lock(2);
1740 ELSE
1741 -- We are the first client
1742
1743 -- This code should not be used in a new transaction after an error
1744 INSERT INTO first_client_table VALUES (1);
1745
1746 PERFORM pg_advisory_lock(2);
1747 END IF;
1748 END$$;
1749
1750 DO $$
1751 DECLARE
1752 num_rows integer;
1753 waiters integer;
1754 BEGIN
1755 -- Check if we are the first client
1756 SELECT COUNT(*) FROM first_client_table INTO STRICT num_rows;
1757 IF num_rows = 1 THEN
1758 -- This code should not be used in a new transaction after an error
1759 INSERT INTO first_client_table VALUES (2);
1760
1761 -- Let the second client begin
1762 PERFORM pg_advisory_unlock(0);
1763 PERFORM pg_advisory_unlock(1);
1764
1765 -- Make sure the second client is ready for deadlock
1766 LOOP
1767 SELECT COUNT(*) INTO STRICT waiters FROM pg_locks WHERE
1768 locktype = 'advisory' AND
1769 objsubid = 1 AND
1770 ((classid::bigint << 32) | objid::bigint = 2::bigint) AND
1771 NOT granted;
1772
1773 IF waiters = 1 THEN
1774 -- Exit loop
1775 EXIT;
1776 END IF;
1777 END LOOP;
1778
1779 PERFORM pg_advisory_lock(0);
1780 -- And the second client took care by itself of the lock 1
1781 END IF;
1782 END$$;
1783
1784 -- The first client can get a deadlock here
1785 SELECT pg_advisory_lock(3);
1786
1787 SELECT pg_advisory_unlock_all();
1788 }
1789 });
1790
1791 # Clean up
1792 $node->safe_psql('postgres', 'DROP TABLE first_client_table, xy;');
1793
1794 # Test --exit-on-abort
1795 $node->safe_psql('postgres',
1796 'CREATE TABLE counter(i int); ' . 'INSERT INTO counter VALUES (0);');
1797
1798 $node->pgbench(
1799 '-t 10 -c 2 -j 2 --exit-on-abort',
1800 2,
1801 [],
1802 [ qr{division by zero}, qr{Run was aborted due to an error in thread} ],
1803 'test --exit-on-abort',
1804 {
1805 '001_exit_on_abort' => q{
1806 update counter set i = i+1 returning i \gset
1807 \if :i = 5
1808 \set y 1/0
1809 \endif
1810 }
1811 });
1812
1813 # Test copy in pgbench
1814 $node->pgbench(
1815 '-t 10',
1816 2,
1817 [],
1818 [ qr{COPY is not supported in pgbench, aborting} ],
1819 'Test copy in script',
1820 {
1821 '001_copy' => q{ COPY pgbench_accounts FROM stdin }
1822 });
1823
1824 # Clean up
1825 $node->safe_psql('postgres', 'DROP TABLE counter;');
1826
1827 # done
1828 $node->safe_psql('postgres', 'DROP TABLESPACE regress_pgbench_tap_1_ts');
1829 $node->stop;
1830 done_testing();