LCOV - code coverage report
Current view: top level - src/bin/pgbench - pgbench.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 86.0 % 2880 2478
Test Date: 2026-07-25 22:15:46 Functions: 96.1 % 128 123
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 77.8 % 1822 1418

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

Generated by: LCOV version 2.0-1