LCOV - differential code coverage report
Current view: top level - src/bin/pgbench - pgbench.c (source / functions) Coverage Total Hit LBC UBC GBC CBC
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 85.6 % 2923 2502 421 2502
Current Date: 2025-09-06 07:49:51 +0900 Functions: 96.0 % 126 121 5 121
Baseline: lcov-20250906-005545-baseline Branches: 75.7 % 1948 1474 2 472 1 1473
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 68.1 % 69 47 22 47
(360..) days: 86.0 % 2854 2455 399 2455
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 96.0 % 124 119 5 119
Branch coverage date bins:
(30,360] days: 52.2 % 46 24 22 24
(360..) days: 76.2 % 1902 1450 2 450 1 1449

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*
                                  2                 :                :  * pgbench.c
                                  3                 :                :  *
                                  4                 :                :  * A simple benchmark program for PostgreSQL
                                  5                 :                :  * Originally written by Tatsuo Ishii and enhanced by many contributors.
                                  6                 :                :  *
                                  7                 :                :  * src/bin/pgbench/pgbench.c
                                  8                 :                :  * Copyright (c) 2000-2025, PostgreSQL Global Development Group
                                  9                 :                :  * ALL RIGHTS RESERVED;
                                 10                 :                :  *
                                 11                 :                :  * Permission to use, copy, modify, and distribute this software and its
                                 12                 :                :  * documentation for any purpose, without fee, and without a written agreement
                                 13                 :                :  * is hereby granted, provided that the above copyright notice and this
                                 14                 :                :  * paragraph and the following two paragraphs appear in all copies.
                                 15                 :                :  *
                                 16                 :                :  * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
                                 17                 :                :  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
                                 18                 :                :  * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
                                 19                 :                :  * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
                                 20                 :                :  * POSSIBILITY OF SUCH DAMAGE.
                                 21                 :                :  *
                                 22                 :                :  * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
                                 23                 :                :  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
                                 24                 :                :  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
                                 25                 :                :  * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
                                 26                 :                :  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
                                 27                 :                :  *
                                 28                 :                :  */
                                 29                 :                : 
                                 30                 :                : #if defined(WIN32) && FD_SETSIZE < 1024
                                 31                 :                : #error FD_SETSIZE needs to have been increased
                                 32                 :                : #endif
                                 33                 :                : 
                                 34                 :                : #include "postgres_fe.h"
                                 35                 :                : 
                                 36                 :                : #include <ctype.h>
                                 37                 :                : #include <float.h>
                                 38                 :                : #include <limits.h>
                                 39                 :                : #include <math.h>
                                 40                 :                : #include <signal.h>
                                 41                 :                : #include <time.h>
                                 42                 :                : #include <sys/time.h>
                                 43                 :                : #include <sys/resource.h>     /* for getrlimit */
                                 44                 :                : 
                                 45                 :                : /* For testing, PGBENCH_USE_SELECT can be defined to force use of that code */
                                 46                 :                : #if defined(HAVE_PPOLL) && !defined(PGBENCH_USE_SELECT)
                                 47                 :                : #define POLL_USING_PPOLL
                                 48                 :                : #ifdef HAVE_POLL_H
                                 49                 :                : #include <poll.h>
                                 50                 :                : #endif
                                 51                 :                : #else                           /* no ppoll(), so use select() */
                                 52                 :                : #define POLL_USING_SELECT
                                 53                 :                : #include <sys/select.h>
                                 54                 :                : #endif
                                 55                 :                : 
                                 56                 :                : #include "catalog/pg_class_d.h"
                                 57                 :                : #include "common/int.h"
                                 58                 :                : #include "common/logging.h"
                                 59                 :                : #include "common/pg_prng.h"
                                 60                 :                : #include "common/string.h"
                                 61                 :                : #include "common/username.h"
                                 62                 :                : #include "fe_utils/cancel.h"
                                 63                 :                : #include "fe_utils/conditional.h"
                                 64                 :                : #include "fe_utils/option_utils.h"
                                 65                 :                : #include "fe_utils/string_utils.h"
                                 66                 :                : #include "getopt_long.h"
                                 67                 :                : #include "libpq-fe.h"
                                 68                 :                : #include "pgbench.h"
                                 69                 :                : #include "port/pg_bitutils.h"
                                 70                 :                : #include "portability/instr_time.h"
                                 71                 :                : 
                                 72                 :                : /* X/Open (XSI) requires <math.h> to provide M_PI, but core POSIX does not */
                                 73                 :                : #ifndef M_PI
                                 74                 :                : #define M_PI 3.14159265358979323846
                                 75                 :                : #endif
                                 76                 :                : 
                                 77                 :                : #define ERRCODE_T_R_SERIALIZATION_FAILURE  "40001"
                                 78                 :                : #define ERRCODE_T_R_DEADLOCK_DETECTED  "40P01"
                                 79                 :                : #define ERRCODE_UNDEFINED_TABLE  "42P01"
                                 80                 :                : 
                                 81                 :                : /*
                                 82                 :                :  * Hashing constants
                                 83                 :                :  */
                                 84                 :                : #define FNV_PRIME           UINT64CONST(0x100000001b3)
                                 85                 :                : #define FNV_OFFSET_BASIS    UINT64CONST(0xcbf29ce484222325)
                                 86                 :                : #define MM2_MUL             UINT64CONST(0xc6a4a7935bd1e995)
                                 87                 :                : #define MM2_MUL_TIMES_8     UINT64CONST(0x35253c9ade8f4ca8)
                                 88                 :                : #define MM2_ROT             47
                                 89                 :                : 
                                 90                 :                : /*
                                 91                 :                :  * Multi-platform socket set implementations
                                 92                 :                :  */
                                 93                 :                : 
                                 94                 :                : #ifdef POLL_USING_PPOLL
                                 95                 :                : #define SOCKET_WAIT_METHOD "ppoll"
                                 96                 :                : 
                                 97                 :                : typedef struct socket_set
                                 98                 :                : {
                                 99                 :                :     int         maxfds;         /* allocated length of pollfds[] array */
                                100                 :                :     int         curfds;         /* number currently in use */
                                101                 :                :     struct pollfd pollfds[FLEXIBLE_ARRAY_MEMBER];
                                102                 :                : } socket_set;
                                103                 :                : 
                                104                 :                : #endif                          /* POLL_USING_PPOLL */
                                105                 :                : 
                                106                 :                : #ifdef POLL_USING_SELECT
                                107                 :                : #define SOCKET_WAIT_METHOD "select"
                                108                 :                : 
                                109                 :                : typedef struct socket_set
                                110                 :                : {
                                111                 :                :     int         maxfd;          /* largest FD currently set in fds */
                                112                 :                :     fd_set      fds;
                                113                 :                : } socket_set;
                                114                 :                : 
                                115                 :                : #endif                          /* POLL_USING_SELECT */
                                116                 :                : 
                                117                 :                : /*
                                118                 :                :  * Multi-platform thread implementations
                                119                 :                :  */
                                120                 :                : 
                                121                 :                : #ifdef WIN32
                                122                 :                : /* Use Windows threads */
                                123                 :                : #include <windows.h>
                                124                 :                : #define GETERRNO() (_dosmaperr(GetLastError()), errno)
                                125                 :                : #define THREAD_T HANDLE
                                126                 :                : #define THREAD_FUNC_RETURN_TYPE unsigned
                                127                 :                : #define THREAD_FUNC_RETURN return 0
                                128                 :                : #define THREAD_FUNC_CC __stdcall
                                129                 :                : #define THREAD_CREATE(handle, function, arg) \
                                130                 :                :     ((*(handle) = (HANDLE) _beginthreadex(NULL, 0, (function), (arg), 0, NULL)) == 0 ? errno : 0)
                                131                 :                : #define THREAD_JOIN(handle) \
                                132                 :                :     (WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0 ? \
                                133                 :                :     GETERRNO() : CloseHandle(handle) ? 0 : GETERRNO())
                                134                 :                : #define THREAD_BARRIER_T SYNCHRONIZATION_BARRIER
                                135                 :                : #define THREAD_BARRIER_INIT(barrier, n) \
                                136                 :                :     (InitializeSynchronizationBarrier((barrier), (n), 0) ? 0 : GETERRNO())
                                137                 :                : #define THREAD_BARRIER_WAIT(barrier) \
                                138                 :                :     EnterSynchronizationBarrier((barrier), \
                                139                 :                :                                 SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY)
                                140                 :                : #define THREAD_BARRIER_DESTROY(barrier)
                                141                 :                : #else
                                142                 :                : /* Use POSIX threads */
                                143                 :                : #include "port/pg_pthread.h"
                                144                 :                : #define THREAD_T pthread_t
                                145                 :                : #define THREAD_FUNC_RETURN_TYPE void *
                                146                 :                : #define THREAD_FUNC_RETURN return NULL
                                147                 :                : #define THREAD_FUNC_CC
                                148                 :                : #define THREAD_CREATE(handle, function, arg) \
                                149                 :                :     pthread_create((handle), NULL, (function), (arg))
                                150                 :                : #define THREAD_JOIN(handle) \
                                151                 :                :     pthread_join((handle), NULL)
                                152                 :                : #define THREAD_BARRIER_T pthread_barrier_t
                                153                 :                : #define THREAD_BARRIER_INIT(barrier, n) \
                                154                 :                :     pthread_barrier_init((barrier), NULL, (n))
                                155                 :                : #define THREAD_BARRIER_WAIT(barrier) pthread_barrier_wait((barrier))
                                156                 :                : #define THREAD_BARRIER_DESTROY(barrier) pthread_barrier_destroy((barrier))
                                157                 :                : #endif
                                158                 :                : 
                                159                 :                : 
                                160                 :                : /********************************************************************
                                161                 :                :  * some configurable parameters */
                                162                 :                : 
                                163                 :                : #define DEFAULT_INIT_STEPS "dtgvp"    /* default -I setting */
                                164                 :                : #define ALL_INIT_STEPS "dtgGvpf"  /* all possible steps */
                                165                 :                : 
                                166                 :                : #define LOG_STEP_SECONDS    5   /* seconds between log messages */
                                167                 :                : #define DEFAULT_NXACTS  10      /* default nxacts */
                                168                 :                : 
                                169                 :                : #define MIN_GAUSSIAN_PARAM      2.0 /* minimum parameter for gauss */
                                170                 :                : 
                                171                 :                : #define MIN_ZIPFIAN_PARAM       1.001   /* minimum parameter for zipfian */
                                172                 :                : #define MAX_ZIPFIAN_PARAM       1000.0  /* maximum parameter for zipfian */
                                173                 :                : 
                                174                 :                : static int  nxacts = 0;         /* number of transactions per client */
                                175                 :                : static int  duration = 0;       /* duration in seconds */
                                176                 :                : static int64 end_time = 0;      /* when to stop in micro seconds, under -T */
                                177                 :                : 
                                178                 :                : /*
                                179                 :                :  * scaling factor. for example, scale = 10 will make 1000000 tuples in
                                180                 :                :  * pgbench_accounts table.
                                181                 :                :  */
                                182                 :                : static int  scale = 1;
                                183                 :                : 
                                184                 :                : /*
                                185                 :                :  * fillfactor. for example, fillfactor = 90 will use only 90 percent
                                186                 :                :  * space during inserts and leave 10 percent free.
                                187                 :                :  */
                                188                 :                : static int  fillfactor = 100;
                                189                 :                : 
                                190                 :                : /*
                                191                 :                :  * use unlogged tables?
                                192                 :                :  */
                                193                 :                : static bool unlogged_tables = false;
                                194                 :                : 
                                195                 :                : /*
                                196                 :                :  * log sampling rate (1.0 = log everything, 0.0 = option not given)
                                197                 :                :  */
                                198                 :                : static double sample_rate = 0.0;
                                199                 :                : 
                                200                 :                : /*
                                201                 :                :  * When threads are throttled to a given rate limit, this is the target delay
                                202                 :                :  * to reach that rate in usec.  0 is the default and means no throttling.
                                203                 :                :  */
                                204                 :                : static double throttle_delay = 0;
                                205                 :                : 
                                206                 :                : /*
                                207                 :                :  * Transactions which take longer than this limit (in usec) are counted as
                                208                 :                :  * late, and reported as such, although they are completed anyway. When
                                209                 :                :  * throttling is enabled, execution time slots that are more than this late
                                210                 :                :  * are skipped altogether, and counted separately.
                                211                 :                :  */
                                212                 :                : static int64 latency_limit = 0;
                                213                 :                : 
                                214                 :                : /*
                                215                 :                :  * tablespace selection
                                216                 :                :  */
                                217                 :                : static char *tablespace = NULL;
                                218                 :                : static char *index_tablespace = NULL;
                                219                 :                : 
                                220                 :                : /*
                                221                 :                :  * Number of "pgbench_accounts" partitions.  0 is the default and means no
                                222                 :                :  * partitioning.
                                223                 :                :  */
                                224                 :                : static int  partitions = 0;
                                225                 :                : 
                                226                 :                : /* partitioning strategy for "pgbench_accounts" */
                                227                 :                : typedef enum
                                228                 :                : {
                                229                 :                :     PART_NONE,                  /* no partitioning */
                                230                 :                :     PART_RANGE,                 /* range partitioning */
                                231                 :                :     PART_HASH,                  /* hash partitioning */
                                232                 :                : } partition_method_t;
                                233                 :                : 
                                234                 :                : static partition_method_t partition_method = PART_NONE;
                                235                 :                : static const char *const PARTITION_METHOD[] = {"none", "range", "hash"};
                                236                 :                : 
                                237                 :                : /* random seed used to initialize base_random_sequence */
                                238                 :                : static int64 random_seed = -1;
                                239                 :                : 
                                240                 :                : /*
                                241                 :                :  * end of configurable parameters
                                242                 :                :  *********************************************************************/
                                243                 :                : 
                                244                 :                : #define nbranches   1           /* Makes little sense to change this.  Change
                                245                 :                :                                  * -s instead */
                                246                 :                : #define ntellers    10
                                247                 :                : #define naccounts   100000
                                248                 :                : 
                                249                 :                : /*
                                250                 :                :  * The scale factor at/beyond which 32bit integers are incapable of storing
                                251                 :                :  * 64bit values.
                                252                 :                :  *
                                253                 :                :  * Although the actual threshold is 21474, we use 20000 because it is easier to
                                254                 :                :  * document and remember, and isn't that far away from the real threshold.
                                255                 :                :  */
                                256                 :                : #define SCALE_32BIT_THRESHOLD 20000
                                257                 :                : 
                                258                 :                : static bool use_log;            /* log transaction latencies to a file */
                                259                 :                : static bool use_quiet;          /* quiet logging onto stderr */
                                260                 :                : static int  agg_interval;       /* log aggregates instead of individual
                                261                 :                :                                  * transactions */
                                262                 :                : static bool per_script_stats = false;   /* whether to collect stats per script */
                                263                 :                : static int  progress = 0;       /* thread progress report every this seconds */
                                264                 :                : static bool progress_timestamp = false; /* progress report with Unix time */
                                265                 :                : static int  nclients = 1;       /* number of clients */
                                266                 :                : static int  nthreads = 1;       /* number of threads */
                                267                 :                : static bool is_connect;         /* establish connection for each transaction */
                                268                 :                : static bool report_per_command = false; /* report per-command latencies,
                                269                 :                :                                          * retries after errors and failures
                                270                 :                :                                          * (errors without retrying) */
                                271                 :                : static int  main_pid;           /* main process id used in log filename */
                                272                 :                : 
                                273                 :                : /*
                                274                 :                :  * There are different types of restrictions for deciding that the current
                                275                 :                :  * transaction with a serialization/deadlock error can no longer be retried and
                                276                 :                :  * should be reported as failed:
                                277                 :                :  * - max_tries (--max-tries) can be used to limit the number of tries;
                                278                 :                :  * - latency_limit (-L) can be used to limit the total time of tries;
                                279                 :                :  * - duration (-T) can be used to limit the total benchmark time.
                                280                 :                :  *
                                281                 :                :  * They can be combined together, and you need to use at least one of them to
                                282                 :                :  * retry the transactions with serialization/deadlock errors. If none of them is
                                283                 :                :  * used, the default value of max_tries is 1 and such transactions will not be
                                284                 :                :  * retried.
                                285                 :                :  */
                                286                 :                : 
                                287                 :                : /*
                                288                 :                :  * We cannot retry a transaction after the serialization/deadlock error if its
                                289                 :                :  * number of tries reaches this maximum; if its value is zero, it is not used.
                                290                 :                :  */
                                291                 :                : static uint32 max_tries = 1;
                                292                 :                : 
                                293                 :                : static bool failures_detailed = false;  /* whether to group failures in
                                294                 :                :                                          * reports or logs by basic types */
                                295                 :                : 
                                296                 :                : static const char *pghost = NULL;
                                297                 :                : static const char *pgport = NULL;
                                298                 :                : static const char *username = NULL;
                                299                 :                : static const char *dbName = NULL;
                                300                 :                : static char *logfile_prefix = NULL;
                                301                 :                : static const char *progname;
                                302                 :                : 
                                303                 :                : #define WSEP '@'                /* weight separator */
                                304                 :                : 
                                305                 :                : static volatile sig_atomic_t timer_exceeded = false;    /* flag from signal
                                306                 :                :                                                          * handler */
                                307                 :                : 
                                308                 :                : /*
                                309                 :                :  * We don't want to allocate variables one by one; for efficiency, add a
                                310                 :                :  * constant margin each time it overflows.
                                311                 :                :  */
                                312                 :                : #define VARIABLES_ALLOC_MARGIN  8
                                313                 :                : 
                                314                 :                : /*
                                315                 :                :  * Variable definitions.
                                316                 :                :  *
                                317                 :                :  * If a variable only has a string value, "svalue" is that value, and value is
                                318                 :                :  * "not set".  If the value is known, "value" contains the value (in any
                                319                 :                :  * variant).
                                320                 :                :  *
                                321                 :                :  * In this case "svalue" contains the string equivalent of the value, if we've
                                322                 :                :  * had occasion to compute that, or NULL if we haven't.
                                323                 :                :  */
                                324                 :                : typedef struct
                                325                 :                : {
                                326                 :                :     char       *name;           /* variable's name */
                                327                 :                :     char       *svalue;         /* its value in string form, if known */
                                328                 :                :     PgBenchValue value;         /* actual variable's value */
                                329                 :                : } Variable;
                                330                 :                : 
                                331                 :                : /*
                                332                 :                :  * Data structure for client variables.
                                333                 :                :  */
                                334                 :                : typedef struct
                                335                 :                : {
                                336                 :                :     Variable   *vars;           /* array of variable definitions */
                                337                 :                :     int         nvars;          /* number of variables */
                                338                 :                : 
                                339                 :                :     /*
                                340                 :                :      * The maximum number of variables that we can currently store in 'vars'
                                341                 :                :      * without having to reallocate more space. We must always have max_vars
                                342                 :                :      * >= nvars.
                                343                 :                :      */
                                344                 :                :     int         max_vars;
                                345                 :                : 
                                346                 :                :     bool        vars_sorted;    /* are variables sorted by name? */
                                347                 :                : } Variables;
                                348                 :                : 
                                349                 :                : #define MAX_SCRIPTS     128     /* max number of SQL scripts allowed */
                                350                 :                : #define SHELL_COMMAND_SIZE  256 /* maximum size allowed for shell command */
                                351                 :                : 
                                352                 :                : /*
                                353                 :                :  * Simple data structure to keep stats about something.
                                354                 :                :  *
                                355                 :                :  * XXX probably the first value should be kept and used as an offset for
                                356                 :                :  * better numerical stability...
                                357                 :                :  */
                                358                 :                : typedef struct SimpleStats
                                359                 :                : {
                                360                 :                :     int64       count;          /* how many values were encountered */
                                361                 :                :     double      min;            /* the minimum seen */
                                362                 :                :     double      max;            /* the maximum seen */
                                363                 :                :     double      sum;            /* sum of values */
                                364                 :                :     double      sum2;           /* sum of squared values */
                                365                 :                : } SimpleStats;
                                366                 :                : 
                                367                 :                : /*
                                368                 :                :  * The instr_time type is expensive when dealing with time arithmetic.  Define
                                369                 :                :  * a type to hold microseconds instead.  Type int64 is good enough for about
                                370                 :                :  * 584500 years.
                                371                 :                :  */
                                372                 :                : typedef int64 pg_time_usec_t;
                                373                 :                : 
                                374                 :                : /*
                                375                 :                :  * Data structure to hold various statistics: per-thread and per-script stats
                                376                 :                :  * are maintained and merged together.
                                377                 :                :  */
                                378                 :                : typedef struct StatsData
                                379                 :                : {
                                380                 :                :     pg_time_usec_t start_time;  /* interval start time, for aggregates */
                                381                 :                : 
                                382                 :                :     /*----------
                                383                 :                :      * Transactions are counted depending on their execution and outcome.
                                384                 :                :      * First a transaction may have started or not: skipped transactions occur
                                385                 :                :      * under --rate and --latency-limit when the client is too late to execute
                                386                 :                :      * them. Secondly, a started transaction may ultimately succeed or fail,
                                387                 :                :      * possibly after some retries when --max-tries is not one. Thus
                                388                 :                :      *
                                389                 :                :      * the number of all transactions =
                                390                 :                :      *   'skipped' (it was too late to execute them) +
                                391                 :                :      *   'cnt' (the number of successful transactions) +
                                392                 :                :      *   'failed' (the number of failed transactions).
                                393                 :                :      *
                                394                 :                :      * A successful transaction can have several unsuccessful tries before a
                                395                 :                :      * successful run. Thus
                                396                 :                :      *
                                397                 :                :      * 'cnt' (the number of successful transactions) =
                                398                 :                :      *   successfully retried transactions (they got a serialization or a
                                399                 :                :      *                                      deadlock error(s), but were
                                400                 :                :      *                                      successfully retried from the very
                                401                 :                :      *                                      beginning) +
                                402                 :                :      *   directly successful transactions (they were successfully completed on
                                403                 :                :      *                                     the first try).
                                404                 :                :      *
                                405                 :                :      * A failed transaction is defined as unsuccessfully retried transactions.
                                406                 :                :      * It can be one of two types:
                                407                 :                :      *
                                408                 :                :      * failed (the number of failed transactions) =
                                409                 :                :      *   'serialization_failures' (they got a serialization error and were not
                                410                 :                :      *                             successfully retried) +
                                411                 :                :      *   'deadlock_failures' (they got a deadlock error and were not
                                412                 :                :      *                        successfully retried).
                                413                 :                :      *
                                414                 :                :      * If the transaction was retried after a serialization or a deadlock
                                415                 :                :      * error this does not guarantee that this retry was successful. Thus
                                416                 :                :      *
                                417                 :                :      * 'retries' (number of retries) =
                                418                 :                :      *   number of retries in all retried transactions =
                                419                 :                :      *   number of retries in (successfully retried transactions +
                                420                 :                :      *                         failed transactions);
                                421                 :                :      *
                                422                 :                :      * 'retried' (number of all retried transactions) =
                                423                 :                :      *   successfully retried transactions +
                                424                 :                :      *   failed transactions.
                                425                 :                :      *----------
                                426                 :                :      */
                                427                 :                :     int64       cnt;            /* number of successful transactions, not
                                428                 :                :                                  * including 'skipped' */
                                429                 :                :     int64       skipped;        /* number of transactions skipped under --rate
                                430                 :                :                                  * and --latency-limit */
                                431                 :                :     int64       retries;        /* number of retries after a serialization or
                                432                 :                :                                  * a deadlock error in all the transactions */
                                433                 :                :     int64       retried;        /* number of all transactions that were
                                434                 :                :                                  * retried after a serialization or a deadlock
                                435                 :                :                                  * error (perhaps the last try was
                                436                 :                :                                  * unsuccessful) */
                                437                 :                :     int64       serialization_failures; /* number of transactions that were
                                438                 :                :                                          * not successfully retried after a
                                439                 :                :                                          * serialization error */
                                440                 :                :     int64       deadlock_failures;  /* number of transactions that were not
                                441                 :                :                                      * successfully retried after a deadlock
                                442                 :                :                                      * error */
                                443                 :                :     SimpleStats latency;
                                444                 :                :     SimpleStats lag;
                                445                 :                : } StatsData;
                                446                 :                : 
                                447                 :                : /*
                                448                 :                :  * For displaying Unix epoch timestamps, as some time functions may have
                                449                 :                :  * another reference.
                                450                 :                :  */
                                451                 :                : static pg_time_usec_t epoch_shift;
                                452                 :                : 
                                453                 :                : /*
                                454                 :                :  * Error status for errors during script execution.
                                455                 :                :  */
                                456                 :                : typedef enum EStatus
                                457                 :                : {
                                458                 :                :     ESTATUS_NO_ERROR = 0,
                                459                 :                :     ESTATUS_META_COMMAND_ERROR,
                                460                 :                : 
                                461                 :                :     /* SQL errors */
                                462                 :                :     ESTATUS_SERIALIZATION_ERROR,
                                463                 :                :     ESTATUS_DEADLOCK_ERROR,
                                464                 :                :     ESTATUS_OTHER_SQL_ERROR,
                                465                 :                : } EStatus;
                                466                 :                : 
                                467                 :                : /*
                                468                 :                :  * Transaction status at the end of a command.
                                469                 :                :  */
                                470                 :                : typedef enum TStatus
                                471                 :                : {
                                472                 :                :     TSTATUS_IDLE,
                                473                 :                :     TSTATUS_IN_BLOCK,
                                474                 :                :     TSTATUS_CONN_ERROR,
                                475                 :                :     TSTATUS_OTHER_ERROR,
                                476                 :                : } TStatus;
                                477                 :                : 
                                478                 :                : /* Various random sequences are initialized from this one. */
                                479                 :                : static pg_prng_state base_random_sequence;
                                480                 :                : 
                                481                 :                : /* Synchronization barrier for start and connection */
                                482                 :                : static THREAD_BARRIER_T barrier;
                                483                 :                : 
                                484                 :                : /*
                                485                 :                :  * Connection state machine states.
                                486                 :                :  */
                                487                 :                : typedef enum
                                488                 :                : {
                                489                 :                :     /*
                                490                 :                :      * The client must first choose a script to execute.  Once chosen, it can
                                491                 :                :      * either be throttled (state CSTATE_PREPARE_THROTTLE under --rate), start
                                492                 :                :      * right away (state CSTATE_START_TX) or not start at all if the timer was
                                493                 :                :      * exceeded (state CSTATE_FINISHED).
                                494                 :                :      */
                                495                 :                :     CSTATE_CHOOSE_SCRIPT,
                                496                 :                : 
                                497                 :                :     /*
                                498                 :                :      * CSTATE_START_TX performs start-of-transaction processing.  Establishes
                                499                 :                :      * a new connection for the transaction in --connect mode, records the
                                500                 :                :      * transaction start time, and proceed to the first command.
                                501                 :                :      *
                                502                 :                :      * Note: once a script is started, it will either error or run till its
                                503                 :                :      * end, where it may be interrupted. It is not interrupted while running,
                                504                 :                :      * so pgbench --time is to be understood as tx are allowed to start in
                                505                 :                :      * that time, and will finish when their work is completed.
                                506                 :                :      */
                                507                 :                :     CSTATE_START_TX,
                                508                 :                : 
                                509                 :                :     /*
                                510                 :                :      * In CSTATE_PREPARE_THROTTLE state, we calculate when to begin the next
                                511                 :                :      * transaction, and advance to CSTATE_THROTTLE.  CSTATE_THROTTLE state
                                512                 :                :      * sleeps until that moment, then advances to CSTATE_START_TX, or
                                513                 :                :      * CSTATE_FINISHED if the next transaction would start beyond the end of
                                514                 :                :      * the run.
                                515                 :                :      */
                                516                 :                :     CSTATE_PREPARE_THROTTLE,
                                517                 :                :     CSTATE_THROTTLE,
                                518                 :                : 
                                519                 :                :     /*
                                520                 :                :      * We loop through these states, to process each command in the script:
                                521                 :                :      *
                                522                 :                :      * CSTATE_START_COMMAND starts the execution of a command.  On a SQL
                                523                 :                :      * command, the command is sent to the server, and we move to
                                524                 :                :      * CSTATE_WAIT_RESULT state unless in pipeline mode. On a \sleep
                                525                 :                :      * meta-command, the timer is set, and we enter the CSTATE_SLEEP state to
                                526                 :                :      * wait for it to expire. Other meta-commands are executed immediately. If
                                527                 :                :      * the command about to start is actually beyond the end of the script,
                                528                 :                :      * advance to CSTATE_END_TX.
                                529                 :                :      *
                                530                 :                :      * CSTATE_WAIT_RESULT waits until we get a result set back from the server
                                531                 :                :      * for the current command.
                                532                 :                :      *
                                533                 :                :      * CSTATE_SLEEP waits until the end of \sleep.
                                534                 :                :      *
                                535                 :                :      * CSTATE_END_COMMAND records the end-of-command timestamp, increments the
                                536                 :                :      * command counter, and loops back to CSTATE_START_COMMAND state.
                                537                 :                :      *
                                538                 :                :      * CSTATE_SKIP_COMMAND is used by conditional branches which are not
                                539                 :                :      * executed. It quickly skip commands that do not need any evaluation.
                                540                 :                :      * This state can move forward several commands, till there is something
                                541                 :                :      * to do or the end of the script.
                                542                 :                :      */
                                543                 :                :     CSTATE_START_COMMAND,
                                544                 :                :     CSTATE_WAIT_RESULT,
                                545                 :                :     CSTATE_SLEEP,
                                546                 :                :     CSTATE_END_COMMAND,
                                547                 :                :     CSTATE_SKIP_COMMAND,
                                548                 :                : 
                                549                 :                :     /*
                                550                 :                :      * States for failed commands.
                                551                 :                :      *
                                552                 :                :      * If the SQL/meta command fails, in CSTATE_ERROR clean up after an error:
                                553                 :                :      * (1) clear the conditional stack; (2) if we have an unterminated
                                554                 :                :      * (possibly failed) transaction block, send the rollback command to the
                                555                 :                :      * server and wait for the result in CSTATE_WAIT_ROLLBACK_RESULT.  If
                                556                 :                :      * something goes wrong with rolling back, go to CSTATE_ABORTED.
                                557                 :                :      *
                                558                 :                :      * But if everything is ok we are ready for future transactions: if this
                                559                 :                :      * is a serialization or deadlock error and we can re-execute the
                                560                 :                :      * transaction from the very beginning, go to CSTATE_RETRY; otherwise go
                                561                 :                :      * to CSTATE_FAILURE.
                                562                 :                :      *
                                563                 :                :      * In CSTATE_RETRY report an error, set the same parameters for the
                                564                 :                :      * transaction execution as in the previous tries and process the first
                                565                 :                :      * transaction command in CSTATE_START_COMMAND.
                                566                 :                :      *
                                567                 :                :      * In CSTATE_FAILURE report a failure, set the parameters for the
                                568                 :                :      * transaction execution as they were before the first run of this
                                569                 :                :      * transaction (except for a random state) and go to CSTATE_END_TX to
                                570                 :                :      * complete this transaction.
                                571                 :                :      */
                                572                 :                :     CSTATE_ERROR,
                                573                 :                :     CSTATE_WAIT_ROLLBACK_RESULT,
                                574                 :                :     CSTATE_RETRY,
                                575                 :                :     CSTATE_FAILURE,
                                576                 :                : 
                                577                 :                :     /*
                                578                 :                :      * CSTATE_END_TX performs end-of-transaction processing.  It calculates
                                579                 :                :      * latency, and logs the transaction.  In --connect mode, it closes the
                                580                 :                :      * current connection.
                                581                 :                :      *
                                582                 :                :      * Then either starts over in CSTATE_CHOOSE_SCRIPT, or enters
                                583                 :                :      * CSTATE_FINISHED if we have no more work to do.
                                584                 :                :      */
                                585                 :                :     CSTATE_END_TX,
                                586                 :                : 
                                587                 :                :     /*
                                588                 :                :      * Final states.  CSTATE_ABORTED means that the script execution was
                                589                 :                :      * aborted because a command failed, CSTATE_FINISHED means success.
                                590                 :                :      */
                                591                 :                :     CSTATE_ABORTED,
                                592                 :                :     CSTATE_FINISHED,
                                593                 :                : } ConnectionStateEnum;
                                594                 :                : 
                                595                 :                : /*
                                596                 :                :  * Connection state.
                                597                 :                :  */
                                598                 :                : typedef struct
                                599                 :                : {
                                600                 :                :     PGconn     *con;            /* connection handle to DB */
                                601                 :                :     int         id;             /* client No. */
                                602                 :                :     ConnectionStateEnum state;  /* state machine's current state. */
                                603                 :                :     ConditionalStack cstack;    /* enclosing conditionals state */
                                604                 :                : 
                                605                 :                :     /*
                                606                 :                :      * Separate randomness for each client. This is used for random functions
                                607                 :                :      * PGBENCH_RANDOM_* during the execution of the script.
                                608                 :                :      */
                                609                 :                :     pg_prng_state cs_func_rs;
                                610                 :                : 
                                611                 :                :     int         use_file;       /* index in sql_script for this client */
                                612                 :                :     int         command;        /* command number in script */
                                613                 :                :     int         num_syncs;      /* number of ongoing sync commands */
                                614                 :                : 
                                615                 :                :     /* client variables */
                                616                 :                :     Variables   variables;
                                617                 :                : 
                                618                 :                :     /* various times about current transaction in microseconds */
                                619                 :                :     pg_time_usec_t txn_scheduled;   /* scheduled start time of transaction */
                                620                 :                :     pg_time_usec_t sleep_until; /* scheduled start time of next cmd */
                                621                 :                :     pg_time_usec_t txn_begin;   /* used for measuring schedule lag times */
                                622                 :                :     pg_time_usec_t stmt_begin;  /* used for measuring statement latencies */
                                623                 :                : 
                                624                 :                :     /* whether client prepared each command of each script */
                                625                 :                :     bool      **prepared;
                                626                 :                : 
                                627                 :                :     /*
                                628                 :                :      * For processing failures and repeating transactions with serialization
                                629                 :                :      * or deadlock errors:
                                630                 :                :      */
                                631                 :                :     EStatus     estatus;        /* the error status of the current transaction
                                632                 :                :                                  * execution; this is ESTATUS_NO_ERROR if
                                633                 :                :                                  * there were no errors */
                                634                 :                :     pg_prng_state random_state; /* random state */
                                635                 :                :     uint32      tries;          /* how many times have we already tried the
                                636                 :                :                                  * current transaction? */
                                637                 :                : 
                                638                 :                :     /* per client collected stats */
                                639                 :                :     int64       cnt;            /* client transaction count, for -t; skipped
                                640                 :                :                                  * and failed transactions are also counted
                                641                 :                :                                  * here */
                                642                 :                : } CState;
                                643                 :                : 
                                644                 :                : /*
                                645                 :                :  * Thread state
                                646                 :                :  */
                                647                 :                : typedef struct
                                648                 :                : {
                                649                 :                :     int         tid;            /* thread id */
                                650                 :                :     THREAD_T    thread;         /* thread handle */
                                651                 :                :     CState     *state;          /* array of CState */
                                652                 :                :     int         nstate;         /* length of state[] */
                                653                 :                : 
                                654                 :                :     /*
                                655                 :                :      * Separate randomness for each thread. Each thread option uses its own
                                656                 :                :      * random state to make all of them independent of each other and
                                657                 :                :      * therefore deterministic at the thread level.
                                658                 :                :      */
                                659                 :                :     pg_prng_state ts_choose_rs; /* random state for selecting a script */
                                660                 :                :     pg_prng_state ts_throttle_rs;   /* random state for transaction throttling */
                                661                 :                :     pg_prng_state ts_sample_rs; /* random state for log sampling */
                                662                 :                : 
                                663                 :                :     int64       throttle_trigger;   /* previous/next throttling (us) */
                                664                 :                :     FILE       *logfile;        /* where to log, or NULL */
                                665                 :                : 
                                666                 :                :     /* per thread collected stats in microseconds */
                                667                 :                :     pg_time_usec_t create_time; /* thread creation time */
                                668                 :                :     pg_time_usec_t started_time;    /* thread is running */
                                669                 :                :     pg_time_usec_t bench_start; /* thread is benchmarking */
                                670                 :                :     pg_time_usec_t conn_duration;   /* cumulated connection and disconnection
                                671                 :                :                                      * delays */
                                672                 :                : 
                                673                 :                :     StatsData   stats;
                                674                 :                :     int64       latency_late;   /* count executed but late transactions */
                                675                 :                : } TState;
                                676                 :                : 
                                677                 :                : /*
                                678                 :                :  * queries read from files
                                679                 :                :  */
                                680                 :                : #define SQL_COMMAND     1
                                681                 :                : #define META_COMMAND    2
                                682                 :                : 
                                683                 :                : /*
                                684                 :                :  * max number of backslash command arguments or SQL variables,
                                685                 :                :  * including the command or SQL statement itself
                                686                 :                :  */
                                687                 :                : #define MAX_ARGS        256
                                688                 :                : 
                                689                 :                : typedef enum MetaCommand
                                690                 :                : {
                                691                 :                :     META_NONE,                  /* not a known meta-command */
                                692                 :                :     META_SET,                   /* \set */
                                693                 :                :     META_SETSHELL,              /* \setshell */
                                694                 :                :     META_SHELL,                 /* \shell */
                                695                 :                :     META_SLEEP,                 /* \sleep */
                                696                 :                :     META_GSET,                  /* \gset */
                                697                 :                :     META_ASET,                  /* \aset */
                                698                 :                :     META_IF,                    /* \if */
                                699                 :                :     META_ELIF,                  /* \elif */
                                700                 :                :     META_ELSE,                  /* \else */
                                701                 :                :     META_ENDIF,                 /* \endif */
                                702                 :                :     META_STARTPIPELINE,         /* \startpipeline */
                                703                 :                :     META_SYNCPIPELINE,          /* \syncpipeline */
                                704                 :                :     META_ENDPIPELINE,           /* \endpipeline */
                                705                 :                : } MetaCommand;
                                706                 :                : 
                                707                 :                : typedef enum QueryMode
                                708                 :                : {
                                709                 :                :     QUERY_SIMPLE,               /* simple query */
                                710                 :                :     QUERY_EXTENDED,             /* extended query */
                                711                 :                :     QUERY_PREPARED,             /* extended query with prepared statements */
                                712                 :                :     NUM_QUERYMODE
                                713                 :                : } QueryMode;
                                714                 :                : 
                                715                 :                : static QueryMode querymode = QUERY_SIMPLE;
                                716                 :                : static const char *const QUERYMODE[] = {"simple", "extended", "prepared"};
                                717                 :                : 
                                718                 :                : /*
                                719                 :                :  * struct Command represents one command in a script.
                                720                 :                :  *
                                721                 :                :  * lines        The raw, possibly multi-line command text.  Variable substitution
                                722                 :                :  *              not applied.
                                723                 :                :  * first_line   A short, single-line extract of 'lines', for error reporting.
                                724                 :                :  * type         SQL_COMMAND or META_COMMAND
                                725                 :                :  * meta         The type of meta-command, with META_NONE/GSET/ASET if command
                                726                 :                :  *              is SQL.
                                727                 :                :  * argc         Number of arguments of the command, 0 if not yet processed.
                                728                 :                :  * argv         Command arguments, the first of which is the command or SQL
                                729                 :                :  *              string itself.  For SQL commands, after post-processing
                                730                 :                :  *              argv[0] is the same as 'lines' with variables substituted.
                                731                 :                :  * prepname     The name that this command is prepared under, in prepare mode
                                732                 :                :  * varprefix    SQL commands terminated with \gset or \aset have this set
                                733                 :                :  *              to a non NULL value.  If nonempty, it's used to prefix the
                                734                 :                :  *              variable name that receives the value.
                                735                 :                :  * aset         do gset on all possible queries of a combined query (\;).
                                736                 :                :  * expr         Parsed expression, if needed.
                                737                 :                :  * stats        Time spent in this command.
                                738                 :                :  * retries      Number of retries after a serialization or deadlock error in the
                                739                 :                :  *              current command.
                                740                 :                :  * failures     Number of errors in the current command that were not retried.
                                741                 :                :  */
                                742                 :                : typedef struct Command
                                743                 :                : {
                                744                 :                :     PQExpBufferData lines;
                                745                 :                :     char       *first_line;
                                746                 :                :     int         type;
                                747                 :                :     MetaCommand meta;
                                748                 :                :     int         argc;
                                749                 :                :     char       *argv[MAX_ARGS];
                                750                 :                :     char       *prepname;
                                751                 :                :     char       *varprefix;
                                752                 :                :     PgBenchExpr *expr;
                                753                 :                :     SimpleStats stats;
                                754                 :                :     int64       retries;
                                755                 :                :     int64       failures;
                                756                 :                : } Command;
                                757                 :                : 
                                758                 :                : typedef struct ParsedScript
                                759                 :                : {
                                760                 :                :     const char *desc;           /* script descriptor (eg, file name) */
                                761                 :                :     int         weight;         /* selection weight */
                                762                 :                :     Command   **commands;       /* NULL-terminated array of Commands */
                                763                 :                :     StatsData   stats;          /* total time spent in script */
                                764                 :                : } ParsedScript;
                                765                 :                : 
                                766                 :                : static ParsedScript sql_script[MAX_SCRIPTS];    /* SQL script files */
                                767                 :                : static int  num_scripts;        /* number of scripts in sql_script[] */
                                768                 :                : static int64 total_weight = 0;
                                769                 :                : 
                                770                 :                : static bool verbose_errors = false; /* print verbose messages of all errors */
                                771                 :                : 
                                772                 :                : static bool exit_on_abort = false;  /* exit when any client is aborted */
                                773                 :                : 
                                774                 :                : /* Builtin test scripts */
                                775                 :                : typedef struct BuiltinScript
                                776                 :                : {
                                777                 :                :     const char *name;           /* very short name for -b ... */
                                778                 :                :     const char *desc;           /* short description */
                                779                 :                :     const char *script;         /* actual pgbench script */
                                780                 :                : } BuiltinScript;
                                781                 :                : 
                                782                 :                : static const BuiltinScript builtin_script[] =
                                783                 :                : {
                                784                 :                :     {
                                785                 :                :         "tpcb-like",
                                786                 :                :         "<builtin: TPC-B (sort of)>",
                                787                 :                :         "\\set aid random(1, " CppAsString2(naccounts) " * :scale)\n"
                                788                 :                :         "\\set bid random(1, " CppAsString2(nbranches) " * :scale)\n"
                                789                 :                :         "\\set tid random(1, " CppAsString2(ntellers) " * :scale)\n"
                                790                 :                :         "\\set delta random(-5000, 5000)\n"
                                791                 :                :         "BEGIN;\n"
                                792                 :                :         "UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
                                793                 :                :         "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
                                794                 :                :         "UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;\n"
                                795                 :                :         "UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;\n"
                                796                 :                :         "INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
                                797                 :                :         "END;\n"
                                798                 :                :     },
                                799                 :                :     {
                                800                 :                :         "simple-update",
                                801                 :                :         "<builtin: simple update>",
                                802                 :                :         "\\set aid random(1, " CppAsString2(naccounts) " * :scale)\n"
                                803                 :                :         "\\set bid random(1, " CppAsString2(nbranches) " * :scale)\n"
                                804                 :                :         "\\set tid random(1, " CppAsString2(ntellers) " * :scale)\n"
                                805                 :                :         "\\set delta random(-5000, 5000)\n"
                                806                 :                :         "BEGIN;\n"
                                807                 :                :         "UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
                                808                 :                :         "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
                                809                 :                :         "INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
                                810                 :                :         "END;\n"
                                811                 :                :     },
                                812                 :                :     {
                                813                 :                :         "select-only",
                                814                 :                :         "<builtin: select only>",
                                815                 :                :         "\\set aid random(1, " CppAsString2(naccounts) " * :scale)\n"
                                816                 :                :         "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
                                817                 :                :     }
                                818                 :                : };
                                819                 :                : 
                                820                 :                : 
                                821                 :                : /* Function prototypes */
                                822                 :                : static void setNullValue(PgBenchValue *pv);
                                823                 :                : static void setBoolValue(PgBenchValue *pv, bool bval);
                                824                 :                : static void setIntValue(PgBenchValue *pv, int64 ival);
                                825                 :                : static void setDoubleValue(PgBenchValue *pv, double dval);
                                826                 :                : static bool evaluateExpr(CState *st, PgBenchExpr *expr,
                                827                 :                :                          PgBenchValue *retval);
                                828                 :                : static ConnectionStateEnum executeMetaCommand(CState *st, pg_time_usec_t *now);
                                829                 :                : static void doLog(TState *thread, CState *st,
                                830                 :                :                   StatsData *agg, bool skipped, double latency, double lag);
                                831                 :                : static void processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
                                832                 :                :                              bool skipped, StatsData *agg);
                                833                 :                : static void addScript(const ParsedScript *script);
                                834                 :                : static THREAD_FUNC_RETURN_TYPE THREAD_FUNC_CC threadRun(void *arg);
                                835                 :                : static void finishCon(CState *st);
                                836                 :                : static void setalarm(int seconds);
                                837                 :                : static socket_set *alloc_socket_set(int count);
                                838                 :                : static void free_socket_set(socket_set *sa);
                                839                 :                : static void clear_socket_set(socket_set *sa);
                                840                 :                : static void add_socket_to_set(socket_set *sa, int fd, int idx);
                                841                 :                : static int  wait_on_socket_set(socket_set *sa, int64 usecs);
                                842                 :                : static bool socket_has_input(socket_set *sa, int fd, int idx);
                                843                 :                : 
                                844                 :                : /* callback used to build rows for COPY during data loading */
                                845                 :                : typedef void (*initRowMethod) (PQExpBufferData *sql, int64 curr);
                                846                 :                : 
                                847                 :                : /* callback functions for our flex lexer */
                                848                 :                : static const PsqlScanCallbacks pgbench_callbacks = {
                                849                 :                :     NULL,                       /* don't need get_variable functionality */
                                850                 :                : };
                                851                 :                : 
                                852                 :                : static char
  207 melanieplageman@gmai      853                 :CBC           6 : get_table_relkind(PGconn *con, const char *table)
                                854                 :                : {
                                855                 :                :     PGresult   *res;
                                856                 :                :     char       *val;
                                857                 :                :     char        relkind;
                                858                 :              6 :     const char *params[1] = {table};
                                859                 :              6 :     const char *sql =
                                860                 :                :         "SELECT relkind FROM pg_catalog.pg_class WHERE oid=$1::pg_catalog.regclass";
                                861                 :                : 
                                862                 :              6 :     res = PQexecParams(con, sql, 1, NULL, params, NULL, NULL, 0);
                                863         [ -  + ]:              6 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
                                864                 :                :     {
  207 melanieplageman@gmai      865                 :UBC           0 :         pg_log_error("query failed: %s", PQerrorMessage(con));
                                866                 :              0 :         pg_log_error_detail("Query was: %s", sql);
                                867                 :              0 :         exit(1);
                                868                 :                :     }
  207 melanieplageman@gmai      869                 :CBC           6 :     val = PQgetvalue(res, 0, 0);
                                870         [ -  + ]:              6 :     Assert(strlen(val) == 1);
                                871                 :              6 :     relkind = val[0];
                                872                 :              6 :     PQclear(res);
                                873                 :                : 
                                874                 :              6 :     return relkind;
                                875                 :                : }
                                876                 :                : 
                                877                 :                : static inline pg_time_usec_t
 1641 tmunro@postgresql.or      878                 :          11874 : pg_time_now(void)
                                879                 :                : {
                                880                 :                :     instr_time  now;
                                881                 :                : 
                                882                 :          11874 :     INSTR_TIME_SET_CURRENT(now);
                                883                 :                : 
                                884                 :          11874 :     return (pg_time_usec_t) INSTR_TIME_GET_MICROSEC(now);
                                885                 :                : }
                                886                 :                : 
                                887                 :                : static inline void
                                888                 :          10743 : pg_time_now_lazy(pg_time_usec_t *now)
                                889                 :                : {
                                890         [ +  + ]:          10743 :     if ((*now) == 0)
                                891                 :           9716 :         (*now) = pg_time_now();
                                892                 :          10743 : }
                                893                 :                : 
                                894                 :                : #define PG_TIME_GET_DOUBLE(t) (0.000001 * (t))
                                895                 :                : 
                                896                 :                : static void
 4812 rhaas@postgresql.org      897                 :              1 : usage(void)
                                898                 :                : {
 6035 peter_e@gmx.net           899                 :              1 :     printf("%s is a benchmarking tool for PostgreSQL.\n\n"
                                900                 :                :            "Usage:\n"
                                901                 :                :            "  %s [OPTION]... [DBNAME]\n"
                                902                 :                :            "\nInitialization options:\n"
                                903                 :                :            "  -i, --initialize         invokes initialization mode\n"
                                904                 :                :            "  -I, --init-steps=[" ALL_INIT_STEPS "]+ (default \"" DEFAULT_INIT_STEPS "\")\n"
                                905                 :                :            "                           run selected initialization steps, in the specified order\n"
                                906                 :                :            "                           d: drop any existing pgbench tables\n"
                                907                 :                :            "                           t: create the tables used by the standard pgbench scenario\n"
                                908                 :                :            "                           g: generate data, client-side\n"
                                909                 :                :            "                           G: generate data, server-side\n"
                                910                 :                :            "                           v: invoke VACUUM on the standard tables\n"
                                911                 :                :            "                           p: create primary key indexes on the standard tables\n"
                                912                 :                :            "                           f: create foreign keys between the standard tables\n"
                                913                 :                :            "  -F, --fillfactor=NUM     set fill factor\n"
                                914                 :                :            "  -n, --no-vacuum          do not run VACUUM during initialization\n"
                                915                 :                :            "  -q, --quiet              quiet logging (one message each 5 seconds)\n"
                                916                 :                :            "  -s, --scale=NUM          scaling factor\n"
                                917                 :                :            "  --foreign-keys           create foreign key constraints between tables\n"
                                918                 :                :            "  --index-tablespace=TABLESPACE\n"
                                919                 :                :            "                           create indexes in the specified tablespace\n"
                                920                 :                :            "  --partition-method=(range|hash)\n"
                                921                 :                :            "                           partition pgbench_accounts with this method (default: range)\n"
                                922                 :                :            "  --partitions=NUM         partition pgbench_accounts into NUM parts (default: 0)\n"
                                923                 :                :            "  --tablespace=TABLESPACE  create tables in the specified tablespace\n"
                                924                 :                :            "  --unlogged-tables        create tables as unlogged tables\n"
                                925                 :                :            "\nOptions to select what to run:\n"
                                926                 :                :            "  -b, --builtin=NAME[@W]   add builtin script NAME weighted at W (default: 1)\n"
                                927                 :                :            "                           (use \"-b list\" to list available scripts)\n"
                                928                 :                :            "  -f, --file=FILENAME[@W]  add script FILENAME weighted at W (default: 1)\n"
                                929                 :                :            "  -N, --skip-some-updates  skip updates of pgbench_tellers and pgbench_branches\n"
                                930                 :                :            "                           (same as \"-b simple-update\")\n"
                                931                 :                :            "  -S, --select-only        perform SELECT-only transactions\n"
                                932                 :                :            "                           (same as \"-b select-only\")\n"
                                933                 :                :            "\nBenchmarking options:\n"
                                934                 :                :            "  -c, --client=NUM         number of concurrent database clients (default: 1)\n"
                                935                 :                :            "  -C, --connect            establish new connection for each transaction\n"
                                936                 :                :            "  -D, --define=VARNAME=VALUE\n"
                                937                 :                :            "                           define variable for use by custom script\n"
                                938                 :                :            "  -j, --jobs=NUM           number of threads (default: 1)\n"
                                939                 :                :            "  -l, --log                write transaction times to log file\n"
                                940                 :                :            "  -L, --latency-limit=NUM  count transactions lasting more than NUM ms as late\n"
                                941                 :                :            "  -M, --protocol=simple|extended|prepared\n"
                                942                 :                :            "                           protocol for submitting queries (default: simple)\n"
                                943                 :                :            "  -n, --no-vacuum          do not run VACUUM before tests\n"
                                944                 :                :            "  -P, --progress=NUM       show thread progress report every NUM seconds\n"
                                945                 :                :            "  -r, --report-per-command report latencies, failures, and retries per command\n"
                                946                 :                :            "  -R, --rate=NUM           target rate in transactions per second\n"
                                947                 :                :            "  -s, --scale=NUM          report this scale factor in output\n"
                                948                 :                :            "  -t, --transactions=NUM   number of transactions each client runs (default: 10)\n"
                                949                 :                :            "  -T, --time=NUM           duration of benchmark test in seconds\n"
                                950                 :                :            "  -v, --vacuum-all         vacuum all four standard tables before tests\n"
                                951                 :                :            "  --aggregate-interval=NUM aggregate data over NUM seconds\n"
                                952                 :                :            "  --exit-on-abort          exit when any client is aborted\n"
                                953                 :                :            "  --failures-detailed      report the failures grouped by basic types\n"
                                954                 :                :            "  --log-prefix=PREFIX      prefix for transaction time log file\n"
                                955                 :                :            "                           (default: \"pgbench_log\")\n"
                                956                 :                :            "  --max-tries=NUM          max number of tries to run transaction (default: 1)\n"
                                957                 :                :            "  --progress-timestamp     use Unix epoch timestamps for progress\n"
                                958                 :                :            "  --random-seed=SEED       set random seed (\"time\", \"rand\", integer)\n"
                                959                 :                :            "  --sampling-rate=NUM      fraction of transactions to log (e.g., 0.01 for 1%%)\n"
                                960                 :                :            "  --show-script=NAME       show builtin script code, then exit\n"
                                961                 :                :            "  --verbose-errors         print messages of all errors\n"
                                962                 :                :            "\nCommon options:\n"
                                963                 :                :            "  --debug                  print debugging output\n"
                                964                 :                :            "  -d, --dbname=DBNAME      database name to connect to\n"
                                965                 :                :            "  -h, --host=HOSTNAME      database server host or socket directory\n"
                                966                 :                :            "  -p, --port=PORT          database server port number\n"
                                967                 :                :            "  -U, --username=USERNAME  connect as specified database user\n"
                                968                 :                :            "  -V, --version            output version information, then exit\n"
                                969                 :                :            "  -?, --help               show this help, then exit\n"
                                970                 :                :            "\n"
                                971                 :                :            "Report bugs to <%s>.\n"
                                972                 :                :            "%s home page: <%s>\n",
                                973                 :                :            progname, progname, PACKAGE_BUGREPORT, PACKAGE_NAME, PACKAGE_URL);
 9366 ishii@postgresql.org      974                 :              1 : }
                                975                 :                : 
                                976                 :                : /* return whether str matches "^\s*[-+]?[0-9]+$" */
                                977                 :                : static bool
 3449 rhaas@postgresql.org      978                 :            531 : is_an_int(const char *str)
                                979                 :                : {
                                980                 :            531 :     const char *ptr = str;
                                981                 :                : 
                                982                 :                :     /* skip leading spaces; cast is consistent with strtoint64 */
                                983   [ +  -  -  + ]:            531 :     while (*ptr && isspace((unsigned char) *ptr))
 3449 rhaas@postgresql.org      984                 :UBC           0 :         ptr++;
                                985                 :                : 
                                986                 :                :     /* skip sign */
 3449 rhaas@postgresql.org      987   [ +  -  +  + ]:CBC         531 :     if (*ptr == '+' || *ptr == '-')
                                988                 :              3 :         ptr++;
                                989                 :                : 
                                990                 :                :     /* at least one digit */
                                991   [ +  -  +  + ]:            531 :     if (*ptr && !isdigit((unsigned char) *ptr))
                                992                 :              2 :         return false;
                                993                 :                : 
                                994                 :                :     /* eat all digits */
                                995   [ +  +  +  + ]:           1113 :     while (*ptr && isdigit((unsigned char) *ptr))
                                996                 :            584 :         ptr++;
                                997                 :                : 
                                998                 :                :     /* must have reached end of string */
                                999                 :            529 :     return *ptr == '\0';
                               1000                 :                : }
                               1001                 :                : 
                               1002                 :                : 
                               1003                 :                : /*
                               1004                 :                :  * strtoint64 -- convert a string to 64-bit integer
                               1005                 :                :  *
                               1006                 :                :  * This function is a slightly modified version of pg_strtoint64() from
                               1007                 :                :  * src/backend/utils/adt/numutils.c.
                               1008                 :                :  *
                               1009                 :                :  * The function returns whether the conversion worked, and if so
                               1010                 :                :  * "*result" is set to the result.
                               1011                 :                :  *
                               1012                 :                :  * If not errorOK, an error message is also printed out on errors.
                               1013                 :                :  */
                               1014                 :                : bool
 2536 andres@anarazel.de       1015                 :           1325 : strtoint64(const char *str, bool errorOK, int64 *result)
                               1016                 :                : {
 4603 heikki.linnakangas@i     1017                 :           1325 :     const char *ptr = str;
 2536 andres@anarazel.de       1018                 :           1325 :     int64       tmp = 0;
                               1019                 :           1325 :     bool        neg = false;
                               1020                 :                : 
                               1021                 :                :     /*
                               1022                 :                :      * Do our own scan, rather than relying on sscanf which might be broken
                               1023                 :                :      * for long long.
                               1024                 :                :      *
                               1025                 :                :      * As INT64_MIN can't be stored as a positive 64 bit integer, accumulate
                               1026                 :                :      * value as a negative number.
                               1027                 :                :      */
                               1028                 :                : 
                               1029                 :                :     /* skip leading spaces */
 4603 heikki.linnakangas@i     1030   [ +  -  -  + ]:           1325 :     while (*ptr && isspace((unsigned char) *ptr))
 4603 heikki.linnakangas@i     1031                 :UBC           0 :         ptr++;
                               1032                 :                : 
                               1033                 :                :     /* handle sign */
 4603 heikki.linnakangas@i     1034         [ +  + ]:CBC        1325 :     if (*ptr == '-')
                               1035                 :                :     {
                               1036                 :              2 :         ptr++;
 2536 andres@anarazel.de       1037                 :              2 :         neg = true;
                               1038                 :                :     }
 4603 heikki.linnakangas@i     1039         [ -  + ]:           1323 :     else if (*ptr == '+')
 4603 heikki.linnakangas@i     1040                 :UBC           0 :         ptr++;
                               1041                 :                : 
                               1042                 :                :     /* require at least one digit */
 2536 andres@anarazel.de       1043         [ -  + ]:CBC        1325 :     if (unlikely(!isdigit((unsigned char) *ptr)))
 2536 andres@anarazel.de       1044                 :UBC           0 :         goto invalid_syntax;
                               1045                 :                : 
                               1046                 :                :     /* process digits */
 4603 heikki.linnakangas@i     1047   [ +  +  +  - ]:CBC        3953 :     while (*ptr && isdigit((unsigned char) *ptr))
                               1048                 :                :     {
 2536 andres@anarazel.de       1049                 :           2629 :         int8        digit = (*ptr++ - '0');
                               1050                 :                : 
                               1051         [ +  + ]:           2629 :         if (unlikely(pg_mul_s64_overflow(tmp, 10, &tmp)) ||
                               1052         [ -  + ]:           2628 :             unlikely(pg_sub_s64_overflow(tmp, digit, &tmp)))
                               1053                 :              1 :             goto out_of_range;
                               1054                 :                :     }
                               1055                 :                : 
                               1056                 :                :     /* allow trailing whitespace, but not other trailing chars */
 4603 heikki.linnakangas@i     1057   [ -  +  -  - ]:           1324 :     while (*ptr != '\0' && isspace((unsigned char) *ptr))
 4603 heikki.linnakangas@i     1058                 :UBC           0 :         ptr++;
                               1059                 :                : 
 2536 andres@anarazel.de       1060         [ -  + ]:CBC        1324 :     if (unlikely(*ptr != '\0'))
 2536 andres@anarazel.de       1061                 :UBC           0 :         goto invalid_syntax;
                               1062                 :                : 
 2536 andres@anarazel.de       1063         [ +  + ]:CBC        1324 :     if (!neg)
                               1064                 :                :     {
                               1065         [ -  + ]:           1322 :         if (unlikely(tmp == PG_INT64_MIN))
 2536 andres@anarazel.de       1066                 :UBC           0 :             goto out_of_range;
 2536 andres@anarazel.de       1067                 :CBC        1322 :         tmp = -tmp;
                               1068                 :                :     }
                               1069                 :                : 
                               1070                 :           1324 :     *result = tmp;
                               1071                 :           1324 :     return true;
                               1072                 :                : 
                               1073                 :              1 : out_of_range:
                               1074         [ -  + ]:              1 :     if (!errorOK)
 2068 peter@eisentraut.org     1075                 :UBC           0 :         pg_log_error("value \"%s\" is out of range for type bigint", str);
 2536 andres@anarazel.de       1076                 :CBC           1 :     return false;
                               1077                 :                : 
 2536 andres@anarazel.de       1078                 :UBC           0 : invalid_syntax:
                               1079         [ #  # ]:              0 :     if (!errorOK)
 2068 peter@eisentraut.org     1080                 :              0 :         pg_log_error("invalid input syntax for type bigint: \"%s\"", str);
 2536 andres@anarazel.de       1081                 :              0 :     return false;
                               1082                 :                : }
                               1083                 :                : 
                               1084                 :                : /* convert string to double, detecting overflows/underflows */
                               1085                 :                : bool
 2536 andres@anarazel.de       1086                 :CBC          66 : strtodouble(const char *str, bool errorOK, double *dv)
                               1087                 :                : {
                               1088                 :                :     char       *end;
                               1089                 :                : 
                               1090                 :             66 :     errno = 0;
                               1091                 :             66 :     *dv = strtod(str, &end);
                               1092                 :                : 
                               1093         [ +  + ]:             66 :     if (unlikely(errno != 0))
                               1094                 :                :     {
                               1095         [ -  + ]:              2 :         if (!errorOK)
 2068 peter@eisentraut.org     1096                 :UBC           0 :             pg_log_error("value \"%s\" is out of range for type double", str);
 2536 andres@anarazel.de       1097                 :CBC           2 :         return false;
                               1098                 :                :     }
                               1099                 :                : 
                               1100   [ +  +  -  +  :             64 :     if (unlikely(end == str || *end != '\0'))
                                              +  + ]
                               1101                 :                :     {
                               1102         [ -  + ]:              2 :         if (!errorOK)
 2068 peter@eisentraut.org     1103                 :UBC           0 :             pg_log_error("invalid input syntax for type double: \"%s\"", str);
 2536 andres@anarazel.de       1104                 :CBC           2 :         return false;
                               1105                 :                :     }
                               1106                 :             62 :     return true;
                               1107                 :                : }
                               1108                 :                : 
                               1109                 :                : /*
                               1110                 :                :  * Initialize a prng state struct.
                               1111                 :                :  *
                               1112                 :                :  * We derive the seed from base_random_sequence, which must be set up already.
                               1113                 :                :  */
                               1114                 :                : static void
 1378 tgl@sss.pgh.pa.us        1115                 :            389 : initRandomState(pg_prng_state *state)
                               1116                 :                : {
                               1117                 :            389 :     pg_prng_seed(state, pg_prng_uint64(&base_random_sequence));
 2486 alvherre@alvh.no-ip.     1118                 :            389 : }
                               1119                 :                : 
                               1120                 :                : 
                               1121                 :                : /*
                               1122                 :                :  * random number generator: uniform distribution from min to max inclusive.
                               1123                 :                :  *
                               1124                 :                :  * Although the limits are expressed as int64, you can't generate the full
                               1125                 :                :  * int64 range in one call, because the difference of the limits mustn't
                               1126                 :                :  * overflow int64.  This is not checked.
                               1127                 :                :  */
                               1128                 :                : static int64
 1378 tgl@sss.pgh.pa.us        1129                 :           2874 : getrand(pg_prng_state *state, int64 min, int64 max)
                               1130                 :                : {
                               1131                 :           2874 :     return min + (int64) pg_prng_uint64_range(state, 0, max - min);
                               1132                 :                : }
                               1133                 :                : 
                               1134                 :                : /*
                               1135                 :                :  * random number generator: exponential distribution from min to max inclusive.
                               1136                 :                :  * the parameter is so that the density of probability for the last cut-off max
                               1137                 :                :  * value is exp(-parameter).
                               1138                 :                :  */
                               1139                 :                : static int64
                               1140                 :              3 : getExponentialRand(pg_prng_state *state, int64 min, int64 max,
                               1141                 :                :                    double parameter)
                               1142                 :                : {
                               1143                 :                :     double      cut,
                               1144                 :                :                 uniform,
                               1145                 :                :                 rand;
                               1146                 :                : 
                               1147                 :                :     /* abort if wrong parameter, but must really be checked beforehand */
 3550 rhaas@postgresql.org     1148         [ -  + ]:              3 :     Assert(parameter > 0.0);
                               1149                 :              3 :     cut = exp(-parameter);
                               1150                 :                :     /* pg_prng_double value in [0, 1), uniform in (0, 1] */
 1378 tgl@sss.pgh.pa.us        1151                 :              3 :     uniform = 1.0 - pg_prng_double(state);
                               1152                 :                : 
                               1153                 :                :     /*
                               1154                 :                :      * inner expression in (cut, 1] (if parameter > 0), rand in [0, 1)
                               1155                 :                :      */
 4056 rhaas@postgresql.org     1156         [ -  + ]:              3 :     Assert((1.0 - cut) != 0.0);
 3550                          1157                 :              3 :     rand = -log(cut + (1.0 - cut) * uniform) / parameter;
                               1158                 :                :     /* return int64 random number within between min and max */
 3759 bruce@momjian.us         1159                 :              3 :     return min + (int64) ((max - min + 1) * rand);
                               1160                 :                : }
                               1161                 :                : 
                               1162                 :                : /* random number generator: gaussian distribution from min to max inclusive */
                               1163                 :                : static int64
 1378 tgl@sss.pgh.pa.us        1164                 :              3 : getGaussianRand(pg_prng_state *state, int64 min, int64 max,
                               1165                 :                :                 double parameter)
                               1166                 :                : {
                               1167                 :                :     double      stdev;
                               1168                 :                :     double      rand;
                               1169                 :                : 
                               1170                 :                :     /* abort if parameter is too low, but must really be checked beforehand */
 3449 rhaas@postgresql.org     1171         [ +  - ]:              3 :     Assert(parameter >= MIN_GAUSSIAN_PARAM);
                               1172                 :                : 
                               1173                 :                :     /*
                               1174                 :                :      * Get normally-distributed random number in the range -parameter <= stdev
                               1175                 :                :      * < parameter.
                               1176                 :                :      *
                               1177                 :                :      * This loop is executed until the number is in the expected range.
                               1178                 :                :      *
                               1179                 :                :      * As the minimum parameter is 2.0, the probability of looping is low:
                               1180                 :                :      * sqrt(-2 ln(r)) <= 2 => r >= e^{-2} ~ 0.135, then when taking the
                               1181                 :                :      * average sinus multiplier as 2/pi, we have a 8.6% looping probability in
                               1182                 :                :      * the worst case. For a parameter value of 5.0, the looping probability
                               1183                 :                :      * is about e^{-5} * 2 / pi ~ 0.43%.
                               1184                 :                :      */
                               1185                 :                :     do
                               1186                 :                :     {
  971 tgl@sss.pgh.pa.us        1187                 :              3 :         stdev = pg_prng_double_normal(state);
                               1188                 :                :     }
 3550 rhaas@postgresql.org     1189   [ -  +  -  + ]:              3 :     while (stdev < -parameter || stdev >= parameter);
                               1190                 :                : 
                               1191                 :                :     /* stdev is in [-parameter, parameter), normalization to [0,1) */
                               1192                 :              3 :     rand = (stdev + parameter) / (parameter * 2.0);
                               1193                 :                : 
                               1194                 :                :     /* return int64 random number within between min and max */
 3759 bruce@momjian.us         1195                 :              3 :     return min + (int64) ((max - min + 1) * rand);
                               1196                 :                : }
                               1197                 :                : 
                               1198                 :                : /*
                               1199                 :                :  * random number generator: generate a value, such that the series of values
                               1200                 :                :  * will approximate a Poisson distribution centered on the given value.
                               1201                 :                :  *
                               1202                 :                :  * Individual results are rounded to integers, though the center value need
                               1203                 :                :  * not be one.
                               1204                 :                :  */
                               1205                 :                : static int64
 1378 tgl@sss.pgh.pa.us        1206                 :            210 : getPoissonRand(pg_prng_state *state, double center)
                               1207                 :                : {
                               1208                 :                :     /*
                               1209                 :                :      * Use inverse transform sampling to generate a value > 0, such that the
                               1210                 :                :      * expected (i.e. average) value is the given argument.
                               1211                 :                :      */
                               1212                 :                :     double      uniform;
                               1213                 :                : 
                               1214                 :                :     /* pg_prng_double value in [0, 1), uniform in (0, 1] */
                               1215                 :            210 :     uniform = 1.0 - pg_prng_double(state);
                               1216                 :                : 
 2538                          1217                 :            210 :     return (int64) (-log(uniform) * center + 0.5);
                               1218                 :                : }
                               1219                 :                : 
                               1220                 :                : /*
                               1221                 :                :  * Computing zipfian using rejection method, based on
                               1222                 :                :  * "Non-Uniform Random Variate Generation",
                               1223                 :                :  * Luc Devroye, p. 550-551, Springer 1986.
                               1224                 :                :  *
                               1225                 :                :  * This works for s > 1.0, but may perform badly for s very close to 1.0.
                               1226                 :                :  */
                               1227                 :                : static int64
 1378                          1228                 :              3 : computeIterativeZipfian(pg_prng_state *state, int64 n, double s)
                               1229                 :                : {
 2823 teodor@sigaev.ru         1230                 :              3 :     double      b = pow(2.0, s - 1.0);
                               1231                 :                :     double      x,
                               1232                 :                :                 t,
                               1233                 :                :                 u,
                               1234                 :                :                 v;
                               1235                 :                : 
                               1236                 :                :     /* Ensure n is sane */
 2350 tgl@sss.pgh.pa.us        1237         [ -  + ]:              3 :     if (n <= 1)
 2350 tgl@sss.pgh.pa.us        1238                 :UBC           0 :         return 1;
                               1239                 :                : 
                               1240                 :                :     while (true)
                               1241                 :                :     {
                               1242                 :                :         /* random variates */
 1378 tgl@sss.pgh.pa.us        1243                 :CBC           3 :         u = pg_prng_double(state);
                               1244                 :              3 :         v = pg_prng_double(state);
                               1245                 :                : 
 2823 teodor@sigaev.ru         1246                 :              3 :         x = floor(pow(u, -1.0 / (s - 1.0)));
                               1247                 :                : 
                               1248                 :              3 :         t = pow(1.0 + 1.0 / x, s - 1.0);
                               1249                 :                :         /* reject if too large or out of bound */
                               1250   [ +  -  +  - ]:              3 :         if (v * x * (t - 1.0) / (b - 1.0) <= t / b && x <= n)
                               1251                 :              3 :             break;
                               1252                 :                :     }
                               1253                 :              3 :     return (int64) x;
                               1254                 :                : }
                               1255                 :                : 
                               1256                 :                : /* random number generator: zipfian distribution from min to max inclusive */
                               1257                 :                : static int64
 1378 tgl@sss.pgh.pa.us        1258                 :              3 : getZipfianRand(pg_prng_state *state, int64 min, int64 max, double s)
                               1259                 :                : {
 2823 teodor@sigaev.ru         1260                 :              3 :     int64       n = max - min + 1;
                               1261                 :                : 
                               1262                 :                :     /* abort if parameter is invalid */
 2350 tgl@sss.pgh.pa.us        1263   [ +  -  +  - ]:              3 :     Assert(MIN_ZIPFIAN_PARAM <= s && s <= MAX_ZIPFIAN_PARAM);
                               1264                 :                : 
 1378                          1265                 :              3 :     return min - 1 + computeIterativeZipfian(state, n, s);
                               1266                 :                : }
                               1267                 :                : 
                               1268                 :                : /*
                               1269                 :                :  * FNV-1a hash function
                               1270                 :                :  */
                               1271                 :                : static int64
 2726 teodor@sigaev.ru         1272                 :              1 : getHashFnv1a(int64 val, uint64 seed)
                               1273                 :                : {
                               1274                 :                :     int64       result;
                               1275                 :                :     int         i;
                               1276                 :                : 
                               1277                 :              1 :     result = FNV_OFFSET_BASIS ^ seed;
                               1278         [ +  + ]:              9 :     for (i = 0; i < 8; ++i)
                               1279                 :                :     {
 2690 tgl@sss.pgh.pa.us        1280                 :              8 :         int32       octet = val & 0xff;
                               1281                 :                : 
 2726 teodor@sigaev.ru         1282                 :              8 :         val = val >> 8;
                               1283                 :              8 :         result = result ^ octet;
                               1284                 :              8 :         result = result * FNV_PRIME;
                               1285                 :                :     }
                               1286                 :                : 
                               1287                 :              1 :     return result;
                               1288                 :                : }
                               1289                 :                : 
                               1290                 :                : /*
                               1291                 :                :  * Murmur2 hash function
                               1292                 :                :  *
                               1293                 :                :  * Based on original work of Austin Appleby
                               1294                 :                :  * https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp
                               1295                 :                :  */
                               1296                 :                : static int64
                               1297                 :              5 : getHashMurmur2(int64 val, uint64 seed)
                               1298                 :                : {
 2685 tgl@sss.pgh.pa.us        1299                 :              5 :     uint64      result = seed ^ MM2_MUL_TIMES_8;    /* sizeof(int64) */
 2690                          1300                 :              5 :     uint64      k = (uint64) val;
                               1301                 :                : 
 2726 teodor@sigaev.ru         1302                 :              5 :     k *= MM2_MUL;
                               1303                 :              5 :     k ^= k >> MM2_ROT;
                               1304                 :              5 :     k *= MM2_MUL;
                               1305                 :                : 
                               1306                 :              5 :     result ^= k;
                               1307                 :              5 :     result *= MM2_MUL;
                               1308                 :                : 
                               1309                 :              5 :     result ^= result >> MM2_ROT;
                               1310                 :              5 :     result *= MM2_MUL;
                               1311                 :              5 :     result ^= result >> MM2_ROT;
                               1312                 :                : 
                               1313                 :              5 :     return (int64) result;
                               1314                 :                : }
                               1315                 :                : 
                               1316                 :                : /*
                               1317                 :                :  * Pseudorandom permutation function
                               1318                 :                :  *
                               1319                 :                :  * For small sizes, this generates each of the (size!) possible permutations
                               1320                 :                :  * of integers in the range [0, size) with roughly equal probability.  Once
                               1321                 :                :  * the size is larger than 20, the number of possible permutations exceeds the
                               1322                 :                :  * number of distinct states of the internal pseudorandom number generator,
                               1323                 :                :  * and so not all possible permutations can be generated, but the permutations
                               1324                 :                :  * chosen should continue to give the appearance of being random.
                               1325                 :                :  *
                               1326                 :                :  * THIS FUNCTION IS NOT CRYPTOGRAPHICALLY SECURE.
                               1327                 :                :  * DO NOT USE FOR SUCH PURPOSE.
                               1328                 :                :  */
                               1329                 :                : static int64
 1614 dean.a.rasheed@gmail     1330                 :             45 : permute(const int64 val, const int64 isize, const int64 seed)
                               1331                 :                : {
                               1332                 :                :     /* using a high-end PRNG is probably overkill */
                               1333                 :                :     pg_prng_state state;
                               1334                 :                :     uint64      size;
                               1335                 :                :     uint64      v;
                               1336                 :                :     int         masklen;
                               1337                 :                :     uint64      mask;
                               1338                 :                :     int         i;
                               1339                 :                : 
                               1340         [ +  + ]:             45 :     if (isize < 2)
                               1341                 :              1 :         return 0;               /* nothing to permute */
                               1342                 :                : 
                               1343                 :                :     /* Initialize prng state using the seed */
 1378 tgl@sss.pgh.pa.us        1344                 :             44 :     pg_prng_seed(&state, (uint64) seed);
                               1345                 :                : 
                               1346                 :                :     /* Computations are performed on unsigned values */
 1614 dean.a.rasheed@gmail     1347                 :             44 :     size = (uint64) isize;
                               1348                 :             44 :     v = (uint64) val % size;
                               1349                 :                : 
                               1350                 :                :     /* Mask to work modulo largest power of 2 less than or equal to size */
                               1351                 :             44 :     masklen = pg_leftmost_one_pos64(size);
                               1352                 :             44 :     mask = (((uint64) 1) << masklen) - 1;
                               1353                 :                : 
                               1354                 :                :     /*
                               1355                 :                :      * Permute the input value by applying several rounds of pseudorandom
                               1356                 :                :      * bijective transformations.  The intention here is to distribute each
                               1357                 :                :      * input uniformly randomly across the range, and separate adjacent inputs
                               1358                 :                :      * approximately uniformly randomly from each other, leading to a fairly
                               1359                 :                :      * random overall choice of permutation.
                               1360                 :                :      *
                               1361                 :                :      * To separate adjacent inputs, we multiply by a random number modulo
                               1362                 :                :      * (mask + 1), which is a power of 2.  For this to be a bijection, the
                               1363                 :                :      * multiplier must be odd.  Since this is known to lead to less randomness
                               1364                 :                :      * in the lower bits, we also apply a rotation that shifts the topmost bit
                               1365                 :                :      * into the least significant bit.  In the special cases where size <= 3,
                               1366                 :                :      * mask = 1 and each of these operations is actually a no-op, so we also
                               1367                 :                :      * XOR the value with a different random number to inject additional
                               1368                 :                :      * randomness.  Since the size is generally not a power of 2, we apply
                               1369                 :                :      * this bijection on overlapping upper and lower halves of the input.
                               1370                 :                :      *
                               1371                 :                :      * To distribute the inputs uniformly across the range, we then also apply
                               1372                 :                :      * a random offset modulo the full range.
                               1373                 :                :      *
                               1374                 :                :      * Taken together, these operations resemble a modified linear
                               1375                 :                :      * congruential generator, as is commonly used in pseudorandom number
                               1376                 :                :      * generators.  The number of rounds is fairly arbitrary, but six has been
                               1377                 :                :      * found empirically to give a fairly good tradeoff between performance
                               1378                 :                :      * and uniform randomness.  For small sizes it selects each of the (size!)
                               1379                 :                :      * possible permutations with roughly equal probability.  For larger
                               1380                 :                :      * sizes, not all permutations can be generated, but the intended random
                               1381                 :                :      * spread is still produced.
                               1382                 :                :      */
                               1383         [ +  + ]:            308 :     for (i = 0; i < 6; i++)
                               1384                 :                :     {
                               1385                 :                :         uint64      m,
                               1386                 :                :                     r,
                               1387                 :                :                     t;
                               1388                 :                : 
                               1389                 :                :         /* Random multiply (by an odd number), XOR and rotate of lower half */
 1378 tgl@sss.pgh.pa.us        1390                 :            264 :         m = (pg_prng_uint64(&state) & mask) | 1;
                               1391                 :            264 :         r = pg_prng_uint64(&state) & mask;
 1614 dean.a.rasheed@gmail     1392         [ +  + ]:            264 :         if (v <= mask)
                               1393                 :                :         {
                               1394                 :            219 :             v = ((v * m) ^ r) & mask;
                               1395                 :            219 :             v = ((v << 1) & mask) | (v >> (masklen - 1));
                               1396                 :                :         }
                               1397                 :                : 
                               1398                 :                :         /* Random multiply (by an odd number), XOR and rotate of upper half */
 1378 tgl@sss.pgh.pa.us        1399                 :            264 :         m = (pg_prng_uint64(&state) & mask) | 1;
                               1400                 :            264 :         r = pg_prng_uint64(&state) & mask;
 1614 dean.a.rasheed@gmail     1401                 :            264 :         t = size - 1 - v;
                               1402         [ +  + ]:            264 :         if (t <= mask)
                               1403                 :                :         {
                               1404                 :            235 :             t = ((t * m) ^ r) & mask;
                               1405                 :            235 :             t = ((t << 1) & mask) | (t >> (masklen - 1));
                               1406                 :            235 :             v = size - 1 - t;
                               1407                 :                :         }
                               1408                 :                : 
                               1409                 :                :         /* Random offset */
 1378 tgl@sss.pgh.pa.us        1410                 :            264 :         r = pg_prng_uint64_range(&state, 0, size - 1);
 1614 dean.a.rasheed@gmail     1411                 :            264 :         v = (v + r) % size;
                               1412                 :                :     }
                               1413                 :                : 
                               1414                 :             44 :     return (int64) v;
                               1415                 :                : }
                               1416                 :                : 
                               1417                 :                : /*
                               1418                 :                :  * Initialize the given SimpleStats struct to all zeroes
                               1419                 :                :  */
                               1420                 :                : static void
 3508 alvherre@alvh.no-ip.     1421                 :           2039 : initSimpleStats(SimpleStats *ss)
                               1422                 :                : {
                               1423                 :           2039 :     memset(ss, 0, sizeof(SimpleStats));
                               1424                 :           2039 : }
                               1425                 :                : 
                               1426                 :                : /*
                               1427                 :                :  * Accumulate one value into a SimpleStats struct.
                               1428                 :                :  */
                               1429                 :                : static void
                               1430                 :           9643 : addToSimpleStats(SimpleStats *ss, double val)
                               1431                 :                : {
                               1432   [ +  +  +  + ]:           9643 :     if (ss->count == 0 || val < ss->min)
                               1433                 :            147 :         ss->min = val;
                               1434   [ +  +  +  + ]:           9643 :     if (ss->count == 0 || val > ss->max)
                               1435                 :            473 :         ss->max = val;
                               1436                 :           9643 :     ss->count++;
                               1437                 :           9643 :     ss->sum += val;
                               1438                 :           9643 :     ss->sum2 += val * val;
                               1439                 :           9643 : }
                               1440                 :                : 
                               1441                 :                : /*
                               1442                 :                :  * Merge two SimpleStats objects
                               1443                 :                :  */
                               1444                 :                : static void
                               1445                 :            170 : mergeSimpleStats(SimpleStats *acc, SimpleStats *ss)
                               1446                 :                : {
                               1447   [ -  +  -  - ]:            170 :     if (acc->count == 0 || ss->min < acc->min)
                               1448                 :            170 :         acc->min = ss->min;
                               1449   [ -  +  -  - ]:            170 :     if (acc->count == 0 || ss->max > acc->max)
                               1450                 :            170 :         acc->max = ss->max;
                               1451                 :            170 :     acc->count += ss->count;
                               1452                 :            170 :     acc->sum += ss->sum;
                               1453                 :            170 :     acc->sum2 += ss->sum2;
                               1454                 :            170 : }
                               1455                 :                : 
                               1456                 :                : /*
                               1457                 :                :  * Initialize a StatsData struct to mostly zeroes, with its start time set to
                               1458                 :                :  * the given value.
                               1459                 :                :  */
                               1460                 :                : static void
 1641 tmunro@postgresql.or     1461                 :            542 : initStats(StatsData *sd, pg_time_usec_t start)
                               1462                 :                : {
                               1463                 :            542 :     sd->start_time = start;
 3508 alvherre@alvh.no-ip.     1464                 :            542 :     sd->cnt = 0;
                               1465                 :            542 :     sd->skipped = 0;
 1263 ishii@postgresql.org     1466                 :            542 :     sd->retries = 0;
                               1467                 :            542 :     sd->retried = 0;
                               1468                 :            542 :     sd->serialization_failures = 0;
                               1469                 :            542 :     sd->deadlock_failures = 0;
 3508 alvherre@alvh.no-ip.     1470                 :            542 :     initSimpleStats(&sd->latency);
                               1471                 :            542 :     initSimpleStats(&sd->lag);
                               1472                 :            542 : }
                               1473                 :                : 
                               1474                 :                : /*
                               1475                 :                :  * Accumulate one additional item into the given stats object.
                               1476                 :                :  */
                               1477                 :                : static void
 1263 ishii@postgresql.org     1478                 :           9050 : accumStats(StatsData *stats, bool skipped, double lat, double lag,
                               1479                 :                :            EStatus estatus, int64 tries)
                               1480                 :                : {
                               1481                 :                :     /* Record the skipped transaction */
 3508 alvherre@alvh.no-ip.     1482         [ +  + ]:           9050 :     if (skipped)
                               1483                 :                :     {
                               1484                 :                :         /* no latency to record on skipped transactions */
                               1485                 :              9 :         stats->skipped++;
 1263 ishii@postgresql.org     1486                 :              9 :         return;
                               1487                 :                :     }
                               1488                 :                : 
                               1489                 :                :     /*
                               1490                 :                :      * Record the number of retries regardless of whether the transaction was
                               1491                 :                :      * successful or failed.
                               1492                 :                :      */
                               1493         [ +  + ]:           9041 :     if (tries > 1)
                               1494                 :                :     {
                               1495                 :              2 :         stats->retries += (tries - 1);
                               1496                 :              2 :         stats->retried++;
                               1497                 :                :     }
                               1498                 :                : 
                               1499   [ +  -  -  - ]:           9041 :     switch (estatus)
                               1500                 :                :     {
                               1501                 :                :             /* Record the successful transaction */
                               1502                 :           9041 :         case ESTATUS_NO_ERROR:
                               1503                 :           9041 :             stats->cnt++;
                               1504                 :                : 
                               1505                 :           9041 :             addToSimpleStats(&stats->latency, lat);
                               1506                 :                : 
                               1507                 :                :             /* and possibly the same for schedule lag */
                               1508         [ +  + ]:           9041 :             if (throttle_delay)
                               1509                 :            201 :                 addToSimpleStats(&stats->lag, lag);
                               1510                 :           9041 :             break;
                               1511                 :                : 
                               1512                 :                :             /* Record the failed transaction */
 1263 ishii@postgresql.org     1513                 :UBC           0 :         case ESTATUS_SERIALIZATION_ERROR:
                               1514                 :              0 :             stats->serialization_failures++;
                               1515                 :              0 :             break;
                               1516                 :              0 :         case ESTATUS_DEADLOCK_ERROR:
                               1517                 :              0 :             stats->deadlock_failures++;
                               1518                 :              0 :             break;
                               1519                 :              0 :         default:
                               1520                 :                :             /* internal error which should never occur */
 1247 tgl@sss.pgh.pa.us        1521                 :              0 :             pg_fatal("unexpected error status: %d", estatus);
                               1522                 :                :     }
                               1523                 :                : }
                               1524                 :                : 
                               1525                 :                : /* call PQexec() and exit() on failure */
                               1526                 :                : static void
 6505 bruce@momjian.us         1527                 :CBC          59 : executeStatement(PGconn *con, const char *sql)
                               1528                 :                : {
                               1529                 :                :     PGresult   *res;
                               1530                 :                : 
 6728 ishii@postgresql.org     1531                 :             59 :     res = PQexec(con, sql);
                               1532         [ -  + ]:             59 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
                               1533                 :                :     {
 1247 tgl@sss.pgh.pa.us        1534                 :UBC           0 :         pg_log_error("query failed: %s", PQerrorMessage(con));
                               1535                 :              0 :         pg_log_error_detail("Query was: %s", sql);
 6728 ishii@postgresql.org     1536                 :              0 :         exit(1);
                               1537                 :                :     }
 6728 ishii@postgresql.org     1538                 :CBC          59 :     PQclear(res);
                               1539                 :             59 : }
                               1540                 :                : 
                               1541                 :                : /* call PQexec() and complain, but without exiting, on failure */
                               1542                 :                : static void
 3770 sfrost@snowman.net       1543                 :             30 : tryExecuteStatement(PGconn *con, const char *sql)
                               1544                 :                : {
                               1545                 :                :     PGresult   *res;
                               1546                 :                : 
                               1547                 :             30 :     res = PQexec(con, sql);
                               1548         [ -  + ]:             30 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
                               1549                 :                :     {
 2068 peter@eisentraut.org     1550                 :UBC           0 :         pg_log_error("%s", PQerrorMessage(con));
 1247 tgl@sss.pgh.pa.us        1551                 :              0 :         pg_log_error_detail("(ignoring this error and continuing anyway)");
                               1552                 :                :     }
 3770 sfrost@snowman.net       1553                 :CBC          30 :     PQclear(res);
                               1554                 :             30 : }
                               1555                 :                : 
                               1556                 :                : /* set up a connection to the backend */
                               1557                 :                : static PGconn *
 7621 tgl@sss.pgh.pa.us        1558                 :            320 : doConnect(void)
                               1559                 :                : {
                               1560                 :                :     PGconn     *conn;
                               1561                 :                :     bool        new_pass;
                               1562                 :                :     static char *password = NULL;
                               1563                 :                : 
                               1564                 :                :     /*
                               1565                 :                :      * Start the connection.  Loop until we have a password if requested by
                               1566                 :                :      * backend.
                               1567                 :                :      */
                               1568                 :                :     do
                               1569                 :                :     {
                               1570                 :                : #define PARAMS_ARRAY_SIZE   7
                               1571                 :                : 
                               1572                 :                :         const char *keywords[PARAMS_ARRAY_SIZE];
                               1573                 :                :         const char *values[PARAMS_ARRAY_SIZE];
                               1574                 :                : 
 4812 rhaas@postgresql.org     1575                 :            320 :         keywords[0] = "host";
                               1576                 :            320 :         values[0] = pghost;
                               1577                 :            320 :         keywords[1] = "port";
                               1578                 :            320 :         values[1] = pgport;
                               1579                 :            320 :         keywords[2] = "user";
 1645 michael@paquier.xyz      1580                 :            320 :         values[2] = username;
 4812 rhaas@postgresql.org     1581                 :            320 :         keywords[3] = "password";
 1829 tgl@sss.pgh.pa.us        1582                 :            320 :         values[3] = password;
 4812 rhaas@postgresql.org     1583                 :            320 :         keywords[4] = "dbname";
                               1584                 :            320 :         values[4] = dbName;
                               1585                 :            320 :         keywords[5] = "fallback_application_name";
                               1586                 :            320 :         values[5] = progname;
                               1587                 :            320 :         keywords[6] = NULL;
                               1588                 :            320 :         values[6] = NULL;
                               1589                 :                : 
 6479 tgl@sss.pgh.pa.us        1590                 :            320 :         new_pass = false;
                               1591                 :                : 
 4812 rhaas@postgresql.org     1592                 :            320 :         conn = PQconnectdbParams(keywords, values, true);
                               1593                 :                : 
 6479 tgl@sss.pgh.pa.us        1594         [ -  + ]:            320 :         if (!conn)
                               1595                 :                :         {
 2068 peter@eisentraut.org     1596                 :UBC           0 :             pg_log_error("connection to database \"%s\" failed", dbName);
 6479 tgl@sss.pgh.pa.us        1597                 :              0 :             return NULL;
                               1598                 :                :         }
                               1599                 :                : 
 6479 tgl@sss.pgh.pa.us        1600   [ +  +  -  + ]:CBC         321 :         if (PQstatus(conn) == CONNECTION_BAD &&
                               1601                 :              1 :             PQconnectionNeedsPassword(conn) &&
 1829 tgl@sss.pgh.pa.us        1602         [ #  # ]:UBC           0 :             !password)
                               1603                 :                :         {
 6479                          1604                 :              0 :             PQfinish(conn);
 1829                          1605                 :              0 :             password = simple_prompt("Password: ", false);
 6479                          1606                 :              0 :             new_pass = true;
                               1607                 :                :         }
 6479 tgl@sss.pgh.pa.us        1608         [ -  + ]:CBC         320 :     } while (new_pass);
                               1609                 :                : 
                               1610                 :                :     /* check to see that the backend connection was successfully made */
                               1611         [ +  + ]:            320 :     if (PQstatus(conn) == CONNECTION_BAD)
                               1612                 :                :     {
 1688                          1613                 :              1 :         pg_log_error("%s", PQerrorMessage(conn));
 6479                          1614                 :              1 :         PQfinish(conn);
                               1615                 :              1 :         return NULL;
                               1616                 :                :     }
                               1617                 :                : 
                               1618                 :            319 :     return conn;
                               1619                 :                : }
                               1620                 :                : 
                               1621                 :                : /* qsort comparator for Variable array */
                               1622                 :                : static int
 3410                          1623                 :          53941 : compareVariableNames(const void *v1, const void *v2)
                               1624                 :                : {
 7274                          1625                 :         107882 :     return strcmp(((const Variable *) v1)->name,
                               1626                 :          53941 :                   ((const Variable *) v2)->name);
                               1627                 :                : }
                               1628                 :                : 
                               1629                 :                : /* Locate a variable by name; returns NULL if unknown */
                               1630                 :                : static Variable *
 1263 ishii@postgresql.org     1631                 :           7993 : lookupVariable(Variables *variables, char *name)
                               1632                 :                : {
                               1633                 :                :     Variable    key;
                               1634                 :                : 
                               1635                 :                :     /* On some versions of Solaris, bsearch of zero items dumps core */
                               1636         [ +  + ]:           7993 :     if (variables->nvars <= 0)
 7274 tgl@sss.pgh.pa.us        1637                 :            199 :         return NULL;
                               1638                 :                : 
                               1639                 :                :     /* Sort if we have to */
 1263 ishii@postgresql.org     1640         [ +  + ]:           7794 :     if (!variables->vars_sorted)
                               1641                 :                :     {
  942 peter@eisentraut.org     1642                 :           1014 :         qsort(variables->vars, variables->nvars, sizeof(Variable),
                               1643                 :                :               compareVariableNames);
 1263 ishii@postgresql.org     1644                 :           1014 :         variables->vars_sorted = true;
                               1645                 :                :     }
                               1646                 :                : 
                               1647                 :                :     /* Now we can search */
 7266 tgl@sss.pgh.pa.us        1648                 :           7794 :     key.name = name;
  942 peter@eisentraut.org     1649                 :           7794 :     return (Variable *) bsearch(&key,
                               1650                 :           7794 :                                 variables->vars,
 1263 ishii@postgresql.org     1651                 :           7794 :                                 variables->nvars,
                               1652                 :                :                                 sizeof(Variable),
                               1653                 :                :                                 compareVariableNames);
                               1654                 :                : }
                               1655                 :                : 
                               1656                 :                : /* Get the value of a variable, in string form; returns NULL if unknown */
                               1657                 :                : static char *
                               1658                 :           2450 : getVariable(Variables *variables, char *name)
                               1659                 :                : {
                               1660                 :                :     Variable   *var;
                               1661                 :                :     char        stringform[64];
                               1662                 :                : 
                               1663                 :           2450 :     var = lookupVariable(variables, name);
 3410 tgl@sss.pgh.pa.us        1664         [ +  + ]:           2450 :     if (var == NULL)
                               1665                 :              4 :         return NULL;            /* not found */
                               1666                 :                : 
 2797 teodor@sigaev.ru         1667         [ +  + ]:           2446 :     if (var->svalue)
                               1668                 :            840 :         return var->svalue;      /* we have it in string form */
                               1669                 :                : 
                               1670                 :                :     /* We need to produce a string equivalent of the value */
                               1671         [ -  + ]:           1606 :     Assert(var->value.type != PGBT_NO_VALUE);
                               1672         [ +  + ]:           1606 :     if (var->value.type == PGBT_NULL)
                               1673                 :              1 :         snprintf(stringform, sizeof(stringform), "NULL");
                               1674         [ +  + ]:           1605 :     else if (var->value.type == PGBT_BOOLEAN)
 3410 tgl@sss.pgh.pa.us        1675                 :              1 :         snprintf(stringform, sizeof(stringform),
 2797 teodor@sigaev.ru         1676         [ +  - ]:              1 :                  "%s", var->value.u.bval ? "true" : "false");
                               1677         [ +  + ]:           1604 :     else if (var->value.type == PGBT_INT)
 3410 tgl@sss.pgh.pa.us        1678                 :           1602 :         snprintf(stringform, sizeof(stringform),
                               1679                 :                :                  INT64_FORMAT, var->value.u.ival);
 2797 teodor@sigaev.ru         1680         [ +  - ]:              2 :     else if (var->value.type == PGBT_DOUBLE)
                               1681                 :              2 :         snprintf(stringform, sizeof(stringform),
                               1682                 :                :                  "%.*g", DBL_DIG, var->value.u.dval);
                               1683                 :                :     else                        /* internal error, unexpected type */
 2797 teodor@sigaev.ru         1684                 :UBC           0 :         Assert(0);
 2797 teodor@sigaev.ru         1685                 :CBC        1606 :     var->svalue = pg_strdup(stringform);
                               1686                 :           1606 :     return var->svalue;
                               1687                 :                : }
                               1688                 :                : 
                               1689                 :                : /* Try to convert variable to a value; return false on failure */
                               1690                 :                : static bool
                               1691                 :           2031 : makeVariableValue(Variable *var)
                               1692                 :                : {
                               1693                 :                :     size_t      slen;
                               1694                 :                : 
                               1695         [ +  + ]:           2031 :     if (var->value.type != PGBT_NO_VALUE)
 3410 tgl@sss.pgh.pa.us        1696                 :           1497 :         return true;            /* no work */
                               1697                 :                : 
 2797 teodor@sigaev.ru         1698                 :            534 :     slen = strlen(var->svalue);
                               1699                 :                : 
                               1700         [ -  + ]:            534 :     if (slen == 0)
                               1701                 :                :         /* what should it do on ""? */
 2797 teodor@sigaev.ru         1702                 :UBC           0 :         return false;
                               1703                 :                : 
 2797 teodor@sigaev.ru         1704         [ +  + ]:CBC         534 :     if (pg_strcasecmp(var->svalue, "null") == 0)
                               1705                 :                :     {
                               1706                 :              1 :         setNullValue(&var->value);
                               1707                 :                :     }
                               1708                 :                : 
                               1709                 :                :     /*
                               1710                 :                :      * accept prefixes such as y, ye, n, no... but not for "o". 0/1 are
                               1711                 :                :      * recognized later as an int, which is converted to bool if needed.
                               1712                 :                :      */
                               1713   [ +  +  +  - ]:           1065 :     else if (pg_strncasecmp(var->svalue, "true", slen) == 0 ||
                               1714         [ -  + ]:           1064 :              pg_strncasecmp(var->svalue, "yes", slen) == 0 ||
                               1715                 :            532 :              pg_strcasecmp(var->svalue, "on") == 0)
                               1716                 :                :     {
                               1717                 :              1 :         setBoolValue(&var->value, true);
                               1718                 :                :     }
                               1719   [ +  -  +  - ]:           1064 :     else if (pg_strncasecmp(var->svalue, "false", slen) == 0 ||
                               1720         [ +  - ]:           1064 :              pg_strncasecmp(var->svalue, "no", slen) == 0 ||
                               1721         [ +  + ]:           1064 :              pg_strcasecmp(var->svalue, "off") == 0 ||
                               1722                 :            532 :              pg_strcasecmp(var->svalue, "of") == 0)
                               1723                 :                :     {
                               1724                 :              1 :         setBoolValue(&var->value, false);
                               1725                 :                :     }
                               1726         [ +  + ]:            531 :     else if (is_an_int(var->svalue))
                               1727                 :                :     {
                               1728                 :                :         /* if it looks like an int, it must be an int without overflow */
                               1729                 :                :         int64       iv;
                               1730                 :                : 
 2536 andres@anarazel.de       1731         [ -  + ]:            528 :         if (!strtoint64(var->svalue, false, &iv))
 2536 andres@anarazel.de       1732                 :UBC           0 :             return false;
                               1733                 :                : 
 2536 andres@anarazel.de       1734                 :CBC         528 :         setIntValue(&var->value, iv);
                               1735                 :                :     }
                               1736                 :                :     else                        /* type should be double */
                               1737                 :                :     {
                               1738                 :                :         double      dv;
                               1739                 :                : 
                               1740         [ +  + ]:              3 :         if (!strtodouble(var->svalue, true, &dv))
                               1741                 :                :         {
 2068 peter@eisentraut.org     1742                 :              2 :             pg_log_error("malformed variable \"%s\" value: \"%s\"",
                               1743                 :                :                          var->name, var->svalue);
 3410 tgl@sss.pgh.pa.us        1744                 :              2 :             return false;
                               1745                 :                :         }
 2797 teodor@sigaev.ru         1746                 :              1 :         setDoubleValue(&var->value, dv);
                               1747                 :                :     }
 3410 tgl@sss.pgh.pa.us        1748                 :            532 :     return true;
                               1749                 :                : }
                               1750                 :                : 
                               1751                 :                : /*
                               1752                 :                :  * Check whether a variable's name is allowed.
                               1753                 :                :  *
                               1754                 :                :  * We allow any non-ASCII character, as well as ASCII letters, digits, and
                               1755                 :                :  * underscore.
                               1756                 :                :  *
                               1757                 :                :  * Keep this in sync with the definitions of variable name characters in
                               1758                 :                :  * "src/fe_utils/psqlscan.l", "src/bin/psql/psqlscanslash.l" and
                               1759                 :                :  * "src/bin/pgbench/exprscan.l".  Also see parseVariable(), below.
                               1760                 :                :  *
                               1761                 :                :  * Note: this static function is copied from "src/bin/psql/variables.c"
                               1762                 :                :  * but changed to disallow variable names starting with a digit.
                               1763                 :                :  */
                               1764                 :                : static bool
 2924                          1765                 :           1105 : valid_variable_name(const char *name)
                               1766                 :                : {
                               1767                 :           1105 :     const unsigned char *ptr = (const unsigned char *) name;
                               1768                 :                : 
                               1769                 :                :     /* Mustn't be zero-length */
                               1770         [ -  + ]:           1105 :     if (*ptr == '\0')
 2924 tgl@sss.pgh.pa.us        1771                 :UBC           0 :         return false;
                               1772                 :                : 
                               1773                 :                :     /* must not start with [0-9] */
 1697 tgl@sss.pgh.pa.us        1774         [ +  - ]:CBC        1105 :     if (IS_HIGHBIT_SET(*ptr) ||
                               1775                 :           1105 :         strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
                               1776         [ +  + ]:           1105 :                "_", *ptr) != NULL)
                               1777                 :           1103 :         ptr++;
                               1778                 :                :     else
                               1779                 :              2 :         return false;
                               1780                 :                : 
                               1781                 :                :     /* remaining characters can include [0-9] */
 2924                          1782         [ +  + ]:           7218 :     while (*ptr)
                               1783                 :                :     {
                               1784         [ +  - ]:           6116 :         if (IS_HIGHBIT_SET(*ptr) ||
                               1785                 :           6116 :             strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
                               1786         [ +  + ]:           6116 :                    "_0123456789", *ptr) != NULL)
                               1787                 :           6115 :             ptr++;
                               1788                 :                :         else
 5722 itagaki.takahiro@gma     1789                 :              1 :             return false;
                               1790                 :                :     }
                               1791                 :                : 
 2924 tgl@sss.pgh.pa.us        1792                 :           1102 :     return true;
                               1793                 :                : }
                               1794                 :                : 
                               1795                 :                : /*
                               1796                 :                :  * Make sure there is enough space for 'needed' more variable in the variables
                               1797                 :                :  * array.
                               1798                 :                :  */
                               1799                 :                : static void
 1263 ishii@postgresql.org     1800                 :           1102 : enlargeVariables(Variables *variables, int needed)
                               1801                 :                : {
                               1802                 :                :     /* total number of variables required now */
                               1803                 :           1102 :     needed += variables->nvars;
                               1804                 :                : 
                               1805         [ +  + ]:           1102 :     if (variables->max_vars < needed)
                               1806                 :                :     {
                               1807                 :            188 :         variables->max_vars = needed + VARIABLES_ALLOC_MARGIN;
                               1808                 :            188 :         variables->vars = (Variable *)
                               1809                 :            188 :             pg_realloc(variables->vars, variables->max_vars * sizeof(Variable));
                               1810                 :                :     }
                               1811                 :           1102 : }
                               1812                 :                : 
                               1813                 :                : /*
                               1814                 :                :  * Lookup a variable by name, creating it if need be.
                               1815                 :                :  * Caller is expected to assign a value to the variable.
                               1816                 :                :  * Returns NULL on failure (bad name).
                               1817                 :                :  */
                               1818                 :                : static Variable *
                               1819                 :           3166 : lookupCreateVariable(Variables *variables, const char *context, char *name)
                               1820                 :                : {
                               1821                 :                :     Variable   *var;
                               1822                 :                : 
                               1823                 :           3166 :     var = lookupVariable(variables, name);
 7282                          1824         [ +  + ]:           3166 :     if (var == NULL)
                               1825                 :                :     {
                               1826                 :                :         /*
                               1827                 :                :          * Check for the name only when declaring a new variable to avoid
                               1828                 :                :          * overhead.
                               1829                 :                :          */
 2924 tgl@sss.pgh.pa.us        1830         [ +  + ]:           1105 :         if (!valid_variable_name(name))
                               1831                 :                :         {
 2068 peter@eisentraut.org     1832                 :              3 :             pg_log_error("%s: invalid variable name: \"%s\"", context, name);
 3410 tgl@sss.pgh.pa.us        1833                 :              3 :             return NULL;
                               1834                 :                :         }
                               1835                 :                : 
                               1836                 :                :         /* Create variable at the end of the array */
 1263 ishii@postgresql.org     1837                 :           1102 :         enlargeVariables(variables, 1);
                               1838                 :                : 
                               1839                 :           1102 :         var = &(variables->vars[variables->nvars]);
                               1840                 :                : 
 4722 tgl@sss.pgh.pa.us        1841                 :           1102 :         var->name = pg_strdup(name);
 2797 teodor@sigaev.ru         1842                 :           1102 :         var->svalue = NULL;
                               1843                 :                :         /* caller is expected to initialize remaining fields */
                               1844                 :                : 
 1263 ishii@postgresql.org     1845                 :           1102 :         variables->nvars++;
                               1846                 :                :         /* we don't re-sort the array till we have to */
                               1847                 :           1102 :         variables->vars_sorted = false;
                               1848                 :                :     }
                               1849                 :                : 
 3410 tgl@sss.pgh.pa.us        1850                 :           3163 :     return var;
                               1851                 :                : }
                               1852                 :                : 
                               1853                 :                : /* Assign a string value to a variable, creating it if need be */
                               1854                 :                : /* Returns false on failure (bad name) */
                               1855                 :                : static bool
 1263 ishii@postgresql.org     1856                 :            972 : putVariable(Variables *variables, const char *context, char *name,
                               1857                 :                :             const char *value)
                               1858                 :                : {
                               1859                 :                :     Variable   *var;
                               1860                 :                :     char       *val;
                               1861                 :                : 
                               1862                 :            972 :     var = lookupCreateVariable(variables, context, name);
 3410 tgl@sss.pgh.pa.us        1863         [ +  + ]:            972 :     if (!var)
                               1864                 :              2 :         return false;
                               1865                 :                : 
                               1866                 :                :     /* dup then free, in case value is pointing at this variable */
                               1867                 :            970 :     val = pg_strdup(value);
                               1868                 :                : 
 1178 peter@eisentraut.org     1869                 :            970 :     free(var->svalue);
 2797 teodor@sigaev.ru         1870                 :            970 :     var->svalue = val;
                               1871                 :            970 :     var->value.type = PGBT_NO_VALUE;
                               1872                 :                : 
 3410 tgl@sss.pgh.pa.us        1873                 :            970 :     return true;
                               1874                 :                : }
                               1875                 :                : 
                               1876                 :                : /* Assign a value to a variable, creating it if need be */
                               1877                 :                : /* Returns false on failure (bad name) */
                               1878                 :                : static bool
 1263 ishii@postgresql.org     1879                 :           2194 : putVariableValue(Variables *variables, const char *context, char *name,
                               1880                 :                :                  const PgBenchValue *value)
                               1881                 :                : {
                               1882                 :                :     Variable   *var;
                               1883                 :                : 
                               1884                 :           2194 :     var = lookupCreateVariable(variables, context, name);
 3410 tgl@sss.pgh.pa.us        1885         [ +  + ]:           2194 :     if (!var)
                               1886                 :              1 :         return false;
                               1887                 :                : 
 1178 peter@eisentraut.org     1888                 :           2193 :     free(var->svalue);
 2797 teodor@sigaev.ru         1889                 :           2193 :     var->svalue = NULL;
                               1890                 :           2193 :     var->value = *value;
                               1891                 :                : 
 7282 ishii@postgresql.org     1892                 :           2193 :     return true;
                               1893                 :                : }
                               1894                 :                : 
                               1895                 :                : /* Assign an integer value to a variable, creating it if need be */
                               1896                 :                : /* Returns false on failure (bad name) */
                               1897                 :                : static bool
 1263                          1898                 :            505 : putVariableInt(Variables *variables, const char *context, char *name,
                               1899                 :                :                int64 value)
                               1900                 :                : {
                               1901                 :                :     PgBenchValue val;
                               1902                 :                : 
 3410 tgl@sss.pgh.pa.us        1903                 :            505 :     setIntValue(&val, value);
 1263 ishii@postgresql.org     1904                 :            505 :     return putVariableValue(variables, context, name, &val);
                               1905                 :                : }
                               1906                 :                : 
                               1907                 :                : /*
                               1908                 :                :  * Parse a possible variable reference (:varname).
                               1909                 :                :  *
                               1910                 :                :  * "sql" points at a colon.  If what follows it looks like a valid
                               1911                 :                :  * variable name, return a malloc'd string containing the variable name,
                               1912                 :                :  * and set *eaten to the number of characters consumed (including the colon).
                               1913                 :                :  * Otherwise, return NULL.
                               1914                 :                :  */
                               1915                 :                : static char *
 6380                          1916                 :           2305 : parseVariable(const char *sql, int *eaten)
                               1917                 :                : {
 1697 tgl@sss.pgh.pa.us        1918                 :           2305 :     int         i = 1;          /* starting at 1 skips the colon */
                               1919                 :                :     char       *name;
                               1920                 :                : 
                               1921                 :                :     /* keep this logic in sync with valid_variable_name() */
                               1922         [ +  - ]:           2305 :     if (IS_HIGHBIT_SET(sql[i]) ||
                               1923                 :           2305 :         strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
                               1924         [ +  + ]:           2305 :                "_", sql[i]) != NULL)
                               1925                 :           1066 :         i++;
                               1926                 :                :     else
                               1927                 :           1239 :         return NULL;
                               1928                 :                : 
                               1929         [ -  + ]:           4843 :     while (IS_HIGHBIT_SET(sql[i]) ||
                               1930                 :           4843 :            strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
                               1931         [ +  + ]:           4843 :                   "_0123456789", sql[i]) != NULL)
 6380 ishii@postgresql.org     1932                 :           3777 :         i++;
                               1933                 :                : 
 4722 tgl@sss.pgh.pa.us        1934                 :           1066 :     name = pg_malloc(i);
 6380 ishii@postgresql.org     1935                 :           1066 :     memcpy(name, &sql[1], i - 1);
                               1936                 :           1066 :     name[i - 1] = '\0';
                               1937                 :                : 
                               1938                 :           1066 :     *eaten = i;
                               1939                 :           1066 :     return name;
                               1940                 :                : }
                               1941                 :                : 
                               1942                 :                : static char *
                               1943                 :           1065 : replaceVariable(char **sql, char *param, int len, char *value)
                               1944                 :                : {
 5931 bruce@momjian.us         1945                 :           1065 :     int         valueln = strlen(value);
                               1946                 :                : 
 6380 ishii@postgresql.org     1947         [ +  + ]:           1065 :     if (valueln > len)
                               1948                 :                :     {
 5931 bruce@momjian.us         1949                 :            587 :         size_t      offset = param - *sql;
                               1950                 :                : 
 4722 tgl@sss.pgh.pa.us        1951                 :            587 :         *sql = pg_realloc(*sql, strlen(*sql) - len + valueln + 1);
 6380 ishii@postgresql.org     1952                 :            587 :         param = *sql + offset;
                               1953                 :                :     }
                               1954                 :                : 
                               1955         [ +  + ]:           1065 :     if (valueln != len)
                               1956                 :           1038 :         memmove(param + valueln, param + len, strlen(param + len) + 1);
 3878 tgl@sss.pgh.pa.us        1957                 :           1065 :     memcpy(param, value, valueln);
                               1958                 :                : 
 6380 ishii@postgresql.org     1959                 :           1065 :     return param + valueln;
                               1960                 :                : }
                               1961                 :                : 
                               1962                 :                : static char *
 1263                          1963                 :           7992 : assignVariables(Variables *variables, char *sql)
                               1964                 :                : {
                               1965                 :                :     char       *p,
                               1966                 :                :                *name,
                               1967                 :                :                *val;
                               1968                 :                : 
 6380                          1969                 :           7992 :     p = sql;
                               1970         [ +  + ]:          10000 :     while ((p = strchr(p, ':')) != NULL)
                               1971                 :                :     {
                               1972                 :                :         int         eaten;
                               1973                 :                : 
                               1974                 :           2008 :         name = parseVariable(p, &eaten);
                               1975         [ +  + ]:           2008 :         if (name == NULL)
                               1976                 :                :         {
 5931 bruce@momjian.us         1977         [ +  + ]:           2980 :             while (*p == ':')
                               1978                 :                :             {
                               1979                 :           1757 :                 p++;
                               1980                 :                :             }
 7282 ishii@postgresql.org     1981                 :           1223 :             continue;
                               1982                 :                :         }
                               1983                 :                : 
 1263                          1984                 :            785 :         val = getVariable(variables, name);
 7282                          1985                 :            785 :         free(name);
                               1986         [ -  + ]:            785 :         if (val == NULL)
                               1987                 :                :         {
 6380 ishii@postgresql.org     1988                 :UBC           0 :             p++;
                               1989                 :              0 :             continue;
                               1990                 :                :         }
                               1991                 :                : 
 5504 tgl@sss.pgh.pa.us        1992                 :CBC         785 :         p = replaceVariable(&sql, p, eaten, val);
                               1993                 :                :     }
                               1994                 :                : 
 6380 ishii@postgresql.org     1995                 :           7992 :     return sql;
                               1996                 :                : }
                               1997                 :                : 
                               1998                 :                : static void
 1263                          1999                 :           2531 : getQueryParams(Variables *variables, const Command *command,
                               2000                 :                :                const char **params)
                               2001                 :                : {
                               2002                 :                :     int         i;
                               2003                 :                : 
 6380                          2004         [ +  + ]:           4191 :     for (i = 0; i < command->argc - 1; i++)
 1263                          2005                 :           1660 :         params[i] = getVariable(variables, command->argv[i + 1]);
 6380                          2006                 :           2531 : }
                               2007                 :                : 
                               2008                 :                : static char *
 2797 teodor@sigaev.ru         2009                 :              4 : valueTypeName(PgBenchValue *pval)
                               2010                 :                : {
                               2011         [ -  + ]:              4 :     if (pval->type == PGBT_NO_VALUE)
 2797 teodor@sigaev.ru         2012                 :UBC           0 :         return "none";
 2797 teodor@sigaev.ru         2013         [ -  + ]:CBC           4 :     else if (pval->type == PGBT_NULL)
 2797 teodor@sigaev.ru         2014                 :UBC           0 :         return "null";
 2797 teodor@sigaev.ru         2015         [ -  + ]:CBC           4 :     else if (pval->type == PGBT_INT)
 2797 teodor@sigaev.ru         2016                 :UBC           0 :         return "int";
 2797 teodor@sigaev.ru         2017         [ +  + ]:CBC           4 :     else if (pval->type == PGBT_DOUBLE)
                               2018                 :              1 :         return "double";
                               2019         [ +  - ]:              3 :     else if (pval->type == PGBT_BOOLEAN)
                               2020                 :              3 :         return "boolean";
                               2021                 :                :     else
                               2022                 :                :     {
                               2023                 :                :         /* internal error, should never get there */
 2797 teodor@sigaev.ru         2024                 :UBC           0 :         Assert(false);
                               2025                 :                :         return NULL;
                               2026                 :                :     }
                               2027                 :                : }
                               2028                 :                : 
                               2029                 :                : /* get a value as a boolean, or tell if there is a problem */
                               2030                 :                : static bool
 2797 teodor@sigaev.ru         2031                 :CBC         108 : coerceToBool(PgBenchValue *pval, bool *bval)
                               2032                 :                : {
                               2033         [ +  + ]:            108 :     if (pval->type == PGBT_BOOLEAN)
                               2034                 :                :     {
                               2035                 :            107 :         *bval = pval->u.bval;
                               2036                 :            107 :         return true;
                               2037                 :                :     }
                               2038                 :                :     else                        /* NULL, INT or DOUBLE */
                               2039                 :                :     {
 2068 peter@eisentraut.org     2040                 :              1 :         pg_log_error("cannot coerce %s to boolean", valueTypeName(pval));
 2761 tgl@sss.pgh.pa.us        2041                 :              1 :         *bval = false;          /* suppress uninitialized-variable warnings */
 2797 teodor@sigaev.ru         2042                 :              1 :         return false;
                               2043                 :                :     }
                               2044                 :                : }
                               2045                 :                : 
                               2046                 :                : /*
                               2047                 :                :  * Return true or false from an expression for conditional purposes.
                               2048                 :                :  * Non zero numerical values are true, zero and NULL are false.
                               2049                 :                :  */
                               2050                 :                : static bool
                               2051                 :            546 : valueTruth(PgBenchValue *pval)
                               2052                 :                : {
                               2053   [ +  +  +  +  :            546 :     switch (pval->type)
                                                 - ]
                               2054                 :                :     {
                               2055                 :              1 :         case PGBT_NULL:
                               2056                 :              1 :             return false;
                               2057                 :             31 :         case PGBT_BOOLEAN:
                               2058                 :             31 :             return pval->u.bval;
                               2059                 :            513 :         case PGBT_INT:
                               2060                 :            513 :             return pval->u.ival != 0;
                               2061                 :              1 :         case PGBT_DOUBLE:
                               2062                 :              1 :             return pval->u.dval != 0.0;
 2797 teodor@sigaev.ru         2063                 :UBC           0 :         default:
                               2064                 :                :             /* internal error, unexpected type */
                               2065                 :              0 :             Assert(0);
                               2066                 :                :             return false;
                               2067                 :                :     }
                               2068                 :                : }
                               2069                 :                : 
                               2070                 :                : /* get a value as an int, tell if there is a problem */
                               2071                 :                : static bool
 3449 rhaas@postgresql.org     2072                 :CBC        6608 : coerceToInt(PgBenchValue *pval, int64 *ival)
                               2073                 :                : {
                               2074         [ +  + ]:           6608 :     if (pval->type == PGBT_INT)
                               2075                 :                :     {
                               2076                 :           6604 :         *ival = pval->u.ival;
                               2077                 :           6604 :         return true;
                               2078                 :                :     }
 2797 teodor@sigaev.ru         2079         [ +  + ]:              4 :     else if (pval->type == PGBT_DOUBLE)
                               2080                 :                :     {
 2130 tgl@sss.pgh.pa.us        2081                 :              2 :         double      dval = rint(pval->u.dval);
                               2082                 :                : 
                               2083   [ +  -  +  -  :              2 :         if (isnan(dval) || !FLOAT8_FITS_IN_INT64(dval))
                                              +  + ]
                               2084                 :                :         {
 2068 peter@eisentraut.org     2085                 :              1 :             pg_log_error("double to int overflow for %f", dval);
 3449 rhaas@postgresql.org     2086                 :              1 :             return false;
                               2087                 :                :         }
                               2088                 :              1 :         *ival = (int64) dval;
                               2089                 :              1 :         return true;
                               2090                 :                :     }
                               2091                 :                :     else                        /* BOOLEAN or NULL */
                               2092                 :                :     {
 2068 peter@eisentraut.org     2093                 :              2 :         pg_log_error("cannot coerce %s to int", valueTypeName(pval));
 2797 teodor@sigaev.ru         2094                 :              2 :         return false;
                               2095                 :                :     }
                               2096                 :                : }
                               2097                 :                : 
                               2098                 :                : /* get a value as a double, or tell if there is a problem */
                               2099                 :                : static bool
 3449 rhaas@postgresql.org     2100                 :            104 : coerceToDouble(PgBenchValue *pval, double *dval)
                               2101                 :                : {
                               2102         [ +  + ]:            104 :     if (pval->type == PGBT_DOUBLE)
                               2103                 :                :     {
                               2104                 :             73 :         *dval = pval->u.dval;
                               2105                 :             73 :         return true;
                               2106                 :                :     }
 2797 teodor@sigaev.ru         2107         [ +  + ]:             31 :     else if (pval->type == PGBT_INT)
                               2108                 :                :     {
 3449 rhaas@postgresql.org     2109                 :             30 :         *dval = (double) pval->u.ival;
                               2110                 :             30 :         return true;
                               2111                 :                :     }
                               2112                 :                :     else                        /* BOOLEAN or NULL */
                               2113                 :                :     {
 2068 peter@eisentraut.org     2114                 :              1 :         pg_log_error("cannot coerce %s to double", valueTypeName(pval));
 2797 teodor@sigaev.ru         2115                 :              1 :         return false;
                               2116                 :                :     }
                               2117                 :                : }
                               2118                 :                : 
                               2119                 :                : /* assign a null value */
                               2120                 :                : static void
                               2121                 :              4 : setNullValue(PgBenchValue *pv)
                               2122                 :                : {
                               2123                 :              4 :     pv->type = PGBT_NULL;
                               2124                 :              4 :     pv->u.ival = 0;
                               2125                 :              4 : }
                               2126                 :                : 
                               2127                 :                : /* assign a boolean value */
                               2128                 :                : static void
                               2129                 :            139 : setBoolValue(PgBenchValue *pv, bool bval)
                               2130                 :                : {
                               2131                 :            139 :     pv->type = PGBT_BOOLEAN;
                               2132                 :            139 :     pv->u.bval = bval;
 3449 rhaas@postgresql.org     2133                 :            139 : }
                               2134                 :                : 
                               2135                 :                : /* assign an integer value */
                               2136                 :                : static void
                               2137                 :           4245 : setIntValue(PgBenchValue *pv, int64 ival)
                               2138                 :                : {
                               2139                 :           4245 :     pv->type = PGBT_INT;
                               2140                 :           4245 :     pv->u.ival = ival;
                               2141                 :           4245 : }
                               2142                 :                : 
                               2143                 :                : /* assign a double value */
                               2144                 :                : static void
                               2145                 :             39 : setDoubleValue(PgBenchValue *pv, double dval)
                               2146                 :                : {
                               2147                 :             39 :     pv->type = PGBT_DOUBLE;
                               2148                 :             39 :     pv->u.dval = dval;
                               2149                 :             39 : }
                               2150                 :                : 
                               2151                 :                : static bool
 2690 tgl@sss.pgh.pa.us        2152                 :           3575 : isLazyFunc(PgBenchFunction func)
                               2153                 :                : {
 2797 teodor@sigaev.ru         2154   [ +  +  +  +  :           3575 :     return func == PGBENCH_AND || func == PGBENCH_OR || func == PGBENCH_CASE;
                                              +  + ]
                               2155                 :                : }
                               2156                 :                : 
                               2157                 :                : /* lazy evaluation of some functions */
                               2158                 :                : static bool
 2348 tgl@sss.pgh.pa.us        2159                 :             65 : evalLazyFunc(CState *st,
                               2160                 :                :              PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
                               2161                 :                : {
                               2162                 :                :     PgBenchValue a1,
                               2163                 :                :                 a2;
                               2164                 :                :     bool        ba1,
                               2165                 :                :                 ba2;
                               2166                 :                : 
 2797 teodor@sigaev.ru         2167   [ +  -  +  -  :             65 :     Assert(isLazyFunc(func) && args != NULL && args->next != NULL);
                                              +  - ]
                               2168                 :                : 
                               2169                 :                :     /* args points to first condition */
 2348 tgl@sss.pgh.pa.us        2170         [ +  + ]:             65 :     if (!evaluateExpr(st, args->expr, &a1))
 2797 teodor@sigaev.ru         2171                 :              1 :         return false;
                               2172                 :                : 
                               2173                 :                :     /* second condition for AND/OR and corresponding branch for CASE */
                               2174                 :             64 :     args = args->next;
                               2175                 :                : 
                               2176   [ +  +  +  - ]:             64 :     switch (func)
                               2177                 :                :     {
 2690 tgl@sss.pgh.pa.us        2178                 :             44 :         case PGBENCH_AND:
                               2179         [ -  + ]:             44 :             if (a1.type == PGBT_NULL)
                               2180                 :                :             {
 2690 tgl@sss.pgh.pa.us        2181                 :UBC           0 :                 setNullValue(retval);
                               2182                 :              0 :                 return true;
                               2183                 :                :             }
                               2184                 :                : 
 2690 tgl@sss.pgh.pa.us        2185         [ -  + ]:CBC          44 :             if (!coerceToBool(&a1, &ba1))
 2690 tgl@sss.pgh.pa.us        2186                 :UBC           0 :                 return false;
                               2187                 :                : 
 2690 tgl@sss.pgh.pa.us        2188         [ +  + ]:CBC          44 :             if (!ba1)
                               2189                 :                :             {
                               2190                 :              3 :                 setBoolValue(retval, false);
                               2191                 :              3 :                 return true;
                               2192                 :                :             }
                               2193                 :                : 
 2348                          2194         [ -  + ]:             41 :             if (!evaluateExpr(st, args->expr, &a2))
 2690 tgl@sss.pgh.pa.us        2195                 :UBC           0 :                 return false;
                               2196                 :                : 
 2690 tgl@sss.pgh.pa.us        2197         [ -  + ]:CBC          41 :             if (a2.type == PGBT_NULL)
                               2198                 :                :             {
 2690 tgl@sss.pgh.pa.us        2199                 :UBC           0 :                 setNullValue(retval);
                               2200                 :              0 :                 return true;
                               2201                 :                :             }
 2690 tgl@sss.pgh.pa.us        2202         [ -  + ]:CBC          41 :             else if (!coerceToBool(&a2, &ba2))
 2690 tgl@sss.pgh.pa.us        2203                 :UBC           0 :                 return false;
                               2204                 :                :             else
                               2205                 :                :             {
 2690 tgl@sss.pgh.pa.us        2206                 :CBC          41 :                 setBoolValue(retval, ba2);
                               2207                 :             41 :                 return true;
                               2208                 :                :             }
                               2209                 :                : 
                               2210                 :                :             return true;
                               2211                 :                : 
                               2212                 :              4 :         case PGBENCH_OR:
                               2213                 :                : 
                               2214         [ -  + ]:              4 :             if (a1.type == PGBT_NULL)
                               2215                 :                :             {
 2690 tgl@sss.pgh.pa.us        2216                 :UBC           0 :                 setNullValue(retval);
                               2217                 :              0 :                 return true;
                               2218                 :                :             }
                               2219                 :                : 
 2690 tgl@sss.pgh.pa.us        2220         [ -  + ]:CBC           4 :             if (!coerceToBool(&a1, &ba1))
 2690 tgl@sss.pgh.pa.us        2221                 :UBC           0 :                 return false;
                               2222                 :                : 
 2690 tgl@sss.pgh.pa.us        2223         [ +  + ]:CBC           4 :             if (ba1)
                               2224                 :                :             {
                               2225                 :              1 :                 setBoolValue(retval, true);
                               2226                 :              1 :                 return true;
                               2227                 :                :             }
                               2228                 :                : 
 2348                          2229         [ -  + ]:              3 :             if (!evaluateExpr(st, args->expr, &a2))
 2690 tgl@sss.pgh.pa.us        2230                 :UBC           0 :                 return false;
                               2231                 :                : 
 2690 tgl@sss.pgh.pa.us        2232         [ -  + ]:CBC           3 :             if (a2.type == PGBT_NULL)
                               2233                 :                :             {
 2690 tgl@sss.pgh.pa.us        2234                 :UBC           0 :                 setNullValue(retval);
                               2235                 :              0 :                 return true;
                               2236                 :                :             }
 2690 tgl@sss.pgh.pa.us        2237         [ -  + ]:CBC           3 :             else if (!coerceToBool(&a2, &ba2))
 2690 tgl@sss.pgh.pa.us        2238                 :UBC           0 :                 return false;
                               2239                 :                :             else
                               2240                 :                :             {
 2690 tgl@sss.pgh.pa.us        2241                 :CBC           3 :                 setBoolValue(retval, ba2);
                               2242                 :              3 :                 return true;
                               2243                 :                :             }
                               2244                 :                : 
                               2245                 :             16 :         case PGBENCH_CASE:
                               2246                 :                :             /* when true, execute branch */
                               2247         [ +  + ]:             16 :             if (valueTruth(&a1))
 2348                          2248                 :             11 :                 return evaluateExpr(st, args->expr, retval);
                               2249                 :                : 
                               2250                 :                :             /* now args contains next condition or final else expression */
 2690                          2251                 :              5 :             args = args->next;
                               2252                 :                : 
                               2253                 :                :             /* final else case? */
                               2254         [ +  + ]:              5 :             if (args->next == NULL)
 2348                          2255                 :              3 :                 return evaluateExpr(st, args->expr, retval);
                               2256                 :                : 
                               2257                 :                :             /* no, another when, proceed */
                               2258                 :              2 :             return evalLazyFunc(st, PGBENCH_CASE, args, retval);
                               2259                 :                : 
 2690 tgl@sss.pgh.pa.us        2260                 :UBC           0 :         default:
                               2261                 :                :             /* internal error, cannot get here */
                               2262                 :              0 :             Assert(0);
                               2263                 :                :             break;
                               2264                 :                :     }
                               2265                 :                :     return false;
                               2266                 :                : }
                               2267                 :                : 
                               2268                 :                : /* maximum number of function arguments */
                               2269                 :                : #define MAX_FARGS 16
                               2270                 :                : 
                               2271                 :                : /*
                               2272                 :                :  * Recursive evaluation of standard functions,
                               2273                 :                :  * which do not require lazy evaluation.
                               2274                 :                :  */
                               2275                 :                : static bool
 2348 tgl@sss.pgh.pa.us        2276                 :CBC        3447 : evalStandardFunc(CState *st,
                               2277                 :                :                  PgBenchFunction func, PgBenchExprLink *args,
                               2278                 :                :                  PgBenchValue *retval)
                               2279                 :                : {
                               2280                 :                :     /* evaluate all function arguments */
 2690                          2281                 :           3447 :     int         nargs = 0;
  170 peter@eisentraut.org     2282                 :           3447 :     PgBenchValue vargs[MAX_FARGS] = {0};
 3476 rhaas@postgresql.org     2283                 :           3447 :     PgBenchExprLink *l = args;
 2690 tgl@sss.pgh.pa.us        2284                 :           3447 :     bool        has_null = false;
                               2285                 :                : 
 3476 rhaas@postgresql.org     2286   [ +  +  +  + ]:          10304 :     for (nargs = 0; nargs < MAX_FARGS && l != NULL; nargs++, l = l->next)
                               2287                 :                :     {
 2348 tgl@sss.pgh.pa.us        2288         [ +  + ]:           6859 :         if (!evaluateExpr(st, l->expr, &vargs[nargs]))
 3476 rhaas@postgresql.org     2289                 :              2 :             return false;
 2797 teodor@sigaev.ru         2290                 :           6857 :         has_null |= vargs[nargs].type == PGBT_NULL;
                               2291                 :                :     }
                               2292                 :                : 
 3476 rhaas@postgresql.org     2293         [ +  + ]:           3445 :     if (l != NULL)
                               2294                 :                :     {
 2068 peter@eisentraut.org     2295                 :              1 :         pg_log_error("too many function arguments, maximum is %d", MAX_FARGS);
 3476 rhaas@postgresql.org     2296                 :              1 :         return false;
                               2297                 :                :     }
                               2298                 :                : 
                               2299                 :                :     /* NULL arguments */
 2797 teodor@sigaev.ru         2300   [ +  +  +  +  :           3444 :     if (has_null && func != PGBENCH_IS && func != PGBENCH_DEBUG)
                                              +  + ]
                               2301                 :                :     {
                               2302                 :              3 :         setNullValue(retval);
                               2303                 :              3 :         return true;
                               2304                 :                :     }
                               2305                 :                : 
                               2306                 :                :     /* then evaluate function */
 3476 rhaas@postgresql.org     2307   [ +  +  +  +  :           3441 :     switch (func)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                                 - ]
                               2308                 :                :     {
                               2309                 :                :             /* overloaded operators */
                               2310                 :           1702 :         case PGBENCH_ADD:
                               2311                 :                :         case PGBENCH_SUB:
                               2312                 :                :         case PGBENCH_MUL:
                               2313                 :                :         case PGBENCH_DIV:
                               2314                 :                :         case PGBENCH_MOD:
                               2315                 :                :         case PGBENCH_EQ:
                               2316                 :                :         case PGBENCH_NE:
                               2317                 :                :         case PGBENCH_LE:
                               2318                 :                :         case PGBENCH_LT:
                               2319                 :                :             {
 3376                          2320                 :           1702 :                 PgBenchValue *lval = &vargs[0],
                               2321                 :           1702 :                            *rval = &vargs[1];
                               2322                 :                : 
 3476                          2323         [ -  + ]:           1702 :                 Assert(nargs == 2);
                               2324                 :                : 
                               2325                 :                :                 /* overloaded type management, double if some double */
 3449                          2326         [ +  + ]:           1702 :                 if ((lval->type == PGBT_DOUBLE ||
                               2327   [ +  +  +  - ]:           1702 :                      rval->type == PGBT_DOUBLE) && func != PGBENCH_MOD)
                               2328                 :                :                 {
                               2329                 :                :                     double      ld,
                               2330                 :                :                                 rd;
                               2331                 :                : 
                               2332         [ +  - ]:             31 :                     if (!coerceToDouble(lval, &ld) ||
                               2333         [ -  + ]:             31 :                         !coerceToDouble(rval, &rd))
                               2334                 :             31 :                         return false;
                               2335                 :                : 
                               2336   [ +  +  +  +  :             31 :                     switch (func)
                                        +  +  +  +  
                                                 - ]
                               2337                 :                :                     {
                               2338                 :              1 :                         case PGBENCH_ADD:
                               2339                 :              1 :                             setDoubleValue(retval, ld + rd);
                               2340                 :              1 :                             return true;
                               2341                 :                : 
                               2342                 :             10 :                         case PGBENCH_SUB:
                               2343                 :             10 :                             setDoubleValue(retval, ld - rd);
                               2344                 :             10 :                             return true;
                               2345                 :                : 
                               2346                 :              8 :                         case PGBENCH_MUL:
                               2347                 :              8 :                             setDoubleValue(retval, ld * rd);
                               2348                 :              8 :                             return true;
                               2349                 :                : 
                               2350                 :              2 :                         case PGBENCH_DIV:
                               2351                 :              2 :                             setDoubleValue(retval, ld / rd);
                               2352                 :              2 :                             return true;
                               2353                 :                : 
 2797 teodor@sigaev.ru         2354                 :              4 :                         case PGBENCH_EQ:
                               2355                 :              4 :                             setBoolValue(retval, ld == rd);
                               2356                 :              4 :                             return true;
                               2357                 :                : 
                               2358                 :              2 :                         case PGBENCH_NE:
                               2359                 :              2 :                             setBoolValue(retval, ld != rd);
                               2360                 :              2 :                             return true;
                               2361                 :                : 
                               2362                 :              2 :                         case PGBENCH_LE:
                               2363                 :              2 :                             setBoolValue(retval, ld <= rd);
                               2364                 :              2 :                             return true;
                               2365                 :                : 
                               2366                 :              2 :                         case PGBENCH_LT:
                               2367                 :              2 :                             setBoolValue(retval, ld < rd);
                               2368                 :              2 :                             return true;
                               2369                 :                : 
 3449 rhaas@postgresql.org     2370                 :UBC           0 :                         default:
                               2371                 :                :                             /* cannot get here */
                               2372                 :              0 :                             Assert(0);
                               2373                 :                :                     }
                               2374                 :                :                 }
                               2375                 :                :                 else            /* we have integer operands, or % */
                               2376                 :                :                 {
                               2377                 :                :                     int64       li,
                               2378                 :                :                                 ri,
                               2379                 :                :                                 res;
                               2380                 :                : 
 3449 rhaas@postgresql.org     2381         [ +  + ]:CBC        1671 :                     if (!coerceToInt(lval, &li) ||
                               2382         [ -  + ]:           1670 :                         !coerceToInt(rval, &ri))
                               2383                 :           1671 :                         return false;
                               2384                 :                : 
                               2385   [ +  +  +  +  :           1670 :                     switch (func)
                                        +  +  +  +  
                                                 - ]
                               2386                 :                :                     {
                               2387                 :             44 :                         case PGBENCH_ADD:
 2536 andres@anarazel.de       2388         [ +  + ]:             44 :                             if (pg_add_s64_overflow(li, ri, &res))
                               2389                 :                :                             {
 2068 peter@eisentraut.org     2390                 :              1 :                                 pg_log_error("bigint add out of range");
 2536 andres@anarazel.de       2391                 :              1 :                                 return false;
                               2392                 :                :                             }
                               2393                 :             43 :                             setIntValue(retval, res);
 3449 rhaas@postgresql.org     2394                 :             43 :                             return true;
                               2395                 :                : 
                               2396                 :            149 :                         case PGBENCH_SUB:
 2536 andres@anarazel.de       2397         [ +  + ]:            149 :                             if (pg_sub_s64_overflow(li, ri, &res))
                               2398                 :                :                             {
 2068 peter@eisentraut.org     2399                 :              1 :                                 pg_log_error("bigint sub out of range");
 2536 andres@anarazel.de       2400                 :              1 :                                 return false;
                               2401                 :                :                             }
                               2402                 :            148 :                             setIntValue(retval, res);
 3449 rhaas@postgresql.org     2403                 :            148 :                             return true;
                               2404                 :                : 
                               2405                 :           1413 :                         case PGBENCH_MUL:
 2536 andres@anarazel.de       2406         [ +  + ]:           1413 :                             if (pg_mul_s64_overflow(li, ri, &res))
                               2407                 :                :                             {
 2068 peter@eisentraut.org     2408                 :              1 :                                 pg_log_error("bigint mul out of range");
 2536 andres@anarazel.de       2409                 :              1 :                                 return false;
                               2410                 :                :                             }
                               2411                 :           1412 :                             setIntValue(retval, res);
 3449 rhaas@postgresql.org     2412                 :           1412 :                             return true;
                               2413                 :                : 
 2797 teodor@sigaev.ru         2414                 :             32 :                         case PGBENCH_EQ:
                               2415                 :             32 :                             setBoolValue(retval, li == ri);
                               2416                 :             32 :                             return true;
                               2417                 :                : 
                               2418                 :              5 :                         case PGBENCH_NE:
                               2419                 :              5 :                             setBoolValue(retval, li != ri);
                               2420                 :              5 :                             return true;
                               2421                 :                : 
                               2422                 :              5 :                         case PGBENCH_LE:
                               2423                 :              5 :                             setBoolValue(retval, li <= ri);
                               2424                 :              5 :                             return true;
                               2425                 :                : 
                               2426                 :             12 :                         case PGBENCH_LT:
                               2427                 :             12 :                             setBoolValue(retval, li < ri);
                               2428                 :             12 :                             return true;
                               2429                 :                : 
 3449 rhaas@postgresql.org     2430                 :             10 :                         case PGBENCH_DIV:
                               2431                 :                :                         case PGBENCH_MOD:
                               2432         [ +  + ]:             10 :                             if (ri == 0)
                               2433                 :                :                             {
 2068 peter@eisentraut.org     2434                 :              2 :                                 pg_log_error("division by zero");
 3449 rhaas@postgresql.org     2435                 :              2 :                                 return false;
                               2436                 :                :                             }
                               2437                 :                :                             /* special handling of -1 divisor */
                               2438         [ +  + ]:              8 :                             if (ri == -1)
                               2439                 :                :                             {
                               2440         [ +  + ]:              3 :                                 if (func == PGBENCH_DIV)
                               2441                 :                :                                 {
                               2442                 :                :                                     /* overflow check (needed for INT64_MIN) */
                               2443         [ +  + ]:              2 :                                     if (li == PG_INT64_MIN)
                               2444                 :                :                                     {
 2068 peter@eisentraut.org     2445                 :              1 :                                         pg_log_error("bigint div out of range");
 3449 rhaas@postgresql.org     2446                 :              1 :                                         return false;
                               2447                 :                :                                     }
                               2448                 :                :                                     else
 3376                          2449                 :              1 :                                         setIntValue(retval, -li);
                               2450                 :                :                                 }
                               2451                 :                :                                 else
 3449                          2452                 :              1 :                                     setIntValue(retval, 0);
                               2453                 :              2 :                                 return true;
                               2454                 :                :                             }
                               2455                 :                :                             /* else divisor is not -1 */
                               2456         [ +  + ]:              5 :                             if (func == PGBENCH_DIV)
                               2457                 :              2 :                                 setIntValue(retval, li / ri);
                               2458                 :                :                             else    /* func == PGBENCH_MOD */
                               2459                 :              3 :                                 setIntValue(retval, li % ri);
                               2460                 :                : 
 3476                          2461                 :              5 :                             return true;
                               2462                 :                : 
 3449 rhaas@postgresql.org     2463                 :UBC           0 :                         default:
                               2464                 :                :                             /* cannot get here */
                               2465                 :              0 :                             Assert(0);
                               2466                 :                :                     }
                               2467                 :                :                 }
                               2468                 :                : 
                               2469                 :                :                 Assert(0);
                               2470                 :                :                 return false;   /* NOTREACHED */
                               2471                 :                :             }
                               2472                 :                : 
                               2473                 :                :             /* integer bitwise operators */
 2797 teodor@sigaev.ru         2474                 :CBC          14 :         case PGBENCH_BITAND:
                               2475                 :                :         case PGBENCH_BITOR:
                               2476                 :                :         case PGBENCH_BITXOR:
                               2477                 :                :         case PGBENCH_LSHIFT:
                               2478                 :                :         case PGBENCH_RSHIFT:
                               2479                 :                :             {
                               2480                 :                :                 int64       li,
                               2481                 :                :                             ri;
                               2482                 :                : 
                               2483   [ +  -  -  + ]:             14 :                 if (!coerceToInt(&vargs[0], &li) || !coerceToInt(&vargs[1], &ri))
 2797 teodor@sigaev.ru         2484                 :UBC           0 :                     return false;
                               2485                 :                : 
 2797 teodor@sigaev.ru         2486         [ +  + ]:CBC          14 :                 if (func == PGBENCH_BITAND)
                               2487                 :              1 :                     setIntValue(retval, li & ri);
                               2488         [ +  + ]:             13 :                 else if (func == PGBENCH_BITOR)
                               2489                 :              2 :                     setIntValue(retval, li | ri);
                               2490         [ +  + ]:             11 :                 else if (func == PGBENCH_BITXOR)
                               2491                 :              3 :                     setIntValue(retval, li ^ ri);
                               2492         [ +  + ]:              8 :                 else if (func == PGBENCH_LSHIFT)
                               2493                 :              7 :                     setIntValue(retval, li << ri);
                               2494         [ +  - ]:              1 :                 else if (func == PGBENCH_RSHIFT)
                               2495                 :              1 :                     setIntValue(retval, li >> ri);
                               2496                 :                :                 else            /* cannot get here */
 2797 teodor@sigaev.ru         2497                 :UBC           0 :                     Assert(0);
                               2498                 :                : 
 2797 teodor@sigaev.ru         2499                 :CBC          14 :                 return true;
                               2500                 :                :             }
                               2501                 :                : 
                               2502                 :                :             /* logical operators */
                               2503                 :             16 :         case PGBENCH_NOT:
                               2504                 :                :             {
                               2505                 :                :                 bool        b;
                               2506                 :                : 
                               2507         [ +  + ]:             16 :                 if (!coerceToBool(&vargs[0], &b))
                               2508                 :              1 :                     return false;
                               2509                 :                : 
                               2510                 :             15 :                 setBoolValue(retval, !b);
                               2511                 :             15 :                 return true;
                               2512                 :                :             }
                               2513                 :                : 
                               2514                 :                :             /* no arguments */
 3449 rhaas@postgresql.org     2515                 :              1 :         case PGBENCH_PI:
                               2516                 :              1 :             setDoubleValue(retval, M_PI);
                               2517                 :              1 :             return true;
                               2518                 :                : 
                               2519                 :                :             /* 1 overloaded argument */
 3476                          2520                 :              2 :         case PGBENCH_ABS:
                               2521                 :                :             {
 3449                          2522                 :              2 :                 PgBenchValue *varg = &vargs[0];
                               2523                 :                : 
 3476                          2524         [ -  + ]:              2 :                 Assert(nargs == 1);
                               2525                 :                : 
 3449                          2526         [ +  + ]:              2 :                 if (varg->type == PGBT_INT)
                               2527                 :                :                 {
 3376                          2528                 :              1 :                     int64       i = varg->u.ival;
                               2529                 :                : 
 3449                          2530                 :              1 :                     setIntValue(retval, i < 0 ? -i : i);
                               2531                 :                :                 }
                               2532                 :                :                 else
                               2533                 :                :                 {
 3376                          2534                 :              1 :                     double      d = varg->u.dval;
                               2535                 :                : 
 3449                          2536         [ -  + ]:              1 :                     Assert(varg->type == PGBT_DOUBLE);
 3376                          2537         [ +  - ]:              1 :                     setDoubleValue(retval, d < 0.0 ? -d : d);
                               2538                 :                :                 }
                               2539                 :                : 
 3476                          2540                 :              2 :                 return true;
                               2541                 :                :             }
                               2542                 :                : 
                               2543                 :             84 :         case PGBENCH_DEBUG:
                               2544                 :                :             {
 3449                          2545                 :             84 :                 PgBenchValue *varg = &vargs[0];
                               2546                 :                : 
                               2547         [ -  + ]:             84 :                 Assert(nargs == 1);
                               2548                 :                : 
 3376                          2549                 :             84 :                 fprintf(stderr, "debug(script=%d,command=%d): ",
 3267 heikki.linnakangas@i     2550                 :             84 :                         st->use_file, st->command + 1);
                               2551                 :                : 
 2797 teodor@sigaev.ru         2552         [ +  + ]:             84 :                 if (varg->type == PGBT_NULL)
                               2553                 :              2 :                     fprintf(stderr, "null\n");
                               2554         [ +  + ]:             82 :                 else if (varg->type == PGBT_BOOLEAN)
                               2555         [ +  + ]:             19 :                     fprintf(stderr, "boolean %s\n", varg->u.bval ? "true" : "false");
                               2556         [ +  + ]:             63 :                 else if (varg->type == PGBT_INT)
 3376 rhaas@postgresql.org     2557                 :             47 :                     fprintf(stderr, "int " INT64_FORMAT "\n", varg->u.ival);
 2797 teodor@sigaev.ru         2558         [ +  - ]:             16 :                 else if (varg->type == PGBT_DOUBLE)
 3410 tgl@sss.pgh.pa.us        2559                 :             16 :                     fprintf(stderr, "double %.*g\n", DBL_DIG, varg->u.dval);
                               2560                 :                :                 else            /* internal error, unexpected type */
 2797 teodor@sigaev.ru         2561                 :UBC           0 :                     Assert(0);
                               2562                 :                : 
 3449 rhaas@postgresql.org     2563                 :CBC          84 :                 *retval = *varg;
                               2564                 :                : 
                               2565                 :             84 :                 return true;
                               2566                 :                :             }
                               2567                 :                : 
                               2568                 :                :             /* 1 double argument */
                               2569                 :              5 :         case PGBENCH_DOUBLE:
                               2570                 :                :         case PGBENCH_SQRT:
                               2571                 :                :         case PGBENCH_LN:
                               2572                 :                :         case PGBENCH_EXP:
                               2573                 :                :             {
                               2574                 :                :                 double      dval;
                               2575                 :                : 
 3476                          2576         [ -  + ]:              5 :                 Assert(nargs == 1);
                               2577                 :                : 
 3449                          2578         [ +  + ]:              5 :                 if (!coerceToDouble(&vargs[0], &dval))
                               2579                 :              1 :                     return false;
                               2580                 :                : 
                               2581         [ +  + ]:              4 :                 if (func == PGBENCH_SQRT)
                               2582                 :              1 :                     dval = sqrt(dval);
 2797 teodor@sigaev.ru         2583         [ +  + ]:              3 :                 else if (func == PGBENCH_LN)
                               2584                 :              1 :                     dval = log(dval);
                               2585         [ +  + ]:              2 :                 else if (func == PGBENCH_EXP)
                               2586                 :              1 :                     dval = exp(dval);
                               2587                 :                :                 /* else is cast: do nothing */
                               2588                 :                : 
 3449 rhaas@postgresql.org     2589                 :              4 :                 setDoubleValue(retval, dval);
                               2590                 :              4 :                 return true;
                               2591                 :                :             }
                               2592                 :                : 
                               2593                 :                :             /* 1 int argument */
                               2594                 :              2 :         case PGBENCH_INT:
                               2595                 :                :             {
                               2596                 :                :                 int64       ival;
                               2597                 :                : 
                               2598         [ -  + ]:              2 :                 Assert(nargs == 1);
                               2599                 :                : 
                               2600         [ +  + ]:              2 :                 if (!coerceToInt(&vargs[0], &ival))
                               2601                 :              1 :                     return false;
                               2602                 :                : 
                               2603                 :              1 :                 setIntValue(retval, ival);
 3476                          2604                 :              1 :                 return true;
                               2605                 :                :             }
                               2606                 :                : 
                               2607                 :                :             /* variable number of arguments */
 3411 tgl@sss.pgh.pa.us        2608                 :              4 :         case PGBENCH_LEAST:
                               2609                 :                :         case PGBENCH_GREATEST:
                               2610                 :                :             {
                               2611                 :                :                 bool        havedouble;
                               2612                 :                :                 int         i;
                               2613                 :                : 
                               2614         [ -  + ]:              4 :                 Assert(nargs >= 1);
                               2615                 :                : 
                               2616                 :                :                 /* need double result if any input is double */
                               2617                 :              4 :                 havedouble = false;
                               2618         [ +  + ]:             14 :                 for (i = 0; i < nargs; i++)
                               2619                 :                :                 {
                               2620         [ +  + ]:             12 :                     if (vargs[i].type == PGBT_DOUBLE)
                               2621                 :                :                     {
                               2622                 :              2 :                         havedouble = true;
                               2623                 :              2 :                         break;
                               2624                 :                :                     }
                               2625                 :                :                 }
                               2626         [ +  + ]:              4 :                 if (havedouble)
                               2627                 :                :                 {
                               2628                 :                :                     double      extremum;
                               2629                 :                : 
                               2630         [ -  + ]:              2 :                     if (!coerceToDouble(&vargs[0], &extremum))
 3449 rhaas@postgresql.org     2631                 :UBC           0 :                         return false;
 3411 tgl@sss.pgh.pa.us        2632         [ +  + ]:CBC           6 :                     for (i = 1; i < nargs; i++)
                               2633                 :                :                     {
                               2634                 :                :                         double      dval;
                               2635                 :                : 
                               2636         [ -  + ]:              4 :                         if (!coerceToDouble(&vargs[i], &dval))
 3411 tgl@sss.pgh.pa.us        2637                 :UBC           0 :                             return false;
 3411 tgl@sss.pgh.pa.us        2638         [ +  + ]:CBC           4 :                         if (func == PGBENCH_LEAST)
                               2639         [ +  - ]:              2 :                             extremum = Min(extremum, dval);
                               2640                 :                :                         else
                               2641         [ +  - ]:              2 :                             extremum = Max(extremum, dval);
                               2642                 :                :                     }
                               2643                 :              2 :                     setDoubleValue(retval, extremum);
                               2644                 :                :                 }
                               2645                 :                :                 else
                               2646                 :                :                 {
                               2647                 :                :                     int64       extremum;
                               2648                 :                : 
                               2649         [ -  + ]:              2 :                     if (!coerceToInt(&vargs[0], &extremum))
 3411 tgl@sss.pgh.pa.us        2650                 :UBC           0 :                         return false;
 3411 tgl@sss.pgh.pa.us        2651         [ +  + ]:CBC           8 :                     for (i = 1; i < nargs; i++)
                               2652                 :                :                     {
                               2653                 :                :                         int64       ival;
                               2654                 :                : 
                               2655         [ -  + ]:              6 :                         if (!coerceToInt(&vargs[i], &ival))
 3411 tgl@sss.pgh.pa.us        2656                 :UBC           0 :                             return false;
 3411 tgl@sss.pgh.pa.us        2657         [ +  + ]:CBC           6 :                         if (func == PGBENCH_LEAST)
                               2658                 :              3 :                             extremum = Min(extremum, ival);
                               2659                 :                :                         else
                               2660                 :              3 :                             extremum = Max(extremum, ival);
                               2661                 :                :                     }
                               2662                 :              2 :                     setIntValue(retval, extremum);
                               2663                 :                :                 }
 3476 rhaas@postgresql.org     2664                 :              4 :                 return true;
                               2665                 :                :             }
                               2666                 :                : 
                               2667                 :                :             /* random functions */
 3449                          2668                 :           1540 :         case PGBENCH_RANDOM:
                               2669                 :                :         case PGBENCH_RANDOM_EXPONENTIAL:
                               2670                 :                :         case PGBENCH_RANDOM_GAUSSIAN:
                               2671                 :                :         case PGBENCH_RANDOM_ZIPFIAN:
                               2672                 :                :             {
                               2673                 :                :                 int64       imin,
                               2674                 :                :                             imax,
                               2675                 :                :                             delta;
                               2676                 :                : 
 3376                          2677         [ -  + ]:           1540 :                 Assert(nargs >= 2);
                               2678                 :                : 
                               2679         [ +  + ]:           1540 :                 if (!coerceToInt(&vargs[0], &imin) ||
                               2680         [ -  + ]:           1539 :                     !coerceToInt(&vargs[1], &imax))
 3449                          2681                 :              1 :                     return false;
                               2682                 :                : 
                               2683                 :                :                 /* check random range */
 1531 tgl@sss.pgh.pa.us        2684         [ +  + ]:           1539 :                 if (unlikely(imin > imax))
                               2685                 :                :                 {
 2068 peter@eisentraut.org     2686                 :              1 :                     pg_log_error("empty range given to random");
 3376 rhaas@postgresql.org     2687                 :              1 :                     return false;
                               2688                 :                :                 }
 1531 tgl@sss.pgh.pa.us        2689   [ +  +  -  +  :           1538 :                 else if (unlikely(pg_sub_s64_overflow(imax, imin, &delta) ||
                                              +  + ]
                               2690                 :                :                                   pg_add_s64_overflow(delta, 1, &delta)))
                               2691                 :                :                 {
                               2692                 :                :                     /* prevent int overflows in random functions */
 2068 peter@eisentraut.org     2693                 :              1 :                     pg_log_error("random range is too large");
 3376 rhaas@postgresql.org     2694                 :              1 :                     return false;
                               2695                 :                :                 }
                               2696                 :                : 
                               2697         [ +  + ]:           1537 :                 if (func == PGBENCH_RANDOM)
                               2698                 :                :                 {
                               2699         [ -  + ]:           1524 :                     Assert(nargs == 2);
 2486 alvherre@alvh.no-ip.     2700                 :           1524 :                     setIntValue(retval, getrand(&st->cs_func_rs, imin, imax));
                               2701                 :                :                 }
                               2702                 :                :                 else            /* gaussian & exponential */
                               2703                 :                :                 {
                               2704                 :                :                     double      param;
                               2705                 :                : 
 3376 rhaas@postgresql.org     2706         [ -  + ]:             13 :                     Assert(nargs == 3);
                               2707                 :                : 
                               2708         [ -  + ]:             13 :                     if (!coerceToDouble(&vargs[2], &param))
 3449                          2709                 :              4 :                         return false;
                               2710                 :                : 
 3376                          2711         [ +  + ]:             13 :                     if (func == PGBENCH_RANDOM_GAUSSIAN)
                               2712                 :                :                     {
                               2713         [ +  + ]:              4 :                         if (param < MIN_GAUSSIAN_PARAM)
                               2714                 :                :                         {
 2068 peter@eisentraut.org     2715                 :              1 :                             pg_log_error("gaussian parameter must be at least %f (not %f)",
                               2716                 :                :                                          MIN_GAUSSIAN_PARAM, param);
 3376 rhaas@postgresql.org     2717                 :              1 :                             return false;
                               2718                 :                :                         }
                               2719                 :                : 
                               2720                 :              3 :                         setIntValue(retval,
                               2721                 :                :                                     getGaussianRand(&st->cs_func_rs,
                               2722                 :                :                                                     imin, imax, param));
                               2723                 :                :                     }
 2823 teodor@sigaev.ru         2724         [ +  + ]:              9 :                     else if (func == PGBENCH_RANDOM_ZIPFIAN)
                               2725                 :                :                     {
 2350 tgl@sss.pgh.pa.us        2726   [ +  +  +  + ]:              5 :                         if (param < MIN_ZIPFIAN_PARAM || param > MAX_ZIPFIAN_PARAM)
                               2727                 :                :                         {
 2068 peter@eisentraut.org     2728                 :              2 :                             pg_log_error("zipfian parameter must be in range [%.3f, %.0f] (not %f)",
                               2729                 :                :                                          MIN_ZIPFIAN_PARAM, MAX_ZIPFIAN_PARAM, param);
 2823 teodor@sigaev.ru         2730                 :              2 :                             return false;
                               2731                 :                :                         }
                               2732                 :                : 
                               2733                 :              3 :                         setIntValue(retval,
                               2734                 :                :                                     getZipfianRand(&st->cs_func_rs, imin, imax, param));
                               2735                 :                :                     }
                               2736                 :                :                     else        /* exponential */
                               2737                 :                :                     {
 3376 rhaas@postgresql.org     2738         [ +  + ]:              4 :                         if (param <= 0.0)
                               2739                 :                :                         {
 2068 peter@eisentraut.org     2740                 :              1 :                             pg_log_error("exponential parameter must be greater than zero (not %f)",
                               2741                 :                :                                          param);
 3376 rhaas@postgresql.org     2742                 :              1 :                             return false;
                               2743                 :                :                         }
                               2744                 :                : 
                               2745                 :              3 :                         setIntValue(retval,
                               2746                 :                :                                     getExponentialRand(&st->cs_func_rs,
                               2747                 :                :                                                        imin, imax, param));
                               2748                 :                :                     }
                               2749                 :                :                 }
                               2750                 :                : 
                               2751                 :           1533 :                 return true;
                               2752                 :                :             }
                               2753                 :                : 
 2810                          2754                 :              9 :         case PGBENCH_POW:
                               2755                 :                :             {
                               2756                 :              9 :                 PgBenchValue *lval = &vargs[0];
                               2757                 :              9 :                 PgBenchValue *rval = &vargs[1];
                               2758                 :                :                 double      ld,
                               2759                 :                :                             rd;
                               2760                 :                : 
                               2761         [ -  + ]:              9 :                 Assert(nargs == 2);
                               2762                 :                : 
                               2763         [ +  - ]:              9 :                 if (!coerceToDouble(lval, &ld) ||
                               2764         [ -  + ]:              9 :                     !coerceToDouble(rval, &rd))
 2810 rhaas@postgresql.org     2765                 :UBC           0 :                     return false;
                               2766                 :                : 
 2810 rhaas@postgresql.org     2767                 :CBC           9 :                 setDoubleValue(retval, pow(ld, rd));
                               2768                 :                : 
                               2769                 :              9 :                 return true;
                               2770                 :                :             }
                               2771                 :                : 
 2797 teodor@sigaev.ru         2772                 :             10 :         case PGBENCH_IS:
                               2773                 :                :             {
                               2774         [ -  + ]:             10 :                 Assert(nargs == 2);
                               2775                 :                : 
                               2776                 :                :                 /*
                               2777                 :                :                  * note: this simple implementation is more permissive than
                               2778                 :                :                  * SQL
                               2779                 :                :                  */
                               2780                 :             10 :                 setBoolValue(retval,
                               2781         [ +  + ]:             15 :                              vargs[0].type == vargs[1].type &&
                               2782         [ +  - ]:              5 :                              vargs[0].u.bval == vargs[1].u.bval);
                               2783                 :             10 :                 return true;
                               2784                 :                :             }
                               2785                 :                : 
                               2786                 :                :             /* hashing */
 2726                          2787                 :              6 :         case PGBENCH_HASH_FNV1A:
                               2788                 :                :         case PGBENCH_HASH_MURMUR2:
                               2789                 :                :             {
                               2790                 :                :                 int64       val,
                               2791                 :                :                             seed;
                               2792                 :                : 
                               2793         [ -  + ]:              6 :                 Assert(nargs == 2);
                               2794                 :                : 
                               2795         [ +  - ]:              6 :                 if (!coerceToInt(&vargs[0], &val) ||
                               2796         [ -  + ]:              6 :                     !coerceToInt(&vargs[1], &seed))
 2726 teodor@sigaev.ru         2797                 :UBC           0 :                     return false;
                               2798                 :                : 
 2726 teodor@sigaev.ru         2799         [ +  + ]:CBC           6 :                 if (func == PGBENCH_HASH_MURMUR2)
                               2800                 :              5 :                     setIntValue(retval, getHashMurmur2(val, seed));
                               2801         [ +  - ]:              1 :                 else if (func == PGBENCH_HASH_FNV1A)
                               2802                 :              1 :                     setIntValue(retval, getHashFnv1a(val, seed));
                               2803                 :                :                 else
                               2804                 :                :                     /* cannot get here */
 2726 teodor@sigaev.ru         2805                 :UBC           0 :                     Assert(0);
                               2806                 :                : 
 2726 teodor@sigaev.ru         2807                 :CBC           6 :                 return true;
                               2808                 :                :             }
                               2809                 :                : 
 1614 dean.a.rasheed@gmail     2810                 :             46 :         case PGBENCH_PERMUTE:
                               2811                 :                :             {
                               2812                 :                :                 int64       val,
                               2813                 :                :                             size,
                               2814                 :                :                             seed;
                               2815                 :                : 
                               2816         [ -  + ]:             46 :                 Assert(nargs == 3);
                               2817                 :                : 
                               2818         [ +  - ]:             46 :                 if (!coerceToInt(&vargs[0], &val) ||
                               2819         [ +  - ]:             46 :                     !coerceToInt(&vargs[1], &size) ||
                               2820         [ -  + ]:             46 :                     !coerceToInt(&vargs[2], &seed))
 1614 dean.a.rasheed@gmail     2821                 :UBC           0 :                     return false;
                               2822                 :                : 
 1614 dean.a.rasheed@gmail     2823         [ +  + ]:CBC          46 :                 if (size <= 0)
                               2824                 :                :                 {
                               2825                 :              1 :                     pg_log_error("permute size parameter must be greater than zero");
                               2826                 :              1 :                     return false;
                               2827                 :                :                 }
                               2828                 :                : 
                               2829                 :             45 :                 setIntValue(retval, permute(val, size, seed));
                               2830                 :             45 :                 return true;
                               2831                 :                :             }
                               2832                 :                : 
 3476 rhaas@postgresql.org     2833                 :UBC           0 :         default:
                               2834                 :                :             /* cannot get here */
 3449                          2835                 :              0 :             Assert(0);
                               2836                 :                :             /* dead code to avoid a compiler warning */
                               2837                 :                :             return false;
                               2838                 :                :     }
                               2839                 :                : }
                               2840                 :                : 
                               2841                 :                : /* evaluate some function */
                               2842                 :                : static bool
 2348 tgl@sss.pgh.pa.us        2843                 :CBC        3510 : evalFunc(CState *st,
                               2844                 :                :          PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
                               2845                 :                : {
 2797 teodor@sigaev.ru         2846         [ +  + ]:           3510 :     if (isLazyFunc(func))
 2348 tgl@sss.pgh.pa.us        2847                 :             63 :         return evalLazyFunc(st, func, args, retval);
                               2848                 :                :     else
                               2849                 :           3447 :         return evalStandardFunc(st, func, args, retval);
                               2850                 :                : }
                               2851                 :                : 
                               2852                 :                : /*
                               2853                 :                :  * Recursive evaluation of an expression in a pgbench script
                               2854                 :                :  * using the current state of variables.
                               2855                 :                :  * Returns whether the evaluation was ok,
                               2856                 :                :  * the value itself is returned through the retval pointer.
                               2857                 :                :  */
                               2858                 :                : static bool
                               2859                 :           9224 : evaluateExpr(CState *st, PgBenchExpr *expr, PgBenchValue *retval)
                               2860                 :                : {
 3476 rhaas@postgresql.org     2861   [ +  +  +  - ]:           9224 :     switch (expr->etype)
                               2862                 :                :     {
 3449                          2863                 :           3681 :         case ENODE_CONSTANT:
                               2864                 :                :             {
                               2865                 :           3681 :                 *retval = expr->u.constant;
 3476                          2866                 :           3681 :                 return true;
                               2867                 :                :             }
                               2868                 :                : 
                               2869                 :           2033 :         case ENODE_VARIABLE:
                               2870                 :                :             {
                               2871                 :                :                 Variable   *var;
                               2872                 :                : 
 1263 ishii@postgresql.org     2873         [ +  + ]:           2033 :                 if ((var = lookupVariable(&st->variables, expr->u.variable.varname)) == NULL)
                               2874                 :                :                 {
 2068 peter@eisentraut.org     2875                 :              2 :                     pg_log_error("undefined variable \"%s\"", expr->u.variable.varname);
 3476 rhaas@postgresql.org     2876                 :              2 :                     return false;
                               2877                 :                :                 }
                               2878                 :                : 
 2797 teodor@sigaev.ru         2879         [ +  + ]:           2031 :                 if (!makeVariableValue(var))
 3410 tgl@sss.pgh.pa.us        2880                 :              2 :                     return false;
                               2881                 :                : 
 2797 teodor@sigaev.ru         2882                 :           2029 :                 *retval = var->value;
 3476 rhaas@postgresql.org     2883                 :           2029 :                 return true;
                               2884                 :                :             }
                               2885                 :                : 
                               2886                 :           3510 :         case ENODE_FUNCTION:
 2348 tgl@sss.pgh.pa.us        2887                 :           3510 :             return evalFunc(st,
                               2888                 :                :                             expr->u.function.function,
                               2889                 :                :                             expr->u.function.args,
                               2890                 :                :                             retval);
                               2891                 :                : 
 3841 rhaas@postgresql.org     2892                 :UBC           0 :         default:
                               2893                 :                :             /* internal error which should never occur */
 1247 tgl@sss.pgh.pa.us        2894                 :              0 :             pg_fatal("unexpected enode type in evaluation: %d", expr->etype);
                               2895                 :                :     }
                               2896                 :                : }
                               2897                 :                : 
                               2898                 :                : /*
                               2899                 :                :  * Convert command name to meta-command enum identifier
                               2900                 :                :  */
                               2901                 :                : static MetaCommand
 2865 tgl@sss.pgh.pa.us        2902                 :CBC         532 : getMetaCommand(const char *cmd)
                               2903                 :                : {
                               2904                 :                :     MetaCommand mc;
                               2905                 :                : 
                               2906         [ -  + ]:            532 :     if (cmd == NULL)
 2865 tgl@sss.pgh.pa.us        2907                 :UBC           0 :         mc = META_NONE;
 2865 tgl@sss.pgh.pa.us        2908         [ +  + ]:CBC         532 :     else if (pg_strcasecmp(cmd, "set") == 0)
                               2909                 :            363 :         mc = META_SET;
                               2910         [ +  + ]:            169 :     else if (pg_strcasecmp(cmd, "setshell") == 0)
                               2911                 :              4 :         mc = META_SETSHELL;
                               2912         [ +  + ]:            165 :     else if (pg_strcasecmp(cmd, "shell") == 0)
                               2913                 :              5 :         mc = META_SHELL;
                               2914         [ +  + ]:            160 :     else if (pg_strcasecmp(cmd, "sleep") == 0)
                               2915                 :              9 :         mc = META_SLEEP;
 2725 teodor@sigaev.ru         2916         [ +  + ]:            151 :     else if (pg_strcasecmp(cmd, "if") == 0)
                               2917                 :             24 :         mc = META_IF;
                               2918         [ +  + ]:            127 :     else if (pg_strcasecmp(cmd, "elif") == 0)
                               2919                 :             13 :         mc = META_ELIF;
                               2920         [ +  + ]:            114 :     else if (pg_strcasecmp(cmd, "else") == 0)
                               2921                 :             14 :         mc = META_ELSE;
                               2922         [ +  + ]:            100 :     else if (pg_strcasecmp(cmd, "endif") == 0)
                               2923                 :             21 :         mc = META_ENDIF;
 2431 alvherre@alvh.no-ip.     2924         [ +  + ]:             79 :     else if (pg_strcasecmp(cmd, "gset") == 0)
                               2925                 :             32 :         mc = META_GSET;
 1982 michael@paquier.xyz      2926         [ +  + ]:             47 :     else if (pg_strcasecmp(cmd, "aset") == 0)
                               2927                 :              3 :         mc = META_ASET;
 1636 alvherre@alvh.no-ip.     2928         [ +  + ]:             44 :     else if (pg_strcasecmp(cmd, "startpipeline") == 0)
                               2929                 :             21 :         mc = META_STARTPIPELINE;
  591 michael@paquier.xyz      2930         [ +  + ]:             23 :     else if (pg_strcasecmp(cmd, "syncpipeline") == 0)
                               2931                 :              5 :         mc = META_SYNCPIPELINE;
 1636 alvherre@alvh.no-ip.     2932         [ +  + ]:             18 :     else if (pg_strcasecmp(cmd, "endpipeline") == 0)
                               2933                 :             17 :         mc = META_ENDPIPELINE;
                               2934                 :                :     else
 2865 tgl@sss.pgh.pa.us        2935                 :              1 :         mc = META_NONE;
                               2936                 :            532 :     return mc;
                               2937                 :                : }
                               2938                 :                : 
                               2939                 :                : /*
                               2940                 :                :  * Run a shell command. The result is assigned to the variable if not NULL.
                               2941                 :                :  * Return true if succeeded, or false on error.
                               2942                 :                :  */
                               2943                 :                : static bool
 1263 ishii@postgresql.org     2944                 :              6 : runShellCommand(Variables *variables, char *variable, char **argv, int argc)
                               2945                 :                : {
                               2946                 :                :     char        command[SHELL_COMMAND_SIZE];
                               2947                 :                :     int         i,
 5671 bruce@momjian.us         2948                 :              6 :                 len = 0;
                               2949                 :                :     FILE       *fp;
                               2950                 :                :     char        res[64];
                               2951                 :                :     char       *endptr;
                               2952                 :                :     int         retval;
                               2953                 :                : 
                               2954                 :                :     /*----------
                               2955                 :                :      * Join arguments with whitespace separators. Arguments starting with
                               2956                 :                :      * exactly one colon are treated as variables:
                               2957                 :                :      *  name - append a string "name"
                               2958                 :                :      *  :var - append a variable named 'var'
                               2959                 :                :      *  ::name - append a string ":name"
                               2960                 :                :      *----------
                               2961                 :                :      */
 5744 itagaki.takahiro@gma     2962         [ +  + ]:             17 :     for (i = 0; i < argc; i++)
                               2963                 :                :     {
                               2964                 :                :         char       *arg;
                               2965                 :                :         int         arglen;
                               2966                 :                : 
                               2967         [ +  + ]:             12 :         if (argv[i][0] != ':')
                               2968                 :                :         {
 5671 bruce@momjian.us         2969                 :              9 :             arg = argv[i];      /* a string literal */
                               2970                 :                :         }
 5744 itagaki.takahiro@gma     2971         [ +  + ]:              3 :         else if (argv[i][1] == ':')
                               2972                 :                :         {
                               2973                 :              1 :             arg = argv[i] + 1;  /* a string literal starting with colons */
                               2974                 :                :         }
 1263 ishii@postgresql.org     2975         [ +  + ]:              2 :         else if ((arg = getVariable(variables, argv[i] + 1)) == NULL)
                               2976                 :                :         {
 2068 peter@eisentraut.org     2977                 :              1 :             pg_log_error("%s: undefined variable \"%s\"", argv[0], argv[i]);
 5744 itagaki.takahiro@gma     2978                 :              1 :             return false;
                               2979                 :                :         }
                               2980                 :                : 
                               2981                 :             11 :         arglen = strlen(arg);
                               2982         [ -  + ]:             11 :         if (len + arglen + (i > 0 ? 1 : 0) >= SHELL_COMMAND_SIZE - 1)
                               2983                 :                :         {
 2068 peter@eisentraut.org     2984                 :UBC           0 :             pg_log_error("%s: shell command is too long", argv[0]);
 5744 itagaki.takahiro@gma     2985                 :              0 :             return false;
                               2986                 :                :         }
                               2987                 :                : 
 5744 itagaki.takahiro@gma     2988         [ +  + ]:CBC          11 :         if (i > 0)
                               2989                 :              5 :             command[len++] = ' ';
                               2990                 :             11 :         memcpy(command + len, arg, arglen);
                               2991                 :             11 :         len += arglen;
                               2992                 :                :     }
                               2993                 :                : 
                               2994                 :              5 :     command[len] = '\0';
                               2995                 :                : 
 1104 tgl@sss.pgh.pa.us        2996                 :              5 :     fflush(NULL);               /* needed before either system() or popen() */
                               2997                 :                : 
                               2998                 :                :     /* Fast path for non-assignment case */
 5744 itagaki.takahiro@gma     2999         [ +  + ]:              5 :     if (variable == NULL)
                               3000                 :                :     {
                               3001         [ +  + ]:              2 :         if (system(command))
                               3002                 :                :         {
                               3003         [ +  - ]:              1 :             if (!timer_exceeded)
 2068 peter@eisentraut.org     3004                 :              1 :                 pg_log_error("%s: could not launch shell command", argv[0]);
 5744 itagaki.takahiro@gma     3005                 :              1 :             return false;
                               3006                 :                :         }
                               3007                 :              1 :         return true;
                               3008                 :                :     }
                               3009                 :                : 
                               3010                 :                :     /* Execute the command with pipe and read the standard output. */
                               3011         [ -  + ]:              3 :     if ((fp = popen(command, "r")) == NULL)
                               3012                 :                :     {
 2068 peter@eisentraut.org     3013                 :UBC           0 :         pg_log_error("%s: could not launch shell command", argv[0]);
 5744 itagaki.takahiro@gma     3014                 :              0 :         return false;
                               3015                 :                :     }
 5744 itagaki.takahiro@gma     3016         [ +  + ]:CBC           3 :     if (fgets(res, sizeof(res), fp) == NULL)
                               3017                 :                :     {
                               3018         [ +  - ]:              1 :         if (!timer_exceeded)
 2068 peter@eisentraut.org     3019                 :              1 :             pg_log_error("%s: could not read result of shell command", argv[0]);
 3917 tgl@sss.pgh.pa.us        3020                 :              1 :         (void) pclose(fp);
 5744 itagaki.takahiro@gma     3021                 :              1 :         return false;
                               3022                 :                :     }
                               3023         [ -  + ]:              2 :     if (pclose(fp) < 0)
                               3024                 :                :     {
 1026 peter@eisentraut.org     3025                 :UBC           0 :         pg_log_error("%s: could not run shell command: %m", argv[0]);
 5744 itagaki.takahiro@gma     3026                 :              0 :         return false;
                               3027                 :                :     }
                               3028                 :                : 
                               3029                 :                :     /* Check whether the result is an integer and assign it to the variable */
 5744 itagaki.takahiro@gma     3030                 :CBC           2 :     retval = (int) strtol(res, &endptr, 10);
                               3031   [ +  +  +  + ]:              3 :     while (*endptr != '\0' && isspace((unsigned char) *endptr))
                               3032                 :              1 :         endptr++;
                               3033   [ +  -  +  + ]:              2 :     if (*res == '\0' || *endptr != '\0')
                               3034                 :                :     {
 2068 peter@eisentraut.org     3035                 :              1 :         pg_log_error("%s: shell command must return an integer (not \"%s\")", argv[0], res);
 5744 itagaki.takahiro@gma     3036                 :              1 :         return false;
                               3037                 :                :     }
 1263 ishii@postgresql.org     3038         [ -  + ]:              1 :     if (!putVariableInt(variables, "setshell", variable, retval))
 5744 itagaki.takahiro@gma     3039                 :UBC           0 :         return false;
                               3040                 :                : 
 2068 peter@eisentraut.org     3041         [ -  + ]:CBC           1 :     pg_log_debug("%s: shell parameter name: \"%s\", value: \"%s\"", argv[0], argv[1], res);
                               3042                 :                : 
 5744 itagaki.takahiro@gma     3043                 :              1 :     return true;
                               3044                 :                : }
                               3045                 :                : 
                               3046                 :                : /*
                               3047                 :                :  * Report the abortion of the client when processing SQL commands.
                               3048                 :                :  */
                               3049                 :                : static void
 2725 teodor@sigaev.ru         3050                 :             32 : commandFailed(CState *st, const char *cmd, const char *message)
                               3051                 :                : {
 2068 peter@eisentraut.org     3052                 :             32 :     pg_log_error("client %d aborted in command %d (%s) of script %d; %s",
                               3053                 :                :                  st->id, st->command, cmd, st->use_file, message);
 5878 ishii@postgresql.org     3054                 :             32 : }
                               3055                 :                : 
                               3056                 :                : /*
                               3057                 :                :  * Report the error in the command while the script is executing.
                               3058                 :                :  */
                               3059                 :                : static void
 1263                          3060                 :              2 : commandError(CState *st, const char *message)
                               3061                 :                : {
                               3062         [ -  + ]:              2 :     Assert(sql_script[st->use_file].commands[st->command]->type == SQL_COMMAND);
                               3063                 :              2 :     pg_log_info("client %d got an error in command %d (SQL) of script %d; %s",
                               3064                 :                :                 st->id, st->command, st->use_file, message);
                               3065                 :              2 : }
                               3066                 :                : 
                               3067                 :                : /* return a script number with a weighted choice. */
                               3068                 :                : static int
 3510 alvherre@alvh.no-ip.     3069                 :           7744 : chooseScript(TState *thread)
                               3070                 :                : {
 3458                          3071                 :           7744 :     int         i = 0;
                               3072                 :                :     int64       w;
                               3073                 :                : 
 3510                          3074         [ +  + ]:           7744 :     if (num_scripts == 1)
                               3075                 :           6394 :         return 0;
                               3076                 :                : 
 2486                          3077                 :           1350 :     w = getrand(&thread->ts_choose_rs, 0, total_weight - 1);
                               3078                 :                :     do
                               3079                 :                :     {
 3458                          3080                 :           3178 :         w -= sql_script[i++].weight;
                               3081         [ +  + ]:           3178 :     } while (w >= 0);
                               3082                 :                : 
                               3083                 :           1350 :     return i - 1;
                               3084                 :                : }
                               3085                 :                : 
                               3086                 :                : /*
                               3087                 :                :  * Allocate space for CState->prepared: we need one boolean for each command
                               3088                 :                :  * of each script.
                               3089                 :                :  */
                               3090                 :                : static void
  835                          3091                 :             34 : allocCStatePrepared(CState *st)
                               3092                 :                : {
                               3093         [ -  + ]:             34 :     Assert(st->prepared == NULL);
                               3094                 :                : 
                               3095                 :             34 :     st->prepared = pg_malloc(sizeof(bool *) * num_scripts);
                               3096         [ +  + ]:             74 :     for (int i = 0; i < num_scripts; i++)
                               3097                 :                :     {
                               3098                 :             40 :         ParsedScript *script = &sql_script[i];
                               3099                 :                :         int         numcmds;
                               3100                 :                : 
                               3101         [ +  + ]:            170 :         for (numcmds = 0; script->commands[numcmds] != NULL; numcmds++)
                               3102                 :                :             ;
                               3103                 :             40 :         st->prepared[i] = pg_malloc0(sizeof(bool) * numcmds);
                               3104                 :                :     }
                               3105                 :             34 : }
                               3106                 :                : 
                               3107                 :                : /*
                               3108                 :                :  * Prepare the SQL command from st->use_file at command_num.
                               3109                 :                :  */
                               3110                 :                : static void
  928                          3111                 :           1996 : prepareCommand(CState *st, int command_num)
                               3112                 :                : {
                               3113                 :           1996 :     Command    *command = sql_script[st->use_file].commands[command_num];
                               3114                 :                : 
                               3115                 :                :     /* No prepare for non-SQL commands */
                               3116         [ -  + ]:           1996 :     if (command->type != SQL_COMMAND)
  928 alvherre@alvh.no-ip.     3117                 :UBC           0 :         return;
                               3118                 :                : 
  928 alvherre@alvh.no-ip.     3119         [ +  + ]:CBC        1996 :     if (!st->prepared)
  835                          3120                 :             29 :         allocCStatePrepared(st);
                               3121                 :                : 
  928                          3122         [ +  + ]:           1996 :     if (!st->prepared[st->use_file][command_num])
                               3123                 :                :     {
                               3124                 :                :         PGresult   *res;
                               3125                 :                : 
                               3126         [ +  + ]:            109 :         pg_log_debug("client %d preparing %s", st->id, command->prepname);
                               3127                 :            109 :         res = PQprepare(st->con, command->prepname,
                               3128                 :            109 :                         command->argv[0], command->argc - 1, NULL);
                               3129         [ +  + ]:            109 :         if (PQresultStatus(res) != PGRES_COMMAND_OK)
                               3130                 :              1 :             pg_log_error("%s", PQerrorMessage(st->con));
                               3131                 :            109 :         PQclear(res);
                               3132                 :            109 :         st->prepared[st->use_file][command_num] = true;
                               3133                 :                :     }
                               3134                 :                : }
                               3135                 :                : 
                               3136                 :                : /*
                               3137                 :                :  * Prepare all the commands in the script that come after the \startpipeline
                               3138                 :                :  * that's at position st->command, and the first \endpipeline we find.
                               3139                 :                :  *
                               3140                 :                :  * This sets the ->prepared flag for each relevant command as well as the
                               3141                 :                :  * \startpipeline itself, but doesn't move the st->command counter.
                               3142                 :                :  */
                               3143                 :                : static void
                               3144                 :             42 : prepareCommandsInPipeline(CState *st)
                               3145                 :                : {
                               3146                 :                :     int         j;
                               3147                 :             42 :     Command   **commands = sql_script[st->use_file].commands;
                               3148                 :                : 
                               3149   [ +  -  +  - ]:             42 :     Assert(commands[st->command]->type == META_COMMAND &&
                               3150                 :                :            commands[st->command]->meta == META_STARTPIPELINE);
                               3151                 :                : 
  835                          3152         [ +  + ]:             42 :     if (!st->prepared)
                               3153                 :              5 :         allocCStatePrepared(st);
                               3154                 :                : 
                               3155                 :                :     /*
                               3156                 :                :      * We set the 'prepared' flag on the \startpipeline itself to flag that we
                               3157                 :                :      * don't need to do this next time without calling prepareCommand(), even
                               3158                 :                :      * though we don't actually prepare this command.
                               3159                 :                :      */
                               3160         [ +  + ]:             42 :     if (st->prepared[st->use_file][st->command])
  928                          3161                 :             36 :         return;
                               3162                 :                : 
                               3163         [ +  - ]:             64 :     for (j = st->command + 1; commands[j] != NULL; j++)
                               3164                 :                :     {
                               3165         [ +  + ]:             64 :         if (commands[j]->type == META_COMMAND &&
                               3166         [ +  - ]:              6 :             commands[j]->meta == META_ENDPIPELINE)
                               3167                 :              6 :             break;
                               3168                 :                : 
                               3169                 :             58 :         prepareCommand(st, j);
                               3170                 :                :     }
                               3171                 :                : 
                               3172                 :              6 :     st->prepared[st->use_file][st->command] = true;
                               3173                 :                : }
                               3174                 :                : 
                               3175                 :                : /* Send a SQL command, using the chosen querymode */
                               3176                 :                : static bool
 3267 heikki.linnakangas@i     3177                 :          10523 : sendCommand(CState *st, Command *command)
                               3178                 :                : {
                               3179                 :                :     int         r;
                               3180                 :                : 
                               3181         [ +  + ]:          10523 :     if (querymode == QUERY_SIMPLE)
                               3182                 :                :     {
                               3183                 :                :         char       *sql;
                               3184                 :                : 
                               3185                 :           7992 :         sql = pg_strdup(command->argv[0]);
 1263 ishii@postgresql.org     3186                 :           7992 :         sql = assignVariables(&st->variables, sql);
                               3187                 :                : 
 2068 peter@eisentraut.org     3188         [ +  + ]:           7992 :         pg_log_debug("client %d sending %s", st->id, sql);
 3267 heikki.linnakangas@i     3189                 :           7992 :         r = PQsendQuery(st->con, sql);
                               3190                 :           7992 :         free(sql);
                               3191                 :                :     }
                               3192         [ +  + ]:           2531 :     else if (querymode == QUERY_EXTENDED)
                               3193                 :                :     {
                               3194                 :            593 :         const char *sql = command->argv[0];
                               3195                 :                :         const char *params[MAX_ARGS];
                               3196                 :                : 
 1263 ishii@postgresql.org     3197                 :            593 :         getQueryParams(&st->variables, command, params);
                               3198                 :                : 
 2068 peter@eisentraut.org     3199         [ -  + ]:            593 :         pg_log_debug("client %d sending %s", st->id, sql);
 3267 heikki.linnakangas@i     3200                 :            593 :         r = PQsendQueryParams(st->con, sql, command->argc - 1,
                               3201                 :                :                               NULL, params, NULL, NULL, 0);
                               3202                 :                :     }
                               3203         [ +  - ]:           1938 :     else if (querymode == QUERY_PREPARED)
                               3204                 :                :     {
                               3205                 :                :         const char *params[MAX_ARGS];
                               3206                 :                : 
  928 alvherre@alvh.no-ip.     3207                 :           1938 :         prepareCommand(st, st->command);
 1263 ishii@postgresql.org     3208                 :           1938 :         getQueryParams(&st->variables, command, params);
                               3209                 :                : 
  928 alvherre@alvh.no-ip.     3210         [ +  + ]:           1938 :         pg_log_debug("client %d sending %s", st->id, command->prepname);
                               3211                 :           1938 :         r = PQsendQueryPrepared(st->con, command->prepname, command->argc - 1,
                               3212                 :                :                                 params, NULL, NULL, 0);
                               3213                 :                :     }
                               3214                 :                :     else                        /* unknown sql mode */
 3267 heikki.linnakangas@i     3215                 :UBC           0 :         r = 0;
                               3216                 :                : 
 3267 heikki.linnakangas@i     3217         [ -  + ]:CBC       10523 :     if (r == 0)
                               3218                 :                :     {
 2068 peter@eisentraut.org     3219         [ #  # ]:UBC           0 :         pg_log_debug("client %d could not send %s", st->id, command->argv[0]);
 3267 heikki.linnakangas@i     3220                 :              0 :         return false;
                               3221                 :                :     }
                               3222                 :                :     else
 3267 heikki.linnakangas@i     3223                 :CBC       10523 :         return true;
                               3224                 :                : }
                               3225                 :                : 
                               3226                 :                : /*
                               3227                 :                :  * Get the error status from the error code.
                               3228                 :                :  */
                               3229                 :                : static EStatus
 1263 ishii@postgresql.org     3230                 :             13 : getSQLErrorStatus(const char *sqlState)
                               3231                 :                : {
                               3232         [ +  - ]:             13 :     if (sqlState != NULL)
                               3233                 :                :     {
                               3234         [ +  + ]:             13 :         if (strcmp(sqlState, ERRCODE_T_R_SERIALIZATION_FAILURE) == 0)
                               3235                 :              1 :             return ESTATUS_SERIALIZATION_ERROR;
                               3236         [ +  + ]:             12 :         else if (strcmp(sqlState, ERRCODE_T_R_DEADLOCK_DETECTED) == 0)
                               3237                 :              1 :             return ESTATUS_DEADLOCK_ERROR;
                               3238                 :                :     }
                               3239                 :                : 
                               3240                 :             11 :     return ESTATUS_OTHER_SQL_ERROR;
                               3241                 :                : }
                               3242                 :                : 
                               3243                 :                : /*
                               3244                 :                :  * Returns true if this type of error can be retried.
                               3245                 :                :  */
                               3246                 :                : static bool
                               3247                 :             33 : canRetryError(EStatus estatus)
                               3248                 :                : {
                               3249   [ +  +  +  + ]:             33 :     return (estatus == ESTATUS_SERIALIZATION_ERROR ||
                               3250                 :                :             estatus == ESTATUS_DEADLOCK_ERROR);
                               3251                 :                : }
                               3252                 :                : 
                               3253                 :                : /*
                               3254                 :                :  * Process query response from the backend.
                               3255                 :                :  *
                               3256                 :                :  * If varprefix is not NULL, it's the variable name prefix where to store
                               3257                 :                :  * the results of the *last* command (META_GSET) or *all* commands
                               3258                 :                :  * (META_ASET).
                               3259                 :                :  *
                               3260                 :                :  * Returns true if everything is A-OK, false if any error occurs.
                               3261                 :                :  */
                               3262                 :                : static bool
 1982 michael@paquier.xyz      3263                 :          10568 : readCommandResponse(CState *st, MetaCommand meta, char *varprefix)
                               3264                 :                : {
                               3265                 :                :     PGresult   *res;
                               3266                 :                :     PGresult   *next_res;
 2431 alvherre@alvh.no-ip.     3267                 :          10568 :     int         qrynum = 0;
                               3268                 :                : 
                               3269                 :                :     /*
                               3270                 :                :      * varprefix should be set only with \gset or \aset, and \endpipeline and
                               3271                 :                :      * SQL commands do not need it.
                               3272                 :                :      */
 1982 michael@paquier.xyz      3273   [ +  +  +  -  :          10568 :     Assert((meta == META_NONE && varprefix == NULL) ||
                                     +  +  +  -  +  
                                        +  +  -  +  
                                                 - ]
                               3274                 :                :            ((meta == META_ENDPIPELINE) && varprefix == NULL) ||
                               3275                 :                :            ((meta == META_GSET || meta == META_ASET) && varprefix != NULL));
                               3276                 :                : 
 2357 alvherre@alvh.no-ip.     3277                 :          10568 :     res = PQgetResult(st->con);
                               3278                 :                : 
                               3279         [ +  + ]:          21124 :     while (res != NULL)
                               3280                 :                :     {
                               3281                 :                :         bool        is_last;
                               3282                 :                : 
                               3283                 :                :         /* peek at the next result to know whether the current is last */
 2342                          3284                 :          10574 :         next_res = PQgetResult(st->con);
 2341                          3285                 :          10574 :         is_last = (next_res == NULL);
                               3286                 :                : 
 2431                          3287   [ +  +  +  +  :          10574 :         switch (PQresultStatus(res))
                                                 - ]
                               3288                 :                :         {
                               3289                 :           8203 :             case PGRES_COMMAND_OK:  /* non-SELECT commands */
                               3290                 :                :             case PGRES_EMPTY_QUERY: /* may be used for testing no-op overhead */
 1982 michael@paquier.xyz      3291   [ +  -  +  + ]:           8203 :                 if (is_last && meta == META_GSET)
                               3292                 :                :                 {
 2068 peter@eisentraut.org     3293                 :              1 :                     pg_log_error("client %d script %d command %d query %d: expected one row, got %d",
                               3294                 :                :                                  st->id, st->use_file, st->command, qrynum, 0);
 1263 ishii@postgresql.org     3295                 :              1 :                     st->estatus = ESTATUS_META_COMMAND_ERROR;
 2342 alvherre@alvh.no-ip.     3296                 :              1 :                     goto error;
                               3297                 :                :                 }
 2431                          3298                 :           8202 :                 break;
                               3299                 :                : 
                               3300                 :           2304 :             case PGRES_TUPLES_OK:
 1982 michael@paquier.xyz      3301   [ +  +  +  +  :           2304 :                 if ((is_last && meta == META_GSET) || meta == META_ASET)
                                              +  + ]
                               3302                 :                :                 {
                               3303                 :            540 :                     int         ntuples = PQntuples(res);
                               3304                 :                : 
                               3305   [ +  +  +  + ]:            540 :                     if (meta == META_GSET && ntuples != 1)
                               3306                 :                :                     {
                               3307                 :                :                         /* under \gset, report the error */
 2068 peter@eisentraut.org     3308                 :              2 :                         pg_log_error("client %d script %d command %d query %d: expected one row, got %d",
                               3309                 :                :                                      st->id, st->use_file, st->command, qrynum, PQntuples(res));
 1263 ishii@postgresql.org     3310                 :              2 :                         st->estatus = ESTATUS_META_COMMAND_ERROR;
 2342 alvherre@alvh.no-ip.     3311                 :              2 :                         goto error;
                               3312                 :                :                     }
 1982 michael@paquier.xyz      3313   [ +  +  +  + ]:            538 :                     else if (meta == META_ASET && ntuples <= 0)
                               3314                 :                :                     {
                               3315                 :                :                         /* coldly skip empty result under \aset */
                               3316                 :              1 :                         break;
                               3317                 :                :                     }
                               3318                 :                : 
                               3319                 :                :                     /* store results into variables */
 2431 alvherre@alvh.no-ip.     3320         [ +  + ]:           1074 :                     for (int fld = 0; fld < PQnfields(res); fld++)
                               3321                 :                :                     {
                               3322                 :            539 :                         char       *varname = PQfname(res, fld);
                               3323                 :                : 
                               3324                 :                :                         /* allocate varname only if necessary, freed below */
 2357                          3325         [ +  + ]:            539 :                         if (*varprefix != '\0')
                               3326                 :              1 :                             varname = psprintf("%s%s", varprefix, varname);
                               3327                 :                : 
                               3328                 :                :                         /* store last row result as a string */
 1263 ishii@postgresql.org     3329   [ +  +  +  + ]:            539 :                         if (!putVariable(&st->variables, meta == META_ASET ? "aset" : "gset", varname,
 1982 michael@paquier.xyz      3330                 :            539 :                                          PQgetvalue(res, ntuples - 1, fld)))
                               3331                 :                :                         {
                               3332                 :                :                             /* internal error */
 2068 peter@eisentraut.org     3333                 :              2 :                             pg_log_error("client %d script %d command %d query %d: error storing into variable %s",
                               3334                 :                :                                          st->id, st->use_file, st->command, qrynum, varname);
 1263 ishii@postgresql.org     3335                 :              2 :                             st->estatus = ESTATUS_META_COMMAND_ERROR;
 2342 alvherre@alvh.no-ip.     3336                 :              2 :                             goto error;
                               3337                 :                :                         }
                               3338                 :                : 
 2357                          3339         [ +  + ]:            537 :                         if (*varprefix != '\0')
 2431                          3340                 :              1 :                             pg_free(varname);
                               3341                 :                :                     }
                               3342                 :                :                 }
                               3343                 :                :                 /* otherwise the result is simply thrown away by PQclear below */
                               3344                 :           2299 :                 break;
                               3345                 :                : 
 1636                          3346                 :             54 :             case PGRES_PIPELINE_SYNC:
  591 michael@paquier.xyz      3347         [ -  + ]:             54 :                 pg_log_debug("client %d pipeline ending, ongoing syncs: %d",
                               3348                 :                :                              st->id, st->num_syncs);
                               3349                 :             54 :                 st->num_syncs--;
                               3350   [ +  +  -  + ]:             54 :                 if (st->num_syncs == 0 && PQexitPipelineMode(st->con) != 1)
 1636 alvherre@alvh.no-ip.     3351                 :UBC           0 :                     pg_log_error("client %d failed to exit pipeline mode: %s", st->id,
                               3352                 :                :                                  PQerrorMessage(st->con));
 1636 alvherre@alvh.no-ip.     3353                 :CBC          54 :                 break;
                               3354                 :                : 
 1263 ishii@postgresql.org     3355                 :             13 :             case PGRES_NONFATAL_ERROR:
                               3356                 :                :             case PGRES_FATAL_ERROR:
 1213 tgl@sss.pgh.pa.us        3357                 :             13 :                 st->estatus = getSQLErrorStatus(PQresultErrorField(res,
                               3358                 :                :                                                                    PG_DIAG_SQLSTATE));
 1263 ishii@postgresql.org     3359         [ +  + ]:             13 :                 if (canRetryError(st->estatus))
                               3360                 :                :                 {
                               3361         [ +  - ]:              2 :                     if (verbose_errors)
                               3362                 :              2 :                         commandError(st, PQerrorMessage(st->con));
                               3363                 :              2 :                     goto error;
                               3364                 :                :                 }
                               3365                 :                :                 /* fall through */
                               3366                 :                : 
                               3367                 :                :             default:
                               3368                 :                :                 /* anything else is unexpected */
 2068 peter@eisentraut.org     3369                 :             11 :                 pg_log_error("client %d script %d aborted in command %d query %d: %s",
                               3370                 :                :                              st->id, st->use_file, st->command, qrynum,
                               3371                 :                :                              PQerrorMessage(st->con));
 2342 alvherre@alvh.no-ip.     3372                 :             11 :                 goto error;
                               3373                 :                :         }
                               3374                 :                : 
 2431                          3375                 :          10556 :         PQclear(res);
                               3376                 :          10556 :         qrynum++;
 2357                          3377                 :          10556 :         res = next_res;
                               3378                 :                :     }
                               3379                 :                : 
 2431                          3380         [ -  + ]:          10550 :     if (qrynum == 0)
                               3381                 :                :     {
 2068 peter@eisentraut.org     3382                 :UBC           0 :         pg_log_error("client %d command %d: no results", st->id, st->command);
 2431 alvherre@alvh.no-ip.     3383                 :              0 :         return false;
                               3384                 :                :     }
                               3385                 :                : 
 2431 alvherre@alvh.no-ip.     3386                 :CBC       10550 :     return true;
                               3387                 :                : 
 2342                          3388                 :             18 : error:
                               3389                 :             18 :     PQclear(res);
                               3390                 :             18 :     PQclear(next_res);
                               3391                 :                :     do
                               3392                 :                :     {
                               3393                 :             22 :         res = PQgetResult(st->con);
                               3394                 :             22 :         PQclear(res);
                               3395         [ +  + ]:             22 :     } while (res);
                               3396                 :                : 
                               3397                 :             18 :     return false;
                               3398                 :                : }
                               3399                 :                : 
                               3400                 :                : /*
                               3401                 :                :  * Parse the argument to a \sleep command, and return the requested amount
                               3402                 :                :  * of delay, in microseconds.  Returns true on success, false on error.
                               3403                 :                :  */
                               3404                 :                : static bool
 1263 ishii@postgresql.org     3405                 :              6 : evaluateSleep(Variables *variables, int argc, char **argv, int *usecs)
                               3406                 :                : {
                               3407                 :                :     char       *var;
                               3408                 :                :     int         usec;
                               3409                 :                : 
 3267 heikki.linnakangas@i     3410         [ +  + ]:              6 :     if (*argv[1] == ':')
                               3411                 :                :     {
 1263 ishii@postgresql.org     3412         [ +  + ]:              3 :         if ((var = getVariable(variables, argv[1] + 1)) == NULL)
                               3413                 :                :         {
 2068 peter@eisentraut.org     3414                 :              1 :             pg_log_error("%s: undefined variable \"%s\"", argv[0], argv[1] + 1);
 3267 heikki.linnakangas@i     3415                 :              1 :             return false;
                               3416                 :                :         }
                               3417                 :                : 
                               3418                 :              2 :         usec = atoi(var);
                               3419                 :                : 
                               3420                 :                :         /* Raise an error if the value of a variable is not a number */
 1629 fujii@postgresql.org     3421   [ +  +  -  + ]:              2 :         if (usec == 0 && !isdigit((unsigned char) *var))
                               3422                 :                :         {
 1629 fujii@postgresql.org     3423                 :UBC           0 :             pg_log_error("%s: invalid sleep time \"%s\" for variable \"%s\"",
                               3424                 :                :                          argv[0], var, argv[1] + 1);
                               3425                 :              0 :             return false;
                               3426                 :                :         }
                               3427                 :                :     }
                               3428                 :                :     else
 3267 heikki.linnakangas@i     3429                 :CBC           3 :         usec = atoi(argv[1]);
                               3430                 :                : 
                               3431         [ +  + ]:              5 :     if (argc > 2)
                               3432                 :                :     {
                               3433         [ +  + ]:              4 :         if (pg_strcasecmp(argv[2], "ms") == 0)
                               3434                 :              2 :             usec *= 1000;
                               3435         [ +  + ]:              2 :         else if (pg_strcasecmp(argv[2], "s") == 0)
                               3436                 :              1 :             usec *= 1000000;
                               3437                 :                :     }
                               3438                 :                :     else
                               3439                 :              1 :         usec *= 1000000;
                               3440                 :                : 
                               3441                 :              5 :     *usecs = usec;
                               3442                 :              5 :     return true;
                               3443                 :                : }
                               3444                 :                : 
                               3445                 :                : 
                               3446                 :                : /*
                               3447                 :                :  * Returns true if the error can be retried.
                               3448                 :                :  */
                               3449                 :                : static bool
 1263 ishii@postgresql.org     3450                 :              2 : doRetry(CState *st, pg_time_usec_t *now)
                               3451                 :                : {
                               3452         [ -  + ]:              2 :     Assert(st->estatus != ESTATUS_NO_ERROR);
                               3453                 :                : 
                               3454                 :                :     /* We can only retry serialization or deadlock errors. */
                               3455         [ -  + ]:              2 :     if (!canRetryError(st->estatus))
 1263 ishii@postgresql.org     3456                 :UBC           0 :         return false;
                               3457                 :                : 
                               3458                 :                :     /*
                               3459                 :                :      * We must have at least one option to limit the retrying of transactions
                               3460                 :                :      * that got an error.
                               3461                 :                :      */
 1263 ishii@postgresql.org     3462   [ -  +  -  -  :CBC           2 :     Assert(max_tries || latency_limit || duration > 0);
                                              -  - ]
                               3463                 :                : 
                               3464                 :                :     /*
                               3465                 :                :      * We cannot retry the error if we have reached the maximum number of
                               3466                 :                :      * tries.
                               3467                 :                :      */
                               3468   [ +  -  -  + ]:              2 :     if (max_tries && st->tries >= max_tries)
 1263 ishii@postgresql.org     3469                 :UBC           0 :         return false;
                               3470                 :                : 
                               3471                 :                :     /*
                               3472                 :                :      * We cannot retry the error if we spent too much time on this
                               3473                 :                :      * transaction.
                               3474                 :                :      */
 1263 ishii@postgresql.org     3475         [ -  + ]:CBC           2 :     if (latency_limit)
                               3476                 :                :     {
 1263 ishii@postgresql.org     3477                 :UBC           0 :         pg_time_now_lazy(now);
                               3478         [ #  # ]:              0 :         if (*now - st->txn_scheduled > latency_limit)
                               3479                 :              0 :             return false;
                               3480                 :                :     }
                               3481                 :                : 
                               3482                 :                :     /*
                               3483                 :                :      * We cannot retry the error if the benchmark duration is over.
                               3484                 :                :      */
 1263 ishii@postgresql.org     3485         [ -  + ]:CBC           2 :     if (timer_exceeded)
 1263 ishii@postgresql.org     3486                 :UBC           0 :         return false;
                               3487                 :                : 
                               3488                 :                :     /* OK */
 1263 ishii@postgresql.org     3489                 :CBC           2 :     return true;
                               3490                 :                : }
                               3491                 :                : 
                               3492                 :                : /*
                               3493                 :                :  * Read results and discard it until a sync point.
                               3494                 :                :  */
                               3495                 :                : static int
 1263 ishii@postgresql.org     3496                 :UBC           0 : discardUntilSync(CState *st)
                               3497                 :                : {
   34 fujii@postgresql.org     3498                 :              0 :     bool        received_sync = false;
                               3499                 :                : 
                               3500                 :                :     /* send a sync */
 1263 ishii@postgresql.org     3501         [ #  # ]:              0 :     if (!PQpipelineSync(st->con))
                               3502                 :                :     {
                               3503                 :              0 :         pg_log_error("client %d aborted: failed to send a pipeline sync",
                               3504                 :                :                      st->id);
                               3505                 :              0 :         return 0;
                               3506                 :                :     }
                               3507                 :                : 
                               3508                 :                :     /* receive PGRES_PIPELINE_SYNC and null following it */
                               3509                 :                :     for (;;)
                               3510                 :              0 :     {
 1213 tgl@sss.pgh.pa.us        3511                 :              0 :         PGresult   *res = PQgetResult(st->con);
                               3512                 :                : 
 1263 ishii@postgresql.org     3513         [ #  # ]:              0 :         if (PQresultStatus(res) == PGRES_PIPELINE_SYNC)
   34 fujii@postgresql.org     3514                 :              0 :             received_sync = true;
                               3515         [ #  # ]:              0 :         else if (received_sync)
                               3516                 :                :         {
                               3517                 :                :             /*
                               3518                 :                :              * PGRES_PIPELINE_SYNC must be followed by another
                               3519                 :                :              * PGRES_PIPELINE_SYNC or NULL; otherwise, assert failure.
                               3520                 :                :              */
 1263 ishii@postgresql.org     3521         [ #  # ]:              0 :             Assert(res == NULL);
                               3522                 :                : 
                               3523                 :                :             /*
                               3524                 :                :              * Reset ongoing sync count to 0 since all PGRES_PIPELINE_SYNC
                               3525                 :                :              * results have been discarded.
                               3526                 :                :              */
   34 fujii@postgresql.org     3527                 :              0 :             st->num_syncs = 0;
                               3528                 :              0 :             PQclear(res);
 1263 ishii@postgresql.org     3529                 :              0 :             break;
                               3530                 :                :         }
                               3531                 :              0 :         PQclear(res);
                               3532                 :                :     }
                               3533                 :                : 
                               3534                 :                :     /* exit pipeline */
                               3535         [ #  # ]:              0 :     if (PQexitPipelineMode(st->con) != 1)
                               3536                 :                :     {
                               3537                 :              0 :         pg_log_error("client %d aborted: failed to exit pipeline mode for rolling back the failed transaction",
                               3538                 :                :                      st->id);
                               3539                 :              0 :         return 0;
                               3540                 :                :     }
                               3541                 :              0 :     return 1;
                               3542                 :                : }
                               3543                 :                : 
                               3544                 :                : /*
                               3545                 :                :  * Get the transaction status at the end of a command especially for
                               3546                 :                :  * checking if we are in a (failed) transaction block.
                               3547                 :                :  */
                               3548                 :                : static TStatus
 1263 ishii@postgresql.org     3549                 :CBC        7693 : getTransactionStatus(PGconn *con)
                               3550                 :                : {
                               3551                 :                :     PGTransactionStatusType tx_status;
                               3552                 :                : 
                               3553                 :           7693 :     tx_status = PQtransactionStatus(con);
                               3554   [ +  +  -  - ]:           7693 :     switch (tx_status)
                               3555                 :                :     {
                               3556                 :           7691 :         case PQTRANS_IDLE:
                               3557                 :           7691 :             return TSTATUS_IDLE;
                               3558                 :              2 :         case PQTRANS_INTRANS:
                               3559                 :                :         case PQTRANS_INERROR:
                               3560                 :              2 :             return TSTATUS_IN_BLOCK;
 1263 ishii@postgresql.org     3561                 :UBC           0 :         case PQTRANS_UNKNOWN:
                               3562                 :                :             /* PQTRANS_UNKNOWN is expected given a broken connection */
                               3563         [ #  # ]:              0 :             if (PQstatus(con) == CONNECTION_BAD)
                               3564                 :              0 :                 return TSTATUS_CONN_ERROR;
                               3565                 :                :             /* fall through */
                               3566                 :                :         case PQTRANS_ACTIVE:
                               3567                 :                :         default:
                               3568                 :                : 
                               3569                 :                :             /*
                               3570                 :                :              * We cannot find out whether we are in a transaction block or
                               3571                 :                :              * not. Internal error which should never occur.
                               3572                 :                :              */
                               3573                 :              0 :             pg_log_error("unexpected transaction status %d", tx_status);
                               3574                 :              0 :             return TSTATUS_OTHER_ERROR;
                               3575                 :                :     }
                               3576                 :                : 
                               3577                 :                :     /* not reached */
                               3578                 :                :     Assert(false);
                               3579                 :                :     return TSTATUS_OTHER_ERROR;
                               3580                 :                : }
                               3581                 :                : 
                               3582                 :                : /*
                               3583                 :                :  * Print verbose messages of an error
                               3584                 :                :  */
                               3585                 :                : static void
 1263 ishii@postgresql.org     3586                 :CBC           2 : printVerboseErrorMessages(CState *st, pg_time_usec_t *now, bool is_retry)
                               3587                 :                : {
                               3588                 :                :     static PQExpBuffer buf = NULL;
                               3589                 :                : 
                               3590         [ +  - ]:              2 :     if (buf == NULL)
                               3591                 :              2 :         buf = createPQExpBuffer();
                               3592                 :                :     else
 1263 ishii@postgresql.org     3593                 :UBC           0 :         resetPQExpBuffer(buf);
                               3594                 :                : 
 1263 ishii@postgresql.org     3595                 :CBC           2 :     printfPQExpBuffer(buf, "client %d ", st->id);
 1096 drowley@postgresql.o     3596         [ +  - ]:              2 :     appendPQExpBufferStr(buf, (is_retry ?
                               3597                 :                :                                "repeats the transaction after the error" :
                               3598                 :                :                                "ends the failed transaction"));
 1235 peter@eisentraut.org     3599                 :              2 :     appendPQExpBuffer(buf, " (try %u", st->tries);
                               3600                 :                : 
                               3601                 :                :     /* Print max_tries if it is not unlimited. */
 1263 ishii@postgresql.org     3602         [ +  - ]:              2 :     if (max_tries)
 1235 peter@eisentraut.org     3603                 :              2 :         appendPQExpBuffer(buf, "/%u", max_tries);
                               3604                 :                : 
                               3605                 :                :     /*
                               3606                 :                :      * If the latency limit is used, print a percentage of the current
                               3607                 :                :      * transaction latency from the latency limit.
                               3608                 :                :      */
 1263 ishii@postgresql.org     3609         [ -  + ]:              2 :     if (latency_limit)
                               3610                 :                :     {
 1263 ishii@postgresql.org     3611                 :UBC           0 :         pg_time_now_lazy(now);
                               3612                 :              0 :         appendPQExpBuffer(buf, ", %.3f%% of the maximum time of tries was used",
                               3613                 :              0 :                           (100.0 * (*now - st->txn_scheduled) / latency_limit));
                               3614                 :                :     }
 1096 drowley@postgresql.o     3615                 :CBC           2 :     appendPQExpBufferStr(buf, ")\n");
                               3616                 :                : 
 1263 ishii@postgresql.org     3617                 :              2 :     pg_log_info("%s", buf->data);
                               3618                 :              2 : }
                               3619                 :                : 
                               3620                 :                : /*
                               3621                 :                :  * Advance the state machine of a connection.
                               3622                 :                :  */
                               3623                 :                : static void
 2481 alvherre@alvh.no-ip.     3624                 :          17734 : advanceConnectionState(TState *thread, CState *st, StatsData *agg)
                               3625                 :                : {
                               3626                 :                : 
                               3627                 :                :     /*
                               3628                 :                :      * gettimeofday() isn't free, so we get the current timestamp lazily the
                               3629                 :                :      * first time it's needed, and reuse the same value throughout this
                               3630                 :                :      * function after that.  This also ensures that e.g. the calculated
                               3631                 :                :      * latency reported in the log file and in the totals are the same. Zero
                               3632                 :                :      * means "not set yet".  Reset "now" when we execute shell commands or
                               3633                 :                :      * expressions, which might take a non-negligible amount of time, though.
                               3634                 :                :      */
 1641 tmunro@postgresql.or     3635                 :          17734 :     pg_time_usec_t now = 0;
                               3636                 :                : 
                               3637                 :                :     /*
                               3638                 :                :      * Loop in the state machine, until we have to wait for a result from the
                               3639                 :                :      * server or have to sleep for throttling or \sleep.
                               3640                 :                :      *
                               3641                 :                :      * Note: In the switch-statement below, 'break' will loop back here,
                               3642                 :                :      * meaning "continue in the state machine".  Return is used to return to
                               3643                 :                :      * the caller, giving the thread the opportunity to advance another
                               3644                 :                :      * client.
                               3645                 :                :      */
                               3646                 :                :     for (;;)
 3267 heikki.linnakangas@i     3647                 :          60557 :     {
                               3648                 :                :         Command    *command;
                               3649                 :                : 
                               3650   [ +  +  +  +  :          78291 :         switch (st->state)
                                     +  +  +  +  +  
                                     +  +  +  -  +  
                                              +  - ]
                               3651                 :                :         {
                               3652                 :                :                 /* Select transaction (script) to run.  */
                               3653                 :           7744 :             case CSTATE_CHOOSE_SCRIPT:
                               3654                 :           7744 :                 st->use_file = chooseScript(thread);
 2481 alvherre@alvh.no-ip.     3655         [ -  + ]:           7744 :                 Assert(conditional_stack_empty(st->cstack));
                               3656                 :                : 
                               3657                 :                :                 /* reset transaction variables to default values */
 1263 ishii@postgresql.org     3658                 :           7744 :                 st->estatus = ESTATUS_NO_ERROR;
                               3659                 :           7744 :                 st->tries = 1;
                               3660                 :                : 
 2068 peter@eisentraut.org     3661         [ +  + ]:           7744 :                 pg_log_debug("client %d executing script \"%s\"",
                               3662                 :                :                              st->id, sql_script[st->use_file].desc);
                               3663                 :                : 
                               3664                 :                :                 /*
                               3665                 :                :                  * If time is over, we're done; otherwise, get ready to start
                               3666                 :                :                  * a new transaction, or to get throttled if that's requested.
                               3667                 :                :                  */
 2481 alvherre@alvh.no-ip.     3668         [ +  - ]:          15488 :                 st->state = timer_exceeded ? CSTATE_FINISHED :
                               3669         [ +  + ]:           7744 :                     throttle_delay > 0 ? CSTATE_PREPARE_THROTTLE : CSTATE_START_TX;
                               3670                 :           7744 :                 break;
                               3671                 :                : 
                               3672                 :                :                 /* Start new transaction (script) */
                               3673                 :           7743 :             case CSTATE_START_TX:
 1641 tmunro@postgresql.or     3674                 :           7743 :                 pg_time_now_lazy(&now);
                               3675                 :                : 
                               3676                 :                :                 /* establish connection if needed, i.e. under --connect */
 2481 alvherre@alvh.no-ip.     3677         [ +  + ]:           7743 :                 if (st->con == NULL)
                               3678                 :                :                 {
 1641 tmunro@postgresql.or     3679                 :            110 :                     pg_time_usec_t start = now;
                               3680                 :                : 
 2481 alvherre@alvh.no-ip.     3681         [ -  + ]:            110 :                     if ((st->con = doConnect()) == NULL)
                               3682                 :                :                     {
                               3683                 :                :                         /*
                               3684                 :                :                          * as the bench is already running, we do not abort
                               3685                 :                :                          * the process
                               3686                 :                :                          */
 2068 peter@eisentraut.org     3687                 :UBC           0 :                         pg_log_error("client %d aborted while establishing connection", st->id);
 2481 alvherre@alvh.no-ip.     3688                 :              0 :                         st->state = CSTATE_ABORTED;
                               3689                 :              0 :                         break;
                               3690                 :                :                     }
                               3691                 :                : 
                               3692                 :                :                     /* reset now after connection */
 1641 tmunro@postgresql.or     3693                 :CBC         110 :                     now = pg_time_now();
                               3694                 :                : 
                               3695                 :            110 :                     thread->conn_duration += now - start;
                               3696                 :                : 
                               3697                 :                :                     /* Reset session-local state */
  928 alvherre@alvh.no-ip.     3698                 :            110 :                     pg_free(st->prepared);
                               3699                 :            110 :                     st->prepared = NULL;
                               3700                 :                :                 }
                               3701                 :                : 
                               3702                 :                :                 /*
                               3703                 :                :                  * It is the first try to run this transaction. Remember the
                               3704                 :                :                  * random state: maybe it will get an error and we will need
                               3705                 :                :                  * to run it again.
                               3706                 :                :                  */
 1263 ishii@postgresql.org     3707                 :           7743 :                 st->random_state = st->cs_func_rs;
                               3708                 :                : 
                               3709                 :                :                 /* record transaction start time */
 2481 alvherre@alvh.no-ip.     3710                 :           7743 :                 st->txn_begin = now;
                               3711                 :                : 
                               3712                 :                :                 /*
                               3713                 :                :                  * When not throttling, this is also the transaction's
                               3714                 :                :                  * scheduled start time.
                               3715                 :                :                  */
                               3716         [ +  + ]:           7743 :                 if (!throttle_delay)
 1641 tmunro@postgresql.or     3717                 :           7542 :                     st->txn_scheduled = now;
                               3718                 :                : 
                               3719                 :                :                 /* Begin with the first command */
 2481 alvherre@alvh.no-ip.     3720                 :           7743 :                 st->state = CSTATE_START_COMMAND;
                               3721                 :           7743 :                 st->command = 0;
 3267 heikki.linnakangas@i     3722                 :           7743 :                 break;
                               3723                 :                : 
                               3724                 :                :                 /*
                               3725                 :                :                  * Handle throttling once per transaction by sleeping.
                               3726                 :                :                  */
 2481 alvherre@alvh.no-ip.     3727                 :            210 :             case CSTATE_PREPARE_THROTTLE:
                               3728                 :                : 
                               3729                 :                :                 /*
                               3730                 :                :                  * Generate a delay such that the series of delays will
                               3731                 :                :                  * approximate a Poisson distribution centered on the
                               3732                 :                :                  * throttle_delay time.
                               3733                 :                :                  *
                               3734                 :                :                  * If transactions are too slow or a given wait is shorter
                               3735                 :                :                  * than a transaction, the next transaction will start right
                               3736                 :                :                  * away.
                               3737                 :                :                  */
 3267 heikki.linnakangas@i     3738         [ -  + ]:            210 :                 Assert(throttle_delay > 0);
                               3739                 :                : 
 2481 alvherre@alvh.no-ip.     3740                 :            210 :                 thread->throttle_trigger +=
                               3741                 :            210 :                     getPoissonRand(&thread->ts_throttle_rs, throttle_delay);
 3267 heikki.linnakangas@i     3742                 :            210 :                 st->txn_scheduled = thread->throttle_trigger;
                               3743                 :                : 
                               3744                 :                :                 /*
                               3745                 :                :                  * If --latency-limit is used, and this slot is already late
                               3746                 :                :                  * so that the transaction will miss the latency limit even if
                               3747                 :                :                  * it completed immediately, skip this time slot and loop to
                               3748                 :                :                  * reschedule.
                               3749                 :                :                  */
                               3750         [ +  - ]:            210 :                 if (latency_limit)
                               3751                 :                :                 {
 1641 tmunro@postgresql.or     3752                 :            210 :                     pg_time_now_lazy(&now);
                               3753                 :                : 
 1457 fujii@postgresql.org     3754         [ +  + ]:            210 :                     if (thread->throttle_trigger < now - latency_limit)
                               3755                 :                :                     {
 3267 heikki.linnakangas@i     3756                 :              9 :                         processXactStats(thread, st, &now, true, agg);
                               3757                 :                : 
                               3758                 :                :                         /*
                               3759                 :                :                          * Finish client if -T or -t was exceeded.
                               3760                 :                :                          *
                               3761                 :                :                          * Stop counting skipped transactions under -T as soon
                               3762                 :                :                          * as the timer is exceeded. Because otherwise it can
                               3763                 :                :                          * take a very long time to count all of them
                               3764                 :                :                          * especially when quite a lot of them happen with
                               3765                 :                :                          * unrealistically high rate setting in -R, which
                               3766                 :                :                          * would prevent pgbench from ending immediately.
                               3767                 :                :                          * Because of this behavior, note that there is no
                               3768                 :                :                          * guarantee that all skipped transactions are counted
                               3769                 :                :                          * under -T though there is under -t. This is OK in
                               3770                 :                :                          * practice because it's very unlikely to happen with
                               3771                 :                :                          * realistic setting.
                               3772                 :                :                          */
 1457 fujii@postgresql.org     3773   [ +  -  +  -  :              9 :                         if (timer_exceeded || (nxacts > 0 && st->cnt >= nxacts))
                                              +  + ]
                               3774                 :              1 :                             st->state = CSTATE_FINISHED;
                               3775                 :                : 
                               3776                 :                :                         /* Go back to top of loop with CSTATE_PREPARE_THROTTLE */
 2924 tgl@sss.pgh.pa.us        3777                 :              9 :                         break;
                               3778                 :                :                     }
                               3779                 :                :                 }
                               3780                 :                : 
                               3781                 :                :                 /*
                               3782                 :                :                  * stop client if next transaction is beyond pgbench end of
                               3783                 :                :                  * execution; otherwise, throttle it.
                               3784                 :                :                  */
 2481 alvherre@alvh.no-ip.     3785         [ #  # ]:UBC           0 :                 st->state = end_time > 0 && st->txn_scheduled > end_time ?
 2481 alvherre@alvh.no-ip.     3786         [ -  + ]:CBC         201 :                     CSTATE_FINISHED : CSTATE_THROTTLE;
 3267 heikki.linnakangas@i     3787                 :            201 :                 break;
                               3788                 :                : 
                               3789                 :                :                 /*
                               3790                 :                :                  * Wait until it's time to start next transaction.
                               3791                 :                :                  */
 2481 alvherre@alvh.no-ip.     3792                 :            201 :             case CSTATE_THROTTLE:
 1641 tmunro@postgresql.or     3793                 :            201 :                 pg_time_now_lazy(&now);
                               3794                 :                : 
                               3795         [ -  + ]:            201 :                 if (now < st->txn_scheduled)
 2481 alvherre@alvh.no-ip.     3796                 :UBC           0 :                     return;     /* still sleeping, nothing to do here */
                               3797                 :                : 
                               3798                 :                :                 /* done sleeping, but don't start transaction if we're done */
 2481 alvherre@alvh.no-ip.     3799         [ -  + ]:CBC         201 :                 st->state = timer_exceeded ? CSTATE_FINISHED : CSTATE_START_TX;
 3267 heikki.linnakangas@i     3800                 :            201 :                 break;
                               3801                 :                : 
                               3802                 :                :                 /*
                               3803                 :                :                  * Send a command to server (or execute a meta-command)
                               3804                 :                :                  */
                               3805                 :          20625 :             case CSTATE_START_COMMAND:
 2355 alvherre@alvh.no-ip.     3806                 :          20625 :                 command = sql_script[st->use_file].commands[st->command];
                               3807                 :                : 
                               3808                 :                :                 /*
                               3809                 :                :                  * Transition to script end processing if done, but close up
                               3810                 :                :                  * shop if a pipeline is open at this point.
                               3811                 :                :                  */
                               3812         [ +  + ]:          20625 :                 if (command == NULL)
                               3813                 :                :                 {
  593                          3814         [ +  + ]:           7694 :                     if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
                               3815                 :           7691 :                         st->state = CSTATE_END_TX;
                               3816                 :                :                     else
                               3817                 :                :                     {
                               3818                 :              3 :                         pg_log_error("client %d aborted: end of script reached with pipeline open",
                               3819                 :                :                                      st->id);
                               3820                 :              3 :                         st->state = CSTATE_ABORTED;
                               3821                 :                :                     }
                               3822                 :                : 
 3267 heikki.linnakangas@i     3823                 :           7694 :                     break;
                               3824                 :                :                 }
                               3825                 :                : 
                               3826                 :                :                 /* record begin time of next command, and initiate it */
 2481 alvherre@alvh.no-ip.     3827         [ +  + ]:          12931 :                 if (report_per_command)
                               3828                 :                :                 {
 1641 tmunro@postgresql.or     3829                 :            401 :                     pg_time_now_lazy(&now);
 3267 heikki.linnakangas@i     3830                 :            401 :                     st->stmt_begin = now;
                               3831                 :                :                 }
                               3832                 :                : 
                               3833                 :                :                 /* Execute the command */
 2355 alvherre@alvh.no-ip.     3834         [ +  + ]:          12931 :                 if (command->type == SQL_COMMAND)
                               3835                 :                :                 {
                               3836                 :                :                     /* disallow \aset and \gset in pipeline mode */
 1636                          3837         [ +  + ]:          10524 :                     if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
                               3838                 :                :                     {
                               3839         [ +  + ]:            524 :                         if (command->meta == META_GSET)
                               3840                 :                :                         {
                               3841                 :              1 :                             commandFailed(st, "gset", "\\gset is not allowed in pipeline mode");
                               3842                 :              1 :                             st->state = CSTATE_ABORTED;
                               3843                 :              1 :                             break;
                               3844                 :                :                         }
                               3845         [ -  + ]:            523 :                         else if (command->meta == META_ASET)
                               3846                 :                :                         {
 1636 alvherre@alvh.no-ip.     3847                 :UBC           0 :                             commandFailed(st, "aset", "\\aset is not allowed in pipeline mode");
                               3848                 :              0 :                             st->state = CSTATE_ABORTED;
                               3849                 :              0 :                             break;
                               3850                 :                :                         }
                               3851                 :                :                     }
                               3852                 :                : 
 2355 alvherre@alvh.no-ip.     3853         [ -  + ]:CBC       10523 :                     if (!sendCommand(st, command))
                               3854                 :                :                     {
 2355 alvherre@alvh.no-ip.     3855                 :UBC           0 :                         commandFailed(st, "SQL", "SQL command send failed");
                               3856                 :              0 :                         st->state = CSTATE_ABORTED;
                               3857                 :                :                     }
                               3858                 :                :                     else
                               3859                 :                :                     {
                               3860                 :                :                         /* Wait for results, unless in pipeline mode */
 1636 alvherre@alvh.no-ip.     3861         [ +  + ]:CBC       10523 :                         if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
                               3862                 :          10000 :                             st->state = CSTATE_WAIT_RESULT;
                               3863                 :                :                         else
                               3864                 :            523 :                             st->state = CSTATE_END_COMMAND;
                               3865                 :                :                     }
                               3866                 :                :                 }
 2355                          3867         [ +  - ]:           2407 :                 else if (command->type == META_COMMAND)
                               3868                 :                :                 {
                               3869                 :                :                     /*-----
                               3870                 :                :                      * Possible state changes when executing meta commands:
                               3871                 :                :                      * - on errors CSTATE_ABORTED
                               3872                 :                :                      * - on sleep CSTATE_SLEEP
                               3873                 :                :                      * - else CSTATE_END_COMMAND
                               3874                 :                :                      */
 2348 tgl@sss.pgh.pa.us        3875                 :           2407 :                     st->state = executeMetaCommand(st, &now);
 1263 ishii@postgresql.org     3876         [ +  + ]:           2407 :                     if (st->state == CSTATE_ABORTED)
                               3877                 :             31 :                         st->estatus = ESTATUS_META_COMMAND_ERROR;
                               3878                 :                :                 }
                               3879                 :                : 
                               3880                 :                :                 /*
                               3881                 :                :                  * We're now waiting for an SQL command to complete, or
                               3882                 :                :                  * finished processing a metacommand, or need to sleep, or
                               3883                 :                :                  * something bad happened.
                               3884                 :                :                  */
 2481 alvherre@alvh.no-ip.     3885   [ +  +  +  +  :          12930 :                 Assert(st->state == CSTATE_WAIT_RESULT ||
                                        +  +  -  + ]
                               3886                 :                :                        st->state == CSTATE_END_COMMAND ||
                               3887                 :                :                        st->state == CSTATE_SLEEP ||
                               3888                 :                :                        st->state == CSTATE_ABORTED);
 2725 teodor@sigaev.ru         3889                 :          12930 :                 break;
                               3890                 :                : 
                               3891                 :                :                 /*
                               3892                 :                :                  * non executed conditional branch
                               3893                 :                :                  */
                               3894                 :            503 :             case CSTATE_SKIP_COMMAND:
                               3895         [ -  + ]:            503 :                 Assert(!conditional_active(st->cstack));
                               3896                 :                :                 /* quickly skip commands until something to do... */
                               3897                 :                :                 while (true)
                               3898                 :                :                 {
                               3899                 :           2839 :                     command = sql_script[st->use_file].commands[st->command];
                               3900                 :                : 
                               3901                 :                :                     /* cannot reach end of script in that state */
                               3902         [ -  + ]:           2839 :                     Assert(command != NULL);
                               3903                 :                : 
                               3904                 :                :                     /*
                               3905                 :                :                      * if this is conditional related, update conditional
                               3906                 :                :                      * state
                               3907                 :                :                      */
                               3908         [ +  + ]:           2839 :                     if (command->type == META_COMMAND &&
                               3909         [ +  + ]:            528 :                         (command->meta == META_IF ||
                               3910         [ +  + ]:            525 :                          command->meta == META_ELIF ||
                               3911         [ +  + ]:            517 :                          command->meta == META_ELSE ||
                               3912         [ +  + ]:            510 :                          command->meta == META_ENDIF))
                               3913                 :                :                     {
                               3914      [ +  +  - ]:           1032 :                         switch (conditional_stack_peek(st->cstack))
                               3915                 :                :                         {
 2690 tgl@sss.pgh.pa.us        3916                 :            501 :                             case IFSTATE_FALSE:
  265                          3917         [ +  + ]:            501 :                                 if (command->meta == META_IF)
                               3918                 :                :                                 {
                               3919                 :                :                                     /* nested if in skipped branch - ignore */
                               3920                 :              2 :                                     conditional_stack_push(st->cstack,
                               3921                 :                :                                                            IFSTATE_IGNORED);
                               3922                 :              2 :                                     st->command++;
                               3923                 :                :                                 }
                               3924         [ +  + ]:            499 :                                 else if (command->meta == META_ELIF)
                               3925                 :                :                                 {
                               3926                 :                :                                     /* we must evaluate the condition */
 2690                          3927                 :              5 :                                     st->state = CSTATE_START_COMMAND;
                               3928                 :                :                                 }
                               3929         [ +  + ]:            494 :                                 else if (command->meta == META_ELSE)
                               3930                 :                :                                 {
                               3931                 :                :                                     /* we must execute next command */
 2481 alvherre@alvh.no-ip.     3932                 :              3 :                                     conditional_stack_poke(st->cstack,
                               3933                 :                :                                                            IFSTATE_ELSE_TRUE);
 2725 teodor@sigaev.ru         3934                 :              3 :                                     st->state = CSTATE_START_COMMAND;
 2690 tgl@sss.pgh.pa.us        3935                 :              3 :                                     st->command++;
                               3936                 :                :                                 }
                               3937         [ +  - ]:            491 :                                 else if (command->meta == META_ENDIF)
                               3938                 :                :                                 {
                               3939         [ -  + ]:            491 :                                     Assert(!conditional_stack_empty(st->cstack));
                               3940                 :            491 :                                     conditional_stack_pop(st->cstack);
                               3941         [ +  - ]:            491 :                                     if (conditional_active(st->cstack))
                               3942                 :            491 :                                         st->state = CSTATE_START_COMMAND;
                               3943                 :                :                                     /* else state remains CSTATE_SKIP_COMMAND */
                               3944                 :            491 :                                     st->command++;
                               3945                 :                :                                 }
                               3946                 :            501 :                                 break;
                               3947                 :                : 
                               3948                 :             15 :                             case IFSTATE_IGNORED:
                               3949                 :                :                             case IFSTATE_ELSE_FALSE:
                               3950         [ +  + ]:             15 :                                 if (command->meta == META_IF)
 2355 alvherre@alvh.no-ip.     3951                 :              1 :                                     conditional_stack_push(st->cstack,
                               3952                 :                :                                                            IFSTATE_IGNORED);
 2690 tgl@sss.pgh.pa.us        3953         [ +  + ]:             14 :                                 else if (command->meta == META_ENDIF)
                               3954                 :                :                                 {
                               3955         [ -  + ]:              7 :                                     Assert(!conditional_stack_empty(st->cstack));
                               3956                 :              7 :                                     conditional_stack_pop(st->cstack);
                               3957         [ +  + ]:              7 :                                     if (conditional_active(st->cstack))
                               3958                 :              4 :                                         st->state = CSTATE_START_COMMAND;
                               3959                 :                :                                 }
                               3960                 :                :                                 /* could detect "else" & "elif" after "else" */
 2725 teodor@sigaev.ru         3961                 :             15 :                                 st->command++;
 2690 tgl@sss.pgh.pa.us        3962                 :             15 :                                 break;
                               3963                 :                : 
 2690 tgl@sss.pgh.pa.us        3964                 :UBC           0 :                             case IFSTATE_NONE:
                               3965                 :                :                             case IFSTATE_TRUE:
                               3966                 :                :                             case IFSTATE_ELSE_TRUE:
                               3967                 :                :                             default:
                               3968                 :                : 
                               3969                 :                :                                 /*
                               3970                 :                :                                  * inconsistent if inactive, unreachable dead
                               3971                 :                :                                  * code
                               3972                 :                :                                  */
                               3973                 :              0 :                                 Assert(false);
                               3974                 :                :                         }
                               3975                 :                :                     }
                               3976                 :                :                     else
                               3977                 :                :                     {
                               3978                 :                :                         /* skip and consider next */
 2725 teodor@sigaev.ru         3979                 :CBC        2323 :                         st->command++;
                               3980                 :                :                     }
                               3981                 :                : 
                               3982         [ +  + ]:           2839 :                     if (st->state != CSTATE_SKIP_COMMAND)
                               3983                 :                :                         /* out of quick skip command loop */
                               3984                 :            503 :                         break;
                               3985                 :                :                 }
 3267 heikki.linnakangas@i     3986                 :            503 :                 break;
                               3987                 :                : 
                               3988                 :                :                 /*
                               3989                 :                :                  * Wait for the current SQL command to complete
                               3990                 :                :                  */
                               3991                 :          20555 :             case CSTATE_WAIT_RESULT:
 2068 peter@eisentraut.org     3992         [ +  + ]:          20555 :                 pg_log_debug("client %d receiving", st->id);
                               3993                 :                : 
                               3994                 :                :                 /*
                               3995                 :                :                  * Only check for new network data if we processed all data
                               3996                 :                :                  * fetched prior. Otherwise we end up doing a syscall for each
                               3997                 :                :                  * individual pipelined query, which has a measurable
                               3998                 :                :                  * performance impact.
                               3999                 :                :                  */
 1494 andres@anarazel.de       4000   [ +  +  -  + ]:          20555 :                 if (PQisBusy(st->con) && !PQconsumeInput(st->con))
                               4001                 :                :                 {
                               4002                 :                :                     /* there's something wrong */
 2725 teodor@sigaev.ru         4003                 :UBC           0 :                     commandFailed(st, "SQL", "perhaps the backend died while processing");
 3267 heikki.linnakangas@i     4004                 :              0 :                     st->state = CSTATE_ABORTED;
                               4005                 :              0 :                     break;
                               4006                 :                :                 }
 3267 heikki.linnakangas@i     4007         [ +  + ]:CBC       20555 :                 if (PQisBusy(st->con))
                               4008                 :           9987 :                     return;     /* don't have the whole result yet */
                               4009                 :                : 
                               4010                 :                :                 /* store or discard the query results */
 1982 michael@paquier.xyz      4011         [ +  + ]:          10568 :                 if (readCommandResponse(st,
                               4012                 :          10568 :                                         sql_script[st->use_file].commands[st->command]->meta,
                               4013                 :          10568 :                                         sql_script[st->use_file].commands[st->command]->varprefix))
                               4014                 :                :                 {
                               4015                 :                :                     /*
                               4016                 :                :                      * outside of pipeline mode: stop reading results.
                               4017                 :                :                      * pipeline mode: continue reading results until an
                               4018                 :                :                      * end-of-pipeline response.
                               4019                 :                :                      */
 1636 alvherre@alvh.no-ip.     4020         [ +  + ]:          10550 :                     if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
                               4021                 :          10035 :                         st->state = CSTATE_END_COMMAND;
                               4022                 :                :                 }
 1263 ishii@postgresql.org     4023         [ +  + ]:             18 :                 else if (canRetryError(st->estatus))
                               4024                 :              2 :                     st->state = CSTATE_ERROR;
                               4025                 :                :                 else
 2431 alvherre@alvh.no-ip.     4026                 :             16 :                     st->state = CSTATE_ABORTED;
 3267 heikki.linnakangas@i     4027                 :          10568 :                 break;
                               4028                 :                : 
                               4029                 :                :                 /*
                               4030                 :                :                  * Wait until sleep is done. This state is entered after a
                               4031                 :                :                  * \sleep metacommand. The behavior is similar to
                               4032                 :                :                  * CSTATE_THROTTLE, but proceeds to CSTATE_START_COMMAND
                               4033                 :                :                  * instead of CSTATE_START_TX.
                               4034                 :                :                  */
                               4035                 :              8 :             case CSTATE_SLEEP:
 1641 tmunro@postgresql.or     4036                 :              8 :                 pg_time_now_lazy(&now);
                               4037         [ +  + ]:              8 :                 if (now < st->sleep_until)
 2481 alvherre@alvh.no-ip.     4038                 :              3 :                     return;     /* still sleeping, nothing to do here */
                               4039                 :                :                 /* Else done sleeping. */
 3267 heikki.linnakangas@i     4040                 :              5 :                 st->state = CSTATE_END_COMMAND;
                               4041                 :              5 :                 break;
                               4042                 :                : 
                               4043                 :                :                 /*
                               4044                 :                :                  * End of command: record stats and proceed to next command.
                               4045                 :                :                  */
                               4046                 :          12880 :             case CSTATE_END_COMMAND:
                               4047                 :                : 
                               4048                 :                :                 /*
                               4049                 :                :                  * command completed: accumulate per-command execution times
                               4050                 :                :                  * in thread-local data structure, if per-command latencies
                               4051                 :                :                  * are requested.
                               4052                 :                :                  */
 2481 alvherre@alvh.no-ip.     4053         [ +  + ]:          12880 :                 if (report_per_command)
                               4054                 :                :                 {
 1641 tmunro@postgresql.or     4055                 :            401 :                     pg_time_now_lazy(&now);
                               4056                 :                : 
 2431 alvherre@alvh.no-ip.     4057                 :            401 :                     command = sql_script[st->use_file].commands[st->command];
                               4058                 :                :                     /* XXX could use a mutex here, but we choose not to */
 3267 heikki.linnakangas@i     4059                 :            401 :                     addToSimpleStats(&command->stats,
 1641 tmunro@postgresql.or     4060                 :            401 :                                      PG_TIME_GET_DOUBLE(now - st->stmt_begin));
                               4061                 :                :                 }
                               4062                 :                : 
                               4063                 :                :                 /* Go ahead with next command, to be executed or skipped */
 3267 heikki.linnakangas@i     4064                 :          12880 :                 st->command++;
 2725 teodor@sigaev.ru         4065                 :          12880 :                 st->state = conditional_active(st->cstack) ?
                               4066         [ +  + ]:          12880 :                     CSTATE_START_COMMAND : CSTATE_SKIP_COMMAND;
 3267 heikki.linnakangas@i     4067                 :          12880 :                 break;
                               4068                 :                : 
                               4069                 :                :                 /*
                               4070                 :                :                  * Clean up after an error.
                               4071                 :                :                  */
 1263 ishii@postgresql.org     4072                 :              2 :             case CSTATE_ERROR:
                               4073                 :                :                 {
                               4074                 :                :                     TStatus     tstatus;
                               4075                 :                : 
                               4076         [ -  + ]:              2 :                     Assert(st->estatus != ESTATUS_NO_ERROR);
                               4077                 :                : 
                               4078                 :                :                     /* Clear the conditional stack */
                               4079                 :              2 :                     conditional_stack_reset(st->cstack);
                               4080                 :                : 
                               4081                 :                :                     /* Read and discard until a sync point in pipeline mode */
                               4082         [ -  + ]:              2 :                     if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
                               4083                 :                :                     {
 1263 ishii@postgresql.org     4084         [ #  # ]:UBC           0 :                         if (!discardUntilSync(st))
                               4085                 :                :                         {
                               4086                 :              0 :                             st->state = CSTATE_ABORTED;
                               4087                 :              0 :                             break;
                               4088                 :                :                         }
                               4089                 :                :                     }
                               4090                 :                : 
                               4091                 :                :                     /*
                               4092                 :                :                      * Check if we have a (failed) transaction block or not,
                               4093                 :                :                      * and roll it back if any.
                               4094                 :                :                      */
 1263 ishii@postgresql.org     4095                 :CBC           2 :                     tstatus = getTransactionStatus(st->con);
                               4096         [ +  + ]:              2 :                     if (tstatus == TSTATUS_IN_BLOCK)
                               4097                 :                :                     {
                               4098                 :                :                         /* Try to rollback a (failed) transaction block. */
                               4099         [ -  + ]:              1 :                         if (!PQsendQuery(st->con, "ROLLBACK"))
                               4100                 :                :                         {
 1263 ishii@postgresql.org     4101                 :UBC           0 :                             pg_log_error("client %d aborted: failed to send sql command for rolling back the failed transaction",
                               4102                 :                :                                          st->id);
                               4103                 :              0 :                             st->state = CSTATE_ABORTED;
                               4104                 :                :                         }
                               4105                 :                :                         else
 1263 ishii@postgresql.org     4106                 :CBC           1 :                             st->state = CSTATE_WAIT_ROLLBACK_RESULT;
                               4107                 :                :                     }
                               4108         [ +  - ]:              1 :                     else if (tstatus == TSTATUS_IDLE)
                               4109                 :                :                     {
                               4110                 :                :                         /*
                               4111                 :                :                          * If time is over, we're done; otherwise, check if we
                               4112                 :                :                          * can retry the error.
                               4113                 :                :                          */
                               4114   [ +  -  +  - ]:              2 :                         st->state = timer_exceeded ? CSTATE_FINISHED :
                               4115                 :              1 :                             doRetry(st, &now) ? CSTATE_RETRY : CSTATE_FAILURE;
                               4116                 :                :                     }
                               4117                 :                :                     else
                               4118                 :                :                     {
 1263 ishii@postgresql.org     4119         [ #  # ]:UBC           0 :                         if (tstatus == TSTATUS_CONN_ERROR)
                               4120                 :              0 :                             pg_log_error("perhaps the backend died while processing");
                               4121                 :                : 
                               4122                 :              0 :                         pg_log_error("client %d aborted while receiving the transaction status", st->id);
                               4123                 :              0 :                         st->state = CSTATE_ABORTED;
                               4124                 :                :                     }
 1263 ishii@postgresql.org     4125                 :CBC           2 :                     break;
                               4126                 :                :                 }
                               4127                 :                : 
                               4128                 :                :                 /*
                               4129                 :                :                  * Wait for the rollback command to complete
                               4130                 :                :                  */
                               4131                 :              2 :             case CSTATE_WAIT_ROLLBACK_RESULT:
                               4132                 :                :                 {
                               4133                 :                :                     PGresult   *res;
                               4134                 :                : 
                               4135         [ +  - ]:              2 :                     pg_log_debug("client %d receiving", st->id);
                               4136         [ -  + ]:              2 :                     if (!PQconsumeInput(st->con))
                               4137                 :                :                     {
 1263 ishii@postgresql.org     4138                 :UBC           0 :                         pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
                               4139                 :                :                                      st->id);
                               4140                 :              0 :                         st->state = CSTATE_ABORTED;
                               4141                 :              0 :                         break;
                               4142                 :                :                     }
 1263 ishii@postgresql.org     4143         [ +  + ]:CBC           2 :                     if (PQisBusy(st->con))
 1213 tgl@sss.pgh.pa.us        4144                 :              1 :                         return; /* don't have the whole result yet */
                               4145                 :                : 
                               4146                 :                :                     /*
                               4147                 :                :                      * Read and discard the query result;
                               4148                 :                :                      */
 1263 ishii@postgresql.org     4149                 :              1 :                     res = PQgetResult(st->con);
                               4150         [ +  - ]:              1 :                     switch (PQresultStatus(res))
                               4151                 :                :                     {
                               4152                 :              1 :                         case PGRES_COMMAND_OK:
                               4153                 :                :                             /* OK */
                               4154                 :              1 :                             PQclear(res);
                               4155                 :                :                             /* null must be returned */
                               4156                 :              1 :                             res = PQgetResult(st->con);
                               4157         [ -  + ]:              1 :                             Assert(res == NULL);
                               4158                 :                : 
                               4159                 :                :                             /*
                               4160                 :                :                              * If time is over, we're done; otherwise, check
                               4161                 :                :                              * if we can retry the error.
                               4162                 :                :                              */
                               4163   [ +  -  +  - ]:              2 :                             st->state = timer_exceeded ? CSTATE_FINISHED :
                               4164                 :              1 :                                 doRetry(st, &now) ? CSTATE_RETRY : CSTATE_FAILURE;
                               4165                 :              1 :                             break;
 1263 ishii@postgresql.org     4166                 :UBC           0 :                         default:
                               4167                 :              0 :                             pg_log_error("client %d aborted while rolling back the transaction after an error; %s",
                               4168                 :                :                                          st->id, PQerrorMessage(st->con));
                               4169                 :              0 :                             PQclear(res);
                               4170                 :              0 :                             st->state = CSTATE_ABORTED;
                               4171                 :              0 :                             break;
                               4172                 :                :                     }
 3267 heikki.linnakangas@i     4173                 :CBC           1 :                     break;
                               4174                 :                :                 }
                               4175                 :                : 
                               4176                 :                :                 /*
                               4177                 :                :                  * Retry the transaction after an error.
                               4178                 :                :                  */
 1263 ishii@postgresql.org     4179                 :              2 :             case CSTATE_RETRY:
                               4180                 :              2 :                 command = sql_script[st->use_file].commands[st->command];
                               4181                 :                : 
                               4182                 :                :                 /*
                               4183                 :                :                  * Inform that the transaction will be retried after the
                               4184                 :                :                  * error.
                               4185                 :                :                  */
                               4186         [ +  - ]:              2 :                 if (verbose_errors)
                               4187                 :              2 :                     printVerboseErrorMessages(st, &now, true);
                               4188                 :                : 
                               4189                 :                :                 /* Count tries and retries */
                               4190                 :              2 :                 st->tries++;
                               4191                 :              2 :                 command->retries++;
                               4192                 :                : 
                               4193                 :                :                 /*
                               4194                 :                :                  * Reset the random state as they were at the beginning of the
                               4195                 :                :                  * transaction.
                               4196                 :                :                  */
                               4197                 :              2 :                 st->cs_func_rs = st->random_state;
                               4198                 :                : 
                               4199                 :                :                 /* Process the first transaction command. */
                               4200                 :              2 :                 st->command = 0;
                               4201                 :              2 :                 st->estatus = ESTATUS_NO_ERROR;
                               4202                 :              2 :                 st->state = CSTATE_START_COMMAND;
                               4203                 :              2 :                 break;
                               4204                 :                : 
                               4205                 :                :                 /*
                               4206                 :                :                  * Record a failed transaction.
                               4207                 :                :                  */
 1263 ishii@postgresql.org     4208                 :UBC           0 :             case CSTATE_FAILURE:
                               4209                 :              0 :                 command = sql_script[st->use_file].commands[st->command];
                               4210                 :                : 
                               4211                 :                :                 /* Accumulate the failure. */
                               4212                 :              0 :                 command->failures++;
                               4213                 :                : 
                               4214                 :                :                 /*
                               4215                 :                :                  * Inform that the failed transaction will not be retried.
                               4216                 :                :                  */
                               4217         [ #  # ]:              0 :                 if (verbose_errors)
                               4218                 :              0 :                     printVerboseErrorMessages(st, &now, false);
                               4219                 :                : 
                               4220                 :                :                 /* End the failed transaction. */
                               4221                 :              0 :                 st->state = CSTATE_END_TX;
                               4222                 :              0 :                 break;
                               4223                 :                : 
                               4224                 :                :                 /*
                               4225                 :                :                  * End of transaction (end of script, really).
                               4226                 :                :                  */
 1263 ishii@postgresql.org     4227                 :CBC        7691 :             case CSTATE_END_TX:
                               4228                 :                :                 {
                               4229                 :                :                     TStatus     tstatus;
                               4230                 :                : 
                               4231                 :                :                     /* transaction finished: calculate latency and do log */
                               4232                 :           7691 :                     processXactStats(thread, st, &now, false, agg);
                               4233                 :                : 
                               4234                 :                :                     /*
                               4235                 :                :                      * missing \endif... cannot happen if CheckConditional was
                               4236                 :                :                      * okay
                               4237                 :                :                      */
                               4238         [ -  + ]:           7691 :                     Assert(conditional_stack_empty(st->cstack));
                               4239                 :                : 
                               4240                 :                :                     /*
                               4241                 :                :                      * We must complete all the transaction blocks that were
                               4242                 :                :                      * started in this script.
                               4243                 :                :                      */
                               4244                 :           7691 :                     tstatus = getTransactionStatus(st->con);
                               4245         [ +  + ]:           7691 :                     if (tstatus == TSTATUS_IN_BLOCK)
                               4246                 :                :                     {
                               4247                 :              1 :                         pg_log_error("client %d aborted: end of script reached without completing the last transaction",
                               4248                 :                :                                      st->id);
                               4249                 :              1 :                         st->state = CSTATE_ABORTED;
                               4250                 :              1 :                         break;
                               4251                 :                :                     }
                               4252         [ -  + ]:           7690 :                     else if (tstatus != TSTATUS_IDLE)
                               4253                 :                :                     {
 1263 ishii@postgresql.org     4254         [ #  # ]:UBC           0 :                         if (tstatus == TSTATUS_CONN_ERROR)
                               4255                 :              0 :                             pg_log_error("perhaps the backend died while processing");
                               4256                 :                : 
                               4257                 :              0 :                         pg_log_error("client %d aborted while receiving the transaction status", st->id);
                               4258                 :              0 :                         st->state = CSTATE_ABORTED;
                               4259                 :              0 :                         break;
                               4260                 :                :                     }
                               4261                 :                : 
 1263 ishii@postgresql.org     4262         [ +  + ]:CBC        7690 :                     if (is_connect)
                               4263                 :                :                     {
                               4264                 :            110 :                         pg_time_usec_t start = now;
                               4265                 :                : 
                               4266                 :            110 :                         pg_time_now_lazy(&start);
                               4267                 :            110 :                         finishCon(st);
                               4268                 :            110 :                         now = pg_time_now();
                               4269                 :            110 :                         thread->conn_duration += now - start;
                               4270                 :                :                     }
                               4271                 :                : 
                               4272   [ +  +  -  +  :           7690 :                     if ((st->cnt >= nxacts && duration <= 0) || timer_exceeded)
                                              -  + ]
                               4273                 :                :                     {
                               4274                 :                :                         /* script completed */
                               4275                 :             72 :                         st->state = CSTATE_FINISHED;
                               4276                 :             72 :                         break;
                               4277                 :                :                     }
                               4278                 :                : 
                               4279                 :                :                     /* next transaction (script) */
                               4280                 :           7618 :                     st->state = CSTATE_CHOOSE_SCRIPT;
                               4281                 :                : 
                               4282                 :                :                     /*
                               4283                 :                :                      * Ensure that we always return on this point, so as to
                               4284                 :                :                      * avoid an infinite loop if the script only contains meta
                               4285                 :                :                      * commands.
                               4286                 :                :                      */
                               4287                 :           7618 :                     return;
                               4288                 :                :                 }
                               4289                 :                : 
                               4290                 :                :                 /*
                               4291                 :                :                  * Final states.  Close the connection if it's still open.
                               4292                 :                :                  */
 3267 heikki.linnakangas@i     4293                 :            125 :             case CSTATE_ABORTED:
                               4294                 :                :             case CSTATE_FINISHED:
                               4295                 :                : 
                               4296                 :                :                 /*
                               4297                 :                :                  * Don't measure the disconnection delays here even if in
                               4298                 :                :                  * CSTATE_FINISHED and -C/--connect option is specified.
                               4299                 :                :                  * Because in this case all the connections that this thread
                               4300                 :                :                  * established are closed at the end of transactions and the
                               4301                 :                :                  * disconnection delays should have already been measured at
                               4302                 :                :                  * that moment.
                               4303                 :                :                  *
                               4304                 :                :                  * In CSTATE_ABORTED state, the measurement is no longer
                               4305                 :                :                  * necessary because we cannot report complete results anyways
                               4306                 :                :                  * in this case.
                               4307                 :                :                  */
 2746 andres@anarazel.de       4308                 :            125 :                 finishCon(st);
 3267 heikki.linnakangas@i     4309                 :            125 :                 return;
                               4310                 :                :         }
                               4311                 :                :     }
                               4312                 :                : }
                               4313                 :                : 
                               4314                 :                : /*
                               4315                 :                :  * Subroutine for advanceConnectionState -- initiate or execute the current
                               4316                 :                :  * meta command, and return the next state to set.
                               4317                 :                :  *
                               4318                 :                :  * *now is updated to the current time, unless the command is expected to
                               4319                 :                :  * take no time to execute.
                               4320                 :                :  */
                               4321                 :                : static ConnectionStateEnum
 1641 tmunro@postgresql.or     4322                 :           2407 : executeMetaCommand(CState *st, pg_time_usec_t *now)
                               4323                 :                : {
 2481 alvherre@alvh.no-ip.     4324                 :           2407 :     Command    *command = sql_script[st->use_file].commands[st->command];
                               4325                 :                :     int         argc;
                               4326                 :                :     char      **argv;
                               4327                 :                : 
 2355                          4328   [ +  -  +  - ]:           2407 :     Assert(command != NULL && command->type == META_COMMAND);
                               4329                 :                : 
                               4330                 :           2407 :     argc = command->argc;
                               4331                 :           2407 :     argv = command->argv;
                               4332                 :                : 
 2068 peter@eisentraut.org     4333         [ +  + ]:           2407 :     if (unlikely(__pg_log_level <= PG_LOG_DEBUG))
                               4334                 :                :     {
                               4335                 :                :         PQExpBufferData buf;
                               4336                 :                : 
 2066 michael@paquier.xyz      4337                 :            703 :         initPQExpBuffer(&buf);
                               4338                 :                : 
                               4339                 :            703 :         printfPQExpBuffer(&buf, "client %d executing \\%s", st->id, argv[0]);
 2355 alvherre@alvh.no-ip.     4340         [ +  + ]:           1406 :         for (int i = 1; i < argc; i++)
 2066 michael@paquier.xyz      4341                 :            703 :             appendPQExpBuffer(&buf, " %s", argv[i]);
                               4342                 :                : 
                               4343         [ +  - ]:            703 :         pg_log_debug("%s", buf.data);
                               4344                 :                : 
                               4345                 :            703 :         termPQExpBuffer(&buf);
                               4346                 :                :     }
                               4347                 :                : 
 2355 alvherre@alvh.no-ip.     4348         [ +  + ]:           2407 :     if (command->meta == META_SLEEP)
                               4349                 :                :     {
                               4350                 :                :         int         usec;
                               4351                 :                : 
                               4352                 :                :         /*
                               4353                 :                :          * A \sleep doesn't execute anything, we just get the delay from the
                               4354                 :                :          * argument, and enter the CSTATE_SLEEP state.  (The per-command
                               4355                 :                :          * latency will be recorded in CSTATE_SLEEP state, not here, after the
                               4356                 :                :          * delay has elapsed.)
                               4357                 :                :          */
 1263 ishii@postgresql.org     4358         [ +  + ]:              6 :         if (!evaluateSleep(&st->variables, argc, argv, &usec))
                               4359                 :                :         {
 2355 alvherre@alvh.no-ip.     4360                 :              1 :             commandFailed(st, "sleep", "execution of meta-command failed");
                               4361                 :              1 :             return CSTATE_ABORTED;
                               4362                 :                :         }
                               4363                 :                : 
 1641 tmunro@postgresql.or     4364                 :              5 :         pg_time_now_lazy(now);
                               4365                 :              5 :         st->sleep_until = (*now) + usec;
 2355 alvherre@alvh.no-ip.     4366                 :              5 :         return CSTATE_SLEEP;
                               4367                 :                :     }
                               4368         [ +  + ]:           2401 :     else if (command->meta == META_SET)
                               4369                 :                :     {
                               4370                 :           1712 :         PgBenchExpr *expr = command->expr;
                               4371                 :                :         PgBenchValue result;
                               4372                 :                : 
 2348 tgl@sss.pgh.pa.us        4373         [ +  + ]:           1712 :         if (!evaluateExpr(st, expr, &result))
                               4374                 :                :         {
 2355 alvherre@alvh.no-ip.     4375                 :             23 :             commandFailed(st, argv[0], "evaluation of meta-command failed");
                               4376                 :             24 :             return CSTATE_ABORTED;
                               4377                 :                :         }
                               4378                 :                : 
 1263 ishii@postgresql.org     4379         [ +  + ]:           1689 :         if (!putVariableValue(&st->variables, argv[0], argv[1], &result))
                               4380                 :                :         {
 2355 alvherre@alvh.no-ip.     4381                 :              1 :             commandFailed(st, "set", "assignment of meta-command failed");
                               4382                 :              1 :             return CSTATE_ABORTED;
                               4383                 :                :         }
                               4384                 :                :     }
                               4385         [ +  + ]:            689 :     else if (command->meta == META_IF)
                               4386                 :                :     {
                               4387                 :                :         /* backslash commands with an expression to evaluate */
                               4388                 :            525 :         PgBenchExpr *expr = command->expr;
                               4389                 :                :         PgBenchValue result;
                               4390                 :                :         bool        cond;
                               4391                 :                : 
 2348 tgl@sss.pgh.pa.us        4392         [ -  + ]:            525 :         if (!evaluateExpr(st, expr, &result))
                               4393                 :                :         {
 2355 alvherre@alvh.no-ip.     4394                 :UBC           0 :             commandFailed(st, argv[0], "evaluation of meta-command failed");
                               4395                 :              0 :             return CSTATE_ABORTED;
                               4396                 :                :         }
                               4397                 :                : 
 2355 alvherre@alvh.no-ip.     4398                 :CBC         525 :         cond = valueTruth(&result);
                               4399         [ +  + ]:            525 :         conditional_stack_push(st->cstack, cond ? IFSTATE_TRUE : IFSTATE_FALSE);
                               4400                 :                :     }
                               4401         [ +  + ]:            164 :     else if (command->meta == META_ELIF)
                               4402                 :                :     {
                               4403                 :                :         /* backslash commands with an expression to evaluate */
                               4404                 :              7 :         PgBenchExpr *expr = command->expr;
                               4405                 :                :         PgBenchValue result;
                               4406                 :                :         bool        cond;
                               4407                 :                : 
                               4408         [ +  + ]:              7 :         if (conditional_stack_peek(st->cstack) == IFSTATE_TRUE)
                               4409                 :                :         {
                               4410                 :                :             /* elif after executed block, skip eval and wait for endif. */
                               4411                 :              2 :             conditional_stack_poke(st->cstack, IFSTATE_IGNORED);
                               4412                 :              2 :             return CSTATE_END_COMMAND;
                               4413                 :                :         }
                               4414                 :                : 
 2348 tgl@sss.pgh.pa.us        4415         [ -  + ]:              5 :         if (!evaluateExpr(st, expr, &result))
                               4416                 :                :         {
 2355 alvherre@alvh.no-ip.     4417                 :UBC           0 :             commandFailed(st, argv[0], "evaluation of meta-command failed");
                               4418                 :              0 :             return CSTATE_ABORTED;
                               4419                 :                :         }
                               4420                 :                : 
 2355 alvherre@alvh.no-ip.     4421                 :CBC           5 :         cond = valueTruth(&result);
                               4422         [ -  + ]:              5 :         Assert(conditional_stack_peek(st->cstack) == IFSTATE_FALSE);
                               4423         [ +  + ]:              5 :         conditional_stack_poke(st->cstack, cond ? IFSTATE_TRUE : IFSTATE_FALSE);
                               4424                 :                :     }
                               4425         [ +  + ]:            157 :     else if (command->meta == META_ELSE)
                               4426                 :                :     {
                               4427         [ +  - ]:              2 :         switch (conditional_stack_peek(st->cstack))
                               4428                 :                :         {
                               4429                 :              2 :             case IFSTATE_TRUE:
                               4430                 :              2 :                 conditional_stack_poke(st->cstack, IFSTATE_ELSE_FALSE);
                               4431                 :              2 :                 break;
 2355 alvherre@alvh.no-ip.     4432                 :UBC           0 :             case IFSTATE_FALSE: /* inconsistent if active */
                               4433                 :                :             case IFSTATE_IGNORED:   /* inconsistent if active */
                               4434                 :                :             case IFSTATE_NONE:  /* else without if */
                               4435                 :                :             case IFSTATE_ELSE_TRUE: /* else after else */
                               4436                 :                :             case IFSTATE_ELSE_FALSE:    /* else after else */
                               4437                 :                :             default:
                               4438                 :                :                 /* dead code if conditional check is ok */
                               4439                 :              0 :                 Assert(false);
                               4440                 :                :         }
                               4441                 :                :     }
 2355 alvherre@alvh.no-ip.     4442         [ +  + ]:CBC         155 :     else if (command->meta == META_ENDIF)
                               4443                 :                :     {
                               4444         [ -  + ]:             29 :         Assert(!conditional_stack_empty(st->cstack));
                               4445                 :             29 :         conditional_stack_pop(st->cstack);
                               4446                 :                :     }
                               4447         [ +  + ]:            126 :     else if (command->meta == META_SETSHELL)
                               4448                 :                :     {
 1263 ishii@postgresql.org     4449         [ +  + ]:              3 :         if (!runShellCommand(&st->variables, argv[1], argv + 2, argc - 2))
                               4450                 :                :         {
 2355 alvherre@alvh.no-ip.     4451                 :              2 :             commandFailed(st, "setshell", "execution of meta-command failed");
                               4452                 :              2 :             return CSTATE_ABORTED;
                               4453                 :                :         }
                               4454                 :                :     }
                               4455         [ +  + ]:            123 :     else if (command->meta == META_SHELL)
                               4456                 :                :     {
 1263 ishii@postgresql.org     4457         [ +  + ]:              3 :         if (!runShellCommand(&st->variables, NULL, argv + 1, argc - 1))
                               4458                 :                :         {
 2355 alvherre@alvh.no-ip.     4459                 :              2 :             commandFailed(st, "shell", "execution of meta-command failed");
                               4460                 :              2 :             return CSTATE_ABORTED;
                               4461                 :                :         }
                               4462                 :                :     }
 1636                          4463         [ +  + ]:            120 :     else if (command->meta == META_STARTPIPELINE)
                               4464                 :                :     {
                               4465                 :                :         /*
                               4466                 :                :          * In pipeline mode, we use a workflow based on libpq pipeline
                               4467                 :                :          * functions.
                               4468                 :                :          */
                               4469         [ -  + ]:             60 :         if (querymode == QUERY_SIMPLE)
                               4470                 :                :         {
 1636 alvherre@alvh.no-ip.     4471                 :UBC           0 :             commandFailed(st, "startpipeline", "cannot use pipeline mode with the simple query protocol");
                               4472                 :              0 :             return CSTATE_ABORTED;
                               4473                 :                :         }
                               4474                 :                : 
                               4475                 :                :         /*
                               4476                 :                :          * If we're in prepared-query mode, we need to prepare all the
                               4477                 :                :          * commands that are inside the pipeline before we actually start the
                               4478                 :                :          * pipeline itself.  This solves the problem that running BEGIN
                               4479                 :                :          * ISOLATION LEVEL SERIALIZABLE in a pipeline would fail due to a
                               4480                 :                :          * snapshot having been acquired by the prepare within the pipeline.
                               4481                 :                :          */
  928 alvherre@alvh.no-ip.     4482         [ +  + ]:CBC          60 :         if (querymode == QUERY_PREPARED)
                               4483                 :             42 :             prepareCommandsInPipeline(st);
                               4484                 :                : 
 1636                          4485         [ +  + ]:             60 :         if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
                               4486                 :                :         {
                               4487                 :              1 :             commandFailed(st, "startpipeline", "already in pipeline mode");
                               4488                 :              1 :             return CSTATE_ABORTED;
                               4489                 :                :         }
                               4490         [ -  + ]:             59 :         if (PQenterPipelineMode(st->con) == 0)
                               4491                 :                :         {
 1636 alvherre@alvh.no-ip.     4492                 :UBC           0 :             commandFailed(st, "startpipeline", "failed to enter pipeline mode");
                               4493                 :              0 :             return CSTATE_ABORTED;
                               4494                 :                :         }
                               4495                 :                :     }
  591 michael@paquier.xyz      4496         [ +  + ]:CBC          60 :     else if (command->meta == META_SYNCPIPELINE)
                               4497                 :                :     {
                               4498         [ -  + ]:              5 :         if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
                               4499                 :                :         {
  591 michael@paquier.xyz      4500                 :UBC           0 :             commandFailed(st, "syncpipeline", "not in pipeline mode");
                               4501                 :              0 :             return CSTATE_ABORTED;
                               4502                 :                :         }
  591 michael@paquier.xyz      4503         [ -  + ]:CBC           5 :         if (PQsendPipelineSync(st->con) == 0)
                               4504                 :                :         {
  591 michael@paquier.xyz      4505                 :UBC           0 :             commandFailed(st, "syncpipeline", "failed to send a pipeline sync");
                               4506                 :              0 :             return CSTATE_ABORTED;
                               4507                 :                :         }
  591 michael@paquier.xyz      4508                 :CBC           5 :         st->num_syncs++;
                               4509                 :                :     }
 1636 alvherre@alvh.no-ip.     4510         [ +  - ]:             55 :     else if (command->meta == META_ENDPIPELINE)
                               4511                 :                :     {
                               4512         [ +  + ]:             55 :         if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
                               4513                 :                :         {
                               4514                 :              1 :             commandFailed(st, "endpipeline", "not in pipeline mode");
                               4515                 :              1 :             return CSTATE_ABORTED;
                               4516                 :                :         }
                               4517         [ -  + ]:             54 :         if (!PQpipelineSync(st->con))
                               4518                 :                :         {
 1636 alvherre@alvh.no-ip.     4519                 :UBC           0 :             commandFailed(st, "endpipeline", "failed to send a pipeline sync");
                               4520                 :              0 :             return CSTATE_ABORTED;
                               4521                 :                :         }
  591 michael@paquier.xyz      4522                 :CBC          54 :         st->num_syncs++;
                               4523                 :                :         /* Now wait for the PGRES_PIPELINE_SYNC and exit pipeline mode there */
                               4524                 :                :         /* collect pending results before getting out of pipeline mode */
 1636 alvherre@alvh.no-ip.     4525                 :             54 :         return CSTATE_WAIT_RESULT;
                               4526                 :                :     }
                               4527                 :                : 
                               4528                 :                :     /*
                               4529                 :                :      * executing the expression or shell command might have taken a
                               4530                 :                :      * non-negligible amount of time, so reset 'now'
                               4531                 :                :      */
 1641 tmunro@postgresql.or     4532                 :           2315 :     *now = 0;
                               4533                 :                : 
 2355 alvherre@alvh.no-ip.     4534                 :           2315 :     return CSTATE_END_COMMAND;
                               4535                 :                : }
                               4536                 :                : 
                               4537                 :                : /*
                               4538                 :                :  * Return the number of failed transactions.
                               4539                 :                :  */
                               4540                 :                : static int64
 1263 ishii@postgresql.org     4541                 :             98 : getFailures(const StatsData *stats)
                               4542                 :                : {
                               4543                 :            196 :     return (stats->serialization_failures +
                               4544                 :             98 :             stats->deadlock_failures);
                               4545                 :                : }
                               4546                 :                : 
                               4547                 :                : /*
                               4548                 :                :  * Return a string constant representing the result of a transaction
                               4549                 :                :  * that is not successfully processed.
                               4550                 :                :  */
                               4551                 :                : static const char *
 1263 ishii@postgresql.org     4552                 :UBC           0 : getResultString(bool skipped, EStatus estatus)
                               4553                 :                : {
                               4554         [ #  # ]:              0 :     if (skipped)
                               4555                 :              0 :         return "skipped";
                               4556         [ #  # ]:              0 :     else if (failures_detailed)
                               4557                 :                :     {
                               4558      [ #  #  # ]:              0 :         switch (estatus)
                               4559                 :                :         {
                               4560                 :              0 :             case ESTATUS_SERIALIZATION_ERROR:
                               4561                 :              0 :                 return "serialization";
                               4562                 :              0 :             case ESTATUS_DEADLOCK_ERROR:
                               4563                 :              0 :                 return "deadlock";
                               4564                 :              0 :             default:
                               4565                 :                :                 /* internal error which should never occur */
 1247 tgl@sss.pgh.pa.us        4566                 :              0 :                 pg_fatal("unexpected error status: %d", estatus);
                               4567                 :                :         }
                               4568                 :                :     }
                               4569                 :                :     else
 1263 ishii@postgresql.org     4570                 :              0 :         return "failed";
                               4571                 :                : }
                               4572                 :                : 
                               4573                 :                : /*
                               4574                 :                :  * Print log entry after completing one transaction.
                               4575                 :                :  *
                               4576                 :                :  * We print Unix-epoch timestamps in the log, so that entries can be
                               4577                 :                :  * correlated against other logs.
                               4578                 :                :  *
                               4579                 :                :  * XXX We could obtain the time from the caller and just shift it here, to
                               4580                 :                :  * avoid the cost of an extra call to pg_time_now().
                               4581                 :                :  */
                               4582                 :                : static void
 3169 tgl@sss.pgh.pa.us        4583                 :CBC         110 : doLog(TState *thread, CState *st,
                               4584                 :                :       StatsData *agg, bool skipped, double latency, double lag)
                               4585                 :                : {
 3376 rhaas@postgresql.org     4586                 :            110 :     FILE       *logfile = thread->logfile;
 1518 tmunro@postgresql.or     4587                 :            110 :     pg_time_usec_t now = pg_time_now() + epoch_shift;
                               4588                 :                : 
 3494 alvherre@alvh.no-ip.     4589         [ -  + ]:            110 :     Assert(use_log);
                               4590                 :                : 
                               4591                 :                :     /*
                               4592                 :                :      * Skip the log entry if sampling is enabled and this row doesn't belong
                               4593                 :                :      * to the random sample.
                               4594                 :                :      */
 3992 heikki.linnakangas@i     4595         [ +  + ]:            110 :     if (sample_rate != 0.0 &&
 1378 tgl@sss.pgh.pa.us        4596         [ +  + ]:            100 :         pg_prng_double(&thread->ts_sample_rs) > sample_rate)
 3992 heikki.linnakangas@i     4597                 :             53 :         return;
                               4598                 :                : 
                               4599                 :                :     /* should we aggregate the results or not? */
                               4600         [ -  + ]:             57 :     if (agg_interval > 0)
                               4601                 :                :     {
                               4602                 :                :         pg_time_usec_t next;
                               4603                 :                : 
                               4604                 :                :         /*
                               4605                 :                :          * Loop until we reach the interval of the current moment, and print
                               4606                 :                :          * any empty intervals in between (this may happen with very low tps,
                               4607                 :                :          * e.g. --rate=0.1).
                               4608                 :                :          */
                               4609                 :                : 
 1518 tmunro@postgresql.or     4610         [ #  # ]:UBC           0 :         while ((next = agg->start_time + agg_interval * INT64CONST(1000000)) <= now)
                               4611                 :                :         {
 1249 ishii@postgresql.org     4612                 :              0 :             double      lag_sum = 0.0;
                               4613                 :              0 :             double      lag_sum2 = 0.0;
                               4614                 :              0 :             double      lag_min = 0.0;
                               4615                 :              0 :             double      lag_max = 0.0;
                               4616                 :              0 :             int64       skipped = 0;
                               4617                 :              0 :             int64       serialization_failures = 0;
                               4618                 :              0 :             int64       deadlock_failures = 0;
                               4619                 :              0 :             int64       retried = 0;
                               4620                 :              0 :             int64       retries = 0;
                               4621                 :                : 
                               4622                 :                :             /* print aggregated report to logfile */
 1641 tmunro@postgresql.or     4623                 :              0 :             fprintf(logfile, INT64_FORMAT " " INT64_FORMAT " %.0f %.0f %.0f %.0f",
 1518                          4624                 :              0 :                     agg->start_time / 1000000,   /* seconds since Unix epoch */
                               4625                 :                :                     agg->cnt,
                               4626                 :                :                     agg->latency.sum,
                               4627                 :                :                     agg->latency.sum2,
                               4628                 :                :                     agg->latency.min,
                               4629                 :                :                     agg->latency.max);
                               4630                 :                : 
 3508 alvherre@alvh.no-ip.     4631         [ #  # ]:              0 :             if (throttle_delay)
                               4632                 :                :             {
 1249 ishii@postgresql.org     4633                 :              0 :                 lag_sum = agg->lag.sum;
                               4634                 :              0 :                 lag_sum2 = agg->lag.sum2;
                               4635                 :              0 :                 lag_min = agg->lag.min;
                               4636                 :              0 :                 lag_max = agg->lag.max;
                               4637                 :                :             }
                               4638                 :              0 :             fprintf(logfile, " %.0f %.0f %.0f %.0f",
                               4639                 :                :                     lag_sum,
                               4640                 :                :                     lag_sum2,
                               4641                 :                :                     lag_min,
                               4642                 :                :                     lag_max);
                               4643                 :                : 
                               4644         [ #  # ]:              0 :             if (latency_limit)
                               4645                 :              0 :                 skipped = agg->skipped;
                               4646                 :              0 :             fprintf(logfile, " " INT64_FORMAT, skipped);
                               4647                 :                : 
 1263                          4648         [ #  # ]:              0 :             if (max_tries != 1)
                               4649                 :                :             {
 1249                          4650                 :              0 :                 retried = agg->retried;
                               4651                 :              0 :                 retries = agg->retries;
                               4652                 :                :             }
                               4653                 :              0 :             fprintf(logfile, " " INT64_FORMAT " " INT64_FORMAT, retried, retries);
                               4654                 :                : 
                               4655         [ #  # ]:              0 :             if (failures_detailed)
                               4656                 :                :             {
                               4657                 :              0 :                 serialization_failures = agg->serialization_failures;
                               4658                 :              0 :                 deadlock_failures = agg->deadlock_failures;
                               4659                 :                :             }
 1236                          4660                 :              0 :             fprintf(logfile, " " INT64_FORMAT " " INT64_FORMAT,
                               4661                 :                :                     serialization_failures,
                               4662                 :                :                     deadlock_failures);
                               4663                 :                : 
 3508 alvherre@alvh.no-ip.     4664                 :              0 :             fputc('\n', logfile);
                               4665                 :                : 
                               4666                 :                :             /* reset data and move to next interval */
 1518 tmunro@postgresql.or     4667                 :              0 :             initStats(agg, next);
                               4668                 :                :         }
                               4669                 :                : 
                               4670                 :                :         /* accumulate the current transaction */
 1263 ishii@postgresql.org     4671                 :              0 :         accumStats(agg, skipped, latency, lag, st->estatus, st->tries);
                               4672                 :                :     }
                               4673                 :                :     else
                               4674                 :                :     {
                               4675                 :                :         /* no, print raw transactions */
 1263 ishii@postgresql.org     4676   [ +  -  +  - ]:CBC          57 :         if (!skipped && st->estatus == ESTATUS_NO_ERROR)
 1641 tmunro@postgresql.or     4677                 :             57 :             fprintf(logfile, "%d " INT64_FORMAT " %.0f %d " INT64_FORMAT " "
                               4678                 :                :                     INT64_FORMAT,
                               4679                 :                :                     st->id, st->cnt, latency, st->use_file,
                               4680                 :                :                     now / 1000000, now % 1000000);
                               4681                 :                :         else
 1263 ishii@postgresql.org     4682                 :UBC           0 :             fprintf(logfile, "%d " INT64_FORMAT " %s %d " INT64_FORMAT " "
                               4683                 :                :                     INT64_FORMAT,
                               4684                 :                :                     st->id, st->cnt, getResultString(skipped, st->estatus),
                               4685                 :                :                     st->use_file, now / 1000000, now % 1000000);
                               4686                 :                : 
 3992 heikki.linnakangas@i     4687         [ -  + ]:CBC          57 :         if (throttle_delay)
 3992 heikki.linnakangas@i     4688                 :UBC           0 :             fprintf(logfile, " %.0f", lag);
 1263 ishii@postgresql.org     4689         [ -  + ]:CBC          57 :         if (max_tries != 1)
 1235 peter@eisentraut.org     4690                 :UBC           0 :             fprintf(logfile, " %u", st->tries - 1);
 3992 heikki.linnakangas@i     4691                 :CBC          57 :         fputc('\n', logfile);
                               4692                 :                :     }
                               4693                 :                : }
                               4694                 :                : 
                               4695                 :                : /*
                               4696                 :                :  * Accumulate and report statistics at end of a transaction.
                               4697                 :                :  *
                               4698                 :                :  * (This is also called when a transaction is late and thus skipped.
                               4699                 :                :  * Note that even skipped and failed transactions are counted in the CState
                               4700                 :                :  * "cnt" field.)
                               4701                 :                :  */
                               4702                 :                : static void
 1641 tmunro@postgresql.or     4703                 :           7700 : processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
                               4704                 :                :                  bool skipped, StatsData *agg)
                               4705                 :                : {
 3508 alvherre@alvh.no-ip.     4706                 :           7700 :     double      latency = 0.0,
                               4707                 :           7700 :                 lag = 0.0;
 1263 ishii@postgresql.org     4708   [ +  +  +  -  :           7700 :     bool        detailed = progress || throttle_delay || latency_limit ||
                                              +  + ]
  841 tgl@sss.pgh.pa.us        4709   [ +  -  +  + ]:          15400 :         use_log || per_script_stats;
                               4710                 :                : 
 1263 ishii@postgresql.org     4711   [ +  +  +  +  :           7700 :     if (detailed && !skipped && st->estatus == ESTATUS_NO_ERROR)
                                              +  - ]
                               4712                 :                :     {
 1641 tmunro@postgresql.or     4713                 :           1661 :         pg_time_now_lazy(now);
                               4714                 :                : 
                               4715                 :                :         /* compute latency & lag */
                               4716                 :           1661 :         latency = (*now) - st->txn_scheduled;
                               4717                 :           1661 :         lag = st->txn_begin - st->txn_scheduled;
                               4718                 :                :     }
                               4719                 :                : 
                               4720                 :                :     /* keep detailed thread stats */
 1263 ishii@postgresql.org     4721                 :           7700 :     accumStats(&thread->stats, skipped, latency, lag, st->estatus, st->tries);
                               4722                 :                : 
                               4723                 :                :     /* count transactions over the latency limit, if needed */
                               4724   [ +  +  +  + ]:           7700 :     if (latency_limit && latency > latency_limit)
                               4725                 :              1 :         thread->latency_late++;
                               4726                 :                : 
                               4727                 :                :     /* client stat is just counting */
 2924 tgl@sss.pgh.pa.us        4728                 :           7700 :     st->cnt++;
                               4729                 :                : 
 3508 alvherre@alvh.no-ip.     4730         [ +  + ]:           7700 :     if (use_log)
 3169 tgl@sss.pgh.pa.us        4731                 :            110 :         doLog(thread, st, agg, skipped, latency, lag);
                               4732                 :                : 
                               4733                 :                :     /* XXX could use a mutex here, but we choose not to */
 3505 alvherre@alvh.no-ip.     4734         [ +  + ]:           7700 :     if (per_script_stats)
 1263 ishii@postgresql.org     4735                 :           1350 :         accumStats(&sql_script[st->use_file].stats, skipped, latency, lag,
                               4736                 :           1350 :                    st->estatus, st->tries);
 3508 alvherre@alvh.no-ip.     4737                 :           7700 : }
                               4738                 :                : 
                               4739                 :                : 
                               4740                 :                : /* discard connections */
                               4741                 :                : static void
 5878 ishii@postgresql.org     4742                 :            170 : disconnect_all(CState *state, int length)
                               4743                 :                : {
                               4744                 :                :     int         i;
                               4745                 :                : 
                               4746         [ +  + ]:            418 :     for (i = 0; i < length; i++)
 2746 andres@anarazel.de       4747                 :            248 :         finishCon(&state[i]);
 9366 ishii@postgresql.org     4748                 :            170 : }
                               4749                 :                : 
                               4750                 :                : /*
                               4751                 :                :  * Remove old pgbench tables, if any exist
                               4752                 :                :  */
                               4753                 :                : static void
 2854 tgl@sss.pgh.pa.us        4754                 :              3 : initDropTables(PGconn *con)
                               4755                 :                : {
                               4756                 :              3 :     fprintf(stderr, "dropping old tables...\n");
                               4757                 :                : 
                               4758                 :                :     /*
                               4759                 :                :      * We drop all the tables in one command, so that whether there are
                               4760                 :                :      * foreign key dependencies or not doesn't matter.
                               4761                 :                :      */
                               4762                 :              3 :     executeStatement(con, "drop table if exists "
                               4763                 :                :                      "pgbench_accounts, "
                               4764                 :                :                      "pgbench_branches, "
                               4765                 :                :                      "pgbench_history, "
                               4766                 :                :                      "pgbench_tellers");
                               4767                 :              3 : }
                               4768                 :                : 
                               4769                 :                : /*
                               4770                 :                :  * Create "pgbench_accounts" partitions if needed.
                               4771                 :                :  *
                               4772                 :                :  * This is the larger table of pgbench default tpc-b like schema
                               4773                 :                :  * with a known size, so we choose to partition it.
                               4774                 :                :  */
                               4775                 :                : static void
 2167 akapila@postgresql.o     4776                 :              2 : createPartitions(PGconn *con)
                               4777                 :                : {
                               4778                 :                :     PQExpBufferData query;
                               4779                 :                : 
                               4780                 :                :     /* we must have to create some partitions */
                               4781         [ -  + ]:              2 :     Assert(partitions > 0);
                               4782                 :                : 
                               4783                 :              2 :     fprintf(stderr, "creating %d partitions...\n", partitions);
                               4784                 :                : 
 1802 heikki.linnakangas@i     4785                 :              2 :     initPQExpBuffer(&query);
                               4786                 :                : 
 2167 akapila@postgresql.o     4787         [ +  + ]:              7 :     for (int p = 1; p <= partitions; p++)
                               4788                 :                :     {
                               4789         [ +  + ]:              5 :         if (partition_method == PART_RANGE)
                               4790                 :                :         {
                               4791                 :              3 :             int64       part_size = (naccounts * (int64) scale + partitions - 1) / partitions;
                               4792                 :                : 
 1802 heikki.linnakangas@i     4793                 :              3 :             printfPQExpBuffer(&query,
                               4794                 :                :                               "create%s table pgbench_accounts_%d\n"
                               4795                 :                :                               "  partition of pgbench_accounts\n"
                               4796                 :                :                               "  for values from (",
                               4797         [ +  - ]:              3 :                               unlogged_tables ? " unlogged" : "", p);
                               4798                 :                : 
                               4799                 :                :             /*
                               4800                 :                :              * For RANGE, we use open-ended partitions at the beginning and
                               4801                 :                :              * end to allow any valid value for the primary key.  Although the
                               4802                 :                :              * actual minimum and maximum values can be derived from the
                               4803                 :                :              * scale, it is more generic and the performance is better.
                               4804                 :                :              */
 2167 akapila@postgresql.o     4805         [ +  + ]:              3 :             if (p == 1)
 1802 heikki.linnakangas@i     4806                 :              1 :                 appendPQExpBufferStr(&query, "minvalue");
                               4807                 :                :             else
                               4808                 :              2 :                 appendPQExpBuffer(&query, INT64_FORMAT, (p - 1) * part_size + 1);
                               4809                 :                : 
                               4810                 :              3 :             appendPQExpBufferStr(&query, ") to (");
                               4811                 :                : 
 2167 akapila@postgresql.o     4812         [ +  + ]:              3 :             if (p < partitions)
 1802 heikki.linnakangas@i     4813                 :              2 :                 appendPQExpBuffer(&query, INT64_FORMAT, p * part_size + 1);
                               4814                 :                :             else
                               4815                 :              1 :                 appendPQExpBufferStr(&query, "maxvalue");
                               4816                 :                : 
                               4817                 :              3 :             appendPQExpBufferChar(&query, ')');
                               4818                 :                :         }
 2167 akapila@postgresql.o     4819         [ +  - ]:              2 :         else if (partition_method == PART_HASH)
 1802 heikki.linnakangas@i     4820                 :              2 :             printfPQExpBuffer(&query,
                               4821                 :                :                               "create%s table pgbench_accounts_%d\n"
                               4822                 :                :                               "  partition of pgbench_accounts\n"
                               4823                 :                :                               "  for values with (modulus %d, remainder %d)",
                               4824         [ +  - ]:              2 :                               unlogged_tables ? " unlogged" : "", p,
                               4825                 :                :                               partitions, p - 1);
                               4826                 :                :         else                    /* cannot get there */
 2167 akapila@postgresql.o     4827                 :UBC           0 :             Assert(0);
                               4828                 :                : 
                               4829                 :                :         /*
                               4830                 :                :          * Per ddlinfo in initCreateTables, fillfactor is needed on table
                               4831                 :                :          * pgbench_accounts.
                               4832                 :                :          */
 1802 heikki.linnakangas@i     4833                 :CBC           5 :         appendPQExpBuffer(&query, " with (fillfactor=%d)", fillfactor);
                               4834                 :                : 
                               4835                 :              5 :         executeStatement(con, query.data);
                               4836                 :                :     }
                               4837                 :                : 
                               4838                 :              2 :     termPQExpBuffer(&query);
 2167 akapila@postgresql.o     4839                 :              2 : }
                               4840                 :                : 
                               4841                 :                : /*
                               4842                 :                :  * Create pgbench's standard tables
                               4843                 :                :  */
                               4844                 :                : static void
 2854 tgl@sss.pgh.pa.us        4845                 :              3 : initCreateTables(PGconn *con)
                               4846                 :                : {
                               4847                 :                :     /*
                               4848                 :                :      * Note: TPC-B requires at least 100 bytes per row, and the "filler"
                               4849                 :                :      * fields in these table declarations were intended to comply with that.
                               4850                 :                :      * The pgbench_accounts table complies with that because the "filler"
                               4851                 :                :      * column is set to blank-padded empty string. But for all other tables
                               4852                 :                :      * the columns default to NULL and so don't actually take any space.  We
                               4853                 :                :      * could fix that by giving them non-null default values.  However, that
                               4854                 :                :      * would completely break comparability of pgbench results with prior
                               4855                 :                :      * versions. Since pgbench has never pretended to be fully TPC-B compliant
                               4856                 :                :      * anyway, we stick with the historical behavior.
                               4857                 :                :      */
                               4858                 :                :     struct ddlinfo
                               4859                 :                :     {
                               4860                 :                :         const char *table;      /* table name */
                               4861                 :                :         const char *smcols;     /* column decls if accountIDs are 32 bits */
                               4862                 :                :         const char *bigcols;    /* column decls if accountIDs are 64 bits */
                               4863                 :                :         int         declare_fillfactor;
                               4864                 :                :     };
                               4865                 :                :     static const struct ddlinfo DDLs[] = {
                               4866                 :                :         {
                               4867                 :                :             "pgbench_history",
                               4868                 :                :             "tid int,bid int,aid    int,delta int,mtime timestamp,filler char(22)",
                               4869                 :                :             "tid int,bid int,aid bigint,delta int,mtime timestamp,filler char(22)",
                               4870                 :                :             0
                               4871                 :                :         },
                               4872                 :                :         {
                               4873                 :                :             "pgbench_tellers",
                               4874                 :                :             "tid int not null,bid int,tbalance int,filler char(84)",
                               4875                 :                :             "tid int not null,bid int,tbalance int,filler char(84)",
                               4876                 :                :             1
                               4877                 :                :         },
                               4878                 :                :         {
                               4879                 :                :             "pgbench_accounts",
                               4880                 :                :             "aid    int not null,bid int,abalance int,filler char(84)",
                               4881                 :                :             "aid bigint not null,bid int,abalance int,filler char(84)",
                               4882                 :                :             1
                               4883                 :                :         },
                               4884                 :                :         {
                               4885                 :                :             "pgbench_branches",
                               4886                 :                :             "bid int not null,bbalance int,filler char(88)",
                               4887                 :                :             "bid int not null,bbalance int,filler char(88)",
                               4888                 :                :             1
                               4889                 :                :         }
                               4890                 :                :     };
                               4891                 :                :     int         i;
                               4892                 :                :     PQExpBufferData query;
                               4893                 :                : 
                               4894                 :              3 :     fprintf(stderr, "creating tables...\n");
                               4895                 :                : 
 1802 heikki.linnakangas@i     4896                 :              3 :     initPQExpBuffer(&query);
                               4897                 :                : 
 6728 ishii@postgresql.org     4898         [ +  + ]:             15 :     for (i = 0; i < lengthof(DDLs); i++)
                               4899                 :                :     {
 4128 tgl@sss.pgh.pa.us        4900                 :             12 :         const struct ddlinfo *ddl = &DDLs[i];
                               4901                 :                : 
                               4902                 :                :         /* Construct new create table statement. */
 1802 heikki.linnakangas@i     4903                 :             24 :         printfPQExpBuffer(&query, "create%s table %s(%s)",
  338 michael@paquier.xyz      4904         [ -  + ]:              8 :                           (unlogged_tables && partition_method == PART_NONE) ? " unlogged" : "",
 1802 heikki.linnakangas@i     4905         [ +  + ]:             12 :                           ddl->table,
                               4906         [ -  + ]:             12 :                           (scale >= SCALE_32BIT_THRESHOLD) ? ddl->bigcols : ddl->smcols);
                               4907                 :                : 
                               4908                 :                :         /* Partition pgbench_accounts table */
 2167 akapila@postgresql.o     4909   [ +  +  +  + ]:             12 :         if (partition_method != PART_NONE && strcmp(ddl->table, "pgbench_accounts") == 0)
 1802 heikki.linnakangas@i     4910                 :              2 :             appendPQExpBuffer(&query,
                               4911                 :              2 :                               " partition by %s (aid)", PARTITION_METHOD[partition_method]);
 2167 akapila@postgresql.o     4912         [ +  + ]:             10 :         else if (ddl->declare_fillfactor)
                               4913                 :                :         {
                               4914                 :                :             /* fillfactor is only expected on actual tables */
 1802 heikki.linnakangas@i     4915                 :              7 :             appendPQExpBuffer(&query, " with (fillfactor=%d)", fillfactor);
                               4916                 :                :         }
                               4917                 :                : 
 5157 rhaas@postgresql.org     4918         [ +  + ]:             12 :         if (tablespace != NULL)
                               4919                 :                :         {
                               4920                 :                :             char       *escape_tablespace;
                               4921                 :                : 
 1802 heikki.linnakangas@i     4922                 :              4 :             escape_tablespace = PQescapeIdentifier(con, tablespace, strlen(tablespace));
                               4923                 :              4 :             appendPQExpBuffer(&query, " tablespace %s", escape_tablespace);
 5157 rhaas@postgresql.org     4924                 :              4 :             PQfreemem(escape_tablespace);
                               4925                 :                :         }
                               4926                 :                : 
 1802 heikki.linnakangas@i     4927                 :             12 :         executeStatement(con, query.data);
                               4928                 :                :     }
                               4929                 :                : 
                               4930                 :              3 :     termPQExpBuffer(&query);
                               4931                 :                : 
 2167 akapila@postgresql.o     4932         [ +  + ]:              3 :     if (partition_method != PART_NONE)
                               4933                 :              2 :         createPartitions(con);
                               4934                 :              3 : }
                               4935                 :                : 
                               4936                 :                : /*
                               4937                 :                :  * Truncate away any old data, in one command in case there are foreign keys
                               4938                 :                :  */
                               4939                 :                : static void
 2131 fujii@postgresql.org     4940                 :              3 : initTruncateTables(PGconn *con)
                               4941                 :                : {
                               4942                 :              3 :     executeStatement(con, "truncate table "
                               4943                 :                :                      "pgbench_accounts, "
                               4944                 :                :                      "pgbench_branches, "
                               4945                 :                :                      "pgbench_history, "
                               4946                 :                :                      "pgbench_tellers");
                               4947                 :              3 : }
                               4948                 :                : 
                               4949                 :                : static void
  775 michael@paquier.xyz      4950                 :              2 : initBranch(PQExpBufferData *sql, int64 curr)
                               4951                 :                : {
                               4952                 :                :     /* "filler" column uses NULL */
                               4953                 :              2 :     printfPQExpBuffer(sql,
                               4954                 :                :                       INT64_FORMAT "\t0\t\\N\n",
                               4955                 :                :                       curr + 1);
                               4956                 :              2 : }
                               4957                 :                : 
                               4958                 :                : static void
                               4959                 :             20 : initTeller(PQExpBufferData *sql, int64 curr)
                               4960                 :                : {
                               4961                 :                :     /* "filler" column uses NULL */
                               4962                 :             20 :     printfPQExpBuffer(sql,
                               4963                 :                :                       INT64_FORMAT "\t" INT64_FORMAT "\t0\t\\N\n",
                               4964                 :             20 :                       curr + 1, curr / ntellers + 1);
                               4965                 :             20 : }
                               4966                 :                : 
                               4967                 :                : static void
                               4968                 :         200000 : initAccount(PQExpBufferData *sql, int64 curr)
                               4969                 :                : {
                               4970                 :                :     /* "filler" column defaults to blank padded empty string */
                               4971                 :         200000 :     printfPQExpBuffer(sql,
                               4972                 :                :                       INT64_FORMAT "\t" INT64_FORMAT "\t0\t\n",
                               4973                 :         200000 :                       curr + 1, curr / naccounts + 1);
                               4974                 :         200000 : }
                               4975                 :                : 
                               4976                 :                : static void
                               4977                 :              6 : initPopulateTable(PGconn *con, const char *table, int64 base,
                               4978                 :                :                   initRowMethod init_row)
                               4979                 :                : {
                               4980                 :                :     int         n;
                               4981                 :                :     int64       k;
                               4982                 :              6 :     int         chars = 0;
  283 fujii@postgresql.org     4983                 :              6 :     int         prev_chars = 0;
                               4984                 :                :     PGresult   *res;
                               4985                 :                :     PQExpBufferData sql;
                               4986                 :                :     char        copy_statement[256];
  775 michael@paquier.xyz      4987                 :              6 :     const char *copy_statement_fmt = "copy %s from stdin";
                               4988                 :              6 :     int64       total = base * scale;
                               4989                 :                : 
                               4990                 :                :     /* used to track elapsed time and estimate of the remaining time */
                               4991                 :                :     pg_time_usec_t start;
 2854 tgl@sss.pgh.pa.us        4992                 :              6 :     int         log_interval = 1;
                               4993                 :                : 
                               4994                 :                :     /* Stay on the same line if reporting to a terminal */
 2103 michael@paquier.xyz      4995         [ -  + ]:              6 :     char        eol = isatty(fileno(stderr)) ? '\r' : '\n';
                               4996                 :                : 
 1802 heikki.linnakangas@i     4997                 :              6 :     initPQExpBuffer(&sql);
                               4998                 :                : 
                               4999                 :                :     /* Use COPY with FREEZE on v14 and later for all ordinary tables */
  207 melanieplageman@gmai     5000   [ +  -  +  + ]:             12 :     if ((PQserverVersion(con) >= 140000) &&
                               5001                 :              6 :         get_table_relkind(con, table) == RELKIND_RELATION)
                               5002                 :              5 :         copy_statement_fmt = "copy %s from stdin with (freeze on)";
                               5003                 :                : 
                               5004                 :                : 
  775 michael@paquier.xyz      5005                 :              6 :     n = pg_snprintf(copy_statement, sizeof(copy_statement), copy_statement_fmt, table);
                               5006         [ -  + ]:              6 :     if (n >= sizeof(copy_statement))
  775 michael@paquier.xyz      5007                 :UBC           0 :         pg_fatal("invalid buffer size: must be at least %d characters long", n);
  775 michael@paquier.xyz      5008         [ -  + ]:CBC           6 :     else if (n == -1)
  775 michael@paquier.xyz      5009                 :UBC           0 :         pg_fatal("invalid format string");
                               5010                 :                : 
 1465 ishii@postgresql.org     5011                 :CBC           6 :     res = PQexec(con, copy_statement);
                               5012                 :                : 
 6728                          5013         [ -  + ]:              6 :     if (PQresultStatus(res) != PGRES_COPY_IN)
 1247 tgl@sss.pgh.pa.us        5014                 :UBC           0 :         pg_fatal("unexpected copy in result: %s", PQerrorMessage(con));
 7754 ishii@postgresql.org     5015                 :CBC           6 :     PQclear(res);
                               5016                 :                : 
 1641 tmunro@postgresql.or     5017                 :              6 :     start = pg_time_now();
                               5018                 :                : 
  775 michael@paquier.xyz      5019         [ +  + ]:         200028 :     for (k = 0; k < total; k++)
                               5020                 :                :     {
 4603 heikki.linnakangas@i     5021                 :         200022 :         int64       j = k + 1;
                               5022                 :                : 
  775 michael@paquier.xyz      5023                 :         200022 :         init_row(&sql, k);
 1802 heikki.linnakangas@i     5024         [ -  + ]:         200022 :         if (PQputline(con, sql.data))
 1247 tgl@sss.pgh.pa.us        5025                 :UBC           0 :             pg_fatal("PQputline failed");
                               5026                 :                : 
 2105 michael@paquier.xyz      5027         [ -  + ]:CBC      200022 :         if (CancelRequested)
 2105 michael@paquier.xyz      5028                 :UBC           0 :             break;
                               5029                 :                : 
                               5030                 :                :         /*
                               5031                 :                :          * If we want to stick with the original logging, print a message each
                               5032                 :                :          * 100k inserted rows.
                               5033                 :                :          */
 4483 bruce@momjian.us         5034   [ +  +  +  + ]:CBC      200022 :         if ((!use_quiet) && (j % 100000 == 0))
 4625 ishii@postgresql.org     5035                 :              1 :         {
 1641 tmunro@postgresql.or     5036                 :              1 :             double      elapsed_sec = PG_TIME_GET_DOUBLE(pg_time_now() - start);
  775 michael@paquier.xyz      5037                 :              1 :             double      remaining_sec = ((double) total - j) * elapsed_sec / j;
                               5038                 :                : 
  283 fujii@postgresql.org     5039                 :              1 :             chars = fprintf(stderr, INT64_FORMAT " of " INT64_FORMAT " tuples (%d%%) of %s done (elapsed %.2f s, remaining %.2f s)",
                               5040                 :                :                             j, total,
  775 michael@paquier.xyz      5041                 :              1 :                             (int) ((j * 100) / total),
                               5042                 :                :                             table, elapsed_sec, remaining_sec);
                               5043                 :                : 
                               5044                 :                :             /*
                               5045                 :                :              * If the previous progress message is longer than the current
                               5046                 :                :              * one, add spaces to the current line to fully overwrite any
                               5047                 :                :              * remaining characters from the previous message.
                               5048                 :                :              */
  211 tgl@sss.pgh.pa.us        5049         [ -  + ]:              1 :             if (prev_chars > chars)
  211 tgl@sss.pgh.pa.us        5050                 :UBC           0 :                 fprintf(stderr, "%*c", prev_chars - chars, ' ');
  211 tgl@sss.pgh.pa.us        5051                 :CBC           1 :             fputc(eol, stderr);
                               5052                 :              1 :             prev_chars = chars;
                               5053                 :                :         }
                               5054                 :                :         /* let's not call the timing for each row, but only each 100 rows */
 4625 ishii@postgresql.org     5055   [ +  +  +  + ]:         200021 :         else if (use_quiet && (j % 100 == 0))
                               5056                 :                :         {
 1641 tmunro@postgresql.or     5057                 :           1000 :             double      elapsed_sec = PG_TIME_GET_DOUBLE(pg_time_now() - start);
  775 michael@paquier.xyz      5058                 :           1000 :             double      remaining_sec = ((double) total - j) * elapsed_sec / j;
                               5059                 :                : 
                               5060                 :                :             /* have we reached the next interval (or end)? */
                               5061   [ +  +  -  + ]:           1000 :             if ((j == total) || (elapsed_sec >= log_interval * LOG_STEP_SECONDS))
                               5062                 :                :             {
  283 fujii@postgresql.org     5063                 :              1 :                 chars = fprintf(stderr, INT64_FORMAT " of " INT64_FORMAT " tuples (%d%%) of %s done (elapsed %.2f s, remaining %.2f s)",
                               5064                 :                :                                 j, total,
  775 michael@paquier.xyz      5065                 :              1 :                                 (int) ((j * 100) / total),
                               5066                 :                :                                 table, elapsed_sec, remaining_sec);
                               5067                 :                : 
                               5068                 :                :                 /*
                               5069                 :                :                  * If the previous progress message is longer than the current
                               5070                 :                :                  * one, add spaces to the current line to fully overwrite any
                               5071                 :                :                  * remaining characters from the previous message.
                               5072                 :                :                  */
  211 tgl@sss.pgh.pa.us        5073         [ -  + ]:              1 :                 if (prev_chars > chars)
  211 tgl@sss.pgh.pa.us        5074                 :UBC           0 :                     fprintf(stderr, "%*c", prev_chars - chars, ' ');
  211 tgl@sss.pgh.pa.us        5075                 :CBC           1 :                 fputc(eol, stderr);
                               5076                 :              1 :                 prev_chars = chars;
                               5077                 :                : 
                               5078                 :                :                 /* skip to the next interval */
 4483 bruce@momjian.us         5079                 :              1 :                 log_interval = (int) ceil(elapsed_sec / LOG_STEP_SECONDS);
                               5080                 :                :             }
                               5081                 :                :         }
                               5082                 :                :     }
                               5083                 :                : 
  775 michael@paquier.xyz      5084   [ +  +  -  + ]:              6 :     if (chars != 0 && eol != '\n')
  283 fujii@postgresql.org     5085                 :UBC           0 :         fprintf(stderr, "%*c\r", chars, ' '); /* Clear the current line */
                               5086                 :                : 
 6728 ishii@postgresql.org     5087         [ -  + ]:CBC           6 :     if (PQputline(con, "\\.\n"))
 1247 tgl@sss.pgh.pa.us        5088                 :UBC           0 :         pg_fatal("very last PQputline failed");
 6728 ishii@postgresql.org     5089         [ -  + ]:CBC           6 :     if (PQendcopy(con))
 1247 tgl@sss.pgh.pa.us        5090                 :UBC           0 :         pg_fatal("PQendcopy failed");
                               5091                 :                : 
 1802 heikki.linnakangas@i     5092                 :CBC           6 :     termPQExpBuffer(&sql);
  775 michael@paquier.xyz      5093                 :              6 : }
                               5094                 :                : 
                               5095                 :                : /*
                               5096                 :                :  * Fill the standard tables with some data generated and sent from the client.
                               5097                 :                :  *
                               5098                 :                :  * The filler column is NULL in pgbench_branches and pgbench_tellers, and is
                               5099                 :                :  * a blank-padded string in pgbench_accounts.
                               5100                 :                :  */
                               5101                 :                : static void
                               5102                 :              2 : initGenerateDataClientSide(PGconn *con)
                               5103                 :                : {
                               5104                 :              2 :     fprintf(stderr, "generating data (client-side)...\n");
                               5105                 :                : 
                               5106                 :                :     /*
                               5107                 :                :      * we do all of this in one transaction to enable the backend's
                               5108                 :                :      * data-loading optimizations
                               5109                 :                :      */
                               5110                 :              2 :     executeStatement(con, "begin");
                               5111                 :                : 
                               5112                 :                :     /* truncate away any old data */
                               5113                 :              2 :     initTruncateTables(con);
                               5114                 :                : 
                               5115                 :                :     /*
                               5116                 :                :      * fill branches, tellers, accounts in that order in case foreign keys
                               5117                 :                :      * already exist
                               5118                 :                :      */
                               5119                 :              2 :     initPopulateTable(con, "pgbench_branches", nbranches, initBranch);
                               5120                 :              2 :     initPopulateTable(con, "pgbench_tellers", ntellers, initTeller);
                               5121                 :              2 :     initPopulateTable(con, "pgbench_accounts", naccounts, initAccount);
                               5122                 :                : 
 6728 ishii@postgresql.org     5123                 :              2 :     executeStatement(con, "commit");
 2854 tgl@sss.pgh.pa.us        5124                 :              2 : }
                               5125                 :                : 
                               5126                 :                : /*
                               5127                 :                :  * Fill the standard tables with some data generated on the server
                               5128                 :                :  *
                               5129                 :                :  * As already the case with the client-side data generation, the filler
                               5130                 :                :  * column defaults to NULL in pgbench_branches and pgbench_tellers,
                               5131                 :                :  * and is a blank-padded string in pgbench_accounts.
                               5132                 :                :  */
                               5133                 :                : static void
 2131 fujii@postgresql.org     5134                 :              1 : initGenerateDataServerSide(PGconn *con)
                               5135                 :                : {
                               5136                 :                :     PQExpBufferData sql;
                               5137                 :                : 
                               5138                 :              1 :     fprintf(stderr, "generating data (server-side)...\n");
                               5139                 :                : 
                               5140                 :                :     /*
                               5141                 :                :      * we do all of this in one transaction to enable the backend's
                               5142                 :                :      * data-loading optimizations
                               5143                 :                :      */
                               5144                 :              1 :     executeStatement(con, "begin");
                               5145                 :                : 
                               5146                 :                :     /* truncate away any old data */
                               5147                 :              1 :     initTruncateTables(con);
                               5148                 :                : 
 1802 heikki.linnakangas@i     5149                 :              1 :     initPQExpBuffer(&sql);
                               5150                 :                : 
                               5151                 :              1 :     printfPQExpBuffer(&sql,
                               5152                 :                :                       "insert into pgbench_branches(bid,bbalance) "
                               5153                 :                :                       "select bid, 0 "
                               5154                 :                :                       "from generate_series(1, %d) as bid", nbranches * scale);
                               5155                 :              1 :     executeStatement(con, sql.data);
                               5156                 :                : 
                               5157                 :              1 :     printfPQExpBuffer(&sql,
                               5158                 :                :                       "insert into pgbench_tellers(tid,bid,tbalance) "
                               5159                 :                :                       "select tid, (tid - 1) / %d + 1, 0 "
                               5160                 :                :                       "from generate_series(1, %d) as tid", ntellers, ntellers * scale);
                               5161                 :              1 :     executeStatement(con, sql.data);
                               5162                 :                : 
                               5163                 :              1 :     printfPQExpBuffer(&sql,
                               5164                 :                :                       "insert into pgbench_accounts(aid,bid,abalance,filler) "
                               5165                 :                :                       "select aid, (aid - 1) / %d + 1, 0, '' "
                               5166                 :                :                       "from generate_series(1, " INT64_FORMAT ") as aid",
                               5167                 :                :                       naccounts, (int64) naccounts * scale);
                               5168                 :              1 :     executeStatement(con, sql.data);
                               5169                 :                : 
                               5170                 :              1 :     termPQExpBuffer(&sql);
                               5171                 :                : 
 2131 fujii@postgresql.org     5172                 :              1 :     executeStatement(con, "commit");
                               5173                 :              1 : }
                               5174                 :                : 
                               5175                 :                : /*
                               5176                 :                :  * Invoke vacuum on the standard tables
                               5177                 :                :  */
                               5178                 :                : static void
 2854 tgl@sss.pgh.pa.us        5179                 :              2 : initVacuum(PGconn *con)
                               5180                 :                : {
                               5181                 :              2 :     fprintf(stderr, "vacuuming...\n");
                               5182                 :              2 :     executeStatement(con, "vacuum analyze pgbench_branches");
                               5183                 :              2 :     executeStatement(con, "vacuum analyze pgbench_tellers");
                               5184                 :              2 :     executeStatement(con, "vacuum analyze pgbench_accounts");
                               5185                 :              2 :     executeStatement(con, "vacuum analyze pgbench_history");
                               5186                 :              2 : }
                               5187                 :                : 
                               5188                 :                : /*
                               5189                 :                :  * Create primary keys on the standard tables
                               5190                 :                :  */
                               5191                 :                : static void
                               5192                 :              3 : initCreatePKeys(PGconn *con)
                               5193                 :                : {
                               5194                 :                :     static const char *const DDLINDEXes[] = {
                               5195                 :                :         "alter table pgbench_branches add primary key (bid)",
                               5196                 :                :         "alter table pgbench_tellers add primary key (tid)",
                               5197                 :                :         "alter table pgbench_accounts add primary key (aid)"
                               5198                 :                :     };
                               5199                 :                :     int         i;
                               5200                 :                :     PQExpBufferData query;
                               5201                 :                : 
                               5202                 :              3 :     fprintf(stderr, "creating primary keys...\n");
 1802 heikki.linnakangas@i     5203                 :              3 :     initPQExpBuffer(&query);
                               5204                 :                : 
 4128 tgl@sss.pgh.pa.us        5205         [ +  + ]:             12 :     for (i = 0; i < lengthof(DDLINDEXes); i++)
                               5206                 :                :     {
 1802 heikki.linnakangas@i     5207                 :              9 :         resetPQExpBuffer(&query);
                               5208                 :              9 :         appendPQExpBufferStr(&query, DDLINDEXes[i]);
                               5209                 :                : 
 5157 rhaas@postgresql.org     5210         [ +  + ]:              9 :         if (index_tablespace != NULL)
                               5211                 :                :         {
                               5212                 :                :             char       *escape_tablespace;
                               5213                 :                : 
                               5214                 :              3 :             escape_tablespace = PQescapeIdentifier(con, index_tablespace,
                               5215                 :                :                                                    strlen(index_tablespace));
 1802 heikki.linnakangas@i     5216                 :              3 :             appendPQExpBuffer(&query, " using index tablespace %s", escape_tablespace);
 5157 rhaas@postgresql.org     5217                 :              3 :             PQfreemem(escape_tablespace);
                               5218                 :                :         }
                               5219                 :                : 
 1802 heikki.linnakangas@i     5220                 :              9 :         executeStatement(con, query.data);
                               5221                 :                :     }
                               5222                 :                : 
                               5223                 :              3 :     termPQExpBuffer(&query);
 2854 tgl@sss.pgh.pa.us        5224                 :              3 : }
                               5225                 :                : 
                               5226                 :                : /*
                               5227                 :                :  * Create foreign key constraints between the standard tables
                               5228                 :                :  */
                               5229                 :                : static void
                               5230                 :              2 : initCreateFKeys(PGconn *con)
                               5231                 :                : {
                               5232                 :                :     static const char *const DDLKEYs[] = {
                               5233                 :                :         "alter table pgbench_tellers add constraint pgbench_tellers_bid_fkey foreign key (bid) references pgbench_branches",
                               5234                 :                :         "alter table pgbench_accounts add constraint pgbench_accounts_bid_fkey foreign key (bid) references pgbench_branches",
                               5235                 :                :         "alter table pgbench_history add constraint pgbench_history_bid_fkey foreign key (bid) references pgbench_branches",
                               5236                 :                :         "alter table pgbench_history add constraint pgbench_history_tid_fkey foreign key (tid) references pgbench_tellers",
                               5237                 :                :         "alter table pgbench_history add constraint pgbench_history_aid_fkey foreign key (aid) references pgbench_accounts"
                               5238                 :                :     };
                               5239                 :                :     int         i;
                               5240                 :                : 
                               5241                 :              2 :     fprintf(stderr, "creating foreign keys...\n");
                               5242         [ +  + ]:             12 :     for (i = 0; i < lengthof(DDLKEYs); i++)
                               5243                 :                :     {
                               5244                 :             10 :         executeStatement(con, DDLKEYs[i]);
                               5245                 :                :     }
                               5246                 :              2 : }
                               5247                 :                : 
                               5248                 :                : /*
                               5249                 :                :  * Validate an initialization-steps string
                               5250                 :                :  *
                               5251                 :                :  * (We could just leave it to runInitSteps() to fail if there are wrong
                               5252                 :                :  * characters, but since initialization can take awhile, it seems friendlier
                               5253                 :                :  * to check during option parsing.)
                               5254                 :                :  */
                               5255                 :                : static void
                               5256                 :              4 : checkInitSteps(const char *initialize_steps)
                               5257                 :                : {
                               5258         [ -  + ]:              4 :     if (initialize_steps[0] == '\0')
 1247 tgl@sss.pgh.pa.us        5259                 :UBC           0 :         pg_fatal("no initialization steps specified");
                               5260                 :                : 
 2131 fujii@postgresql.org     5261         [ +  + ]:CBC          21 :     for (const char *step = initialize_steps; *step != '\0'; step++)
                               5262                 :                :     {
                               5263         [ +  + ]:             18 :         if (strchr(ALL_INIT_STEPS " ", *step) == NULL)
                               5264                 :                :         {
 1247 tgl@sss.pgh.pa.us        5265                 :              1 :             pg_log_error("unrecognized initialization step \"%c\"", *step);
                               5266                 :              1 :             pg_log_error_detail("Allowed step characters are: \"" ALL_INIT_STEPS "\".");
 2854                          5267                 :              1 :             exit(1);
                               5268                 :                :         }
                               5269                 :                :     }
                               5270                 :              3 : }
                               5271                 :                : 
                               5272                 :                : /*
                               5273                 :                :  * Invoke each initialization step in the given string
                               5274                 :                :  */
                               5275                 :                : static void
                               5276                 :              3 : runInitSteps(const char *initialize_steps)
                               5277                 :                : {
                               5278                 :                :     PQExpBufferData stats;
                               5279                 :                :     PGconn     *con;
                               5280                 :                :     const char *step;
 2244 tmunro@postgresql.or     5281                 :              3 :     double      run_time = 0.0;
                               5282                 :              3 :     bool        first = true;
                               5283                 :                : 
                               5284                 :              3 :     initPQExpBuffer(&stats);
                               5285                 :                : 
 2854 tgl@sss.pgh.pa.us        5286         [ -  + ]:              3 :     if ((con = doConnect()) == NULL)
 1247 tgl@sss.pgh.pa.us        5287                 :UBC           0 :         pg_fatal("could not create connection for initialization");
                               5288                 :                : 
 2105 michael@paquier.xyz      5289                 :CBC           3 :     setup_cancel_handler(NULL);
                               5290                 :              3 :     SetCancelConn(con);
                               5291                 :                : 
 2854 tgl@sss.pgh.pa.us        5292         [ +  + ]:             22 :     for (step = initialize_steps; *step != '\0'; step++)
                               5293                 :                :     {
 2244 tmunro@postgresql.or     5294                 :             19 :         char       *op = NULL;
 1641                          5295                 :             19 :         pg_time_usec_t start = pg_time_now();
                               5296                 :                : 
 2854 tgl@sss.pgh.pa.us        5297   [ +  +  +  +  :             19 :         switch (*step)
                                        +  +  +  +  
                                                 - ]
                               5298                 :                :         {
                               5299                 :              3 :             case 'd':
 2244 tmunro@postgresql.or     5300                 :              3 :                 op = "drop tables";
 2854 tgl@sss.pgh.pa.us        5301                 :              3 :                 initDropTables(con);
                               5302                 :              3 :                 break;
                               5303                 :              3 :             case 't':
 2244 tmunro@postgresql.or     5304                 :              3 :                 op = "create tables";
 2854 tgl@sss.pgh.pa.us        5305                 :              3 :                 initCreateTables(con);
                               5306                 :              3 :                 break;
                               5307                 :              2 :             case 'g':
 2131 fujii@postgresql.org     5308                 :              2 :                 op = "client-side generate";
                               5309                 :              2 :                 initGenerateDataClientSide(con);
                               5310                 :              2 :                 break;
                               5311                 :              1 :             case 'G':
                               5312                 :              1 :                 op = "server-side generate";
                               5313                 :              1 :                 initGenerateDataServerSide(con);
 2854 tgl@sss.pgh.pa.us        5314                 :              1 :                 break;
                               5315                 :              2 :             case 'v':
 2244 tmunro@postgresql.or     5316                 :              2 :                 op = "vacuum";
 2854 tgl@sss.pgh.pa.us        5317                 :              2 :                 initVacuum(con);
                               5318                 :              2 :                 break;
                               5319                 :              3 :             case 'p':
 2244 tmunro@postgresql.or     5320                 :              3 :                 op = "primary keys";
 2854 tgl@sss.pgh.pa.us        5321                 :              3 :                 initCreatePKeys(con);
                               5322                 :              3 :                 break;
                               5323                 :              2 :             case 'f':
 2244 tmunro@postgresql.or     5324                 :              2 :                 op = "foreign keys";
 2854 tgl@sss.pgh.pa.us        5325                 :              2 :                 initCreateFKeys(con);
                               5326                 :              2 :                 break;
                               5327                 :              3 :             case ' ':
                               5328                 :              3 :                 break;          /* ignore */
 2854 tgl@sss.pgh.pa.us        5329                 :UBC           0 :             default:
 1247                          5330                 :              0 :                 pg_log_error("unrecognized initialization step \"%c\"", *step);
 2854                          5331                 :              0 :                 PQfinish(con);
                               5332                 :              0 :                 exit(1);
                               5333                 :                :         }
                               5334                 :                : 
 2244 tmunro@postgresql.or     5335         [ +  + ]:CBC          19 :         if (op != NULL)
                               5336                 :                :         {
 1641                          5337                 :             16 :             double      elapsed_sec = PG_TIME_GET_DOUBLE(pg_time_now() - start);
                               5338                 :                : 
 2244                          5339         [ +  + ]:             16 :             if (!first)
                               5340                 :             13 :                 appendPQExpBufferStr(&stats, ", ");
                               5341                 :                :             else
                               5342                 :              3 :                 first = false;
                               5343                 :                : 
                               5344                 :             16 :             appendPQExpBuffer(&stats, "%s %.2f s", op, elapsed_sec);
                               5345                 :                : 
                               5346                 :             16 :             run_time += elapsed_sec;
                               5347                 :                :         }
                               5348                 :                :     }
                               5349                 :                : 
                               5350                 :              3 :     fprintf(stderr, "done in %.2f s (%s).\n", run_time, stats.data);
 2105 michael@paquier.xyz      5351                 :              3 :     ResetCancelConn();
 9278 bruce@momjian.us         5352                 :              3 :     PQfinish(con);
 2244 tmunro@postgresql.or     5353                 :              3 :     termPQExpBuffer(&stats);
 9278 bruce@momjian.us         5354                 :              3 : }
                               5355                 :                : 
                               5356                 :                : /*
                               5357                 :                :  * Extract pgbench table information into global variables scale,
                               5358                 :                :  * partition_method and partitions.
                               5359                 :                :  */
                               5360                 :                : static void
 2167 akapila@postgresql.o     5361                 :              7 : GetTableInfo(PGconn *con, bool scale_given)
                               5362                 :                : {
                               5363                 :                :     PGresult   *res;
                               5364                 :                : 
                               5365                 :                :     /*
                               5366                 :                :      * get the scaling factor that should be same as count(*) from
                               5367                 :                :      * pgbench_branches if this is not a custom query
                               5368                 :                :      */
                               5369                 :              7 :     res = PQexec(con, "select count(*) from pgbench_branches");
                               5370         [ +  + ]:              7 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
                               5371                 :                :     {
                               5372                 :              1 :         char       *sqlState = PQresultErrorField(res, PG_DIAG_SQLSTATE);
                               5373                 :                : 
 1247 tgl@sss.pgh.pa.us        5374                 :              1 :         pg_log_error("could not count number of branches: %s", PQerrorMessage(con));
                               5375                 :                : 
 2167 akapila@postgresql.o     5376   [ +  -  +  - ]:              1 :         if (sqlState && strcmp(sqlState, ERRCODE_UNDEFINED_TABLE) == 0)
 1247 tgl@sss.pgh.pa.us        5377                 :              1 :             pg_log_error_hint("Perhaps you need to do initialization (\"pgbench -i\") in database \"%s\".",
                               5378                 :                :                               PQdb(con));
                               5379                 :                : 
 2167 akapila@postgresql.o     5380                 :              1 :         exit(1);
                               5381                 :                :     }
                               5382                 :              6 :     scale = atoi(PQgetvalue(res, 0, 0));
                               5383         [ -  + ]:              6 :     if (scale < 0)
 1247 tgl@sss.pgh.pa.us        5384                 :UBC           0 :         pg_fatal("invalid count(*) from pgbench_branches: \"%s\"",
                               5385                 :                :                  PQgetvalue(res, 0, 0));
 2167 akapila@postgresql.o     5386                 :CBC           6 :     PQclear(res);
                               5387                 :                : 
                               5388                 :                :     /* warn if we override user-given -s switch */
                               5389         [ +  + ]:              6 :     if (scale_given)
 2068 peter@eisentraut.org     5390                 :              1 :         pg_log_warning("scale option ignored, using count from pgbench_branches table (%d)",
                               5391                 :                :                        scale);
                               5392                 :                : 
                               5393                 :                :     /*
                               5394                 :                :      * Get the partition information for the first "pgbench_accounts" table
                               5395                 :                :      * found in search_path.
                               5396                 :                :      *
                               5397                 :                :      * The result is empty if no "pgbench_accounts" is found.
                               5398                 :                :      *
                               5399                 :                :      * Otherwise, it always returns one row even if the table is not
                               5400                 :                :      * partitioned (in which case the partition strategy is NULL).
                               5401                 :                :      *
                               5402                 :                :      * The number of partitions can be 0 even for partitioned tables, if no
                               5403                 :                :      * partition is attached.
                               5404                 :                :      *
                               5405                 :                :      * We assume no partitioning on any failure, so as to avoid failing on an
                               5406                 :                :      * old version without "pg_partitioned_table".
                               5407                 :                :      */
 2167 akapila@postgresql.o     5408                 :              6 :     res = PQexec(con,
                               5409                 :                :                  "select o.n, p.partstrat, pg_catalog.count(i.inhparent) "
                               5410                 :                :                  "from pg_catalog.pg_class as c "
                               5411                 :                :                  "join pg_catalog.pg_namespace as n on (n.oid = c.relnamespace) "
                               5412                 :                :                  "cross join lateral (select pg_catalog.array_position(pg_catalog.current_schemas(true), n.nspname)) as o(n) "
                               5413                 :                :                  "left join pg_catalog.pg_partitioned_table as p on (p.partrelid = c.oid) "
                               5414                 :                :                  "left join pg_catalog.pg_inherits as i on (c.oid = i.inhparent) "
                               5415                 :                :                  "where c.relname = 'pgbench_accounts' and o.n is not null "
                               5416                 :                :                  "group by 1, 2 "
                               5417                 :                :                  "order by 1 asc "
                               5418                 :                :                  "limit 1");
                               5419                 :                : 
                               5420         [ -  + ]:              6 :     if (PQresultStatus(res) != PGRES_TUPLES_OK)
                               5421                 :                :     {
                               5422                 :                :         /* probably an older version, coldly assume no partitioning */
 2167 akapila@postgresql.o     5423                 :UBC           0 :         partition_method = PART_NONE;
                               5424                 :              0 :         partitions = 0;
                               5425                 :                :     }
 2167 akapila@postgresql.o     5426         [ -  + ]:CBC           6 :     else if (PQntuples(res) == 0)
                               5427                 :                :     {
                               5428                 :                :         /*
                               5429                 :                :          * This case is unlikely as pgbench already found "pgbench_branches"
                               5430                 :                :          * above to compute the scale.
                               5431                 :                :          */
  477 peter@eisentraut.org     5432                 :UBC           0 :         pg_log_error("no pgbench_accounts table found in \"search_path\"");
 1247 tgl@sss.pgh.pa.us        5433                 :              0 :         pg_log_error_hint("Perhaps you need to do initialization (\"pgbench -i\") in database \"%s\".", PQdb(con));
 2167 akapila@postgresql.o     5434                 :              0 :         exit(1);
                               5435                 :                :     }
                               5436                 :                :     else                        /* PQntuples(res) == 1 */
                               5437                 :                :     {
                               5438                 :                :         /* normal case, extract partition information */
 2167 akapila@postgresql.o     5439         [ -  + ]:CBC           6 :         if (PQgetisnull(res, 0, 1))
 2167 akapila@postgresql.o     5440                 :UBC           0 :             partition_method = PART_NONE;
                               5441                 :                :         else
                               5442                 :                :         {
 2167 akapila@postgresql.o     5443                 :CBC           6 :             char       *ps = PQgetvalue(res, 0, 1);
                               5444                 :                : 
                               5445                 :                :             /* column must be there */
                               5446         [ -  + ]:              6 :             Assert(ps != NULL);
                               5447                 :                : 
                               5448         [ +  - ]:              6 :             if (strcmp(ps, "r") == 0)
                               5449                 :              6 :                 partition_method = PART_RANGE;
 2167 akapila@postgresql.o     5450         [ #  # ]:UBC           0 :             else if (strcmp(ps, "h") == 0)
                               5451                 :              0 :                 partition_method = PART_HASH;
                               5452                 :                :             else
                               5453                 :                :             {
                               5454                 :                :                 /* possibly a newer version with new partition method */
 1247 tgl@sss.pgh.pa.us        5455                 :              0 :                 pg_fatal("unexpected partition method: \"%s\"", ps);
                               5456                 :                :             }
                               5457                 :                :         }
                               5458                 :                : 
 2167 akapila@postgresql.o     5459                 :CBC           6 :         partitions = atoi(PQgetvalue(res, 0, 2));
                               5460                 :                :     }
                               5461                 :                : 
                               5462                 :              6 :     PQclear(res);
                               5463                 :              6 : }
                               5464                 :                : 
                               5465                 :                : /*
                               5466                 :                :  * Replace :param with $n throughout the command's SQL text, which
                               5467                 :                :  * is a modifiable string in cmd->lines.
                               5468                 :                :  */
                               5469                 :                : static bool
 2948 tgl@sss.pgh.pa.us        5470                 :             94 : parseQuery(Command *cmd)
                               5471                 :                : {
                               5472                 :                :     char       *sql,
                               5473                 :                :                *p;
                               5474                 :                : 
 6380 ishii@postgresql.org     5475                 :             94 :     cmd->argc = 1;
                               5476                 :                : 
 2431 alvherre@alvh.no-ip.     5477                 :             94 :     p = sql = pg_strdup(cmd->lines.data);
 6380 ishii@postgresql.org     5478         [ +  + ]:            390 :     while ((p = strchr(p, ':')) != NULL)
                               5479                 :                :     {
                               5480                 :                :         char        var[13];
                               5481                 :                :         char       *name;
                               5482                 :                :         int         eaten;
                               5483                 :                : 
                               5484                 :            297 :         name = parseVariable(p, &eaten);
                               5485         [ +  + ]:            297 :         if (name == NULL)
                               5486                 :                :         {
 5931 bruce@momjian.us         5487         [ +  + ]:             48 :             while (*p == ':')
                               5488                 :                :             {
                               5489                 :             32 :                 p++;
                               5490                 :                :             }
 6380 ishii@postgresql.org     5491                 :             16 :             continue;
                               5492                 :                :         }
                               5493                 :                : 
                               5494                 :                :         /*
                               5495                 :                :          * cmd->argv[0] is the SQL statement itself, so the max number of
                               5496                 :                :          * arguments is one less than MAX_ARGS
                               5497                 :                :          */
                               5498         [ +  + ]:            281 :         if (cmd->argc >= MAX_ARGS)
                               5499                 :                :         {
 2068 peter@eisentraut.org     5500                 :              1 :             pg_log_error("statement has too many arguments (maximum is %d): %s",
                               5501                 :                :                          MAX_ARGS - 1, cmd->lines.data);
 3903 ishii@postgresql.org     5502                 :              1 :             pg_free(name);
 6380                          5503                 :              1 :             return false;
                               5504                 :                :         }
                               5505                 :                : 
                               5506                 :            280 :         sprintf(var, "$%d", cmd->argc);
 5504 tgl@sss.pgh.pa.us        5507                 :            280 :         p = replaceVariable(&sql, p, eaten, var);
                               5508                 :                : 
 6380 ishii@postgresql.org     5509                 :            280 :         cmd->argv[cmd->argc] = name;
                               5510                 :            280 :         cmd->argc++;
                               5511                 :                :     }
                               5512                 :                : 
 2431 alvherre@alvh.no-ip.     5513         [ -  + ]:             93 :     Assert(cmd->argv[0] == NULL);
 6380 ishii@postgresql.org     5514                 :             93 :     cmd->argv[0] = sql;
                               5515                 :             93 :     return true;
                               5516                 :                : }
                               5517                 :                : 
                               5518                 :                : /*
                               5519                 :                :  * syntax error while parsing a script (in practice, while parsing a
                               5520                 :                :  * backslash command, because we don't detect syntax errors in SQL)
                               5521                 :                :  *
                               5522                 :                :  * source: source of script (filename or builtin-script ID)
                               5523                 :                :  * lineno: line number within script (count from 1)
                               5524                 :                :  * line: whole line of backslash command, if available
                               5525                 :                :  * command: backslash command name, if available
                               5526                 :                :  * msg: the actual error message
                               5527                 :                :  * more: optional extra message
                               5528                 :                :  * column: zero-based column number, or -1 if unknown
                               5529                 :                :  */
                               5530                 :                : void
 3457 tgl@sss.pgh.pa.us        5531                 :             33 : syntax_error(const char *source, int lineno,
                               5532                 :                :              const char *line, const char *command,
                               5533                 :                :              const char *msg, const char *more, int column)
                               5534                 :                : {
                               5535                 :                :     PQExpBufferData buf;
                               5536                 :                : 
 2068 peter@eisentraut.org     5537                 :             33 :     initPQExpBuffer(&buf);
                               5538                 :                : 
                               5539                 :             33 :     printfPQExpBuffer(&buf, "%s:%d: %s", source, lineno, msg);
 3810 rhaas@postgresql.org     5540         [ +  + ]:             33 :     if (more != NULL)
 2068 peter@eisentraut.org     5541                 :             15 :         appendPQExpBuffer(&buf, " (%s)", more);
 3457 tgl@sss.pgh.pa.us        5542   [ +  +  -  + ]:             33 :     if (column >= 0 && line == NULL)
 2068 peter@eisentraut.org     5543                 :UBC           0 :         appendPQExpBuffer(&buf, " at column %d", column + 1);
 3457 tgl@sss.pgh.pa.us        5544         [ +  + ]:CBC          33 :     if (command != NULL)
 2068 peter@eisentraut.org     5545                 :             30 :         appendPQExpBuffer(&buf, " in command \"%s\"", command);
                               5546                 :                : 
 1247 tgl@sss.pgh.pa.us        5547                 :             33 :     pg_log_error("%s", buf.data);
                               5548                 :                : 
 2068 peter@eisentraut.org     5549                 :             33 :     termPQExpBuffer(&buf);
                               5550                 :                : 
 3810 rhaas@postgresql.org     5551         [ +  + ]:             33 :     if (line != NULL)
                               5552                 :                :     {
                               5553                 :             28 :         fprintf(stderr, "%s\n", line);
 3457 tgl@sss.pgh.pa.us        5554         [ +  + ]:             28 :         if (column >= 0)
 1941                          5555                 :             21 :             fprintf(stderr, "%*c error found here\n", column + 1, '^');
                               5556                 :                :     }
                               5557                 :                : 
 3810 rhaas@postgresql.org     5558                 :             33 :     exit(1);
                               5559                 :                : }
                               5560                 :                : 
                               5561                 :                : /*
                               5562                 :                :  * Return a pointer to the start of the SQL command, after skipping over
                               5563                 :                :  * whitespace and "--" comments.
                               5564                 :                :  * If the end of the string is reached, return NULL.
                               5565                 :                :  */
                               5566                 :                : static char *
 2431 alvherre@alvh.no-ip.     5567                 :           1171 : skip_sql_comments(char *sql_command)
                               5568                 :                : {
                               5569                 :           1171 :     char       *p = sql_command;
                               5570                 :                : 
                               5571                 :                :     /* Skip any leading whitespace, as well as "--" style comments */
                               5572                 :                :     for (;;)
                               5573                 :                :     {
 3457 tgl@sss.pgh.pa.us        5574         [ -  + ]:           1171 :         if (isspace((unsigned char) *p))
 3457 tgl@sss.pgh.pa.us        5575                 :UBC           0 :             p++;
 3457 tgl@sss.pgh.pa.us        5576         [ -  + ]:CBC        1171 :         else if (strncmp(p, "--", 2) == 0)
                               5577                 :                :         {
 3457 tgl@sss.pgh.pa.us        5578                 :UBC           0 :             p = strchr(p, '\n');
                               5579         [ #  # ]:              0 :             if (p == NULL)
                               5580                 :              0 :                 return NULL;
                               5581                 :              0 :             p++;
                               5582                 :                :         }
                               5583                 :                :         else
 3457 tgl@sss.pgh.pa.us        5584                 :CBC        1171 :             break;
                               5585                 :                :     }
                               5586                 :                : 
                               5587                 :                :     /* NULL if there's nothing but whitespace and comments */
                               5588         [ +  + ]:           1171 :     if (*p == '\0')
                               5589                 :            748 :         return NULL;
                               5590                 :                : 
 2431 alvherre@alvh.no-ip.     5591                 :            423 :     return p;
                               5592                 :                : }
                               5593                 :                : 
                               5594                 :                : /*
                               5595                 :                :  * Parse a SQL command; return a Command struct, or NULL if it's a comment
                               5596                 :                :  *
                               5597                 :                :  * On entry, psqlscan.l has collected the command into "buf", so we don't
                               5598                 :                :  * really need to do much here except check for comments and set up a Command
                               5599                 :                :  * struct.
                               5600                 :                :  */
                               5601                 :                : static Command *
 2357                          5602                 :           1171 : create_sql_command(PQExpBuffer buf, const char *source)
                               5603                 :                : {
                               5604                 :                :     Command    *my_command;
 2431                          5605                 :           1171 :     char       *p = skip_sql_comments(buf->data);
                               5606                 :                : 
                               5607         [ +  + ]:           1171 :     if (p == NULL)
                               5608                 :            748 :         return NULL;
                               5609                 :                : 
                               5610                 :                :     /* Allocate and initialize Command structure */
                               5611                 :            423 :     my_command = (Command *) pg_malloc(sizeof(Command));
                               5612                 :            423 :     initPQExpBuffer(&my_command->lines);
                               5613                 :            423 :     appendPQExpBufferStr(&my_command->lines, p);
                               5614                 :            423 :     my_command->first_line = NULL;   /* this is set later */
 3457 tgl@sss.pgh.pa.us        5615                 :            423 :     my_command->type = SQL_COMMAND;
 2865                          5616                 :            423 :     my_command->meta = META_NONE;
 2431 alvherre@alvh.no-ip.     5617                 :            423 :     my_command->argc = 0;
 1263 ishii@postgresql.org     5618                 :            423 :     my_command->retries = 0;
                               5619                 :            423 :     my_command->failures = 0;
 2431 alvherre@alvh.no-ip.     5620                 :            423 :     memset(my_command->argv, 0, sizeof(my_command->argv));
                               5621                 :            423 :     my_command->varprefix = NULL;    /* allocated later, if needed */
                               5622                 :            423 :     my_command->expr = NULL;
 3457 tgl@sss.pgh.pa.us        5623                 :            423 :     initSimpleStats(&my_command->stats);
  928 alvherre@alvh.no-ip.     5624                 :            423 :     my_command->prepname = NULL; /* set later, if needed */
                               5625                 :                : 
 2431                          5626                 :            423 :     return my_command;
                               5627                 :                : }
                               5628                 :                : 
                               5629                 :                : /* Free a Command structure and associated data */
                               5630                 :                : static void
                               5631                 :             31 : free_command(Command *command)
                               5632                 :                : {
                               5633                 :             31 :     termPQExpBuffer(&command->lines);
 1177 peter@eisentraut.org     5634                 :             31 :     pg_free(command->first_line);
 2431 alvherre@alvh.no-ip.     5635         [ +  + ]:             64 :     for (int i = 0; i < command->argc; i++)
                               5636                 :             33 :         pg_free(command->argv[i]);
 1177 peter@eisentraut.org     5637                 :             31 :     pg_free(command->varprefix);
                               5638                 :                : 
                               5639                 :                :     /*
                               5640                 :                :      * It should also free expr recursively, but this is currently not needed
                               5641                 :                :      * as only gset commands (which do not have an expression) are freed.
                               5642                 :                :      */
 2431 alvherre@alvh.no-ip.     5643                 :             31 :     pg_free(command);
                               5644                 :             31 : }
                               5645                 :                : 
                               5646                 :                : /*
                               5647                 :                :  * Once an SQL command is fully parsed, possibly by accumulating several
                               5648                 :                :  * parts, complete other fields of the Command structure.
                               5649                 :                :  */
                               5650                 :                : static void
                               5651                 :            292 : postprocess_sql_command(Command *my_command)
                               5652                 :                : {
                               5653                 :                :     char        buffer[128];
                               5654                 :                :     static int  prepnum = 0;
                               5655                 :                : 
                               5656         [ -  + ]:            292 :     Assert(my_command->type == SQL_COMMAND);
                               5657                 :                : 
                               5658                 :                :     /* Save the first line for error display. */
                               5659                 :            292 :     strlcpy(buffer, my_command->lines.data, sizeof(buffer));
                               5660                 :            292 :     buffer[strcspn(buffer, "\n\r")] = '\0';
                               5661                 :            292 :     my_command->first_line = pg_strdup(buffer);
                               5662                 :                : 
                               5663                 :                :     /* Parse query and generate prepared statement name, if necessary */
                               5664   [ +  +  +  - ]:            292 :     switch (querymode)
                               5665                 :                :     {
                               5666                 :            198 :         case QUERY_SIMPLE:
                               5667                 :            198 :             my_command->argv[0] = my_command->lines.data;
                               5668                 :            198 :             my_command->argc++;
                               5669                 :            198 :             break;
                               5670                 :             52 :         case QUERY_PREPARED:
  928                          5671                 :             52 :             my_command->prepname = psprintf("P_%d", prepnum++);
                               5672                 :                :             /* fall through */
                               5673                 :             94 :         case QUERY_EXTENDED:
 2431                          5674         [ +  + ]:             94 :             if (!parseQuery(my_command))
                               5675                 :              1 :                 exit(1);
                               5676                 :             93 :             break;
 2431 alvherre@alvh.no-ip.     5677                 :UBC           0 :         default:
                               5678                 :              0 :             exit(1);
                               5679                 :                :     }
 2431 alvherre@alvh.no-ip.     5680                 :CBC         291 : }
                               5681                 :                : 
                               5682                 :                : /*
                               5683                 :                :  * Parse a backslash command; return a Command struct, or NULL if comment
                               5684                 :                :  *
                               5685                 :                :  * At call, we have scanned only the initial backslash.
                               5686                 :                :  */
                               5687                 :                : static Command *
  191 tgl@sss.pgh.pa.us        5688                 :            532 : process_backslash_command(PsqlScanState sstate, const char *source,
                               5689                 :                :                           int lineno, int start_offset)
                               5690                 :                : {
                               5691                 :                :     Command    *my_command;
                               5692                 :                :     PQExpBufferData word_buf;
                               5693                 :                :     int         word_offset;
                               5694                 :                :     int         offsets[MAX_ARGS];  /* offsets of argument words */
                               5695                 :                :     int         j;
                               5696                 :                : 
 3457                          5697                 :            532 :     initPQExpBuffer(&word_buf);
                               5698                 :                : 
                               5699                 :                :     /* Collect first word of command */
                               5700         [ -  + ]:            532 :     if (!expr_lex_one_word(sstate, &word_buf, &word_offset))
                               5701                 :                :     {
 3457 tgl@sss.pgh.pa.us        5702                 :UBC           0 :         termPQExpBuffer(&word_buf);
 7277 ishii@postgresql.org     5703                 :              0 :         return NULL;
                               5704                 :                :     }
                               5705                 :                : 
                               5706                 :                :     /* Allocate and initialize Command structure */
 3457 tgl@sss.pgh.pa.us        5707                 :CBC         532 :     my_command = (Command *) pg_malloc0(sizeof(Command));
                               5708                 :            532 :     my_command->type = META_COMMAND;
                               5709                 :            532 :     my_command->argc = 0;
                               5710                 :            532 :     initSimpleStats(&my_command->stats);
                               5711                 :                : 
                               5712                 :                :     /* Save first word (command name) */
                               5713                 :            532 :     j = 0;
                               5714                 :            532 :     offsets[j] = word_offset;
                               5715                 :            532 :     my_command->argv[j++] = pg_strdup(word_buf.data);
                               5716                 :            532 :     my_command->argc++;
                               5717                 :                : 
                               5718                 :                :     /* ... and convert it to enum form */
 2865                          5719                 :            532 :     my_command->meta = getMetaCommand(my_command->argv[0]);
                               5720                 :                : 
 2725 teodor@sigaev.ru         5721         [ +  + ]:            532 :     if (my_command->meta == META_SET ||
                               5722         [ +  + ]:            169 :         my_command->meta == META_IF ||
                               5723         [ +  + ]:            145 :         my_command->meta == META_ELIF)
                               5724                 :                :     {
                               5725                 :                :         yyscan_t    yyscanner;
                               5726                 :                : 
                               5727                 :                :         /* For \set, collect var name */
                               5728         [ +  + ]:            400 :         if (my_command->meta == META_SET)
                               5729                 :                :         {
                               5730         [ +  + ]:            363 :             if (!expr_lex_one_word(sstate, &word_buf, &word_offset))
 2431 alvherre@alvh.no-ip.     5731                 :              1 :                 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5732                 :                :                              "missing argument", NULL, -1);
                               5733                 :                : 
 2725 teodor@sigaev.ru         5734                 :            362 :             offsets[j] = word_offset;
                               5735                 :            362 :             my_command->argv[j++] = pg_strdup(word_buf.data);
                               5736                 :            362 :             my_command->argc++;
                               5737                 :                :         }
                               5738                 :                : 
                               5739                 :                :         /* then for all parse the expression */
 3457 tgl@sss.pgh.pa.us        5740                 :            399 :         yyscanner = expr_scanner_init(sstate, source, lineno, start_offset,
                               5741                 :            399 :                                       my_command->argv[0]);
                               5742                 :                : 
  225 peter@eisentraut.org     5743         [ -  + ]:            399 :         if (expr_yyparse(&my_command->expr, yyscanner) != 0)
                               5744                 :                :         {
                               5745                 :                :             /* dead code: exit done from syntax_error called by yyerror */
 3457 tgl@sss.pgh.pa.us        5746                 :UBC           0 :             exit(1);
                               5747                 :                :         }
                               5748                 :                : 
                               5749                 :                :         /* Save line, trimming any trailing newline */
 2431 alvherre@alvh.no-ip.     5750                 :CBC         380 :         my_command->first_line =
                               5751                 :            380 :             expr_scanner_get_substring(sstate,
                               5752                 :                :                                        start_offset,
                               5753                 :                :                                        true);
                               5754                 :                : 
 3457 tgl@sss.pgh.pa.us        5755                 :            380 :         expr_scanner_finish(yyscanner);
                               5756                 :                : 
                               5757                 :            380 :         termPQExpBuffer(&word_buf);
                               5758                 :                : 
                               5759                 :            380 :         return my_command;
                               5760                 :                :     }
                               5761                 :                : 
                               5762                 :                :     /* For all other commands, collect remaining words. */
                               5763         [ +  + ]:            423 :     while (expr_lex_one_word(sstate, &word_buf, &word_offset))
                               5764                 :                :     {
                               5765                 :                :         /*
                               5766                 :                :          * my_command->argv[0] is the command itself, so the max number of
                               5767                 :                :          * arguments is one less than MAX_ARGS
                               5768                 :                :          */
                               5769         [ +  + ]:            292 :         if (j >= MAX_ARGS)
 2431 alvherre@alvh.no-ip.     5770                 :              1 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5771                 :                :                          "too many arguments", NULL, -1);
                               5772                 :                : 
 3457 tgl@sss.pgh.pa.us        5773                 :            291 :         offsets[j] = word_offset;
                               5774                 :            291 :         my_command->argv[j++] = pg_strdup(word_buf.data);
                               5775                 :            291 :         my_command->argc++;
                               5776                 :                :     }
                               5777                 :                : 
                               5778                 :                :     /* Save line, trimming any trailing newline */
 2431 alvherre@alvh.no-ip.     5779                 :            131 :     my_command->first_line =
                               5780                 :            131 :         expr_scanner_get_substring(sstate,
                               5781                 :                :                                    start_offset,
                               5782                 :                :                                    true);
                               5783                 :                : 
 2865 tgl@sss.pgh.pa.us        5784         [ +  + ]:            131 :     if (my_command->meta == META_SLEEP)
                               5785                 :                :     {
 3457                          5786         [ +  + ]:              9 :         if (my_command->argc < 2)
 2431 alvherre@alvh.no-ip.     5787                 :              1 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5788                 :                :                          "missing argument", NULL, -1);
                               5789                 :                : 
 3457 tgl@sss.pgh.pa.us        5790         [ +  + ]:              8 :         if (my_command->argc > 3)
 2431 alvherre@alvh.no-ip.     5791                 :              1 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5792                 :                :                          "too many arguments", NULL,
 3457 tgl@sss.pgh.pa.us        5793                 :              1 :                          offsets[3] - start_offset);
                               5794                 :                : 
                               5795                 :                :         /*
                               5796                 :                :          * Split argument into number and unit to allow "sleep 1ms" etc. We
                               5797                 :                :          * don't have to terminate the number argument with null because it
                               5798                 :                :          * will be parsed with atoi, which ignores trailing non-digit
                               5799                 :                :          * characters.
                               5800                 :                :          */
 1629 fujii@postgresql.org     5801         [ +  + ]:              7 :         if (my_command->argv[1][0] != ':')
                               5802                 :                :         {
 3457 tgl@sss.pgh.pa.us        5803                 :              4 :             char       *c = my_command->argv[1];
 1629 fujii@postgresql.org     5804                 :              4 :             bool        have_digit = false;
                               5805                 :                : 
                               5806                 :                :             /* Skip sign */
                               5807   [ +  -  -  + ]:              4 :             if (*c == '+' || *c == '-')
 1629 fujii@postgresql.org     5808                 :UBC           0 :                 c++;
                               5809                 :                : 
                               5810                 :                :             /* Require at least one digit */
 1629 fujii@postgresql.org     5811   [ +  -  +  - ]:CBC           4 :             if (*c && isdigit((unsigned char) *c))
                               5812                 :              4 :                 have_digit = true;
                               5813                 :                : 
                               5814                 :                :             /* Eat all digits */
                               5815   [ +  +  +  + ]:             10 :             while (*c && isdigit((unsigned char) *c))
 3457 tgl@sss.pgh.pa.us        5816                 :              6 :                 c++;
                               5817                 :                : 
                               5818         [ +  + ]:              4 :             if (*c)
                               5819                 :                :             {
 1629 fujii@postgresql.org     5820   [ +  -  +  - ]:              1 :                 if (my_command->argc == 2 && have_digit)
                               5821                 :                :                 {
                               5822                 :              1 :                     my_command->argv[2] = c;
                               5823                 :              1 :                     offsets[2] = offsets[1] + (c - my_command->argv[1]);
                               5824                 :              1 :                     my_command->argc = 3;
                               5825                 :                :                 }
                               5826                 :                :                 else
                               5827                 :                :                 {
                               5828                 :                :                     /*
                               5829                 :                :                      * Raise an error if argument starts with non-digit
                               5830                 :                :                      * character (after sign).
                               5831                 :                :                      */
 1629 fujii@postgresql.org     5832                 :UBC           0 :                     syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5833                 :                :                                  "invalid sleep time, must be an integer",
                               5834                 :              0 :                                  my_command->argv[1], offsets[1] - start_offset);
                               5835                 :                :                 }
                               5836                 :                :             }
                               5837                 :                :         }
                               5838                 :                : 
 3457 tgl@sss.pgh.pa.us        5839         [ +  + ]:CBC           7 :         if (my_command->argc == 3)
                               5840                 :                :         {
                               5841   [ +  +  +  + ]:              9 :             if (pg_strcasecmp(my_command->argv[2], "us") != 0 &&
                               5842         [ +  + ]:              6 :                 pg_strcasecmp(my_command->argv[2], "ms") != 0 &&
                               5843                 :              2 :                 pg_strcasecmp(my_command->argv[2], "s") != 0)
 2431 alvherre@alvh.no-ip.     5844                 :              1 :                 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5845                 :                :                              "unrecognized time unit, must be us, ms or s",
 3457 tgl@sss.pgh.pa.us        5846                 :              1 :                              my_command->argv[2], offsets[2] - start_offset);
                               5847                 :                :         }
                               5848                 :                :     }
 2865                          5849         [ +  + ]:            122 :     else if (my_command->meta == META_SETSHELL)
                               5850                 :                :     {
 3457                          5851         [ +  + ]:              4 :         if (my_command->argc < 3)
 2431 alvherre@alvh.no-ip.     5852                 :              1 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5853                 :                :                          "missing argument", NULL, -1);
                               5854                 :                :     }
 2865 tgl@sss.pgh.pa.us        5855         [ +  + ]:            118 :     else if (my_command->meta == META_SHELL)
                               5856                 :                :     {
 3457                          5857         [ +  + ]:              4 :         if (my_command->argc < 2)
 2431 alvherre@alvh.no-ip.     5858                 :              1 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5859                 :                :                          "missing command", NULL, -1);
                               5860                 :                :     }
 1636                          5861   [ +  +  +  + ]:            114 :     else if (my_command->meta == META_ELSE || my_command->meta == META_ENDIF ||
                               5862         [ +  + ]:             79 :              my_command->meta == META_STARTPIPELINE ||
  591 michael@paquier.xyz      5863         [ +  + ]:             58 :              my_command->meta == META_ENDPIPELINE ||
                               5864         [ +  + ]:             41 :              my_command->meta == META_SYNCPIPELINE)
                               5865                 :                :     {
 2725 teodor@sigaev.ru         5866         [ +  + ]:             78 :         if (my_command->argc != 1)
 2431 alvherre@alvh.no-ip.     5867                 :              2 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5868                 :                :                          "unexpected argument", NULL, -1);
                               5869                 :                :     }
 1982 michael@paquier.xyz      5870   [ +  +  +  + ]:             36 :     else if (my_command->meta == META_GSET || my_command->meta == META_ASET)
                               5871                 :                :     {
 2431 alvherre@alvh.no-ip.     5872         [ +  + ]:             35 :         if (my_command->argc > 2)
                               5873                 :              1 :             syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5874                 :                :                          "too many arguments", NULL, -1);
                               5875                 :                :     }
                               5876                 :                :     else
                               5877                 :                :     {
                               5878                 :                :         /* my_command->meta == META_NONE */
                               5879                 :              1 :         syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
                               5880                 :                :                      "invalid command", NULL, -1);
                               5881                 :                :     }
                               5882                 :                : 
 3457 tgl@sss.pgh.pa.us        5883                 :            122 :     termPQExpBuffer(&word_buf);
                               5884                 :                : 
                               5885                 :            122 :     return my_command;
                               5886                 :                : }
                               5887                 :                : 
                               5888                 :                : static void
 2725 teodor@sigaev.ru         5889                 :              6 : ConditionError(const char *desc, int cmdn, const char *msg)
                               5890                 :                : {
 1247 tgl@sss.pgh.pa.us        5891                 :              6 :     pg_fatal("condition error in script \"%s\" command %d: %s",
                               5892                 :                :              desc, cmdn, msg);
                               5893                 :                : }
                               5894                 :                : 
                               5895                 :                : /*
                               5896                 :                :  * Partial evaluation of conditionals before recording and running the script.
                               5897                 :                :  */
                               5898                 :                : static void
 1259                          5899                 :            248 : CheckConditional(const ParsedScript *ps)
                               5900                 :                : {
                               5901                 :                :     /* statically check conditional structure */
 2725 teodor@sigaev.ru         5902                 :            248 :     ConditionalStack cs = conditional_stack_create();
                               5903                 :                :     int         i;
                               5904                 :                : 
 1259 tgl@sss.pgh.pa.us        5905         [ +  + ]:           1124 :     for (i = 0; ps->commands[i] != NULL; i++)
                               5906                 :                :     {
                               5907                 :            881 :         Command    *cmd = ps->commands[i];
                               5908                 :                : 
 2725 teodor@sigaev.ru         5909         [ +  + ]:            881 :         if (cmd->type == META_COMMAND)
                               5910                 :                :         {
                               5911   [ +  +  +  +  :            461 :             switch (cmd->meta)
                                                 + ]
                               5912                 :                :             {
 2690 tgl@sss.pgh.pa.us        5913                 :             20 :                 case META_IF:
                               5914                 :             20 :                     conditional_stack_push(cs, IFSTATE_FALSE);
                               5915                 :             20 :                     break;
                               5916                 :             12 :                 case META_ELIF:
                               5917         [ +  + ]:             12 :                     if (conditional_stack_empty(cs))
 1259                          5918                 :              1 :                         ConditionError(ps->desc, i + 1, "\\elif without matching \\if");
 2690                          5919         [ +  + ]:             11 :                     if (conditional_stack_peek(cs) == IFSTATE_ELSE_FALSE)
 1259                          5920                 :              1 :                         ConditionError(ps->desc, i + 1, "\\elif after \\else");
 2690                          5921                 :             10 :                     break;
                               5922                 :             13 :                 case META_ELSE:
                               5923         [ +  + ]:             13 :                     if (conditional_stack_empty(cs))
 1259                          5924                 :              1 :                         ConditionError(ps->desc, i + 1, "\\else without matching \\if");
 2690                          5925         [ +  + ]:             12 :                     if (conditional_stack_peek(cs) == IFSTATE_ELSE_FALSE)
 1259                          5926                 :              1 :                         ConditionError(ps->desc, i + 1, "\\else after \\else");
 2690                          5927                 :             11 :                     conditional_stack_poke(cs, IFSTATE_ELSE_FALSE);
                               5928                 :             11 :                     break;
                               5929                 :             18 :                 case META_ENDIF:
                               5930         [ +  + ]:             18 :                     if (!conditional_stack_pop(cs))
 1259                          5931                 :              1 :                         ConditionError(ps->desc, i + 1, "\\endif without matching \\if");
 2690                          5932                 :             17 :                     break;
                               5933                 :            398 :                 default:
                               5934                 :                :                     /* ignore anything else... */
                               5935                 :            398 :                     break;
                               5936                 :                :             }
                               5937                 :                :         }
                               5938                 :                :     }
 2725 teodor@sigaev.ru         5939         [ +  + ]:            243 :     if (!conditional_stack_empty(cs))
 1259 tgl@sss.pgh.pa.us        5940                 :              1 :         ConditionError(ps->desc, i + 1, "\\if without matching \\endif");
 2725 teodor@sigaev.ru         5941                 :            242 :     conditional_stack_destroy(cs);
                               5942                 :            242 : }
                               5943                 :                : 
                               5944                 :                : /*
                               5945                 :                :  * Parse a script (either the contents of a file, or a built-in script)
                               5946                 :                :  * and add it to the list of scripts.
                               5947                 :                :  */
                               5948                 :                : static void
 3457 tgl@sss.pgh.pa.us        5949                 :            283 : ParseScript(const char *script, const char *desc, int weight)
                               5950                 :                : {
                               5951                 :                :     ParsedScript ps;
                               5952                 :                :     PsqlScanState sstate;
                               5953                 :                :     PQExpBufferData line_buf;
                               5954                 :                :     int         alloc_num;
                               5955                 :                :     int         index;
                               5956                 :                : 
                               5957                 :                : #define COMMANDS_ALLOC_NUM 128
                               5958                 :            283 :     alloc_num = COMMANDS_ALLOC_NUM;
                               5959                 :                : 
                               5960                 :                :     /* Initialize all fields of ps */
                               5961                 :            283 :     ps.desc = desc;
                               5962                 :            283 :     ps.weight = weight;
                               5963                 :            283 :     ps.commands = (Command **) pg_malloc(sizeof(Command *) * alloc_num);
 3169                          5964                 :            283 :     initStats(&ps.stats, 0);
                               5965                 :                : 
                               5966                 :                :     /* Prepare to parse script */
 3457                          5967                 :            283 :     sstate = psql_scan_create(&pgbench_callbacks);
                               5968                 :                : 
                               5969                 :                :     /*
                               5970                 :                :      * Ideally, we'd scan scripts using the encoding and stdstrings settings
                               5971                 :                :      * we get from a DB connection.  However, without major rearrangement of
                               5972                 :                :      * pgbench's argument parsing, we can't have a DB connection at the time
                               5973                 :                :      * we parse scripts.  Using SQL_ASCII (encoding 0) should work well enough
                               5974                 :                :      * with any backend-safe encoding, though conceivably we could be fooled
                               5975                 :                :      * if a script file uses a client-only encoding.  We also assume that
                               5976                 :                :      * stdstrings should be true, which is a bit riskier.
                               5977                 :                :      */
                               5978                 :            283 :     psql_scan_setup(sstate, script, strlen(script), 0, true);
                               5979                 :                : 
                               5980                 :            283 :     initPQExpBuffer(&line_buf);
                               5981                 :                : 
                               5982                 :            283 :     index = 0;
                               5983                 :                : 
                               5984                 :                :     for (;;)
                               5985                 :            888 :     {
                               5986                 :                :         PsqlScanResult sr;
                               5987                 :                :         promptStatus_t prompt;
 2431 alvherre@alvh.no-ip.     5988                 :           1171 :         Command    *command = NULL;
                               5989                 :                : 
 3457 tgl@sss.pgh.pa.us        5990                 :           1171 :         resetPQExpBuffer(&line_buf);
                               5991                 :                : 
                               5992                 :           1171 :         sr = psql_scan(sstate, &line_buf, &prompt);
                               5993                 :                : 
                               5994                 :                :         /* If we collected a new SQL command, process that */
 2357 alvherre@alvh.no-ip.     5995                 :           1171 :         command = create_sql_command(&line_buf, desc);
                               5996                 :                : 
                               5997                 :                :         /* store new command */
                               5998         [ +  + ]:           1171 :         if (command)
                               5999                 :            423 :             ps.commands[index++] = command;
                               6000                 :                : 
                               6001                 :                :         /* If we reached a backslash, process that */
 3457 tgl@sss.pgh.pa.us        6002         [ +  + ]:           1171 :         if (sr == PSCAN_BACKSLASH)
                               6003                 :                :         {
                               6004                 :                :             int         lineno;
                               6005                 :                :             int         start_offset;
                               6006                 :                : 
                               6007                 :                :             /* Capture location of the backslash */
  191                          6008                 :            532 :             psql_scan_get_location(sstate, &lineno, &start_offset);
                               6009                 :            532 :             start_offset--;
                               6010                 :                : 
                               6011                 :            532 :             command = process_backslash_command(sstate, desc,
                               6012                 :                :                                                 lineno, start_offset);
                               6013                 :                : 
 3457                          6014         [ +  - ]:            502 :             if (command)
                               6015                 :                :             {
                               6016                 :                :                 /*
                               6017                 :                :                  * If this is gset or aset, merge into the preceding command.
                               6018                 :                :                  * (We don't use a command slot in this case).
                               6019                 :                :                  */
 1982 michael@paquier.xyz      6020   [ +  +  +  + ]:            502 :                 if (command->meta == META_GSET || command->meta == META_ASET)
 3457 tgl@sss.pgh.pa.us        6021                 :             31 :                 {
                               6022                 :                :                     Command    *cmd;
                               6023                 :                : 
 2431 alvherre@alvh.no-ip.     6024         [ +  + ]:             34 :                     if (index == 0)
                               6025                 :              1 :                         syntax_error(desc, lineno, NULL, NULL,
                               6026                 :                :                                      "\\gset must follow an SQL command",
                               6027                 :                :                                      NULL, -1);
                               6028                 :                : 
                               6029                 :             33 :                     cmd = ps.commands[index - 1];
                               6030                 :                : 
 2357                          6031         [ +  + ]:             33 :                     if (cmd->type != SQL_COMMAND ||
                               6032         [ +  + ]:             32 :                         cmd->varprefix != NULL)
 2431                          6033                 :              2 :                         syntax_error(desc, lineno, NULL, NULL,
                               6034                 :                :                                      "\\gset must follow an SQL command",
                               6035                 :              2 :                                      cmd->first_line, -1);
                               6036                 :                : 
                               6037                 :                :                     /* get variable prefix */
                               6038   [ +  +  -  + ]:             31 :                     if (command->argc <= 1 || command->argv[1][0] == '\0')
 2357                          6039                 :             29 :                         cmd->varprefix = pg_strdup("");
                               6040                 :                :                     else
                               6041                 :              2 :                         cmd->varprefix = pg_strdup(command->argv[1]);
                               6042                 :                : 
                               6043                 :                :                     /* update the sql command meta */
 1982 michael@paquier.xyz      6044                 :             31 :                     cmd->meta = command->meta;
                               6045                 :                : 
                               6046                 :                :                     /* cleanup unused command */
 2431 alvherre@alvh.no-ip.     6047                 :             31 :                     free_command(command);
                               6048                 :                : 
                               6049                 :             31 :                     continue;
                               6050                 :                :                 }
                               6051                 :                : 
                               6052                 :                :                 /* Attach any other backslash command as a new command */
                               6053                 :            468 :                 ps.commands[index++] = command;
                               6054                 :                :             }
                               6055                 :                :         }
                               6056                 :                : 
                               6057                 :                :         /*
                               6058                 :                :          * Since we used a command slot, allocate more if needed.  Note we
                               6059                 :                :          * always allocate one more in order to accommodate the NULL
                               6060                 :                :          * terminator below.
                               6061                 :                :          */
                               6062         [ -  + ]:           1107 :         if (index >= alloc_num)
                               6063                 :                :         {
 2431 alvherre@alvh.no-ip.     6064                 :UBC           0 :             alloc_num += COMMANDS_ALLOC_NUM;
                               6065                 :              0 :             ps.commands = (Command **)
                               6066                 :              0 :                 pg_realloc(ps.commands, sizeof(Command *) * alloc_num);
                               6067                 :                :         }
                               6068                 :                : 
                               6069                 :                :         /* Done if we reached EOF */
 3457 tgl@sss.pgh.pa.us        6070   [ +  +  +  + ]:CBC        1107 :         if (sr == PSCAN_INCOMPLETE || sr == PSCAN_EOL)
                               6071                 :                :             break;
                               6072                 :                :     }
                               6073                 :                : 
                               6074                 :            250 :     ps.commands[index] = NULL;
                               6075                 :                : 
 1259                          6076                 :            250 :     addScript(&ps);
                               6077                 :                : 
 3457                          6078                 :            242 :     termPQExpBuffer(&line_buf);
                               6079                 :            242 :     psql_scan_finish(sstate);
                               6080                 :            242 :     psql_scan_destroy(sstate);
 7277 ishii@postgresql.org     6081                 :            242 : }
                               6082                 :                : 
                               6083                 :                : /*
                               6084                 :                :  * Read the entire contents of file fd, and return it in a malloc'd buffer.
                               6085                 :                :  *
                               6086                 :                :  * The buffer will typically be larger than necessary, but we don't care
                               6087                 :                :  * in this program, because we'll free it as soon as we've parsed the script.
                               6088                 :                :  */
                               6089                 :                : static char *
 3457 tgl@sss.pgh.pa.us        6090                 :            130 : read_file_contents(FILE *fd)
                               6091                 :                : {
                               6092                 :                :     char       *buf;
 4313                          6093                 :            130 :     size_t      buflen = BUFSIZ;
                               6094                 :            130 :     size_t      used = 0;
                               6095                 :                : 
 3457                          6096                 :            130 :     buf = (char *) pg_malloc(buflen);
                               6097                 :                : 
                               6098                 :                :     for (;;)
 4313 tgl@sss.pgh.pa.us        6099                 :UBC           0 :     {
                               6100                 :                :         size_t      nread;
                               6101                 :                : 
 3457 tgl@sss.pgh.pa.us        6102                 :CBC         130 :         nread = fread(buf + used, 1, BUFSIZ, fd);
                               6103                 :            130 :         used += nread;
                               6104                 :                :         /* If fread() read less than requested, must be EOF or error */
                               6105         [ +  - ]:            130 :         if (nread < BUFSIZ)
 4313                          6106                 :            130 :             break;
                               6107                 :                :         /* Enlarge buf so we can read some more */
 4313 tgl@sss.pgh.pa.us        6108                 :UBC           0 :         buflen += BUFSIZ;
                               6109                 :              0 :         buf = (char *) pg_realloc(buf, buflen);
                               6110                 :                :     }
                               6111                 :                :     /* There is surely room for a terminator */
 3457 tgl@sss.pgh.pa.us        6112                 :CBC         130 :     buf[used] = '\0';
                               6113                 :                : 
                               6114                 :            130 :     return buf;
                               6115                 :                : }
                               6116                 :                : 
                               6117                 :                : /*
                               6118                 :                :  * Given a file name, read it and add its script to the list.
                               6119                 :                :  * "-" means to read stdin.
                               6120                 :                :  * NB: filename must be storage that won't disappear.
                               6121                 :                :  */
                               6122                 :                : static void
                               6123                 :            131 : process_file(const char *filename, int weight)
                               6124                 :                : {
                               6125                 :                :     FILE       *fd;
                               6126                 :                :     char       *buf;
                               6127                 :                : 
                               6128                 :                :     /* Slurp the file contents into "buf" */
 7277 ishii@postgresql.org     6129         [ -  + ]:            131 :     if (strcmp(filename, "-") == 0)
 7277 ishii@postgresql.org     6130                 :UBC           0 :         fd = stdin;
 7277 ishii@postgresql.org     6131         [ +  + ]:CBC         131 :     else if ((fd = fopen(filename, "r")) == NULL)
 1247 tgl@sss.pgh.pa.us        6132                 :              1 :         pg_fatal("could not open file \"%s\": %m", filename);
                               6133                 :                : 
 3457                          6134                 :            130 :     buf = read_file_contents(fd);
                               6135                 :                : 
                               6136         [ -  + ]:            130 :     if (ferror(fd))
 1247 tgl@sss.pgh.pa.us        6137                 :UBC           0 :         pg_fatal("could not read file \"%s\": %m", filename);
                               6138                 :                : 
 3457 tgl@sss.pgh.pa.us        6139         [ +  - ]:CBC         130 :     if (fd != stdin)
                               6140                 :            130 :         fclose(fd);
                               6141                 :                : 
                               6142                 :            130 :     ParseScript(buf, filename, weight);
                               6143                 :                : 
                               6144                 :             90 :     free(buf);
 7277 ishii@postgresql.org     6145                 :             90 : }
                               6146                 :                : 
                               6147                 :                : /* Parse the given builtin script and add it to the list. */
                               6148                 :                : static void
 3457 tgl@sss.pgh.pa.us        6149                 :            153 : process_builtin(const BuiltinScript *bi, int weight)
                               6150                 :                : {
                               6151                 :            153 :     ParseScript(bi->script, bi->desc, weight);
 7282 ishii@postgresql.org     6152                 :            152 : }
                               6153                 :                : 
                               6154                 :                : /* show available builtin scripts */
                               6155                 :                : static void
 3510 alvherre@alvh.no-ip.     6156                 :              3 : listAvailableScripts(void)
                               6157                 :                : {
                               6158                 :                :     int         i;
                               6159                 :                : 
                               6160                 :              3 :     fprintf(stderr, "Available builtin scripts:\n");
 3458                          6161         [ +  + ]:             12 :     for (i = 0; i < lengthof(builtin_script); i++)
 2244 tmunro@postgresql.or     6162                 :              9 :         fprintf(stderr, "  %13s: %s\n", builtin_script[i].name, builtin_script[i].desc);
 3510 alvherre@alvh.no-ip.     6163                 :              3 :     fprintf(stderr, "\n");
                               6164                 :              3 : }
                               6165                 :                : 
                               6166                 :                : /* return builtin script "name" if unambiguous, fails if not found */
                               6167                 :                : static const BuiltinScript *
 3458                          6168                 :            156 : findBuiltin(const char *name)
                               6169                 :                : {
                               6170                 :                :     int         i,
 3474                          6171                 :            156 :                 found = 0,
                               6172                 :            156 :                 len = strlen(name);
 3457 tgl@sss.pgh.pa.us        6173                 :            156 :     const BuiltinScript *result = NULL;
                               6174                 :                : 
 3458 alvherre@alvh.no-ip.     6175         [ +  + ]:            624 :     for (i = 0; i < lengthof(builtin_script); i++)
                               6176                 :                :     {
 3474                          6177         [ +  + ]:            468 :         if (strncmp(builtin_script[i].name, name, len) == 0)
                               6178                 :                :         {
 3458                          6179                 :            156 :             result = &builtin_script[i];
 3474                          6180                 :            156 :             found++;
                               6181                 :                :         }
                               6182                 :                :     }
                               6183                 :                : 
                               6184                 :                :     /* ok, unambiguous result */
                               6185         [ +  + ]:            156 :     if (found == 1)
 3458                          6186                 :            154 :         return result;
                               6187                 :                : 
                               6188                 :                :     /* error cases */
 3474                          6189         [ +  + ]:              2 :     if (found == 0)
 1247 tgl@sss.pgh.pa.us        6190                 :              1 :         pg_log_error("no builtin script found for name \"%s\"", name);
                               6191                 :                :     else                        /* found > 1 */
                               6192                 :              1 :         pg_log_error("ambiguous builtin name: %d builtin scripts found for prefix \"%s\"", found, name);
                               6193                 :                : 
 3510 alvherre@alvh.no-ip.     6194                 :              2 :     listAvailableScripts();
                               6195                 :              2 :     exit(1);
                               6196                 :                : }
                               6197                 :                : 
                               6198                 :                : /*
                               6199                 :                :  * Determine the weight specification from a script option (-b, -f), if any,
                               6200                 :                :  * and return it as an integer (1 is returned if there's no weight).  The
                               6201                 :                :  * script name is returned in *script as a malloc'd string.
                               6202                 :                :  */
                               6203                 :                : static int
 3458                          6204                 :            142 : parseScriptWeight(const char *option, char **script)
                               6205                 :                : {
                               6206                 :                :     char       *sep;
                               6207                 :                :     int         weight;
                               6208                 :                : 
                               6209         [ +  + ]:            142 :     if ((sep = strrchr(option, WSEP)))
                               6210                 :                :     {
                               6211                 :              9 :         int         namelen = sep - option;
                               6212                 :                :         long        wtmp;
                               6213                 :                :         char       *badp;
                               6214                 :                : 
                               6215                 :                :         /* generate the script name */
                               6216                 :              9 :         *script = pg_malloc(namelen + 1);
                               6217                 :              9 :         strncpy(*script, option, namelen);
                               6218                 :              9 :         (*script)[namelen] = '\0';
                               6219                 :                : 
                               6220                 :                :         /* process digits of the weight spec */
                               6221                 :              9 :         errno = 0;
                               6222                 :              9 :         wtmp = strtol(sep + 1, &badp, 10);
                               6223   [ +  -  +  +  :              9 :         if (errno != 0 || badp == sep + 1 || *badp != '\0')
                                              -  + ]
 1247 tgl@sss.pgh.pa.us        6224                 :              1 :             pg_fatal("invalid weight specification: %s", sep);
 3448 alvherre@alvh.no-ip.     6225   [ +  -  +  + ]:              8 :         if (wtmp > INT_MAX || wtmp < 0)
 1247 tgl@sss.pgh.pa.us        6226                 :              1 :             pg_fatal("weight specification out of range (0 .. %d): %lld",
                               6227                 :                :                      INT_MAX, (long long) wtmp);
 3458 alvherre@alvh.no-ip.     6228                 :              7 :         weight = wtmp;
                               6229                 :                :     }
                               6230                 :                :     else
                               6231                 :                :     {
                               6232                 :            133 :         *script = pg_strdup(option);
                               6233                 :            133 :         weight = 1;
                               6234                 :                :     }
                               6235                 :                : 
                               6236                 :            140 :     return weight;
                               6237                 :                : }
                               6238                 :                : 
                               6239                 :                : /* append a script to the list of scripts to process */
                               6240                 :                : static void
 1259 tgl@sss.pgh.pa.us        6241                 :            250 : addScript(const ParsedScript *script)
                               6242                 :                : {
                               6243   [ +  -  +  + ]:            250 :     if (script->commands == NULL || script->commands[0] == NULL)
 1247                          6244                 :              1 :         pg_fatal("empty command list for script \"%s\"", script->desc);
                               6245                 :                : 
 3510 alvherre@alvh.no-ip.     6246         [ +  + ]:            249 :     if (num_scripts >= MAX_SCRIPTS)
 1247 tgl@sss.pgh.pa.us        6247                 :              1 :         pg_fatal("at most %d SQL scripts are allowed", MAX_SCRIPTS);
                               6248                 :                : 
 2725 teodor@sigaev.ru         6249                 :            248 :     CheckConditional(script);
                               6250                 :                : 
 1259 tgl@sss.pgh.pa.us        6251                 :            242 :     sql_script[num_scripts] = *script;
 3510 alvherre@alvh.no-ip.     6252                 :            242 :     num_scripts++;
                               6253                 :            242 : }
                               6254                 :                : 
                               6255                 :                : /*
                               6256                 :                :  * Print progress report.
                               6257                 :                :  *
                               6258                 :                :  * On entry, *last and *last_report contain the statistics and time of last
                               6259                 :                :  * progress report.  On exit, they are updated with the new stats.
                               6260                 :                :  */
                               6261                 :                : static void
 1641 tmunro@postgresql.or     6262                 :UBC           0 : printProgressReport(TState *threads, int64 test_start, pg_time_usec_t now,
                               6263                 :                :                     StatsData *last, int64 *last_report)
                               6264                 :                : {
                               6265                 :                :     /* generate and show report */
                               6266                 :              0 :     pg_time_usec_t run = now - *last_report;
                               6267                 :                :     int64       cnt,
                               6268                 :                :                 failures,
                               6269                 :                :                 retried;
                               6270                 :                :     double      tps,
                               6271                 :                :                 total_run,
                               6272                 :                :                 latency,
                               6273                 :                :                 sqlat,
                               6274                 :                :                 lag,
                               6275                 :                :                 stdev;
                               6276                 :                :     char        tbuf[315];
                               6277                 :                :     StatsData   cur;
                               6278                 :                : 
                               6279                 :                :     /*
                               6280                 :                :      * Add up the statistics of all threads.
                               6281                 :                :      *
                               6282                 :                :      * XXX: No locking.  There is no guarantee that we get an atomic snapshot
                               6283                 :                :      * of the transaction count and latencies, so these figures can well be
                               6284                 :                :      * off by a small amount.  The progress report's purpose is to give a
                               6285                 :                :      * quick overview of how the test is going, so that shouldn't matter too
                               6286                 :                :      * much.  (If a read from a 64-bit integer is not atomic, you might get a
                               6287                 :                :      * "torn" read and completely bogus latencies though!)
                               6288                 :                :      */
 2357 heikki.linnakangas@i     6289                 :              0 :     initStats(&cur, 0);
                               6290         [ #  # ]:              0 :     for (int i = 0; i < nthreads; i++)
                               6291                 :                :     {
 2348 tgl@sss.pgh.pa.us        6292                 :              0 :         mergeSimpleStats(&cur.latency, &threads[i].stats.latency);
                               6293                 :              0 :         mergeSimpleStats(&cur.lag, &threads[i].stats.lag);
                               6294                 :              0 :         cur.cnt += threads[i].stats.cnt;
                               6295                 :              0 :         cur.skipped += threads[i].stats.skipped;
 1263 ishii@postgresql.org     6296                 :              0 :         cur.retries += threads[i].stats.retries;
                               6297                 :              0 :         cur.retried += threads[i].stats.retried;
                               6298                 :              0 :         cur.serialization_failures +=
                               6299                 :              0 :             threads[i].stats.serialization_failures;
                               6300                 :              0 :         cur.deadlock_failures += threads[i].stats.deadlock_failures;
                               6301                 :                :     }
                               6302                 :                : 
                               6303                 :                :     /* we count only actually executed transactions */
                               6304                 :              0 :     cnt = cur.cnt - last->cnt;
 2357 heikki.linnakangas@i     6305                 :              0 :     total_run = (now - test_start) / 1000000.0;
 1263 ishii@postgresql.org     6306                 :              0 :     tps = 1000000.0 * cnt / run;
                               6307         [ #  # ]:              0 :     if (cnt > 0)
                               6308                 :                :     {
                               6309                 :              0 :         latency = 0.001 * (cur.latency.sum - last->latency.sum) / cnt;
                               6310                 :              0 :         sqlat = 1.0 * (cur.latency.sum2 - last->latency.sum2) / cnt;
 2357 heikki.linnakangas@i     6311                 :              0 :         stdev = 0.001 * sqrt(sqlat - 1000000.0 * latency * latency);
 1263 ishii@postgresql.org     6312                 :              0 :         lag = 0.001 * (cur.lag.sum - last->lag.sum) / cnt;
                               6313                 :                :     }
                               6314                 :                :     else
                               6315                 :                :     {
 2357 heikki.linnakangas@i     6316                 :              0 :         latency = sqlat = stdev = lag = 0;
                               6317                 :                :     }
 1263 ishii@postgresql.org     6318                 :              0 :     failures = getFailures(&cur) - getFailures(last);
                               6319                 :              0 :     retried = cur.retried - last->retried;
                               6320                 :                : 
 2357 heikki.linnakangas@i     6321         [ #  # ]:              0 :     if (progress_timestamp)
                               6322                 :                :     {
 1518 tmunro@postgresql.or     6323                 :              0 :         snprintf(tbuf, sizeof(tbuf), "%.3f s",
                               6324                 :              0 :                  PG_TIME_GET_DOUBLE(now + epoch_shift));
                               6325                 :                :     }
                               6326                 :                :     else
                               6327                 :                :     {
                               6328                 :                :         /* round seconds are expected, but the thread may be late */
 2357 heikki.linnakangas@i     6329                 :              0 :         snprintf(tbuf, sizeof(tbuf), "%.1f s", total_run);
                               6330                 :                :     }
                               6331                 :                : 
                               6332                 :              0 :     fprintf(stderr,
                               6333                 :                :             "progress: %s, %.1f tps, lat %.3f ms stddev %.3f, " INT64_FORMAT " failed",
                               6334                 :                :             tbuf, tps, latency, stdev, failures);
                               6335                 :                : 
                               6336         [ #  # ]:              0 :     if (throttle_delay)
                               6337                 :                :     {
                               6338                 :              0 :         fprintf(stderr, ", lag %.3f ms", lag);
                               6339         [ #  # ]:              0 :         if (latency_limit)
                               6340                 :              0 :             fprintf(stderr, ", " INT64_FORMAT " skipped",
                               6341                 :              0 :                     cur.skipped - last->skipped);
                               6342                 :                :     }
                               6343                 :                : 
                               6344                 :                :     /* it can be non-zero only if max_tries is not equal to one */
 1263 ishii@postgresql.org     6345         [ #  # ]:              0 :     if (max_tries != 1)
                               6346                 :              0 :         fprintf(stderr,
                               6347                 :                :                 ", " INT64_FORMAT " retried, " INT64_FORMAT " retries",
                               6348                 :              0 :                 retried, cur.retries - last->retries);
 2357 heikki.linnakangas@i     6349                 :              0 :     fprintf(stderr, "\n");
                               6350                 :                : 
                               6351                 :              0 :     *last = cur;
                               6352                 :              0 :     *last_report = now;
                               6353                 :              0 : }
                               6354                 :                : 
                               6355                 :                : static void
 2867 peter_e@gmx.net          6356                 :CBC          15 : printSimpleStats(const char *prefix, SimpleStats *ss)
                               6357                 :                : {
 2846 tgl@sss.pgh.pa.us        6358         [ +  - ]:             15 :     if (ss->count > 0)
                               6359                 :                :     {
                               6360                 :             15 :         double      latency = ss->sum / ss->count;
                               6361                 :             15 :         double      stddev = sqrt(ss->sum2 / ss->count - latency * latency);
                               6362                 :                : 
                               6363                 :             15 :         printf("%s average = %.3f ms\n", prefix, 0.001 * latency);
                               6364                 :             15 :         printf("%s stddev = %.3f ms\n", prefix, 0.001 * stddev);
                               6365                 :                :     }
 3508 alvherre@alvh.no-ip.     6366                 :             15 : }
                               6367                 :                : 
                               6368                 :                : /* print version banner */
                               6369                 :                : static void
 1541 tgl@sss.pgh.pa.us        6370                 :             87 : printVersion(PGconn *con)
                               6371                 :                : {
                               6372                 :             87 :     int         server_ver = PQserverVersion(con);
                               6373                 :             87 :     int         client_ver = PG_VERSION_NUM;
                               6374                 :                : 
                               6375         [ -  + ]:             87 :     if (server_ver != client_ver)
                               6376                 :                :     {
                               6377                 :                :         const char *server_version;
                               6378                 :                :         char        sverbuf[32];
                               6379                 :                : 
                               6380                 :                :         /* Try to get full text form, might include "devel" etc */
 1541 tgl@sss.pgh.pa.us        6381                 :UBC           0 :         server_version = PQparameterStatus(con, "server_version");
                               6382                 :                :         /* Otherwise fall back on server_ver */
                               6383         [ #  # ]:              0 :         if (!server_version)
                               6384                 :                :         {
                               6385                 :              0 :             formatPGVersionNumber(server_ver, true,
                               6386                 :                :                                   sverbuf, sizeof(sverbuf));
                               6387                 :              0 :             server_version = sverbuf;
                               6388                 :                :         }
                               6389                 :                : 
                               6390                 :              0 :         printf(_("%s (%s, server %s)\n"),
                               6391                 :                :                "pgbench", PG_VERSION, server_version);
                               6392                 :                :     }
                               6393                 :                :     /* For version match, only print pgbench version */
                               6394                 :                :     else
 1541 tgl@sss.pgh.pa.us        6395                 :CBC          87 :         printf("%s (%s)\n", "pgbench", PG_VERSION);
                               6396                 :             87 :     fflush(stdout);
                               6397                 :             87 : }
                               6398                 :                : 
                               6399                 :                : /* print out results */
                               6400                 :                : static void
 1641 tmunro@postgresql.or     6401                 :             85 : printResults(StatsData *total,
                               6402                 :                :              pg_time_usec_t total_duration, /* benchmarking time */
                               6403                 :                :              pg_time_usec_t conn_total_duration,    /* is_connect */
                               6404                 :                :              pg_time_usec_t conn_elapsed_duration,  /* !is_connect */
                               6405                 :                :              int64 latency_late)
                               6406                 :                : {
                               6407                 :                :     /* tps is about actually executed transactions during benchmarking */
 1263 ishii@postgresql.org     6408                 :             85 :     int64       failures = getFailures(total);
                               6409                 :             85 :     int64       total_cnt = total->cnt + total->skipped + failures;
 1641 tmunro@postgresql.or     6410                 :             85 :     double      bench_duration = PG_TIME_GET_DOUBLE(total_duration);
 1263 ishii@postgresql.org     6411                 :             85 :     double      tps = total->cnt / bench_duration;
                               6412                 :                : 
                               6413                 :                :     /* Report test parameters. */
 3510 alvherre@alvh.no-ip.     6414         [ +  + ]:             85 :     printf("transaction type: %s\n",
                               6415                 :                :            num_scripts == 1 ? sql_script[0].desc : "multiple scripts");
 6933 ishii@postgresql.org     6416                 :             85 :     printf("scaling factor: %d\n", scale);
                               6417                 :                :     /* only print partitioning information if some partitioning was detected */
 2167 akapila@postgresql.o     6418         [ +  + ]:             85 :     if (partition_method != PART_NONE)
                               6419                 :              6 :         printf("partition method: %s\npartitions: %d\n",
                               6420                 :                :                PARTITION_METHOD[partition_method], partitions);
 6380 ishii@postgresql.org     6421                 :             85 :     printf("query mode: %s\n", QUERYMODE[querymode]);
 9278 bruce@momjian.us         6422                 :             85 :     printf("number of clients: %d\n", nclients);
 5878 ishii@postgresql.org     6423                 :             85 :     printf("number of threads: %d\n", nthreads);
                               6424                 :                : 
 1263                          6425         [ +  - ]:             85 :     if (max_tries)
 1235 peter@eisentraut.org     6426                 :             85 :         printf("maximum number of tries: %u\n", max_tries);
                               6427                 :                : 
 6204 tgl@sss.pgh.pa.us        6428         [ +  - ]:             85 :     if (duration <= 0)
                               6429                 :                :     {
                               6430                 :             85 :         printf("number of transactions per client: %d\n", nxacts);
 3508 alvherre@alvh.no-ip.     6431                 :             85 :         printf("number of transactions actually processed: " INT64_FORMAT "/%d\n",
                               6432                 :                :                total->cnt, nxacts * nclients);
                               6433                 :                :     }
                               6434                 :                :     else
                               6435                 :                :     {
 6204 tgl@sss.pgh.pa.us        6436                 :UBC           0 :         printf("duration: %d s\n", duration);
 4122                          6437                 :              0 :         printf("number of transactions actually processed: " INT64_FORMAT "\n",
                               6438                 :                :                total->cnt);
                               6439                 :                :     }
                               6440                 :                : 
                               6441                 :                :     /*
                               6442                 :                :      * Remaining stats are nonsensical if we failed to execute any xacts due
                               6443                 :                :      * to others than serialization or deadlock errors
                               6444                 :                :      */
  330 ishii@postgresql.org     6445         [ +  + ]:CBC          85 :     if (total_cnt <= 0)
                               6446                 :             50 :         return;
                               6447                 :                : 
 1263                          6448                 :             35 :     printf("number of failed transactions: " INT64_FORMAT " (%.3f%%)\n",
                               6449                 :                :            failures, 100.0 * failures / total_cnt);
                               6450                 :                : 
                               6451         [ -  + ]:             35 :     if (failures_detailed)
                               6452                 :                :     {
 1263 ishii@postgresql.org     6453                 :UBC           0 :         printf("number of serialization failures: " INT64_FORMAT " (%.3f%%)\n",
                               6454                 :                :                total->serialization_failures,
                               6455                 :                :                100.0 * total->serialization_failures / total_cnt);
                               6456                 :              0 :         printf("number of deadlock failures: " INT64_FORMAT " (%.3f%%)\n",
                               6457                 :                :                total->deadlock_failures,
                               6458                 :                :                100.0 * total->deadlock_failures / total_cnt);
                               6459                 :                :     }
                               6460                 :                : 
                               6461                 :                :     /* it can be non-zero only if max_tries is not equal to one */
 1263 ishii@postgresql.org     6462         [ +  + ]:CBC          35 :     if (max_tries != 1)
                               6463                 :                :     {
                               6464                 :              2 :         printf("number of transactions retried: " INT64_FORMAT " (%.3f%%)\n",
                               6465                 :                :                total->retried, 100.0 * total->retried / total_cnt);
                               6466                 :              2 :         printf("total number of retries: " INT64_FORMAT "\n", total->retries);
                               6467                 :                :     }
                               6468                 :                : 
 3981 heikki.linnakangas@i     6469   [ +  +  +  - ]:             35 :     if (throttle_delay && latency_limit)
 1284 ishii@postgresql.org     6470                 :              2 :         printf("number of transactions skipped: " INT64_FORMAT " (%.3f%%)\n",
                               6471                 :                :                total->skipped, 100.0 * total->skipped / total_cnt);
                               6472                 :                : 
 3981 heikki.linnakangas@i     6473         [ +  + ]:             35 :     if (latency_limit)
 1284 ishii@postgresql.org     6474         [ +  - ]:              2 :         printf("number of transactions above the %.1f ms latency limit: " INT64_FORMAT "/" INT64_FORMAT " (%.3f%%)\n",
                               6475                 :                :                latency_limit / 1000.0, latency_late, total->cnt,
                               6476                 :                :                (total->cnt > 0) ? 100.0 * latency_late / total->cnt : 0.0);
                               6477                 :                : 
 3981 heikki.linnakangas@i     6478   [ +  +  +  -  :             35 :     if (throttle_delay || progress || latency_limit)
                                              -  + ]
 3508 alvherre@alvh.no-ip.     6479                 :              2 :         printSimpleStats("latency", &total->latency);
                               6480                 :                :     else
                               6481                 :                :     {
                               6482                 :                :         /* no measurement, show average latency computed from run time */
 1263 ishii@postgresql.org     6483         [ -  + ]:             33 :         printf("latency average = %.3f ms%s\n",
                               6484                 :                :                0.001 * total_duration * nclients / total_cnt,
                               6485                 :                :                failures > 0 ? " (including failures)" : "");
                               6486                 :                :     }
                               6487                 :                : 
 4428                          6488         [ +  + ]:             35 :     if (throttle_delay)
                               6489                 :                :     {
                               6490                 :                :         /*
                               6491                 :                :          * Report average transaction lag under rate limit throttling.  This
                               6492                 :                :          * is the delay between scheduled and actual start times for the
                               6493                 :                :          * transaction.  The measured lag may be caused by thread/client load,
                               6494                 :                :          * the database load, or the Poisson throttling process.
                               6495                 :                :          */
 4354 noah@leadboat.com        6496                 :              2 :         printf("rate limit schedule lag: avg %.3f (max %.3f) ms\n",
                               6497                 :                :                0.001 * total->lag.sum / total->cnt, 0.001 * total->lag.max);
                               6498                 :                :     }
                               6499                 :                : 
                               6500                 :                :     /*
                               6501                 :                :      * Under -C/--connect, each transaction incurs a significant connection
                               6502                 :                :      * cost, it would not make much sense to ignore it in tps, and it would
                               6503                 :                :      * not be tps anyway.
                               6504                 :                :      *
                               6505                 :                :      * Otherwise connections are made just once at the beginning of the run
                               6506                 :                :      * and should not impact performance but for very short run, so they are
                               6507                 :                :      * (right)fully ignored in tps.
                               6508                 :                :      */
 1641 tmunro@postgresql.or     6509         [ +  + ]:             35 :     if (is_connect)
                               6510                 :                :     {
 1263 ishii@postgresql.org     6511                 :              2 :         printf("average connection time = %.3f ms\n", 0.001 * conn_total_duration / (total->cnt + failures));
 1641 tmunro@postgresql.or     6512                 :              2 :         printf("tps = %f (including reconnection times)\n", tps);
                               6513                 :                :     }
                               6514                 :                :     else
                               6515                 :                :     {
                               6516                 :             33 :         printf("initial connection time = %.3f ms\n", 0.001 * conn_elapsed_duration);
                               6517                 :             33 :         printf("tps = %f (without initial connection time)\n", tps);
                               6518                 :                :     }
                               6519                 :                : 
                               6520                 :                :     /* Report per-script/command statistics */
 2481 alvherre@alvh.no-ip.     6521   [ +  +  +  + ]:             35 :     if (per_script_stats || report_per_command)
                               6522                 :                :     {
                               6523                 :                :         int         i;
                               6524                 :                : 
 3510                          6525         [ +  + ]:             21 :         for (i = 0; i < num_scripts; i++)
                               6526                 :                :         {
 2846 tgl@sss.pgh.pa.us        6527         [ +  + ]:             15 :             if (per_script_stats)
                               6528                 :                :             {
                               6529                 :             13 :                 StatsData  *sstats = &sql_script[i].stats;
 1263 ishii@postgresql.org     6530                 :             13 :                 int64       script_failures = getFailures(sstats);
                               6531                 :             13 :                 int64       script_total_cnt =
  841 tgl@sss.pgh.pa.us        6532                 :             13 :                     sstats->cnt + sstats->skipped + script_failures;
                               6533                 :                : 
 3458 alvherre@alvh.no-ip.     6534                 :             13 :                 printf("SQL script %d: %s\n"
                               6535                 :                :                        " - weight: %d (targets %.1f%% of total)\n"
                               6536                 :                :                        " - " INT64_FORMAT " transactions (%.1f%% of total)\n",
                               6537                 :                :                        i + 1, sql_script[i].desc,
                               6538                 :                :                        sql_script[i].weight,
                               6539                 :                :                        100.0 * sql_script[i].weight / total_weight,
                               6540                 :                :                        script_total_cnt,
                               6541                 :                :                        100.0 * script_total_cnt / total_cnt);
                               6542                 :                : 
  330 ishii@postgresql.org     6543         [ +  - ]:             13 :                 if (script_total_cnt > 0)
                               6544                 :                :                 {
  316                          6545                 :             13 :                     printf(" - number of transactions actually processed: " INT64_FORMAT " (tps = %f)\n",
                               6546                 :                :                            sstats->cnt, sstats->cnt / bench_duration);
                               6547                 :                : 
  330                          6548                 :             13 :                     printf(" - number of failed transactions: " INT64_FORMAT " (%.3f%%)\n",
                               6549                 :                :                            script_failures,
                               6550                 :                :                            100.0 * script_failures / script_total_cnt);
                               6551                 :                : 
                               6552         [ -  + ]:             13 :                     if (failures_detailed)
                               6553                 :                :                     {
  330 ishii@postgresql.org     6554                 :UBC           0 :                         printf(" - number of serialization failures: " INT64_FORMAT " (%.3f%%)\n",
                               6555                 :                :                                sstats->serialization_failures,
                               6556                 :                :                                (100.0 * sstats->serialization_failures /
                               6557                 :                :                                 script_total_cnt));
                               6558                 :              0 :                         printf(" - number of deadlock failures: " INT64_FORMAT " (%.3f%%)\n",
                               6559                 :                :                                sstats->deadlock_failures,
                               6560                 :                :                                (100.0 * sstats->deadlock_failures /
                               6561                 :                :                                 script_total_cnt));
                               6562                 :                :                     }
                               6563                 :                : 
                               6564                 :                :                     /*
                               6565                 :                :                      * it can be non-zero only if max_tries is not equal to
                               6566                 :                :                      * one
                               6567                 :                :                      */
  330 ishii@postgresql.org     6568         [ -  + ]:CBC          13 :                     if (max_tries != 1)
                               6569                 :                :                     {
  330 ishii@postgresql.org     6570                 :UBC           0 :                         printf(" - number of transactions retried: " INT64_FORMAT " (%.3f%%)\n",
                               6571                 :                :                                sstats->retried,
                               6572                 :                :                                100.0 * sstats->retried / script_total_cnt);
                               6573                 :              0 :                         printf(" - total number of retries: " INT64_FORMAT "\n",
                               6574                 :                :                                sstats->retries);
                               6575                 :                :                     }
                               6576                 :                : 
  330 ishii@postgresql.org     6577   [ -  +  -  - ]:CBC          13 :                     if (throttle_delay && latency_limit)
  330 ishii@postgresql.org     6578                 :UBC           0 :                         printf(" - number of transactions skipped: " INT64_FORMAT " (%.3f%%)\n",
                               6579                 :                :                                sstats->skipped,
                               6580                 :                :                                100.0 * sstats->skipped / script_total_cnt);
                               6581                 :                : 
                               6582                 :                :                 }
 2846 tgl@sss.pgh.pa.us        6583                 :CBC          13 :                 printSimpleStats(" - latency", &sstats->latency);
                               6584                 :                :             }
                               6585                 :                : 
                               6586                 :                :             /*
                               6587                 :                :              * Report per-command statistics: latencies, retries after errors,
                               6588                 :                :              * failures (errors without retrying).
                               6589                 :                :              */
 2481 alvherre@alvh.no-ip.     6590         [ +  + ]:             15 :             if (report_per_command)
                               6591                 :                :             {
                               6592                 :                :                 Command   **commands;
                               6593                 :                : 
 1263 ishii@postgresql.org     6594   [ +  -  -  + ]:              2 :                 printf("%sstatement latencies in milliseconds%s:\n",
                               6595                 :                :                        per_script_stats ? " - " : "",
                               6596                 :                :                        (max_tries == 1 ?
                               6597                 :                :                         " and failures" :
                               6598                 :                :                         ", failures and retries"));
                               6599                 :                : 
 3505 alvherre@alvh.no-ip.     6600                 :              2 :                 for (commands = sql_script[i].commands;
                               6601         [ +  + ]:              5 :                      *commands != NULL;
                               6602                 :              3 :                      commands++)
                               6603                 :                :                 {
 2846 tgl@sss.pgh.pa.us        6604                 :              3 :                     SimpleStats *cstats = &(*commands)->stats;
                               6605                 :                : 
 1263 ishii@postgresql.org     6606         [ +  - ]:              3 :                     if (max_tries == 1)
  276 tmunro@postgresql.or     6607         [ +  - ]:              3 :                         printf("   %11.3f  %10" PRId64 " %s\n",
                               6608                 :                :                                (cstats->count > 0) ?
                               6609                 :                :                                1000.0 * cstats->sum / cstats->count : 0.0,
                               6610                 :                :                                (*commands)->failures,
                               6611                 :                :                                (*commands)->first_line);
                               6612                 :                :                     else
  276 tmunro@postgresql.or     6613         [ #  # ]:UBC           0 :                         printf("   %11.3f  %10" PRId64 " %10" PRId64 " %s\n",
                               6614                 :                :                                (cstats->count > 0) ?
                               6615                 :                :                                1000.0 * cstats->sum / cstats->count : 0.0,
                               6616                 :                :                                (*commands)->failures,
                               6617                 :                :                                (*commands)->retries,
                               6618                 :                :                                (*commands)->first_line);
                               6619                 :                :                 }
                               6620                 :                :             }
                               6621                 :                :         }
                               6622                 :                :     }
                               6623                 :                : }
                               6624                 :                : 
                               6625                 :                : /*
                               6626                 :                :  * Set up a random seed according to seed parameter (NULL means default),
                               6627                 :                :  * and initialize base_random_sequence for use in initializing other sequences.
                               6628                 :                :  */
                               6629                 :                : static bool
 2716 tgl@sss.pgh.pa.us        6630                 :CBC         180 : set_random_seed(const char *seed)
                               6631                 :                : {
                               6632                 :                :     uint64      iseed;
                               6633                 :                : 
 2721 teodor@sigaev.ru         6634   [ +  +  -  + ]:            180 :     if (seed == NULL || strcmp(seed, "time") == 0)
                               6635                 :                :     {
                               6636                 :                :         /* rely on current time */
 1641 tmunro@postgresql.or     6637                 :            176 :         iseed = pg_time_now();
                               6638                 :                :     }
 2721 teodor@sigaev.ru         6639         [ -  + ]:              4 :     else if (strcmp(seed, "rand") == 0)
                               6640                 :                :     {
                               6641                 :                :         /* use some "strong" random source */
 2721 teodor@sigaev.ru         6642         [ #  # ]:UBC           0 :         if (!pg_strong_random(&iseed, sizeof(iseed)))
                               6643                 :                :         {
 2068 peter@eisentraut.org     6644                 :              0 :             pg_log_error("could not generate random seed");
 2716 tgl@sss.pgh.pa.us        6645                 :              0 :             return false;
                               6646                 :                :         }
                               6647                 :                :     }
                               6648                 :                :     else
                               6649                 :                :     {
                               6650                 :                :         char        garbage;
                               6651                 :                : 
  161 peter@eisentraut.org     6652         [ +  + ]:CBC           4 :         if (sscanf(seed, "%" SCNu64 "%c", &iseed, &garbage) != 1)
                               6653                 :                :         {
 2068                          6654                 :              1 :             pg_log_error("unrecognized random seed option \"%s\"", seed);
 1247 tgl@sss.pgh.pa.us        6655                 :              1 :             pg_log_error_detail("Expecting an unsigned integer, \"time\" or \"rand\".");
 2716                          6656                 :              1 :             return false;
                               6657                 :                :         }
                               6658                 :                :     }
                               6659                 :                : 
 2721 teodor@sigaev.ru         6660         [ +  + ]:            179 :     if (seed != NULL)
  161 peter@eisentraut.org     6661                 :              3 :         pg_log_info("setting random seed to %" PRIu64, iseed);
                               6662                 :                : 
 2721 teodor@sigaev.ru         6663                 :            179 :     random_seed = iseed;
                               6664                 :                : 
                               6665                 :                :     /* Initialize base_random_sequence using seed */
  161 peter@eisentraut.org     6666                 :            179 :     pg_prng_seed(&base_random_sequence, iseed);
                               6667                 :                : 
 2716 tgl@sss.pgh.pa.us        6668                 :            179 :     return true;
                               6669                 :                : }
                               6670                 :                : 
                               6671                 :                : int
 9278 bruce@momjian.us         6672                 :            178 : main(int argc, char **argv)
                               6673                 :                : {
                               6674                 :                :     static struct option long_options[] = {
                               6675                 :                :         /* systematic long/short named options */
                               6676                 :                :         {"builtin", required_argument, NULL, 'b'},
                               6677                 :                :         {"client", required_argument, NULL, 'c'},
                               6678                 :                :         {"connect", no_argument, NULL, 'C'},
                               6679                 :                :         {"dbname", required_argument, NULL, 'd'},
                               6680                 :                :         {"define", required_argument, NULL, 'D'},
                               6681                 :                :         {"file", required_argument, NULL, 'f'},
                               6682                 :                :         {"fillfactor", required_argument, NULL, 'F'},
                               6683                 :                :         {"host", required_argument, NULL, 'h'},
                               6684                 :                :         {"initialize", no_argument, NULL, 'i'},
                               6685                 :                :         {"init-steps", required_argument, NULL, 'I'},
                               6686                 :                :         {"jobs", required_argument, NULL, 'j'},
                               6687                 :                :         {"log", no_argument, NULL, 'l'},
                               6688                 :                :         {"latency-limit", required_argument, NULL, 'L'},
                               6689                 :                :         {"no-vacuum", no_argument, NULL, 'n'},
                               6690                 :                :         {"port", required_argument, NULL, 'p'},
                               6691                 :                :         {"progress", required_argument, NULL, 'P'},
                               6692                 :                :         {"protocol", required_argument, NULL, 'M'},
                               6693                 :                :         {"quiet", no_argument, NULL, 'q'},
                               6694                 :                :         {"report-per-command", no_argument, NULL, 'r'},
                               6695                 :                :         {"rate", required_argument, NULL, 'R'},
                               6696                 :                :         {"scale", required_argument, NULL, 's'},
                               6697                 :                :         {"select-only", no_argument, NULL, 'S'},
                               6698                 :                :         {"skip-some-updates", no_argument, NULL, 'N'},
                               6699                 :                :         {"time", required_argument, NULL, 'T'},
                               6700                 :                :         {"transactions", required_argument, NULL, 't'},
                               6701                 :                :         {"username", required_argument, NULL, 'U'},
                               6702                 :                :         {"vacuum-all", no_argument, NULL, 'v'},
                               6703                 :                :         /* long-named only options */
                               6704                 :                :         {"unlogged-tables", no_argument, NULL, 1},
                               6705                 :                :         {"tablespace", required_argument, NULL, 2},
                               6706                 :                :         {"index-tablespace", required_argument, NULL, 3},
                               6707                 :                :         {"sampling-rate", required_argument, NULL, 4},
                               6708                 :                :         {"aggregate-interval", required_argument, NULL, 5},
                               6709                 :                :         {"progress-timestamp", no_argument, NULL, 6},
                               6710                 :                :         {"log-prefix", required_argument, NULL, 7},
                               6711                 :                :         {"foreign-keys", no_argument, NULL, 8},
                               6712                 :                :         {"random-seed", required_argument, NULL, 9},
                               6713                 :                :         {"show-script", required_argument, NULL, 10},
                               6714                 :                :         {"partitions", required_argument, NULL, 11},
                               6715                 :                :         {"partition-method", required_argument, NULL, 12},
                               6716                 :                :         {"failures-detailed", no_argument, NULL, 13},
                               6717                 :                :         {"max-tries", required_argument, NULL, 14},
                               6718                 :                :         {"verbose-errors", no_argument, NULL, 15},
                               6719                 :                :         {"exit-on-abort", no_argument, NULL, 16},
                               6720                 :                :         {"debug", no_argument, NULL, 17},
                               6721                 :                :         {NULL, 0, NULL, 0}
                               6722                 :                :     };
                               6723                 :                : 
                               6724                 :                :     int         c;
 2854 tgl@sss.pgh.pa.us        6725                 :            178 :     bool        is_init_mode = false;   /* initialize mode? */
                               6726                 :            178 :     char       *initialize_steps = NULL;
                               6727                 :            178 :     bool        foreign_keys = false;
                               6728                 :            178 :     bool        is_no_vacuum = false;
                               6729                 :            178 :     bool        do_vacuum_accounts = false; /* vacuum accounts table? */
                               6730                 :                :     int         optindex;
 6329                          6731                 :            178 :     bool        scale_given = false;
                               6732                 :                : 
 4043 ishii@postgresql.org     6733                 :            178 :     bool        benchmarking_option_set = false;
                               6734                 :            178 :     bool        initialization_option_set = false;
 3510 alvherre@alvh.no-ip.     6735                 :            178 :     bool        internal_script_used = false;
                               6736                 :                : 
                               6737                 :                :     CState     *state;          /* status of clients */
                               6738                 :                :     TState     *threads;        /* array of thread */
                               6739                 :                : 
                               6740                 :                :     pg_time_usec_t
                               6741                 :                :                 start_time,     /* start up time */
 1641 tmunro@postgresql.or     6742                 :            178 :                 bench_start = 0,    /* first recorded benchmarking time */
                               6743                 :                :                 conn_total_duration;    /* cumulated connection time in
                               6744                 :                :                                          * threads */
 3981 heikki.linnakangas@i     6745                 :            178 :     int64       latency_late = 0;
                               6746                 :                :     StatsData   stats;
                               6747                 :                :     int         weight;
                               6748                 :                : 
                               6749                 :                :     int         i;
                               6750                 :                :     int         nclients_dealt;
                               6751                 :                : 
                               6752                 :                : #ifdef HAVE_GETRLIMIT
                               6753                 :                :     struct rlimit rlim;
                               6754                 :                : #endif
                               6755                 :                : 
                               6756                 :                :     PGconn     *con;
                               6757                 :                :     char       *env;
                               6758                 :                : 
 2524 peter_e@gmx.net          6759                 :            178 :     int         exit_code = 0;
                               6760                 :                :     struct timeval tv;
                               6761                 :                : 
                               6762                 :                :     /*
                               6763                 :                :      * Record difference between Unix time and instr_time time.  We'll use
                               6764                 :                :      * this for logging and aggregation.
                               6765                 :                :      */
 1518 tmunro@postgresql.or     6766                 :            178 :     gettimeofday(&tv, NULL);
                               6767                 :            178 :     epoch_shift = tv.tv_sec * INT64CONST(1000000) + tv.tv_usec - pg_time_now();
                               6768                 :                : 
 2350 peter@eisentraut.org     6769                 :            178 :     pg_logging_init(argv[0]);
 6035 peter_e@gmx.net          6770                 :            178 :     progname = get_progname(argv[0]);
                               6771                 :                : 
                               6772         [ +  - ]:            178 :     if (argc > 1)
                               6773                 :                :     {
                               6774   [ +  +  -  + ]:            178 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
                               6775                 :                :         {
 4812 rhaas@postgresql.org     6776                 :              1 :             usage();
 6035 peter_e@gmx.net          6777                 :              1 :             exit(0);
                               6778                 :                :         }
                               6779   [ +  +  -  + ]:            177 :         if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
                               6780                 :                :         {
                               6781                 :              1 :             puts("pgbench (PostgreSQL) " PG_VERSION);
                               6782                 :              1 :             exit(0);
                               6783                 :                :         }
                               6784                 :                :     }
                               6785                 :                : 
 2355 michael@paquier.xyz      6786                 :            176 :     state = (CState *) pg_malloc0(sizeof(CState));
                               6787                 :                : 
                               6788                 :                :     /* set random seed early, because it may be used while parsing scripts. */
 2716 tgl@sss.pgh.pa.us        6789         [ -  + ]:            176 :     if (!set_random_seed(getenv("PGBENCH_RANDOM_SEED")))
 1247 tgl@sss.pgh.pa.us        6790                 :UBC           0 :         pg_fatal("error while setting random seed from PGBENCH_RANDOM_SEED environment variable");
                               6791                 :                : 
  530 nathan@postgresql.or     6792         [ +  + ]:CBC        1239 :     while ((c = getopt_long(argc, argv, "b:c:Cd:D:f:F:h:iI:j:lL:M:nNp:P:qrR:s:St:T:U:v", long_options, &optindex)) != -1)
                               6793                 :                :     {
                               6794                 :                :         char       *script;
                               6795                 :                : 
 9278 bruce@momjian.us         6796   [ +  +  +  -  :           1132 :         switch (c)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     -  +  +  +  +  
                                                 + ]
                               6797                 :                :         {
  999 peter@eisentraut.org     6798                 :             12 :             case 'b':
                               6799         [ +  + ]:             12 :                 if (strcmp(optarg, "list") == 0)
                               6800                 :                :                 {
                               6801                 :              1 :                     listAvailableScripts();
                               6802                 :              1 :                     exit(0);
                               6803                 :                :                 }
                               6804                 :             11 :                 weight = parseScriptWeight(optarg, &script);
                               6805                 :              9 :                 process_builtin(findBuiltin(script), weight);
 2854 tgl@sss.pgh.pa.us        6806                 :              7 :                 benchmarking_option_set = true;
  999 peter@eisentraut.org     6807                 :              7 :                 internal_script_used = true;
 9278 bruce@momjian.us         6808                 :              7 :                 break;
                               6809                 :             25 :             case 'c':
 4043 ishii@postgresql.org     6810                 :             25 :                 benchmarking_option_set = true;
 1505 michael@paquier.xyz      6811         [ +  + ]:             25 :                 if (!option_parse_int(optarg, "-c/--clients", 1, INT_MAX,
                               6812                 :                :                                       &nclients))
                               6813                 :                :                 {
 9278 bruce@momjian.us         6814                 :              1 :                     exit(1);
                               6815                 :                :                 }
                               6816                 :                : #ifdef HAVE_GETRLIMIT
                               6817         [ -  + ]:             24 :                 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
 1247 tgl@sss.pgh.pa.us        6818                 :UBC           0 :                     pg_fatal("getrlimit failed: %m");
                               6819                 :                : 
  199 andres@anarazel.de       6820         [ -  + ]:CBC          24 :                 if (rlim.rlim_max < nclients + 3)
                               6821                 :                :                 {
 1247 tgl@sss.pgh.pa.us        6822                 :UBC           0 :                     pg_log_error("need at least %d open files, but system limit is %ld",
                               6823                 :                :                                  nclients + 3, (long) rlim.rlim_max);
                               6824                 :              0 :                     pg_log_error_hint("Reduce number of clients, or use limit/ulimit to increase the system limit.");
 9278 bruce@momjian.us         6825                 :              0 :                     exit(1);
                               6826                 :                :                 }
                               6827                 :                : 
  199 andres@anarazel.de       6828         [ -  + ]:CBC          24 :                 if (rlim.rlim_cur < nclients + 3)
                               6829                 :                :                 {
  199 andres@anarazel.de       6830                 :UBC           0 :                     rlim.rlim_cur = nclients + 3;
                               6831         [ #  # ]:              0 :                     if (setrlimit(RLIMIT_NOFILE, &rlim) == -1)
                               6832                 :                :                     {
                               6833                 :              0 :                         pg_log_error("need at least %d open files, but couldn't raise the limit: %m",
                               6834                 :                :                                      nclients + 3);
                               6835                 :              0 :                         pg_log_error_hint("Reduce number of clients, or use limit/ulimit to increase the system limit.");
                               6836                 :              0 :                         exit(1);
                               6837                 :                :                     }
                               6838                 :                :                 }
                               6839                 :                : #endif                          /* HAVE_GETRLIMIT */
 9278 bruce@momjian.us         6840                 :CBC          24 :                 break;
 8717                          6841                 :              2 :             case 'C':
 4043 ishii@postgresql.org     6842                 :              2 :                 benchmarking_option_set = true;
 5646 itagaki.takahiro@gma     6843                 :              2 :                 is_connect = true;
 8717 bruce@momjian.us         6844                 :              2 :                 break;
  999 peter@eisentraut.org     6845                 :UBC           0 :             case 'd':
  530 nathan@postgresql.or     6846                 :              0 :                 dbName = pg_strdup(optarg);
 7282 ishii@postgresql.org     6847                 :              0 :                 break;
 6982 ishii@postgresql.org     6848                 :CBC         433 :             case 'D':
                               6849                 :                :                 {
                               6850                 :                :                     char       *p;
                               6851                 :                : 
 4043                          6852                 :            433 :                     benchmarking_option_set = true;
                               6853                 :                : 
 6982                          6854   [ +  +  +  -  :            433 :                     if ((p = strchr(optarg, '=')) == NULL || p == optarg || *(p + 1) == '\0')
                                              -  + ]
 1247 tgl@sss.pgh.pa.us        6855                 :              1 :                         pg_fatal("invalid variable definition: \"%s\"", optarg);
                               6856                 :                : 
 6982 ishii@postgresql.org     6857                 :            432 :                     *p++ = '\0';
 1263                          6858         [ -  + ]:            432 :                     if (!putVariable(&state[0].variables, "option", optarg, p))
 6982 ishii@postgresql.org     6859                 :UBC           0 :                         exit(1);
                               6860                 :                :                 }
 6982 ishii@postgresql.org     6861                 :CBC         432 :                 break;
  999 peter@eisentraut.org     6862                 :            131 :             case 'f':
                               6863                 :            131 :                 weight = parseScriptWeight(optarg, &script);
                               6864                 :            131 :                 process_file(script, weight);
                               6865                 :             90 :                 benchmarking_option_set = true;
                               6866                 :             90 :                 break;
 6726 ishii@postgresql.org     6867                 :              3 :             case 'F':
 4043                          6868                 :              3 :                 initialization_option_set = true;
 1505 michael@paquier.xyz      6869         [ +  + ]:              3 :                 if (!option_parse_int(optarg, "-F/--fillfactor", 10, 100,
                               6870                 :                :                                       &fillfactor))
 6726 ishii@postgresql.org     6871                 :              1 :                     exit(1);
                               6872                 :              2 :                 break;
  999 peter@eisentraut.org     6873                 :              1 :             case 'h':
                               6874                 :              1 :                 pghost = pg_strdup(optarg);
                               6875                 :              1 :                 break;
                               6876                 :              9 :             case 'i':
                               6877                 :              9 :                 is_init_mode = true;
                               6878                 :              9 :                 break;
                               6879                 :              4 :             case 'I':
                               6880                 :              4 :                 pg_free(initialize_steps);
                               6881                 :              4 :                 initialize_steps = pg_strdup(optarg);
                               6882                 :              4 :                 checkInitSteps(initialize_steps);
                               6883                 :              3 :                 initialization_option_set = true;
                               6884                 :              3 :                 break;
                               6885                 :              4 :             case 'j':           /* jobs */
                               6886                 :              4 :                 benchmarking_option_set = true;
                               6887         [ +  + ]:              4 :                 if (!option_parse_int(optarg, "-j/--jobs", 1, INT_MAX,
                               6888                 :                :                                       &nthreads))
                               6889                 :                :                 {
                               6890                 :              1 :                     exit(1);
                               6891                 :                :                 }
                               6892                 :              3 :                 break;
                               6893                 :              7 :             case 'l':
                               6894                 :              7 :                 benchmarking_option_set = true;
                               6895                 :              7 :                 use_log = true;
                               6896                 :              7 :                 break;
                               6897                 :              3 :             case 'L':
                               6898                 :                :                 {
                               6899                 :              3 :                     double      limit_ms = atof(optarg);
                               6900                 :                : 
                               6901         [ +  + ]:              3 :                     if (limit_ms <= 0.0)
                               6902                 :              1 :                         pg_fatal("invalid latency limit: \"%s\"", optarg);
                               6903                 :              2 :                     benchmarking_option_set = true;
                               6904                 :              2 :                     latency_limit = (int64) (limit_ms * 1000);
                               6905                 :                :                 }
                               6906                 :              2 :                 break;
 6380 ishii@postgresql.org     6907                 :             88 :             case 'M':
 4043                          6908                 :             88 :                 benchmarking_option_set = true;
 6380                          6909         [ +  + ]:            241 :                 for (querymode = 0; querymode < NUM_QUERYMODE; querymode++)
                               6910         [ +  + ]:            240 :                     if (strcmp(optarg, QUERYMODE[querymode]) == 0)
                               6911                 :             87 :                         break;
                               6912         [ +  + ]:             88 :                 if (querymode >= NUM_QUERYMODE)
 1247 tgl@sss.pgh.pa.us        6913                 :              1 :                     pg_fatal("invalid query mode (-M): \"%s\"", optarg);
 6380 ishii@postgresql.org     6914                 :             87 :                 break;
  999 peter@eisentraut.org     6915                 :             99 :             case 'n':
                               6916                 :             99 :                 is_no_vacuum = true;
                               6917                 :             99 :                 break;
                               6918                 :              1 :             case 'N':
                               6919                 :              1 :                 process_builtin(findBuiltin("simple-update"), 1);
                               6920                 :              1 :                 benchmarking_option_set = true;
                               6921                 :              1 :                 internal_script_used = true;
                               6922                 :              1 :                 break;
                               6923                 :              1 :             case 'p':
                               6924                 :              1 :                 pgport = pg_strdup(optarg);
                               6925                 :              1 :                 break;
 4434 ishii@postgresql.org     6926                 :              2 :             case 'P':
 4043                          6927                 :              2 :                 benchmarking_option_set = true;
 1505 michael@paquier.xyz      6928         [ +  + ]:              2 :                 if (!option_parse_int(optarg, "-P/--progress", 1, INT_MAX,
                               6929                 :                :                                       &progress))
 4434 ishii@postgresql.org     6930                 :              1 :                     exit(1);
                               6931                 :              1 :                 break;
  999 peter@eisentraut.org     6932                 :              1 :             case 'q':
                               6933                 :              1 :                 initialization_option_set = true;
                               6934                 :              1 :                 use_quiet = true;
                               6935                 :              1 :                 break;
                               6936                 :              2 :             case 'r':
                               6937                 :              2 :                 benchmarking_option_set = true;
                               6938                 :              2 :                 report_per_command = true;
                               6939                 :              2 :                 break;
 4428 ishii@postgresql.org     6940                 :              3 :             case 'R':
                               6941                 :                :                 {
                               6942                 :                :                     /* get a double from the beginning of option value */
 4141 bruce@momjian.us         6943                 :              3 :                     double      throttle_value = atof(optarg);
                               6944                 :                : 
 4043 ishii@postgresql.org     6945                 :              3 :                     benchmarking_option_set = true;
                               6946                 :                : 
 4141 bruce@momjian.us         6947         [ +  + ]:              3 :                     if (throttle_value <= 0.0)
 1247 tgl@sss.pgh.pa.us        6948                 :              1 :                         pg_fatal("invalid rate limit: \"%s\"", optarg);
                               6949                 :                :                     /* Invert rate limit into per-transaction delay in usec */
 2538                          6950                 :              2 :                     throttle_delay = 1000000.0 / throttle_value;
                               6951                 :                :                 }
 4428 ishii@postgresql.org     6952                 :              2 :                 break;
  999 peter@eisentraut.org     6953                 :              3 :             case 's':
                               6954                 :              3 :                 scale_given = true;
                               6955         [ +  + ]:              3 :                 if (!option_parse_int(optarg, "-s/--scale", 1, INT_MAX,
                               6956                 :                :                                       &scale))
                               6957                 :              1 :                     exit(1);
                               6958                 :              2 :                 break;
                               6959                 :            134 :             case 'S':
                               6960                 :            134 :                 process_builtin(findBuiltin("select-only"), 1);
                               6961                 :            133 :                 benchmarking_option_set = true;
                               6962                 :            133 :                 internal_script_used = true;
                               6963                 :            133 :                 break;
                               6964                 :            110 :             case 't':
                               6965                 :            110 :                 benchmarking_option_set = true;
                               6966         [ +  + ]:            110 :                 if (!option_parse_int(optarg, "-t/--transactions", 1, INT_MAX,
                               6967                 :                :                                       &nxacts))
                               6968                 :              1 :                     exit(1);
                               6969                 :            109 :                 break;
                               6970                 :              5 :             case 'T':
                               6971                 :              5 :                 benchmarking_option_set = true;
                               6972         [ +  + ]:              5 :                 if (!option_parse_int(optarg, "-T/--time", 1, INT_MAX,
                               6973                 :                :                                       &duration))
                               6974                 :              1 :                     exit(1);
                               6975                 :              4 :                 break;
                               6976                 :              1 :             case 'U':
                               6977                 :              1 :                 username = pg_strdup(optarg);
                               6978                 :              1 :                 break;
                               6979                 :              1 :             case 'v':
                               6980                 :              1 :                 benchmarking_option_set = true;
                               6981                 :              1 :                 do_vacuum_accounts = true;
 3981 heikki.linnakangas@i     6982                 :              1 :                 break;
 2854 tgl@sss.pgh.pa.us        6983                 :              2 :             case 1:             /* unlogged-tables */
                               6984                 :              2 :                 initialization_option_set = true;
                               6985                 :              2 :                 unlogged_tables = true;
 5157 rhaas@postgresql.org     6986                 :              2 :                 break;
 4836 bruce@momjian.us         6987                 :              1 :             case 2:             /* tablespace */
 4043 ishii@postgresql.org     6988                 :              1 :                 initialization_option_set = true;
 4712 bruce@momjian.us         6989                 :              1 :                 tablespace = pg_strdup(optarg);
 5157 rhaas@postgresql.org     6990                 :              1 :                 break;
 4836 bruce@momjian.us         6991                 :              1 :             case 3:             /* index-tablespace */
 4043 ishii@postgresql.org     6992                 :              1 :                 initialization_option_set = true;
 4712 bruce@momjian.us         6993                 :              1 :                 index_tablespace = pg_strdup(optarg);
 5157 rhaas@postgresql.org     6994                 :              1 :                 break;
 2854 tgl@sss.pgh.pa.us        6995                 :              5 :             case 4:             /* sampling-rate */
 4043 ishii@postgresql.org     6996                 :              5 :                 benchmarking_option_set = true;
 4721 heikki.linnakangas@i     6997                 :              5 :                 sample_rate = atof(optarg);
                               6998   [ +  +  -  + ]:              5 :                 if (sample_rate <= 0.0 || sample_rate > 1.0)
 1247 tgl@sss.pgh.pa.us        6999                 :              1 :                     pg_fatal("invalid sampling rate: \"%s\"", optarg);
 4721 heikki.linnakangas@i     7000                 :              4 :                 break;
 2854 tgl@sss.pgh.pa.us        7001                 :              6 :             case 5:             /* aggregate-interval */
 4043 ishii@postgresql.org     7002                 :              6 :                 benchmarking_option_set = true;
 1505 michael@paquier.xyz      7003         [ +  + ]:              6 :                 if (!option_parse_int(optarg, "--aggregate-interval", 1, INT_MAX,
                               7004                 :                :                                       &agg_interval))
 4601 ishii@postgresql.org     7005                 :              1 :                     exit(1);
                               7006                 :              5 :                 break;
 2854 tgl@sss.pgh.pa.us        7007                 :              2 :             case 6:             /* progress-timestamp */
 3643 teodor@sigaev.ru         7008                 :              2 :                 progress_timestamp = true;
                               7009                 :              2 :                 benchmarking_option_set = true;
                               7010                 :              2 :                 break;
 2854 tgl@sss.pgh.pa.us        7011                 :              4 :             case 7:             /* log-prefix */
 3223 rhaas@postgresql.org     7012                 :              4 :                 benchmarking_option_set = true;
                               7013                 :              4 :                 logfile_prefix = pg_strdup(optarg);
                               7014                 :              4 :                 break;
 2854 tgl@sss.pgh.pa.us        7015                 :              2 :             case 8:             /* foreign-keys */
                               7016                 :              2 :                 initialization_option_set = true;
                               7017                 :              2 :                 foreign_keys = true;
                               7018                 :              2 :                 break;
 2721 teodor@sigaev.ru         7019                 :              4 :             case 9:             /* random-seed */
                               7020                 :              4 :                 benchmarking_option_set = true;
 2716 tgl@sss.pgh.pa.us        7021         [ +  + ]:              4 :                 if (!set_random_seed(optarg))
 1247                          7022                 :              1 :                     pg_fatal("error while setting random seed from --random-seed option");
 2721 teodor@sigaev.ru         7023                 :              3 :                 break;
 2244 tmunro@postgresql.or     7024                 :              1 :             case 10:            /* list */
                               7025                 :                :                 {
                               7026                 :              1 :                     const BuiltinScript *s = findBuiltin(optarg);
                               7027                 :                : 
                               7028                 :              1 :                     fprintf(stderr, "-- %s: %s\n%s\n", s->name, s->desc, s->script);
                               7029                 :              1 :                     exit(0);
                               7030                 :                :                 }
                               7031                 :                :                 break;
 2167 akapila@postgresql.o     7032                 :              3 :             case 11:            /* partitions */
                               7033                 :              3 :                 initialization_option_set = true;
 1207 michael@paquier.xyz      7034         [ +  + ]:              3 :                 if (!option_parse_int(optarg, "--partitions", 0, INT_MAX,
                               7035                 :                :                                       &partitions))
 2167 akapila@postgresql.o     7036                 :              1 :                     exit(1);
                               7037                 :              2 :                 break;
                               7038                 :              3 :             case 12:            /* partition-method */
                               7039                 :              3 :                 initialization_option_set = true;
                               7040         [ -  + ]:              3 :                 if (pg_strcasecmp(optarg, "range") == 0)
 2167 akapila@postgresql.o     7041                 :UBC           0 :                     partition_method = PART_RANGE;
 2167 akapila@postgresql.o     7042         [ +  + ]:CBC           3 :                 else if (pg_strcasecmp(optarg, "hash") == 0)
                               7043                 :              2 :                     partition_method = PART_HASH;
                               7044                 :                :                 else
 1247 tgl@sss.pgh.pa.us        7045                 :              1 :                     pg_fatal("invalid partition method, expecting \"range\" or \"hash\", got: \"%s\"",
                               7046                 :                :                              optarg);
 2167 akapila@postgresql.o     7047                 :              2 :                 break;
 1263 ishii@postgresql.org     7048                 :UBC           0 :             case 13:            /* failures-detailed */
                               7049                 :              0 :                 benchmarking_option_set = true;
                               7050                 :              0 :                 failures_detailed = true;
                               7051                 :              0 :                 break;
 1263 ishii@postgresql.org     7052                 :CBC           4 :             case 14:            /* max-tries */
                               7053                 :                :                 {
                               7054                 :              4 :                     int32       max_tries_arg = atoi(optarg);
                               7055                 :                : 
                               7056         [ +  + ]:              4 :                     if (max_tries_arg < 0)
 1247 tgl@sss.pgh.pa.us        7057                 :              1 :                         pg_fatal("invalid number of maximum tries: \"%s\"", optarg);
                               7058                 :                : 
 1263 ishii@postgresql.org     7059                 :              3 :                     benchmarking_option_set = true;
                               7060                 :              3 :                     max_tries = (uint32) max_tries_arg;
                               7061                 :                :                 }
                               7062                 :              3 :                 break;
                               7063                 :              2 :             case 15:            /* verbose-errors */
                               7064                 :              2 :                 benchmarking_option_set = true;
                               7065                 :              2 :                 verbose_errors = true;
                               7066                 :              2 :                 break;
  738                          7067                 :              2 :             case 16:            /* exit-on-abort */
                               7068                 :              2 :                 benchmarking_option_set = true;
                               7069                 :              2 :                 exit_on_abort = true;
                               7070                 :              2 :                 break;
  530 nathan@postgresql.or     7071                 :              2 :             case 17:            /* debug */
                               7072                 :              2 :                 pg_logging_increase_verbosity();
                               7073                 :              2 :                 break;
 9278 bruce@momjian.us         7074                 :              3 :             default:
                               7075                 :                :                 /* getopt_long already emitted a complaint */
 1247 tgl@sss.pgh.pa.us        7076                 :              3 :                 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 9278 bruce@momjian.us         7077                 :              3 :                 exit(1);
                               7078                 :                :         }
                               7079                 :                :     }
                               7080                 :                : 
                               7081                 :                :     /* set default script if none */
 3510 alvherre@alvh.no-ip.     7082   [ +  +  +  + ]:            107 :     if (num_scripts == 0 && !is_init_mode)
                               7083                 :                :     {
 3457 tgl@sss.pgh.pa.us        7084                 :             11 :         process_builtin(findBuiltin("tpcb-like"), 1);
 3510 alvherre@alvh.no-ip.     7085                 :             11 :         benchmarking_option_set = true;
                               7086                 :             11 :         internal_script_used = true;
                               7087                 :                :     }
                               7088                 :                : 
                               7089                 :                :     /* complete SQL command initialization and compute total weight */
 2431                          7090         [ +  + ]:            220 :     for (i = 0; i < num_scripts; i++)
                               7091                 :                :     {
                               7092                 :            114 :         Command   **commands = sql_script[i].commands;
                               7093                 :                : 
                               7094         [ +  + ]:            728 :         for (int j = 0; commands[j] != NULL; j++)
                               7095         [ +  + ]:            615 :             if (commands[j]->type == SQL_COMMAND)
                               7096                 :            292 :                 postprocess_sql_command(commands[j]);
                               7097                 :                : 
                               7098                 :                :         /* cannot overflow: weight is 32b, total_weight 64b */
 3458                          7099                 :            113 :         total_weight += sql_script[i].weight;
                               7100                 :                :     }
                               7101                 :                : 
 3448                          7102   [ +  +  +  + ]:            106 :     if (total_weight == 0 && !is_init_mode)
 1247 tgl@sss.pgh.pa.us        7103                 :              1 :         pg_fatal("total script weight must not be zero");
                               7104                 :                : 
                               7105                 :                :     /* show per script stats if several scripts are used */
 3505 alvherre@alvh.no-ip.     7106         [ +  + ]:            105 :     if (num_scripts > 1)
                               7107                 :              4 :         per_script_stats = true;
                               7108                 :                : 
                               7109                 :                :     /*
                               7110                 :                :      * Don't need more threads than there are clients.  (This is not merely an
                               7111                 :                :      * optimization; throttle_delay is calculated incorrectly below if some
                               7112                 :                :      * threads have no clients assigned to them.)
                               7113                 :                :      */
 3718 heikki.linnakangas@i     7114         [ +  + ]:            105 :     if (nthreads > nclients)
                               7115                 :              1 :         nthreads = nclients;
                               7116                 :                : 
                               7117                 :                :     /*
                               7118                 :                :      * Convert throttle_delay to a per-thread delay time.  Note that this
                               7119                 :                :      * might be a fractional number of usec, but that's OK, since it's just
                               7120                 :                :      * the center of a Poisson distribution of delays.
                               7121                 :                :      */
 4428 ishii@postgresql.org     7122                 :            105 :     throttle_delay *= nthreads;
                               7123                 :                : 
  530 nathan@postgresql.or     7124         [ +  - ]:            105 :     if (dbName == NULL)
                               7125                 :                :     {
                               7126         [ +  + ]:            105 :         if (argc > optind)
                               7127                 :              1 :             dbName = argv[optind++];
                               7128                 :                :         else
                               7129                 :                :         {
                               7130   [ +  +  +  - ]:            104 :             if ((env = getenv("PGDATABASE")) != NULL && *env != '\0')
                               7131                 :             90 :                 dbName = env;
                               7132   [ -  +  -  - ]:             14 :             else if ((env = getenv("PGUSER")) != NULL && *env != '\0')
  530 nathan@postgresql.or     7133                 :UBC           0 :                 dbName = env;
                               7134                 :                :             else
  530 nathan@postgresql.or     7135                 :CBC          14 :                 dbName = get_user_name_or_exit(progname);
                               7136                 :                :         }
                               7137                 :                :     }
                               7138                 :                : 
 2200 peter@eisentraut.org     7139         [ -  + ]:            105 :     if (optind < argc)
                               7140                 :                :     {
 1247 tgl@sss.pgh.pa.us        7141                 :UBC           0 :         pg_log_error("too many command-line arguments (first is \"%s\")",
                               7142                 :                :                      argv[optind]);
                               7143                 :              0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
 2200 peter@eisentraut.org     7144                 :              0 :         exit(1);
                               7145                 :                :     }
                               7146                 :                : 
 9278 bruce@momjian.us         7147         [ +  + ]:CBC         105 :     if (is_init_mode)
                               7148                 :                :     {
 4043 ishii@postgresql.org     7149         [ +  + ]:              5 :         if (benchmarking_option_set)
 1247 tgl@sss.pgh.pa.us        7150                 :              1 :             pg_fatal("some of the specified options cannot be used in initialization (-i) mode");
                               7151                 :                : 
 2167 akapila@postgresql.o     7152   [ +  +  +  + ]:              4 :         if (partitions == 0 && partition_method != PART_NONE)
 1247 tgl@sss.pgh.pa.us        7153                 :              1 :             pg_fatal("--partition-method requires greater than zero --partitions");
                               7154                 :                : 
                               7155                 :                :         /* set default method */
 2167 akapila@postgresql.o     7156   [ +  +  +  + ]:              3 :         if (partitions > 0 && partition_method == PART_NONE)
                               7157                 :              1 :             partition_method = PART_RANGE;
                               7158                 :                : 
 2854 tgl@sss.pgh.pa.us        7159         [ +  + ]:              3 :         if (initialize_steps == NULL)
                               7160                 :              1 :             initialize_steps = pg_strdup(DEFAULT_INIT_STEPS);
                               7161                 :                : 
                               7162         [ +  + ]:              3 :         if (is_no_vacuum)
                               7163                 :                :         {
                               7164                 :                :             /* Remove any vacuum step in initialize_steps */
                               7165                 :                :             char       *p;
                               7166                 :                : 
                               7167         [ +  + ]:              4 :             while ((p = strchr(initialize_steps, 'v')) != NULL)
                               7168                 :              3 :                 *p = ' ';
                               7169                 :                :         }
                               7170                 :                : 
                               7171         [ +  + ]:              3 :         if (foreign_keys)
                               7172                 :                :         {
                               7173                 :                :             /* Add 'f' to end of initialize_steps, if not already there */
                               7174         [ +  - ]:              2 :             if (strchr(initialize_steps, 'f') == NULL)
                               7175                 :                :             {
                               7176                 :                :                 initialize_steps = (char *)
                               7177                 :              2 :                     pg_realloc(initialize_steps,
                               7178                 :              2 :                                strlen(initialize_steps) + 2);
                               7179                 :              2 :                 strcat(initialize_steps, "f");
                               7180                 :                :             }
                               7181                 :                :         }
                               7182                 :                : 
                               7183                 :              3 :         runInitSteps(initialize_steps);
 9278 bruce@momjian.us         7184                 :              3 :         exit(0);
                               7185                 :                :     }
                               7186                 :                :     else
                               7187                 :                :     {
 4043 ishii@postgresql.org     7188         [ +  + ]:            100 :         if (initialization_option_set)
 1247 tgl@sss.pgh.pa.us        7189                 :              2 :             pg_fatal("some of the specified options cannot be used in benchmarking mode");
                               7190                 :                :     }
                               7191                 :                : 
 2854                          7192   [ +  +  +  + ]:             98 :     if (nxacts > 0 && duration > 0)
 1247                          7193                 :              2 :         pg_fatal("specify either a number of transactions (-t) or a duration (-T), not both");
                               7194                 :                : 
                               7195                 :                :     /* Use DEFAULT_NXACTS if neither nxacts nor duration is specified. */
 6204                          7196   [ +  +  +  + ]:             96 :     if (nxacts <= 0 && duration <= 0)
                               7197                 :              8 :         nxacts = DEFAULT_NXACTS;
                               7198                 :                : 
                               7199                 :                :     /* --sampling-rate may be used only with -l */
 4721 heikki.linnakangas@i     7200   [ +  +  +  + ]:             96 :     if (sample_rate > 0.0 && !use_log)
 1247 tgl@sss.pgh.pa.us        7201                 :              1 :         pg_fatal("log sampling (--sampling-rate) is allowed only when logging transactions (-l)");
                               7202                 :                : 
                               7203                 :                :     /* --sampling-rate may not be used with --aggregate-interval */
 4601 ishii@postgresql.org     7204   [ +  +  +  + ]:             95 :     if (sample_rate > 0.0 && agg_interval > 0)
 1247 tgl@sss.pgh.pa.us        7205                 :              1 :         pg_fatal("log sampling (--sampling-rate) and aggregation (--aggregate-interval) cannot be used at the same time");
                               7206                 :                : 
 3716                          7207   [ +  +  +  + ]:             94 :     if (agg_interval > 0 && !use_log)
 1247                          7208                 :              1 :         pg_fatal("log aggregation is allowed only when actually logging transactions");
                               7209                 :                : 
 3223 rhaas@postgresql.org     7210   [ +  +  +  + ]:             93 :     if (!use_log && logfile_prefix)
 1247 tgl@sss.pgh.pa.us        7211                 :              1 :         pg_fatal("log file prefix (--log-prefix) is allowed only when logging transactions (-l)");
                               7212                 :                : 
 3716                          7213   [ +  +  +  + ]:             92 :     if (duration > 0 && agg_interval > duration)
 1247                          7214                 :              1 :         pg_fatal("number of seconds for aggregation (%d) must not be higher than test duration (%d)", agg_interval, duration);
                               7215                 :                : 
 3716                          7216   [ +  +  +  -  :             91 :     if (duration > 0 && agg_interval > 0 && duration % agg_interval != 0)
                                              +  - ]
 1247                          7217                 :              1 :         pg_fatal("duration (%d) must be a multiple of aggregation interval (%d)", duration, agg_interval);
                               7218                 :                : 
 2924                          7219   [ +  +  +  - ]:             90 :     if (progress_timestamp && progress == 0)
 1247                          7220                 :              1 :         pg_fatal("--progress-timestamp is allowed only under --progress");
                               7221                 :                : 
 1263 ishii@postgresql.org     7222         [ +  + ]:             89 :     if (!max_tries)
                               7223                 :                :     {
                               7224   [ +  -  +  - ]:              1 :         if (!latency_limit && duration <= 0)
 1247 tgl@sss.pgh.pa.us        7225                 :              1 :             pg_fatal("an unlimited number of transaction tries can only be used with --latency-limit or a duration (-T)");
                               7226                 :                :     }
                               7227                 :                : 
                               7228                 :                :     /*
                               7229                 :                :      * save main process id in the global variable because process id will be
                               7230                 :                :      * changed after fork.
                               7231                 :                :      */
 5646 itagaki.takahiro@gma     7232                 :             88 :     main_pid = (int) getpid();
                               7233                 :                : 
 6982 ishii@postgresql.org     7234         [ +  + ]:             88 :     if (nclients > 1)
                               7235                 :                :     {
 4722 tgl@sss.pgh.pa.us        7236                 :             15 :         state = (CState *) pg_realloc(state, sizeof(CState) * nclients);
 5504                          7237                 :             15 :         memset(state + 1, 0, sizeof(CState) * (nclients - 1));
                               7238                 :                : 
                               7239                 :                :         /* copy any -D switch values to all clients */
 6982 ishii@postgresql.org     7240         [ +  + ]:             55 :         for (i = 1; i < nclients; i++)
                               7241                 :                :         {
                               7242                 :                :             int         j;
                               7243                 :                : 
 5878                          7244                 :             40 :             state[i].id = i;
 1263                          7245         [ +  + ]:             41 :             for (j = 0; j < state[0].variables.nvars; j++)
                               7246                 :                :             {
                               7247                 :              1 :                 Variable   *var = &state[0].variables.vars[j];
                               7248                 :                : 
 2797 teodor@sigaev.ru         7249         [ -  + ]:              1 :                 if (var->value.type != PGBT_NO_VALUE)
                               7250                 :                :                 {
 1263 ishii@postgresql.org     7251         [ #  # ]:UBC           0 :                     if (!putVariableValue(&state[i].variables, "startup",
 2690 tgl@sss.pgh.pa.us        7252                 :              0 :                                           var->name, &var->value))
 3410                          7253                 :              0 :                         exit(1);
                               7254                 :                :                 }
                               7255                 :                :                 else
                               7256                 :                :                 {
 1263 ishii@postgresql.org     7257         [ -  + ]:CBC           1 :                     if (!putVariable(&state[i].variables, "startup",
 2797 teodor@sigaev.ru         7258                 :              1 :                                      var->name, var->svalue))
 3410 tgl@sss.pgh.pa.us        7259                 :UBC           0 :                         exit(1);
                               7260                 :                :                 }
                               7261                 :                :             }
                               7262                 :                :         }
                               7263                 :                :     }
                               7264                 :                : 
                               7265                 :                :     /* other CState initializations */
 2725 teodor@sigaev.ru         7266         [ +  + ]:CBC         216 :     for (i = 0; i < nclients; i++)
                               7267                 :                :     {
                               7268                 :            128 :         state[i].cstack = conditional_stack_create();
 2486 alvherre@alvh.no-ip.     7269                 :            128 :         initRandomState(&state[i].cs_func_rs);
                               7270                 :                :     }
                               7271                 :                : 
                               7272                 :                :     /* opening connection... */
 8763 ishii@postgresql.org     7273                 :             88 :     con = doConnect();
                               7274         [ +  + ]:             88 :     if (con == NULL)
 1247 tgl@sss.pgh.pa.us        7275                 :              1 :         pg_fatal("could not create connection for setup");
                               7276                 :                : 
                               7277                 :                :     /* report pgbench and server versions */
 1541                          7278                 :             87 :     printVersion(con);
                               7279                 :                : 
 1645 michael@paquier.xyz      7280   [ +  +  +  -  :             87 :     pg_log_debug("pghost: %s pgport: %s nclients: %d %s: %d dbName: %s",
                                              +  - ]
                               7281                 :                :                  PQhost(con), PQport(con), nclients,
                               7282                 :                :                  duration <= 0 ? "nxacts" : "duration",
                               7283                 :                :                  duration <= 0 ? nxacts : duration, PQdb(con));
                               7284                 :                : 
 3510 alvherre@alvh.no-ip.     7285         [ +  + ]:             87 :     if (internal_script_used)
 2167 akapila@postgresql.o     7286                 :              7 :         GetTableInfo(con, scale_given);
                               7287                 :                : 
                               7288                 :                :     /*
                               7289                 :                :      * :scale variables normally get -s or database scale, but don't override
                               7290                 :                :      * an explicit -D switch
                               7291                 :                :      */
 1263 ishii@postgresql.org     7292         [ +  - ]:             86 :     if (lookupVariable(&state[0].variables, "scale") == NULL)
                               7293                 :                :     {
 6329 tgl@sss.pgh.pa.us        7294         [ +  + ]:            212 :         for (i = 0; i < nclients; i++)
                               7295                 :                :         {
 1263 ishii@postgresql.org     7296         [ -  + ]:            126 :             if (!putVariableInt(&state[i].variables, "startup", "scale", scale))
 6329 tgl@sss.pgh.pa.us        7297                 :UBC           0 :                 exit(1);
                               7298                 :                :         }
                               7299                 :                :     }
                               7300                 :                : 
                               7301                 :                :     /*
                               7302                 :                :      * Define a :client_id variable that is unique per connection. But don't
                               7303                 :                :      * override an explicit -D switch.
                               7304                 :                :      */
 1263 ishii@postgresql.org     7305         [ +  - ]:CBC          86 :     if (lookupVariable(&state[0].variables, "client_id") == NULL)
                               7306                 :                :     {
 4467 heikki.linnakangas@i     7307         [ +  + ]:            212 :         for (i = 0; i < nclients; i++)
 1263 ishii@postgresql.org     7308         [ -  + ]:            126 :             if (!putVariableInt(&state[i].variables, "startup", "client_id", i))
 4467 heikki.linnakangas@i     7309                 :UBC           0 :                 exit(1);
                               7310                 :                :     }
                               7311                 :                : 
                               7312                 :                :     /* set default seed for hash functions */
 1263 ishii@postgresql.org     7313         [ +  - ]:CBC          86 :     if (lookupVariable(&state[0].variables, "default_seed") == NULL)
                               7314                 :                :     {
 1378 tgl@sss.pgh.pa.us        7315                 :             86 :         uint64      seed = pg_prng_uint64(&base_random_sequence);
                               7316                 :                : 
 2726 teodor@sigaev.ru         7317         [ +  + ]:            212 :         for (i = 0; i < nclients; i++)
 1263 ishii@postgresql.org     7318         [ -  + ]:            126 :             if (!putVariableInt(&state[i].variables, "startup", "default_seed",
                               7319                 :                :                                 (int64) seed))
 2726 teodor@sigaev.ru         7320                 :UBC           0 :                 exit(1);
                               7321                 :                :     }
                               7322                 :                : 
                               7323                 :                :     /* set random seed unless overwritten */
 1263 ishii@postgresql.org     7324         [ +  - ]:CBC          86 :     if (lookupVariable(&state[0].variables, "random_seed") == NULL)
                               7325                 :                :     {
 2721 teodor@sigaev.ru         7326         [ +  + ]:            212 :         for (i = 0; i < nclients; i++)
 1263 ishii@postgresql.org     7327         [ -  + ]:            126 :             if (!putVariableInt(&state[i].variables, "startup", "random_seed",
                               7328                 :                :                                 random_seed))
 2721 teodor@sigaev.ru         7329                 :UBC           0 :                 exit(1);
                               7330                 :                :     }
                               7331                 :                : 
 7277 ishii@postgresql.org     7332         [ +  + ]:CBC          86 :     if (!is_no_vacuum)
                               7333                 :                :     {
                               7334                 :             10 :         fprintf(stderr, "starting vacuum...");
 3770 sfrost@snowman.net       7335                 :             10 :         tryExecuteStatement(con, "vacuum pgbench_branches");
                               7336                 :             10 :         tryExecuteStatement(con, "vacuum pgbench_tellers");
                               7337                 :             10 :         tryExecuteStatement(con, "truncate pgbench_history");
 7277 ishii@postgresql.org     7338                 :             10 :         fprintf(stderr, "end.\n");
                               7339                 :                : 
 6728                          7340         [ -  + ]:             10 :         if (do_vacuum_accounts)
                               7341                 :                :         {
 5966 tgl@sss.pgh.pa.us        7342                 :UBC           0 :             fprintf(stderr, "starting vacuum pgbench_accounts...");
 3770 sfrost@snowman.net       7343                 :              0 :             tryExecuteStatement(con, "vacuum analyze pgbench_accounts");
 9278 bruce@momjian.us         7344                 :              0 :             fprintf(stderr, "end.\n");
                               7345                 :                :         }
                               7346                 :                :     }
 7277 ishii@postgresql.org     7347                 :CBC          86 :     PQfinish(con);
                               7348                 :                : 
                               7349                 :                :     /* set up thread data structures */
 4722 tgl@sss.pgh.pa.us        7350                 :             86 :     threads = (TState *) pg_malloc(sizeof(TState) * nthreads);
 3718 heikki.linnakangas@i     7351                 :             86 :     nclients_dealt = 0;
                               7352                 :                : 
 5504 tgl@sss.pgh.pa.us        7353         [ +  + ]:            173 :     for (i = 0; i < nthreads; i++)
                               7354                 :                :     {
 5263 bruce@momjian.us         7355                 :             87 :         TState     *thread = &threads[i];
                               7356                 :                : 
 5504 tgl@sss.pgh.pa.us        7357                 :             87 :         thread->tid = i;
 3718 heikki.linnakangas@i     7358                 :             87 :         thread->state = &state[nclients_dealt];
                               7359                 :             87 :         thread->nstate =
                               7360                 :             87 :             (nclients - nclients_dealt + nthreads - i - 1) / (nthreads - i);
 2486 alvherre@alvh.no-ip.     7361                 :             87 :         initRandomState(&thread->ts_choose_rs);
                               7362                 :             87 :         initRandomState(&thread->ts_throttle_rs);
                               7363                 :             87 :         initRandomState(&thread->ts_sample_rs);
 3376 rhaas@postgresql.org     7364                 :             87 :         thread->logfile = NULL; /* filled in later */
 3981 heikki.linnakangas@i     7365                 :             87 :         thread->latency_late = 0;
 3169 tgl@sss.pgh.pa.us        7366                 :             87 :         initStats(&thread->stats, 0);
                               7367                 :                : 
 3718 heikki.linnakangas@i     7368                 :             87 :         nclients_dealt += thread->nstate;
                               7369                 :                :     }
                               7370                 :                : 
                               7371                 :                :     /* all clients must be assigned to a thread */
                               7372         [ -  + ]:             86 :     Assert(nclients_dealt == nclients);
                               7373                 :                : 
                               7374                 :                :     /* get start up time for the whole computation */
 1641 tmunro@postgresql.or     7375                 :             86 :     start_time = pg_time_now();
                               7376                 :                : 
                               7377                 :                :     /* set alarm if duration is specified. */
 5878 ishii@postgresql.org     7378         [ -  + ]:             86 :     if (duration > 0)
 5878 ishii@postgresql.org     7379                 :UBC           0 :         setalarm(duration);
                               7380                 :                : 
 1641 tmunro@postgresql.or     7381                 :CBC          86 :     errno = THREAD_BARRIER_INIT(&barrier, nthreads);
                               7382         [ -  + ]:             86 :     if (errno != 0)
 1247 tgl@sss.pgh.pa.us        7383                 :UBC           0 :         pg_fatal("could not initialize barrier: %m");
                               7384                 :                : 
                               7385                 :                :     /* start all threads but thread 0 which is executed directly later */
 1641 tmunro@postgresql.or     7386         [ +  + ]:CBC          87 :     for (i = 1; i < nthreads; i++)
                               7387                 :                :     {
 5263 bruce@momjian.us         7388                 :              1 :         TState     *thread = &threads[i];
                               7389                 :                : 
 1641 tmunro@postgresql.or     7390                 :              1 :         thread->create_time = pg_time_now();
                               7391                 :              1 :         errno = THREAD_CREATE(&thread->thread, threadRun, thread);
                               7392                 :                : 
                               7393         [ -  + ]:              1 :         if (errno != 0)
 1247 tgl@sss.pgh.pa.us        7394                 :UBC           0 :             pg_fatal("could not create thread: %m");
                               7395                 :                :     }
                               7396                 :                : 
                               7397                 :                :     /* compute when to stop */
 1641 tmunro@postgresql.or     7398                 :CBC          86 :     threads[0].create_time = pg_time_now();
 3468 rhaas@postgresql.org     7399         [ -  + ]:             86 :     if (duration > 0)
 1641 tmunro@postgresql.or     7400                 :UBC           0 :         end_time = threads[0].create_time + (int64) 1000000 * duration;
                               7401                 :                : 
                               7402                 :                :     /* run thread 0 directly */
 1641 tmunro@postgresql.or     7403                 :CBC          86 :     (void) threadRun(&threads[0]);
                               7404                 :                : 
                               7405                 :                :     /* wait for other threads and accumulate results */
 3169 tgl@sss.pgh.pa.us        7406                 :             85 :     initStats(&stats, 0);
 1641 tmunro@postgresql.or     7407                 :             85 :     conn_total_duration = 0;
                               7408                 :                : 
 5878 ishii@postgresql.org     7409         [ +  + ]:            170 :     for (i = 0; i < nthreads; i++)
                               7410                 :                :     {
 3718 heikki.linnakangas@i     7411                 :             85 :         TState     *thread = &threads[i];
                               7412                 :                : 
 1641 tmunro@postgresql.or     7413         [ -  + ]:             85 :         if (i > 0)
 1641 tmunro@postgresql.or     7414                 :UBC           0 :             THREAD_JOIN(thread->thread);
                               7415                 :                : 
 2524 peter_e@gmx.net          7416         [ +  + ]:CBC         209 :         for (int j = 0; j < thread->nstate; j++)
 1438 fujii@postgresql.org     7417         [ +  + ]:            124 :             if (thread->state[j].state != CSTATE_FINISHED)
 2524 peter_e@gmx.net          7418                 :             51 :                 exit_code = 2;
                               7419                 :                : 
                               7420                 :                :         /* aggregate thread level stats */
 3508 alvherre@alvh.no-ip.     7421                 :             85 :         mergeSimpleStats(&stats.latency, &thread->stats.latency);
                               7422                 :             85 :         mergeSimpleStats(&stats.lag, &thread->stats.lag);
                               7423                 :             85 :         stats.cnt += thread->stats.cnt;
                               7424                 :             85 :         stats.skipped += thread->stats.skipped;
 1263 ishii@postgresql.org     7425                 :             85 :         stats.retries += thread->stats.retries;
                               7426                 :             85 :         stats.retried += thread->stats.retried;
                               7427                 :             85 :         stats.serialization_failures += thread->stats.serialization_failures;
                               7428                 :             85 :         stats.deadlock_failures += thread->stats.deadlock_failures;
 3673 heikki.linnakangas@i     7429                 :             85 :         latency_late += thread->latency_late;
 1641 tmunro@postgresql.or     7430                 :             85 :         conn_total_duration += thread->conn_duration;
                               7431                 :                : 
                               7432                 :                :         /* first recorded benchmarking start time */
                               7433   [ -  +  -  - ]:             85 :         if (bench_start == 0 || thread->bench_start < bench_start)
                               7434                 :             85 :             bench_start = thread->bench_start;
                               7435                 :                :     }
                               7436                 :                : 
                               7437                 :                :     /*
                               7438                 :                :      * All connections should be already closed in threadRun(), so this
                               7439                 :                :      * disconnect_all() will be a no-op, but clean up the connections just to
                               7440                 :                :      * be sure. We don't need to measure the disconnection delays here.
                               7441                 :                :      */
 5878 ishii@postgresql.org     7442                 :             85 :     disconnect_all(state, nclients);
                               7443                 :                : 
                               7444                 :                :     /*
                               7445                 :                :      * Beware that performance of short benchmarks with many threads and
                               7446                 :                :      * possibly long transactions can be deceptive because threads do not
                               7447                 :                :      * start and finish at the exact same time. The total duration computed
                               7448                 :                :      * here encompasses all transactions so that tps shown is somehow slightly
                               7449                 :                :      * underestimated.
                               7450                 :                :      */
 1641 tmunro@postgresql.or     7451                 :             85 :     printResults(&stats, pg_time_now() - bench_start, conn_total_duration,
                               7452                 :                :                  bench_start - start_time, latency_late);
                               7453                 :                : 
                               7454                 :             85 :     THREAD_BARRIER_DESTROY(&barrier);
                               7455                 :                : 
 2524 peter_e@gmx.net          7456         [ +  + ]:             85 :     if (exit_code != 0)
 1247 tgl@sss.pgh.pa.us        7457                 :             51 :         pg_log_error("Run was aborted; the above results are incomplete.");
                               7458                 :                : 
 2524 peter_e@gmx.net          7459                 :             85 :     return exit_code;
                               7460                 :                : }
                               7461                 :                : 
                               7462                 :                : static THREAD_FUNC_RETURN_TYPE THREAD_FUNC_CC
 5878 ishii@postgresql.org     7463                 :             87 : threadRun(void *arg)
                               7464                 :                : {
                               7465                 :             87 :     TState     *thread = (TState *) arg;
                               7466                 :             87 :     CState     *state = thread->state;
                               7467                 :                :     pg_time_usec_t start;
                               7468                 :             87 :     int         nstate = thread->nstate;
 2999 tgl@sss.pgh.pa.us        7469                 :             87 :     int         remains = nstate;   /* number of remaining clients */
 2539                          7470                 :             87 :     socket_set *sockets = alloc_socket_set(nstate);
                               7471                 :                :     int64       thread_start,
                               7472                 :                :                 last_report,
                               7473                 :                :                 next_report;
                               7474                 :                :     StatsData   last,
                               7475                 :                :                 aggs;
                               7476                 :                : 
                               7477                 :                :     /* open log file if requested */
 5646 itagaki.takahiro@gma     7478         [ +  + ]:             87 :     if (use_log)
                               7479                 :                :     {
                               7480                 :                :         char        logpath[MAXPGPATH];
 3170 tgl@sss.pgh.pa.us        7481         [ +  - ]:              2 :         char       *prefix = logfile_prefix ? logfile_prefix : "pgbench_log";
                               7482                 :                : 
 5646 itagaki.takahiro@gma     7483         [ +  - ]:              2 :         if (thread->tid == 0)
 3223 rhaas@postgresql.org     7484                 :              2 :             snprintf(logpath, sizeof(logpath), "%s.%d", prefix, main_pid);
                               7485                 :                :         else
 3223 rhaas@postgresql.org     7486                 :UBC           0 :             snprintf(logpath, sizeof(logpath), "%s.%d.%d", prefix, main_pid, thread->tid);
                               7487                 :                : 
 3494 alvherre@alvh.no-ip.     7488                 :CBC           2 :         thread->logfile = fopen(logpath, "w");
                               7489                 :                : 
                               7490         [ -  + ]:              2 :         if (thread->logfile == NULL)
 1247 tgl@sss.pgh.pa.us        7491                 :UBC           0 :             pg_fatal("could not open logfile \"%s\": %m", logpath);
                               7492                 :                :     }
                               7493                 :                : 
                               7494                 :                :     /* explicitly initialize the state machines */
 1641 tmunro@postgresql.or     7495         [ +  + ]:CBC         213 :     for (int i = 0; i < nstate; i++)
                               7496                 :            126 :         state[i].state = CSTATE_CHOOSE_SCRIPT;
                               7497                 :                : 
                               7498                 :                :     /* READY */
                               7499                 :             87 :     THREAD_BARRIER_WAIT(&barrier);
                               7500                 :                : 
                               7501                 :             87 :     thread_start = pg_time_now();
                               7502                 :             87 :     thread->started_time = thread_start;
 1468 fujii@postgresql.org     7503                 :             87 :     thread->conn_duration = 0;
 1641 tmunro@postgresql.or     7504                 :             87 :     last_report = thread_start;
                               7505                 :             87 :     next_report = last_report + (int64) 1000000 * progress;
                               7506                 :                : 
                               7507                 :                :     /* STEADY */
 5646 itagaki.takahiro@gma     7508         [ +  + ]:             87 :     if (!is_connect)
                               7509                 :                :     {
                               7510                 :                :         /* make connections to the database before starting */
 1641 tmunro@postgresql.or     7511         [ +  + ]:            204 :         for (int i = 0; i < nstate; i++)
                               7512                 :                :         {
 5878 ishii@postgresql.org     7513         [ -  + ]:            119 :             if ((state[i].con = doConnect()) == NULL)
                               7514                 :                :             {
                               7515                 :                :                 /* coldly abort on initial connection failure */
 1247 tgl@sss.pgh.pa.us        7516                 :UBC           0 :                 pg_fatal("could not create connection for client %d",
                               7517                 :                :                          state[i].id);
                               7518                 :                :             }
                               7519                 :                :         }
                               7520                 :                :     }
                               7521                 :                : 
                               7522                 :                :     /* GO */
 1641 tmunro@postgresql.or     7523                 :CBC          87 :     THREAD_BARRIER_WAIT(&barrier);
                               7524                 :                : 
                               7525                 :             87 :     start = pg_time_now();
                               7526                 :             87 :     thread->bench_start = start;
                               7527                 :             87 :     thread->throttle_trigger = start;
                               7528                 :                : 
                               7529                 :                :     /*
                               7530                 :                :      * The log format currently has Unix epoch timestamps with whole numbers
                               7531                 :                :      * of seconds.  Round the first aggregate's start time down to the nearest
                               7532                 :                :      * Unix epoch second (the very first aggregate might really have started a
                               7533                 :                :      * fraction of a second later, but later aggregates are measured from the
                               7534                 :                :      * whole number time that is actually logged).
                               7535                 :                :      */
 1518                          7536                 :             87 :     initStats(&aggs, (start + epoch_shift) / 1000000 * 1000000);
 1641                          7537                 :             87 :     last = aggs;
                               7538                 :                : 
                               7539                 :                :     /* loop till all clients have terminated */
 5878 ishii@postgresql.org     7540         [ +  + ]:          13305 :     while (remains > 0)
                               7541                 :                :     {
                               7542                 :                :         int         nsocks;     /* number of sockets to be waited for */
                               7543                 :                :         pg_time_usec_t min_usec;
 1641 tmunro@postgresql.or     7544                 :          13220 :         pg_time_usec_t now = 0; /* set this only if needed */
                               7545                 :                : 
                               7546                 :                :         /*
                               7547                 :                :          * identify which client sockets should be checked for input, and
                               7548                 :                :          * compute the nearest time (if any) at which we need to wake up.
                               7549                 :                :          */
 2539 tgl@sss.pgh.pa.us        7550                 :          13220 :         clear_socket_set(sockets);
                               7551                 :          13220 :         nsocks = 0;
 3810 andres@anarazel.de       7552                 :          13220 :         min_usec = PG_INT64_MAX;
 1641 tmunro@postgresql.or     7553         [ +  + ]:          57814 :         for (int i = 0; i < nstate; i++)
                               7554                 :                :         {
 5878 ishii@postgresql.org     7555                 :          50375 :             CState     *st = &state[i];
                               7556                 :                : 
 2481 alvherre@alvh.no-ip.     7557   [ +  +  -  + ]:          50375 :             if (st->state == CSTATE_SLEEP || st->state == CSTATE_THROTTLE)
 4428 ishii@postgresql.org     7558                 :              3 :             {
                               7559                 :                :                 /* a nap from the script, or under throttling */
                               7560                 :                :                 pg_time_usec_t this_usec;
                               7561                 :                : 
                               7562                 :                :                 /* get current time if needed */
 1641 tmunro@postgresql.or     7563                 :              3 :                 pg_time_now_lazy(&now);
                               7564                 :                : 
                               7565                 :                :                 /* min_usec should be the minimum delay across all clients */
 3267 heikki.linnakangas@i     7566                 :              6 :                 this_usec = (st->state == CSTATE_SLEEP ?
 1641 tmunro@postgresql.or     7567         [ +  - ]:              3 :                              st->sleep_until : st->txn_scheduled) - now;
 3267 heikki.linnakangas@i     7568         [ +  - ]:              3 :                 if (min_usec > this_usec)
                               7569                 :              3 :                     min_usec = this_usec;
                               7570                 :                :             }
 1263 ishii@postgresql.org     7571         [ +  + ]:          50372 :             else if (st->state == CSTATE_WAIT_RESULT ||
                               7572         [ +  + ]:           8618 :                      st->state == CSTATE_WAIT_ROLLBACK_RESULT)
 5878                          7573                 :          41755 :             {
                               7574                 :                :                 /*
                               7575                 :                :                  * waiting for result from server - nothing to do unless the
                               7576                 :                :                  * socket is readable
                               7577                 :                :                  */
 3267 tgl@sss.pgh.pa.us        7578                 :          41755 :                 int         sock = PQsocket(st->con);
                               7579                 :                : 
      heikki.linnakangas@i     7580         [ -  + ]:          41755 :                 if (sock < 0)
                               7581                 :                :                 {
 2068 peter@eisentraut.org     7582                 :UBC           0 :                     pg_log_error("invalid socket: %s", PQerrorMessage(st->con));
 3267 heikki.linnakangas@i     7583                 :CBC           1 :                     goto done;
                               7584                 :                :                 }
                               7585                 :                : 
 2539 tgl@sss.pgh.pa.us        7586                 :          41755 :                 add_socket_to_set(sockets, sock, nsocks++);
                               7587                 :                :             }
 3267                          7588         [ +  - ]:           8617 :             else if (st->state != CSTATE_ABORTED &&
                               7589         [ +  + ]:           8617 :                      st->state != CSTATE_FINISHED)
                               7590                 :                :             {
                               7591                 :                :                 /*
                               7592                 :                :                  * This client thread is ready to do something, so we don't
                               7593                 :                :                  * want to wait.  No need to examine additional clients.
                               7594                 :                :                  */
      heikki.linnakangas@i     7595                 :           5781 :                 min_usec = 0;
                               7596                 :           5781 :                 break;
                               7597                 :                :             }
                               7598                 :                :         }
                               7599                 :                : 
                               7600                 :                :         /* also wake up to print the next progress report on time */
 3682 andres@anarazel.de       7601   [ -  +  -  -  :          13220 :         if (progress && min_usec > 0 && thread->tid == 0)
                                              -  - ]
                               7602                 :                :         {
 1641 tmunro@postgresql.or     7603                 :UBC           0 :             pg_time_now_lazy(&now);
                               7604                 :                : 
                               7605         [ #  # ]:              0 :             if (now >= next_report)
 3718 heikki.linnakangas@i     7606                 :              0 :                 min_usec = 0;
 1641 tmunro@postgresql.or     7607         [ #  # ]:              0 :             else if ((next_report - now) < min_usec)
                               7608                 :              0 :                 min_usec = next_report - now;
                               7609                 :                :         }
                               7610                 :                : 
                               7611                 :                :         /*
                               7612                 :                :          * If no clients are ready to execute actions, sleep until we receive
                               7613                 :                :          * data on some client socket or the timeout (if any) elapses.
                               7614                 :                :          */
 2897 heikki.linnakangas@i     7615         [ +  + ]:CBC       13220 :         if (min_usec > 0)
                               7616                 :                :         {
 2539 tgl@sss.pgh.pa.us        7617                 :           7439 :             int         rc = 0;
                               7618                 :                : 
 3810 andres@anarazel.de       7619         [ +  + ]:           7439 :             if (min_usec != PG_INT64_MAX)
                               7620                 :                :             {
 2539 tgl@sss.pgh.pa.us        7621         [ -  + ]:              3 :                 if (nsocks > 0)
                               7622                 :                :                 {
 2539 tgl@sss.pgh.pa.us        7623                 :UBC           0 :                     rc = wait_on_socket_set(sockets, min_usec);
                               7624                 :                :                 }
                               7625                 :                :                 else            /* nothing active, simple sleep */
                               7626                 :                :                 {
 2897 heikki.linnakangas@i     7627                 :CBC           3 :                     pg_usleep(min_usec);
                               7628                 :                :                 }
                               7629                 :                :             }
                               7630                 :                :             else                /* no explicit delay, wait without timeout */
                               7631                 :                :             {
 2539 tgl@sss.pgh.pa.us        7632                 :           7436 :                 rc = wait_on_socket_set(sockets, 0);
                               7633                 :                :             }
                               7634                 :                : 
                               7635         [ -  + ]:           7438 :             if (rc < 0)
                               7636                 :                :             {
 7282 ishii@postgresql.org     7637         [ #  # ]:UBC           0 :                 if (errno == EINTR)
                               7638                 :                :                 {
                               7639                 :                :                     /* On EINTR, go back to top of loop */
                               7640                 :              0 :                     continue;
                               7641                 :                :                 }
                               7642                 :                :                 /* must be something wrong */
 1438 fujii@postgresql.org     7643                 :              0 :                 pg_log_error("%s() failed: %m", SOCKET_WAIT_METHOD);
 5878 ishii@postgresql.org     7644                 :              0 :                 goto done;
                               7645                 :                :             }
                               7646                 :                :         }
                               7647                 :                :         else
                               7648                 :                :         {
                               7649                 :                :             /* min_usec <= 0, i.e. something needs to be executed now */
                               7650                 :                : 
                               7651                 :                :             /* If we didn't wait, don't try to read any data */
 2539 tgl@sss.pgh.pa.us        7652                 :CBC        5781 :             clear_socket_set(sockets);
                               7653                 :                :         }
                               7654                 :                : 
                               7655                 :                :         /* ok, advance the state machine of each connection */
                               7656                 :          13219 :         nsocks = 0;
 1641 tmunro@postgresql.or     7657         [ +  + ]:          76198 :         for (int i = 0; i < nstate; i++)
                               7658                 :                :         {
 5878 ishii@postgresql.org     7659                 :          62980 :             CState     *st = &state[i];
                               7660                 :                : 
 1263                          7661         [ +  + ]:          62980 :             if (st->state == CSTATE_WAIT_RESULT ||
                               7662         [ +  + ]:          10925 :                 st->state == CSTATE_WAIT_ROLLBACK_RESULT)
 9278 bruce@momjian.us         7663                 :           9987 :             {
                               7664                 :                :                 /* don't call advanceConnectionState unless data is available */
 3491 alvherre@alvh.no-ip.     7665                 :          52056 :                 int         sock = PQsocket(st->con);
                               7666                 :                : 
                               7667         [ -  + ]:          52056 :                 if (sock < 0)
                               7668                 :                :                 {
 2068 peter@eisentraut.org     7669                 :UBC           0 :                     pg_log_error("invalid socket: %s", PQerrorMessage(st->con));
 3491 alvherre@alvh.no-ip.     7670                 :              0 :                     goto done;
                               7671                 :                :                 }
                               7672                 :                : 
 2539 tgl@sss.pgh.pa.us        7673         [ +  + ]:CBC       52056 :                 if (!socket_has_input(sockets, sock, nsocks++))
 3267                          7674                 :          42069 :                     continue;
                               7675                 :                :             }
                               7676         [ +  + ]:          10924 :             else if (st->state == CSTATE_FINISHED ||
                               7677         [ -  + ]:           7747 :                      st->state == CSTATE_ABORTED)
                               7678                 :                :             {
                               7679                 :                :                 /* this client is done, no need to consider it anymore */
                               7680                 :           3177 :                 continue;
                               7681                 :                :             }
                               7682                 :                : 
 2481 alvherre@alvh.no-ip.     7683                 :          17734 :             advanceConnectionState(thread, st, &aggs);
                               7684                 :                : 
                               7685                 :                :             /*
                               7686                 :                :              * If --exit-on-abort is used, the program is going to exit when
                               7687                 :                :              * any client is aborted.
                               7688                 :                :              */
  738 ishii@postgresql.org     7689   [ +  +  +  + ]:          17734 :             if (exit_on_abort && st->state == CSTATE_ABORTED)
                               7690                 :              1 :                 goto done;
                               7691                 :                : 
                               7692                 :                :             /*
                               7693                 :                :              * If advanceConnectionState changed client to finished state,
                               7694                 :                :              * that's one fewer client that remains.
                               7695                 :                :              */
                               7696         [ +  + ]:          17733 :             else if (st->state == CSTATE_FINISHED ||
                               7697         [ +  + ]:          17660 :                      st->state == CSTATE_ABORTED)
 3267 tgl@sss.pgh.pa.us        7698                 :            124 :                 remains--;
                               7699                 :                :         }
                               7700                 :                : 
                               7701                 :                :         /* progress report is made by thread 0 for all threads */
 4434 ishii@postgresql.org     7702   [ -  +  -  - ]:          13218 :         if (progress && thread->tid == 0)
                               7703                 :                :         {
 1066 drowley@postgresql.o     7704                 :UBC           0 :             pg_time_usec_t now2 = pg_time_now();
                               7705                 :                : 
                               7706         [ #  # ]:              0 :             if (now2 >= next_report)
                               7707                 :                :             {
                               7708                 :                :                 /*
                               7709                 :                :                  * Horrible hack: this relies on the thread pointer we are
                               7710                 :                :                  * passed to be equivalent to threads[0], that is the first
                               7711                 :                :                  * entry of the threads array.  That is why this MUST be done
                               7712                 :                :                  * by thread 0 and not any other.
                               7713                 :                :                  */
                               7714                 :              0 :                 printProgressReport(thread, thread_start, now2,
                               7715                 :                :                                     &last, &last_report);
                               7716                 :                : 
                               7717                 :                :                 /*
                               7718                 :                :                  * Ensure that the next report is in the future, in case
                               7719                 :                :                  * pgbench/postgres got stuck somewhere.
                               7720                 :                :                  */
                               7721                 :                :                 do
                               7722                 :                :                 {
 1641 tmunro@postgresql.or     7723                 :              0 :                     next_report += (int64) 1000000 * progress;
 1066 drowley@postgresql.o     7724         [ #  # ]:              0 :                 } while (now2 >= next_report);
                               7725                 :                :             }
                               7726                 :                :         }
                               7727                 :                :     }
                               7728                 :                : 
 5878 ishii@postgresql.org     7729                 :CBC          85 : done:
  738                          7730         [ +  + ]:             86 :     if (exit_on_abort)
                               7731                 :                :     {
                               7732                 :                :         /*
                               7733                 :                :          * Abort if any client is not finished, meaning some error occurred.
                               7734                 :                :          */
                               7735         [ +  + ]:              3 :         for (int i = 0; i < nstate; i++)
                               7736                 :                :         {
                               7737         [ +  + ]:              2 :             if (state[i].state != CSTATE_FINISHED)
                               7738                 :                :             {
                               7739                 :              1 :                 pg_log_error("Run was aborted due to an error in thread %d",
                               7740                 :                :                              thread->tid);
                               7741                 :              1 :                 exit(2);
                               7742                 :                :             }
                               7743                 :                :         }
                               7744                 :                :     }
                               7745                 :                : 
 5878                          7746                 :             85 :     disconnect_all(state, nstate);
                               7747                 :                : 
 3494 alvherre@alvh.no-ip.     7748         [ +  + ]:             85 :     if (thread->logfile)
                               7749                 :                :     {
 3169 tgl@sss.pgh.pa.us        7750         [ -  + ]:              2 :         if (agg_interval > 0)
                               7751                 :                :         {
                               7752                 :                :             /* log aggregated but not yet reported transactions */
 3169 tgl@sss.pgh.pa.us        7753                 :UBC           0 :             doLog(thread, state, &aggs, false, 0, 0);
                               7754                 :                :         }
 3494 alvherre@alvh.no-ip.     7755                 :CBC           2 :         fclose(thread->logfile);
 3169 tgl@sss.pgh.pa.us        7756                 :              2 :         thread->logfile = NULL;
                               7757                 :                :     }
 2539                          7758                 :             85 :     free_socket_set(sockets);
 1641 tmunro@postgresql.or     7759                 :             85 :     THREAD_FUNC_RETURN;
                               7760                 :                : }
                               7761                 :                : 
                               7762                 :                : static void
 2746 andres@anarazel.de       7763                 :            483 : finishCon(CState *st)
                               7764                 :                : {
                               7765         [ +  + ]:            483 :     if (st->con != NULL)
                               7766                 :                :     {
                               7767                 :            228 :         PQfinish(st->con);
                               7768                 :            228 :         st->con = NULL;
                               7769                 :                :     }
                               7770                 :            483 : }
                               7771                 :                : 
                               7772                 :                : /*
                               7773                 :                :  * Support for duration option: set timer_exceeded after so many seconds.
                               7774                 :                :  */
                               7775                 :                : 
                               7776                 :                : #ifndef WIN32
                               7777                 :                : 
                               7778                 :                : static void
 6204 tgl@sss.pgh.pa.us        7779                 :UBC           0 : handle_sig_alarm(SIGNAL_ARGS)
                               7780                 :                : {
                               7781                 :              0 :     timer_exceeded = true;
                               7782                 :              0 : }
                               7783                 :                : 
                               7784                 :                : static void
                               7785                 :              0 : setalarm(int seconds)
                               7786                 :                : {
                               7787                 :              0 :     pqsignal(SIGALRM, handle_sig_alarm);
                               7788                 :              0 :     alarm(seconds);
                               7789                 :              0 : }
                               7790                 :                : 
                               7791                 :                : #else                           /* WIN32 */
                               7792                 :                : 
                               7793                 :                : static VOID CALLBACK
                               7794                 :                : win32_timer_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
                               7795                 :                : {
                               7796                 :                :     timer_exceeded = true;
                               7797                 :                : }
                               7798                 :                : 
                               7799                 :                : static void
                               7800                 :                : setalarm(int seconds)
                               7801                 :                : {
                               7802                 :                :     HANDLE      queue;
                               7803                 :                :     HANDLE      timer;
                               7804                 :                : 
                               7805                 :                :     /* This function will be called at most once, so we can cheat a bit. */
                               7806                 :                :     queue = CreateTimerQueue();
                               7807                 :                :     if (seconds > ((DWORD) -1) / 1000 ||
                               7808                 :                :         !CreateTimerQueueTimer(&timer, queue,
                               7809                 :                :                                win32_timer_callback, NULL, seconds * 1000, 0,
                               7810                 :                :                                WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE))
                               7811                 :                :         pg_fatal("failed to set timer");
                               7812                 :                : }
                               7813                 :                : 
                               7814                 :                : #endif                          /* WIN32 */
                               7815                 :                : 
                               7816                 :                : 
                               7817                 :                : /*
                               7818                 :                :  * These functions provide an abstraction layer that hides the syscall
                               7819                 :                :  * we use to wait for input on a set of sockets.
                               7820                 :                :  *
                               7821                 :                :  * Currently there are two implementations, based on ppoll(2) and select(2).
                               7822                 :                :  * ppoll() is preferred where available due to its typically higher ceiling
                               7823                 :                :  * on the number of usable sockets.  We do not use the more-widely-available
                               7824                 :                :  * poll(2) because it only offers millisecond timeout resolution, which could
                               7825                 :                :  * be problematic with high --rate settings.
                               7826                 :                :  *
                               7827                 :                :  * Function APIs:
                               7828                 :                :  *
                               7829                 :                :  * alloc_socket_set: allocate an empty socket set with room for up to
                               7830                 :                :  *      "count" sockets.
                               7831                 :                :  *
                               7832                 :                :  * free_socket_set: deallocate a socket set.
                               7833                 :                :  *
                               7834                 :                :  * clear_socket_set: reset a socket set to empty.
                               7835                 :                :  *
                               7836                 :                :  * add_socket_to_set: add socket with indicated FD to slot "idx" in the
                               7837                 :                :  *      socket set.  Slots must be filled in order, starting with 0.
                               7838                 :                :  *
                               7839                 :                :  * wait_on_socket_set: wait for input on any socket in set, or for timeout
                               7840                 :                :  *      to expire.  timeout is measured in microseconds; 0 means wait forever.
                               7841                 :                :  *      Returns result code of underlying syscall (>=0 if OK, else see errno).
                               7842                 :                :  *
                               7843                 :                :  * socket_has_input: after waiting, call this to see if given socket has
                               7844                 :                :  *      input.  fd and idx parameters should match some previous call to
                               7845                 :                :  *      add_socket_to_set.
                               7846                 :                :  *
                               7847                 :                :  * Note that wait_on_socket_set destructively modifies the state of the
                               7848                 :                :  * socket set.  After checking for input, caller must apply clear_socket_set
                               7849                 :                :  * and add_socket_to_set again before waiting again.
                               7850                 :                :  */
                               7851                 :                : 
                               7852                 :                : #ifdef POLL_USING_PPOLL
                               7853                 :                : 
                               7854                 :                : static socket_set *
 2539 tgl@sss.pgh.pa.us        7855                 :CBC          87 : alloc_socket_set(int count)
                               7856                 :                : {
                               7857                 :                :     socket_set *sa;
                               7858                 :                : 
                               7859                 :             87 :     sa = (socket_set *) pg_malloc0(offsetof(socket_set, pollfds) +
                               7860                 :                :                                    sizeof(struct pollfd) * count);
                               7861                 :             87 :     sa->maxfds = count;
                               7862                 :             87 :     sa->curfds = 0;
                               7863                 :             87 :     return sa;
                               7864                 :                : }
                               7865                 :                : 
                               7866                 :                : static void
                               7867                 :             85 : free_socket_set(socket_set *sa)
                               7868                 :                : {
                               7869                 :             85 :     pg_free(sa);
                               7870                 :             85 : }
                               7871                 :                : 
                               7872                 :                : static void
                               7873                 :          19001 : clear_socket_set(socket_set *sa)
                               7874                 :                : {
                               7875                 :          19001 :     sa->curfds = 0;
                               7876                 :          19001 : }
                               7877                 :                : 
                               7878                 :                : static void
                               7879                 :          41755 : add_socket_to_set(socket_set *sa, int fd, int idx)
                               7880                 :                : {
                               7881   [ +  -  +  - ]:          41755 :     Assert(idx < sa->maxfds && idx == sa->curfds);
                               7882                 :          41755 :     sa->pollfds[idx].fd = fd;
                               7883                 :          41755 :     sa->pollfds[idx].events = POLLIN;
                               7884                 :          41755 :     sa->pollfds[idx].revents = 0;
                               7885                 :          41755 :     sa->curfds++;
                               7886                 :          41755 : }
                               7887                 :                : 
                               7888                 :                : static int
                               7889                 :           7436 : wait_on_socket_set(socket_set *sa, int64 usecs)
                               7890                 :                : {
                               7891         [ -  + ]:           7436 :     if (usecs > 0)
                               7892                 :                :     {
                               7893                 :                :         struct timespec timeout;
                               7894                 :                : 
 2539 tgl@sss.pgh.pa.us        7895                 :UBC           0 :         timeout.tv_sec = usecs / 1000000;
                               7896                 :              0 :         timeout.tv_nsec = (usecs % 1000000) * 1000;
                               7897                 :              0 :         return ppoll(sa->pollfds, sa->curfds, &timeout, NULL);
                               7898                 :                :     }
                               7899                 :                :     else
                               7900                 :                :     {
 2539 tgl@sss.pgh.pa.us        7901                 :CBC        7436 :         return ppoll(sa->pollfds, sa->curfds, NULL, NULL);
                               7902                 :                :     }
                               7903                 :                : }
                               7904                 :                : 
                               7905                 :                : static bool
                               7906                 :          52056 : socket_has_input(socket_set *sa, int fd, int idx)
                               7907                 :                : {
                               7908                 :                :     /*
                               7909                 :                :      * In some cases, threadRun will apply clear_socket_set and then try to
                               7910                 :                :      * apply socket_has_input anyway with arguments that it used before that,
                               7911                 :                :      * or might've used before that except that it exited its setup loop
                               7912                 :                :      * early.  Hence, if the socket set is empty, silently return false
                               7913                 :                :      * regardless of the parameters.  If it's not empty, we can Assert that
                               7914                 :                :      * the parameters match a previous call.
                               7915                 :                :      */
                               7916         [ +  + ]:          52056 :     if (sa->curfds == 0)
                               7917                 :          18946 :         return false;
                               7918                 :                : 
                               7919   [ +  -  +  - ]:          33110 :     Assert(idx < sa->curfds && sa->pollfds[idx].fd == fd);
                               7920                 :          33110 :     return (sa->pollfds[idx].revents & POLLIN) != 0;
                               7921                 :                : }
                               7922                 :                : 
                               7923                 :                : #endif                          /* POLL_USING_PPOLL */
                               7924                 :                : 
                               7925                 :                : #ifdef POLL_USING_SELECT
                               7926                 :                : 
                               7927                 :                : static socket_set *
                               7928                 :                : alloc_socket_set(int count)
                               7929                 :                : {
                               7930                 :                :     return (socket_set *) pg_malloc0(sizeof(socket_set));
                               7931                 :                : }
                               7932                 :                : 
                               7933                 :                : static void
                               7934                 :                : free_socket_set(socket_set *sa)
                               7935                 :                : {
                               7936                 :                :     pg_free(sa);
                               7937                 :                : }
                               7938                 :                : 
                               7939                 :                : static void
                               7940                 :                : clear_socket_set(socket_set *sa)
                               7941                 :                : {
                               7942                 :                :     FD_ZERO(&sa->fds);
                               7943                 :                :     sa->maxfd = -1;
                               7944                 :                : }
                               7945                 :                : 
                               7946                 :                : static void
                               7947                 :                : add_socket_to_set(socket_set *sa, int fd, int idx)
                               7948                 :                : {
                               7949                 :                :     /* See connect_slot() for background on this code. */
                               7950                 :                : #ifdef WIN32
                               7951                 :                :     if (sa->fds.fd_count + 1 >= FD_SETSIZE)
                               7952                 :                :     {
                               7953                 :                :         pg_log_error("too many concurrent database clients for this platform: %d",
                               7954                 :                :                      sa->fds.fd_count + 1);
                               7955                 :                :         exit(1);
                               7956                 :                :     }
                               7957                 :                : #else
                               7958                 :                :     if (fd < 0 || fd >= FD_SETSIZE)
                               7959                 :                :     {
                               7960                 :                :         pg_log_error("socket file descriptor out of range for select(): %d",
                               7961                 :                :                      fd);
                               7962                 :                :         pg_log_error_hint("Try fewer concurrent database clients.");
                               7963                 :                :         exit(1);
                               7964                 :                :     }
                               7965                 :                : #endif
                               7966                 :                :     FD_SET(fd, &sa->fds);
                               7967                 :                :     if (fd > sa->maxfd)
                               7968                 :                :         sa->maxfd = fd;
                               7969                 :                : }
                               7970                 :                : 
                               7971                 :                : static int
                               7972                 :                : wait_on_socket_set(socket_set *sa, int64 usecs)
                               7973                 :                : {
                               7974                 :                :     if (usecs > 0)
                               7975                 :                :     {
                               7976                 :                :         struct timeval timeout;
                               7977                 :                : 
                               7978                 :                :         timeout.tv_sec = usecs / 1000000;
                               7979                 :                :         timeout.tv_usec = usecs % 1000000;
                               7980                 :                :         return select(sa->maxfd + 1, &sa->fds, NULL, NULL, &timeout);
                               7981                 :                :     }
                               7982                 :                :     else
                               7983                 :                :     {
                               7984                 :                :         return select(sa->maxfd + 1, &sa->fds, NULL, NULL, NULL);
                               7985                 :                :     }
                               7986                 :                : }
                               7987                 :                : 
                               7988                 :                : static bool
                               7989                 :                : socket_has_input(socket_set *sa, int fd, int idx)
                               7990                 :                : {
                               7991                 :                :     return (FD_ISSET(fd, &sa->fds) != 0);
                               7992                 :                : }
                               7993                 :                : 
                               7994                 :                : #endif                          /* POLL_USING_SELECT */
        

Generated by: LCOV version 2.4-beta