LCOV - code coverage report
Current view: top level - src/bin/pgbench - pgbench.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16devel Lines: 2376 2771 85.7 %
Date: 2022-08-17 05:10:35 Functions: 114 119 95.8 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14