PostgreSQL Source Code  git master
pgbench.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/select.h>
#include "common/int.h"
#include "common/logging.h"
#include "common/pg_prng.h"
#include "common/string.h"
#include "common/username.h"
#include "fe_utils/cancel.h"
#include "fe_utils/conditional.h"
#include "fe_utils/option_utils.h"
#include "fe_utils/string_utils.h"
#include "getopt_long.h"
#include "libpq-fe.h"
#include "pgbench.h"
#include "port/pg_bitutils.h"
#include "portability/instr_time.h"
#include "port/pg_pthread.h"
Include dependency graph for pgbench.c:

Go to the source code of this file.

Data Structures

struct  socket_set
 
struct  Variable
 
struct  Variables
 
struct  SimpleStats
 
struct  StatsData
 
struct  CState
 
struct  TState
 
struct  Command
 
struct  ParsedScript
 
struct  BuiltinScript
 

Macros

#define POLL_USING_SELECT
 
#define M_PI   3.14159265358979323846
 
#define ERRCODE_T_R_SERIALIZATION_FAILURE   "40001"
 
#define ERRCODE_T_R_DEADLOCK_DETECTED   "40P01"
 
#define ERRCODE_UNDEFINED_TABLE   "42P01"
 
#define FNV_PRIME   UINT64CONST(0x100000001b3)
 
#define FNV_OFFSET_BASIS   UINT64CONST(0xcbf29ce484222325)
 
#define MM2_MUL   UINT64CONST(0xc6a4a7935bd1e995)
 
#define MM2_MUL_TIMES_8   UINT64CONST(0x35253c9ade8f4ca8)
 
#define MM2_ROT   47
 
#define SOCKET_WAIT_METHOD   "select"
 
#define THREAD_T   pthread_t
 
#define THREAD_FUNC_RETURN_TYPE   void *
 
#define THREAD_FUNC_RETURN   return NULL
 
#define THREAD_FUNC_CC
 
#define THREAD_CREATE(handle, function, arg)    pthread_create((handle), NULL, (function), (arg))
 
#define THREAD_JOIN(handle)    pthread_join((handle), NULL)
 
#define THREAD_BARRIER_T   pthread_barrier_t
 
#define THREAD_BARRIER_INIT(barrier, n)    pthread_barrier_init((barrier), NULL, (n))
 
#define THREAD_BARRIER_WAIT(barrier)   pthread_barrier_wait((barrier))
 
#define THREAD_BARRIER_DESTROY(barrier)   pthread_barrier_destroy((barrier))
 
#define DEFAULT_INIT_STEPS   "dtgvp" /* default -I setting */
 
#define ALL_INIT_STEPS   "dtgGvpf" /* all possible steps */
 
#define LOG_STEP_SECONDS   5 /* seconds between log messages */
 
#define DEFAULT_NXACTS   10 /* default nxacts */
 
#define MIN_GAUSSIAN_PARAM   2.0 /* minimum parameter for gauss */
 
#define MIN_ZIPFIAN_PARAM   1.001 /* minimum parameter for zipfian */
 
#define MAX_ZIPFIAN_PARAM   1000.0 /* maximum parameter for zipfian */
 
#define nbranches
 
#define ntellers   10
 
#define naccounts   100000
 
#define SCALE_32BIT_THRESHOLD   20000
 
#define WSEP   '@' /* weight separator */
 
#define VARIABLES_ALLOC_MARGIN   8
 
#define MAX_SCRIPTS   128 /* max number of SQL scripts allowed */
 
#define SHELL_COMMAND_SIZE   256 /* maximum size allowed for shell command */
 
#define SQL_COMMAND   1
 
#define META_COMMAND   2
 
#define MAX_ARGS   256
 
#define PG_TIME_GET_DOUBLE(t)   (0.000001 * (t))
 
#define PARAMS_ARRAY_SIZE   7
 
#define MAX_FARGS   16
 
#define COMMANDS_ALLOC_NUM   128
 

Typedefs

typedef struct socket_set socket_set
 
typedef struct SimpleStats SimpleStats
 
typedef int64 pg_time_usec_t
 
typedef struct StatsData StatsData
 
typedef enum EStatus EStatus
 
typedef enum TStatus TStatus
 
typedef enum MetaCommand MetaCommand
 
typedef enum QueryMode QueryMode
 
typedef struct Command Command
 
typedef struct ParsedScript ParsedScript
 
typedef struct BuiltinScript BuiltinScript
 
typedef void(* initRowMethod) (PQExpBufferData *sql, int64 curr)
 

Enumerations

enum  partition_method_t { PART_NONE , PART_RANGE , PART_HASH }
 
enum  EStatus {
  ESTATUS_NO_ERROR = 0 , ESTATUS_META_COMMAND_ERROR , ESTATUS_SERIALIZATION_ERROR , ESTATUS_DEADLOCK_ERROR ,
  ESTATUS_OTHER_SQL_ERROR
}
 
enum  TStatus { TSTATUS_IDLE , TSTATUS_IN_BLOCK , TSTATUS_CONN_ERROR , TSTATUS_OTHER_ERROR }
 
enum  ConnectionStateEnum {
  CSTATE_CHOOSE_SCRIPT , CSTATE_START_TX , CSTATE_PREPARE_THROTTLE , CSTATE_THROTTLE ,
  CSTATE_START_COMMAND , CSTATE_WAIT_RESULT , CSTATE_SLEEP , CSTATE_END_COMMAND ,
  CSTATE_SKIP_COMMAND , CSTATE_ERROR , CSTATE_WAIT_ROLLBACK_RESULT , CSTATE_RETRY ,
  CSTATE_FAILURE , CSTATE_END_TX , CSTATE_ABORTED , CSTATE_FINISHED
}
 
enum  MetaCommand {
  META_NONE , META_SET , META_SETSHELL , META_SHELL ,
  META_SLEEP , META_GSET , META_ASET , META_IF ,
  META_ELIF , META_ELSE , META_ENDIF , META_STARTPIPELINE ,
  META_SYNCPIPELINE , META_ENDPIPELINE
}
 
enum  QueryMode { QUERY_SIMPLE , QUERY_EXTENDED , QUERY_PREPARED , NUM_QUERYMODE }
 

Functions

static void setNullValue (PgBenchValue *pv)
 
static void setBoolValue (PgBenchValue *pv, bool bval)
 
static void setIntValue (PgBenchValue *pv, int64 ival)
 
static void setDoubleValue (PgBenchValue *pv, double dval)
 
static bool evaluateExpr (CState *st, PgBenchExpr *expr, PgBenchValue *retval)
 
static ConnectionStateEnum executeMetaCommand (CState *st, pg_time_usec_t *now)
 
static void doLog (TState *thread, CState *st, StatsData *agg, bool skipped, double latency, double lag)
 
static void processXactStats (TState *thread, CState *st, pg_time_usec_t *now, bool skipped, StatsData *agg)
 
static void addScript (const ParsedScript *script)
 
static THREAD_FUNC_RETURN_TYPE THREAD_FUNC_CC threadRun (void *arg)
 
static void finishCon (CState *st)
 
static void setalarm (int seconds)
 
static socket_setalloc_socket_set (int count)
 
static void free_socket_set (socket_set *sa)
 
static void clear_socket_set (socket_set *sa)
 
static void add_socket_to_set (socket_set *sa, int fd, int idx)
 
static int wait_on_socket_set (socket_set *sa, int64 usecs)
 
static bool socket_has_input (socket_set *sa, int fd, int idx)
 
static pg_time_usec_t pg_time_now (void)
 
static void pg_time_now_lazy (pg_time_usec_t *now)
 
static void usage (void)
 
static bool is_an_int (const char *str)
 
bool strtoint64 (const char *str, bool errorOK, int64 *result)
 
bool strtodouble (const char *str, bool errorOK, double *dv)
 
static void initRandomState (pg_prng_state *state)
 
static int64 getrand (pg_prng_state *state, int64 min, int64 max)
 
static int64 getExponentialRand (pg_prng_state *state, int64 min, int64 max, double parameter)
 
static int64 getGaussianRand (pg_prng_state *state, int64 min, int64 max, double parameter)
 
static int64 getPoissonRand (pg_prng_state *state, double center)
 
static int64 computeIterativeZipfian (pg_prng_state *state, int64 n, double s)
 
static int64 getZipfianRand (pg_prng_state *state, int64 min, int64 max, double s)
 
static int64 getHashFnv1a (int64 val, uint64 seed)
 
static int64 getHashMurmur2 (int64 val, uint64 seed)
 
static int64 permute (const int64 val, const int64 isize, const int64 seed)
 
static void initSimpleStats (SimpleStats *ss)
 
static void addToSimpleStats (SimpleStats *ss, double val)
 
static void mergeSimpleStats (SimpleStats *acc, SimpleStats *ss)
 
static void initStats (StatsData *sd, pg_time_usec_t start)
 
static void accumStats (StatsData *stats, bool skipped, double lat, double lag, EStatus estatus, int64 tries)
 
static void executeStatement (PGconn *con, const char *sql)
 
static void tryExecuteStatement (PGconn *con, const char *sql)
 
static PGconndoConnect (void)
 
static int compareVariableNames (const void *v1, const void *v2)
 
static VariablelookupVariable (Variables *variables, char *name)
 
static char * getVariable (Variables *variables, char *name)
 
static bool makeVariableValue (Variable *var)
 
static bool valid_variable_name (const char *name)
 
static void enlargeVariables (Variables *variables, int needed)
 
static VariablelookupCreateVariable (Variables *variables, const char *context, char *name)
 
static bool putVariable (Variables *variables, const char *context, char *name, const char *value)
 
static bool putVariableValue (Variables *variables, const char *context, char *name, const PgBenchValue *value)
 
static bool putVariableInt (Variables *variables, const char *context, char *name, int64 value)
 
static char * parseVariable (const char *sql, int *eaten)
 
static char * replaceVariable (char **sql, char *param, int len, char *value)
 
static char * assignVariables (Variables *variables, char *sql)
 
static void getQueryParams (Variables *variables, const Command *command, const char **params)
 
static char * valueTypeName (PgBenchValue *pval)
 
static bool coerceToBool (PgBenchValue *pval, bool *bval)
 
static bool valueTruth (PgBenchValue *pval)
 
static bool coerceToInt (PgBenchValue *pval, int64 *ival)
 
static bool coerceToDouble (PgBenchValue *pval, double *dval)
 
static bool isLazyFunc (PgBenchFunction func)
 
static bool evalLazyFunc (CState *st, PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
 
static bool evalStandardFunc (CState *st, PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
 
static bool evalFunc (CState *st, PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
 
static MetaCommand getMetaCommand (const char *cmd)
 
static bool runShellCommand (Variables *variables, char *variable, char **argv, int argc)
 
static void commandFailed (CState *st, const char *cmd, const char *message)
 
static void commandError (CState *st, const char *message)
 
static int chooseScript (TState *thread)
 
static void allocCStatePrepared (CState *st)
 
static void prepareCommand (CState *st, int command_num)
 
static void prepareCommandsInPipeline (CState *st)
 
static bool sendCommand (CState *st, Command *command)
 
static EStatus getSQLErrorStatus (const char *sqlState)
 
static bool canRetryError (EStatus estatus)
 
static bool readCommandResponse (CState *st, MetaCommand meta, char *varprefix)
 
static bool evaluateSleep (Variables *variables, int argc, char **argv, int *usecs)
 
static bool doRetry (CState *st, pg_time_usec_t *now)
 
static int discardUntilSync (CState *st)
 
static TStatus getTransactionStatus (PGconn *con)
 
static void printVerboseErrorMessages (CState *st, pg_time_usec_t *now, bool is_retry)
 
static void advanceConnectionState (TState *thread, CState *st, StatsData *agg)
 
static int64 getFailures (const StatsData *stats)
 
static const char * getResultString (bool skipped, EStatus estatus)
 
static void disconnect_all (CState *state, int length)
 
static void initDropTables (PGconn *con)
 
static void createPartitions (PGconn *con)
 
static void initCreateTables (PGconn *con)
 
static void initTruncateTables (PGconn *con)
 
static void initBranch (PQExpBufferData *sql, int64 curr)
 
static void initTeller (PQExpBufferData *sql, int64 curr)
 
static void initAccount (PQExpBufferData *sql, int64 curr)
 
static void initPopulateTable (PGconn *con, const char *table, int64 base, initRowMethod init_row)
 
static void initGenerateDataClientSide (PGconn *con)
 
static void initGenerateDataServerSide (PGconn *con)
 
static void initVacuum (PGconn *con)
 
static void initCreatePKeys (PGconn *con)
 
static void initCreateFKeys (PGconn *con)
 
static void checkInitSteps (const char *initialize_steps)
 
static void runInitSteps (const char *initialize_steps)
 
static void GetTableInfo (PGconn *con, bool scale_given)
 
static bool parseQuery (Command *cmd)
 
void syntax_error (const char *source, int lineno, const char *line, const char *command, const char *msg, const char *more, int column)
 
static char * skip_sql_comments (char *sql_command)
 
static Commandcreate_sql_command (PQExpBuffer buf, const char *source)
 
static void free_command (Command *command)
 
static void postprocess_sql_command (Command *my_command)
 
static Commandprocess_backslash_command (PsqlScanState sstate, const char *source)
 
static void ConditionError (const char *desc, int cmdn, const char *msg)
 
static void CheckConditional (const ParsedScript *ps)
 
static void ParseScript (const char *script, const char *desc, int weight)
 
static char * read_file_contents (FILE *fd)
 
static void process_file (const char *filename, int weight)
 
static void process_builtin (const BuiltinScript *bi, int weight)
 
static void listAvailableScripts (void)
 
static const BuiltinScriptfindBuiltin (const char *name)
 
static int parseScriptWeight (const char *option, char **script)
 
static void printProgressReport (TState *threads, int64 test_start, pg_time_usec_t now, StatsData *last, int64 *last_report)
 
static void printSimpleStats (const char *prefix, SimpleStats *ss)
 
static void printVersion (PGconn *con)
 
static void printResults (StatsData *total, pg_time_usec_t total_duration, pg_time_usec_t conn_total_duration, pg_time_usec_t conn_elapsed_duration, int64 latency_late)
 
static bool set_random_seed (const char *seed)
 
int main (int argc, char **argv)
 
static void handle_sig_alarm (SIGNAL_ARGS)
 

Variables

int nxacts = 0
 
int duration = 0
 
int64 end_time = 0
 
int scale = 1
 
int fillfactor = 100
 
bool unlogged_tables = false
 
double sample_rate = 0.0
 
double throttle_delay = 0
 
int64 latency_limit = 0
 
char * tablespace = NULL
 
char * index_tablespace = NULL
 
static int partitions = 0
 
static partition_method_t partition_method = PART_NONE
 
static const char *const PARTITION_METHOD [] = {"none", "range", "hash"}
 
int64 random_seed = -1
 
bool use_log
 
bool use_quiet
 
int agg_interval
 
bool per_script_stats = false
 
int progress = 0
 
bool progress_timestamp = false
 
int nclients = 1
 
int nthreads = 1
 
bool is_connect
 
bool report_per_command = false
 
int main_pid
 
uint32 max_tries = 1
 
bool failures_detailed = false
 
const char * pghost = NULL
 
const char * pgport = NULL
 
const char * username = NULL
 
const char * dbName = NULL
 
char * logfile_prefix = NULL
 
const char * progname
 
volatile sig_atomic_t timer_exceeded = false
 
pg_time_usec_t epoch_shift
 
static pg_prng_state base_random_sequence
 
static THREAD_BARRIER_T barrier
 
static QueryMode querymode = QUERY_SIMPLE
 
static const char *const QUERYMODE [] = {"simple", "extended", "prepared"}
 
static ParsedScript sql_script [MAX_SCRIPTS]
 
static int num_scripts
 
static int64 total_weight = 0
 
static bool verbose_errors = false
 
static bool exit_on_abort = false
 
static const BuiltinScript builtin_script []
 
static const PsqlScanCallbacks pgbench_callbacks
 

Macro Definition Documentation

◆ ALL_INIT_STEPS

#define ALL_INIT_STEPS   "dtgGvpf" /* all possible steps */

Definition at line 163 of file pgbench.c.

◆ COMMANDS_ALLOC_NUM

#define COMMANDS_ALLOC_NUM   128

◆ DEFAULT_INIT_STEPS

#define DEFAULT_INIT_STEPS   "dtgvp" /* default -I setting */

Definition at line 162 of file pgbench.c.

◆ DEFAULT_NXACTS

#define DEFAULT_NXACTS   10 /* default nxacts */

Definition at line 166 of file pgbench.c.

◆ ERRCODE_T_R_DEADLOCK_DETECTED

#define ERRCODE_T_R_DEADLOCK_DETECTED   "40P01"

Definition at line 77 of file pgbench.c.

◆ ERRCODE_T_R_SERIALIZATION_FAILURE

#define ERRCODE_T_R_SERIALIZATION_FAILURE   "40001"

Definition at line 76 of file pgbench.c.

◆ ERRCODE_UNDEFINED_TABLE

#define ERRCODE_UNDEFINED_TABLE   "42P01"

Definition at line 78 of file pgbench.c.

◆ FNV_OFFSET_BASIS

#define FNV_OFFSET_BASIS   UINT64CONST(0xcbf29ce484222325)

Definition at line 84 of file pgbench.c.

◆ FNV_PRIME

#define FNV_PRIME   UINT64CONST(0x100000001b3)

Definition at line 83 of file pgbench.c.

◆ LOG_STEP_SECONDS

#define LOG_STEP_SECONDS   5 /* seconds between log messages */

Definition at line 165 of file pgbench.c.

◆ M_PI

#define M_PI   3.14159265358979323846

Definition at line 73 of file pgbench.c.

◆ MAX_ARGS

#define MAX_ARGS   256

Definition at line 684 of file pgbench.c.

◆ MAX_FARGS

#define MAX_FARGS   16

Definition at line 2241 of file pgbench.c.

◆ MAX_SCRIPTS

#define MAX_SCRIPTS   128 /* max number of SQL scripts allowed */

Definition at line 346 of file pgbench.c.

◆ MAX_ZIPFIAN_PARAM

#define MAX_ZIPFIAN_PARAM   1000.0 /* maximum parameter for zipfian */

Definition at line 171 of file pgbench.c.

◆ META_COMMAND

#define META_COMMAND   2

Definition at line 678 of file pgbench.c.

◆ MIN_GAUSSIAN_PARAM

#define MIN_GAUSSIAN_PARAM   2.0 /* minimum parameter for gauss */

Definition at line 168 of file pgbench.c.

◆ MIN_ZIPFIAN_PARAM

#define MIN_ZIPFIAN_PARAM   1.001 /* minimum parameter for zipfian */

Definition at line 170 of file pgbench.c.

◆ MM2_MUL

#define MM2_MUL   UINT64CONST(0xc6a4a7935bd1e995)

Definition at line 85 of file pgbench.c.

◆ MM2_MUL_TIMES_8

#define MM2_MUL_TIMES_8   UINT64CONST(0x35253c9ade8f4ca8)

Definition at line 86 of file pgbench.c.

◆ MM2_ROT

#define MM2_ROT   47

Definition at line 87 of file pgbench.c.

◆ naccounts

#define naccounts   100000

Definition at line 245 of file pgbench.c.

◆ nbranches

#define nbranches
Value:
1 /* Makes little sense to change this. Change
* -s instead */

Definition at line 243 of file pgbench.c.

◆ ntellers

#define ntellers   10

Definition at line 244 of file pgbench.c.

◆ PARAMS_ARRAY_SIZE

#define PARAMS_ARRAY_SIZE   7

◆ PG_TIME_GET_DOUBLE

#define PG_TIME_GET_DOUBLE (   t)    (0.000001 * (t))

Definition at line 866 of file pgbench.c.

◆ POLL_USING_SELECT

#define POLL_USING_SELECT

Definition at line 52 of file pgbench.c.

◆ SCALE_32BIT_THRESHOLD

#define SCALE_32BIT_THRESHOLD   20000

Definition at line 254 of file pgbench.c.

◆ SHELL_COMMAND_SIZE

#define SHELL_COMMAND_SIZE   256 /* maximum size allowed for shell command */

Definition at line 347 of file pgbench.c.

◆ SOCKET_WAIT_METHOD

#define SOCKET_WAIT_METHOD   "select"

Definition at line 106 of file pgbench.c.

◆ SQL_COMMAND

#define SQL_COMMAND   1

Definition at line 677 of file pgbench.c.

◆ THREAD_BARRIER_DESTROY

#define THREAD_BARRIER_DESTROY (   barrier)    pthread_barrier_destroy((barrier))

Definition at line 155 of file pgbench.c.

◆ THREAD_BARRIER_INIT

#define THREAD_BARRIER_INIT (   barrier,
 
)     pthread_barrier_init((barrier), NULL, (n))

Definition at line 152 of file pgbench.c.

◆ THREAD_BARRIER_T

#define THREAD_BARRIER_T   pthread_barrier_t

Definition at line 151 of file pgbench.c.

◆ THREAD_BARRIER_WAIT

#define THREAD_BARRIER_WAIT (   barrier)    pthread_barrier_wait((barrier))

Definition at line 154 of file pgbench.c.

◆ THREAD_CREATE

#define THREAD_CREATE (   handle,
  function,
  arg 
)     pthread_create((handle), NULL, (function), (arg))

Definition at line 147 of file pgbench.c.

◆ THREAD_FUNC_CC

#define THREAD_FUNC_CC

Definition at line 146 of file pgbench.c.

◆ THREAD_FUNC_RETURN

#define THREAD_FUNC_RETURN   return NULL

Definition at line 145 of file pgbench.c.

◆ THREAD_FUNC_RETURN_TYPE

#define THREAD_FUNC_RETURN_TYPE   void *

Definition at line 144 of file pgbench.c.

◆ THREAD_JOIN

#define THREAD_JOIN (   handle)     pthread_join((handle), NULL)

Definition at line 149 of file pgbench.c.

◆ THREAD_T

#define THREAD_T   pthread_t

Definition at line 143 of file pgbench.c.

◆ VARIABLES_ALLOC_MARGIN

#define VARIABLES_ALLOC_MARGIN   8

Definition at line 309 of file pgbench.c.

◆ WSEP

#define WSEP   '@' /* weight separator */

Definition at line 301 of file pgbench.c.

Typedef Documentation

◆ BuiltinScript

typedef struct BuiltinScript BuiltinScript

◆ Command

typedef struct Command Command

◆ EStatus

typedef enum EStatus EStatus

◆ initRowMethod

typedef void(* initRowMethod) (PQExpBufferData *sql, int64 curr)

Definition at line 842 of file pgbench.c.

◆ MetaCommand

typedef enum MetaCommand MetaCommand

◆ ParsedScript

typedef struct ParsedScript ParsedScript

◆ pg_time_usec_t

typedef int64 pg_time_usec_t

Definition at line 369 of file pgbench.c.

◆ QueryMode

typedef enum QueryMode QueryMode

◆ SimpleStats

typedef struct SimpleStats SimpleStats

◆ socket_set

typedef struct socket_set socket_set

◆ StatsData

typedef struct StatsData StatsData

◆ TStatus

typedef enum TStatus TStatus

Enumeration Type Documentation

◆ ConnectionStateEnum

Enumerator
CSTATE_CHOOSE_SCRIPT 
CSTATE_START_TX 
CSTATE_PREPARE_THROTTLE 
CSTATE_THROTTLE 
CSTATE_START_COMMAND 
CSTATE_WAIT_RESULT 
CSTATE_SLEEP 
CSTATE_END_COMMAND 
CSTATE_SKIP_COMMAND 
CSTATE_ERROR 
CSTATE_WAIT_ROLLBACK_RESULT 
CSTATE_RETRY 
CSTATE_FAILURE 
CSTATE_END_TX 
CSTATE_ABORTED 
CSTATE_FINISHED 

Definition at line 484 of file pgbench.c.

486 {
487  /*
488  * The client must first choose a script to execute. Once chosen, it can
489  * either be throttled (state CSTATE_PREPARE_THROTTLE under --rate), start
490  * right away (state CSTATE_START_TX) or not start at all if the timer was
491  * exceeded (state CSTATE_FINISHED).
492  */
494 
495  /*
496  * CSTATE_START_TX performs start-of-transaction processing. Establishes
497  * a new connection for the transaction in --connect mode, records the
498  * transaction start time, and proceed to the first command.
499  *
500  * Note: once a script is started, it will either error or run till its
501  * end, where it may be interrupted. It is not interrupted while running,
502  * so pgbench --time is to be understood as tx are allowed to start in
503  * that time, and will finish when their work is completed.
504  */
506 
507  /*
508  * In CSTATE_PREPARE_THROTTLE state, we calculate when to begin the next
509  * transaction, and advance to CSTATE_THROTTLE. CSTATE_THROTTLE state
510  * sleeps until that moment, then advances to CSTATE_START_TX, or
511  * CSTATE_FINISHED if the next transaction would start beyond the end of
512  * the run.
513  */
516 
517  /*
518  * We loop through these states, to process each command in the script:
519  *
520  * CSTATE_START_COMMAND starts the execution of a command. On a SQL
521  * command, the command is sent to the server, and we move to
522  * CSTATE_WAIT_RESULT state unless in pipeline mode. On a \sleep
523  * meta-command, the timer is set, and we enter the CSTATE_SLEEP state to
524  * wait for it to expire. Other meta-commands are executed immediately. If
525  * the command about to start is actually beyond the end of the script,
526  * advance to CSTATE_END_TX.
527  *
528  * CSTATE_WAIT_RESULT waits until we get a result set back from the server
529  * for the current command.
530  *
531  * CSTATE_SLEEP waits until the end of \sleep.
532  *
533  * CSTATE_END_COMMAND records the end-of-command timestamp, increments the
534  * command counter, and loops back to CSTATE_START_COMMAND state.
535  *
536  * CSTATE_SKIP_COMMAND is used by conditional branches which are not
537  * executed. It quickly skip commands that do not need any evaluation.
538  * This state can move forward several commands, till there is something
539  * to do or the end of the script.
540  */
543  CSTATE_SLEEP,
546 
547  /*
548  * States for failed commands.
549  *
550  * If the SQL/meta command fails, in CSTATE_ERROR clean up after an error:
551  * (1) clear the conditional stack; (2) if we have an unterminated
552  * (possibly failed) transaction block, send the rollback command to the
553  * server and wait for the result in CSTATE_WAIT_ROLLBACK_RESULT. If
554  * something goes wrong with rolling back, go to CSTATE_ABORTED.
555  *
556  * But if everything is ok we are ready for future transactions: if this
557  * is a serialization or deadlock error and we can re-execute the
558  * transaction from the very beginning, go to CSTATE_RETRY; otherwise go
559  * to CSTATE_FAILURE.
560  *
561  * In CSTATE_RETRY report an error, set the same parameters for the
562  * transaction execution as in the previous tries and process the first
563  * transaction command in CSTATE_START_COMMAND.
564  *
565  * In CSTATE_FAILURE report a failure, set the parameters for the
566  * transaction execution as they were before the first run of this
567  * transaction (except for a random state) and go to CSTATE_END_TX to
568  * complete this transaction.
569  */
570  CSTATE_ERROR,
572  CSTATE_RETRY,
574 
575  /*
576  * CSTATE_END_TX performs end-of-transaction processing. It calculates
577  * latency, and logs the transaction. In --connect mode, it closes the
578  * current connection.
579  *
580  * Then either starts over in CSTATE_CHOOSE_SCRIPT, or enters
581  * CSTATE_FINISHED if we have no more work to do.
582  */
584 
585  /*
586  * Final states. CSTATE_ABORTED means that the script execution was
587  * aborted because a command failed, CSTATE_FINISHED means success.
588  */
@ CSTATE_START_TX
Definition: pgbench.c:504
@ CSTATE_END_TX
Definition: pgbench.c:582
@ CSTATE_RETRY
Definition: pgbench.c:571
@ CSTATE_FINISHED
Definition: pgbench.c:589
@ CSTATE_SKIP_COMMAND
Definition: pgbench.c:544
@ CSTATE_THROTTLE
Definition: pgbench.c:514
@ CSTATE_FAILURE
Definition: pgbench.c:572
@ CSTATE_START_COMMAND
Definition: pgbench.c:540
@ CSTATE_END_COMMAND
Definition: pgbench.c:543
@ CSTATE_WAIT_RESULT
Definition: pgbench.c:541
@ CSTATE_CHOOSE_SCRIPT
Definition: pgbench.c:492
@ CSTATE_WAIT_ROLLBACK_RESULT
Definition: pgbench.c:570
@ CSTATE_ABORTED
Definition: pgbench.c:588
@ CSTATE_PREPARE_THROTTLE
Definition: pgbench.c:513
@ CSTATE_SLEEP
Definition: pgbench.c:542
@ CSTATE_ERROR
Definition: pgbench.c:569

◆ EStatus

enum EStatus
Enumerator
ESTATUS_NO_ERROR 
ESTATUS_META_COMMAND_ERROR 
ESTATUS_SERIALIZATION_ERROR 
ESTATUS_DEADLOCK_ERROR 
ESTATUS_OTHER_SQL_ERROR 

Definition at line 453 of file pgbench.c.

455 {
456  ESTATUS_NO_ERROR = 0,
458 
459  /* SQL errors */
@ ESTATUS_DEADLOCK_ERROR
Definition: pgbench.c:460
@ ESTATUS_META_COMMAND_ERROR
Definition: pgbench.c:456
@ ESTATUS_OTHER_SQL_ERROR
Definition: pgbench.c:461
@ ESTATUS_NO_ERROR
Definition: pgbench.c:455
@ ESTATUS_SERIALIZATION_ERROR
Definition: pgbench.c:459

◆ MetaCommand

Enumerator
META_NONE 
META_SET 
META_SETSHELL 
META_SHELL 
META_SLEEP 
META_GSET 
META_ASET 
META_IF 
META_ELIF 
META_ELSE 
META_ENDIF 
META_STARTPIPELINE 
META_SYNCPIPELINE 
META_ENDPIPELINE 

Definition at line 686 of file pgbench.c.

688 {
689  META_NONE, /* not a known meta-command */
690  META_SET, /* \set */
691  META_SETSHELL, /* \setshell */
692  META_SHELL, /* \shell */
693  META_SLEEP, /* \sleep */
694  META_GSET, /* \gset */
695  META_ASET, /* \aset */
696  META_IF, /* \if */
697  META_ELIF, /* \elif */
698  META_ELSE, /* \else */
699  META_ENDIF, /* \endif */
700  META_STARTPIPELINE, /* \startpipeline */
701  META_SYNCPIPELINE, /* \syncpipeline */
702  META_ENDPIPELINE, /* \endpipeline */
@ META_ELSE
Definition: pgbench.c:697
@ META_SETSHELL
Definition: pgbench.c:690
@ META_ENDIF
Definition: pgbench.c:698
@ META_SHELL
Definition: pgbench.c:691
@ META_STARTPIPELINE
Definition: pgbench.c:699
@ META_SET
Definition: pgbench.c:689
@ META_ELIF
Definition: pgbench.c:696
@ META_SYNCPIPELINE
Definition: pgbench.c:700
@ META_SLEEP
Definition: pgbench.c:692
@ META_NONE
Definition: pgbench.c:688
@ META_IF
Definition: pgbench.c:695
@ META_ENDPIPELINE
Definition: pgbench.c:701
@ META_ASET
Definition: pgbench.c:694
@ META_GSET
Definition: pgbench.c:693

◆ partition_method_t

Enumerator
PART_NONE 
PART_RANGE 
PART_HASH 

Definition at line 226 of file pgbench.c.

227 {
228  PART_NONE, /* no partitioning */
229  PART_RANGE, /* range partitioning */
230  PART_HASH, /* hash partitioning */
partition_method_t
Definition: pgbench.c:227
@ PART_NONE
Definition: pgbench.c:228
@ PART_RANGE
Definition: pgbench.c:229
@ PART_HASH
Definition: pgbench.c:230

◆ QueryMode

enum QueryMode
Enumerator
QUERY_SIMPLE 
QUERY_EXTENDED 
QUERY_PREPARED 
NUM_QUERYMODE 

Definition at line 704 of file pgbench.c.

706 {
707  QUERY_SIMPLE, /* simple query */
708  QUERY_EXTENDED, /* extended query */
709  QUERY_PREPARED, /* extended query with prepared statements */
@ QUERY_PREPARED
Definition: pgbench.c:708
@ NUM_QUERYMODE
Definition: pgbench.c:709
@ QUERY_SIMPLE
Definition: pgbench.c:706
@ QUERY_EXTENDED
Definition: pgbench.c:707

◆ TStatus

enum TStatus
Enumerator
TSTATUS_IDLE 
TSTATUS_IN_BLOCK 
TSTATUS_CONN_ERROR 
TSTATUS_OTHER_ERROR 

Definition at line 467 of file pgbench.c.

469 {
470  TSTATUS_IDLE,
@ TSTATUS_CONN_ERROR
Definition: pgbench.c:471
@ TSTATUS_IDLE
Definition: pgbench.c:469
@ TSTATUS_IN_BLOCK
Definition: pgbench.c:470
@ TSTATUS_OTHER_ERROR
Definition: pgbench.c:472

Function Documentation

◆ accumStats()

static void accumStats ( StatsData stats,
bool  skipped,
double  lat,
double  lag,
EStatus  estatus,
int64  tries 
)
static

Definition at line 1450 of file pgbench.c.

1453 {
1454  /* Record the skipped transaction */
1455  if (skipped)
1456  {
1457  /* no latency to record on skipped transactions */
1458  stats->skipped++;
1459  return;
1460  }
1461 
1462  /*
1463  * Record the number of retries regardless of whether the transaction was
1464  * successful or failed.
1465  */
1466  if (tries > 1)
1467  {
1468  stats->retries += (tries - 1);
1469  stats->retried++;
1470  }
1471 
1472  switch (estatus)
1473  {
1474  /* Record the successful transaction */
1475  case ESTATUS_NO_ERROR:
1476  stats->cnt++;
1477 
1478  addToSimpleStats(&stats->latency, lat);
1479 
1480  /* and possibly the same for schedule lag */
1481  if (throttle_delay)
1482  addToSimpleStats(&stats->lag, lag);
1483  break;
1484 
1485  /* Record the failed transaction */
1487  stats->serialization_failures++;
1488  break;
1490  stats->deadlock_failures++;
1491  break;
1492  default:
1493  /* internal error which should never occur */
1494  pg_fatal("unexpected error status: %d", estatus);
1495  }
#define pg_fatal(...)
double throttle_delay
Definition: pgbench.c:203
static void addToSimpleStats(SimpleStats *ss, double val)
Definition: pgbench.c:1402
int64 serialization_failures
Definition: pgbench.c:434
int64 cnt
Definition: pgbench.c:424
int64 retried
Definition: pgbench.c:430
int64 deadlock_failures
Definition: pgbench.c:437
int64 skipped
Definition: pgbench.c:426
SimpleStats lag
Definition: pgbench.c:441
int64 retries
Definition: pgbench.c:428
SimpleStats latency
Definition: pgbench.c:440

References addToSimpleStats(), StatsData::cnt, StatsData::deadlock_failures, ESTATUS_DEADLOCK_ERROR, ESTATUS_NO_ERROR, ESTATUS_SERIALIZATION_ERROR, StatsData::lag, StatsData::latency, pg_fatal, StatsData::retried, StatsData::retries, StatsData::serialization_failures, StatsData::skipped, and throttle_delay.

Referenced by doLog(), and processXactStats().

◆ add_socket_to_set()

static void add_socket_to_set ( socket_set sa,
int  fd,
int  idx 
)
static

Definition at line 7878 of file pgbench.c.

7880 {
7881  /* See connect_slot() for background on this code. */
7882 #ifdef WIN32
7883  if (sa->fds.fd_count + 1 >= FD_SETSIZE)
7884  {
7885  pg_log_error("too many concurrent database clients for this platform: %d",
7886  sa->fds.fd_count + 1);
7887  exit(1);
7888  }
7889 #else
7890  if (fd < 0 || fd >= FD_SETSIZE)
7891  {
7892  pg_log_error("socket file descriptor out of range for select(): %d",
7893  fd);
7894  pg_log_error_hint("Try fewer concurrent database clients.");
7895  exit(1);
7896  }
7897 #endif
7898  FD_SET(fd, &sa->fds);
7899  if (fd > sa->maxfd)
7900  sa->maxfd = fd;
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
static int fd(const char *x, int i)
Definition: preproc-init.c:105

References exit(), fd(), pg_log_error, and pg_log_error_hint.

Referenced by threadRun().

◆ addScript()

static void addScript ( const ParsedScript script)
static

Definition at line 6192 of file pgbench.c.

6194 {
6195  if (script->commands == NULL || script->commands[0] == NULL)
6196  pg_fatal("empty command list for script \"%s\"", script->desc);
6197 
6198  if (num_scripts >= MAX_SCRIPTS)
6199  pg_fatal("at most %d SQL scripts are allowed", MAX_SCRIPTS);
6200 
6201  CheckConditional(script);
6202 
6203  sql_script[num_scripts] = *script;
6204  num_scripts++;
static void CheckConditional(const ParsedScript *ps)
Definition: pgbench.c:5854
#define MAX_SCRIPTS
Definition: pgbench.c:346
static ParsedScript sql_script[MAX_SCRIPTS]
Definition: pgbench.c:763
static int num_scripts
Definition: pgbench.c:764
const char * desc
Definition: pgbench.c:757
Command ** commands
Definition: pgbench.c:759

References CheckConditional(), ParsedScript::commands, ParsedScript::desc, MAX_SCRIPTS, num_scripts, pg_fatal, and sql_script.

Referenced by ParseScript().

◆ addToSimpleStats()

static void addToSimpleStats ( SimpleStats ss,
double  val 
)
static

Definition at line 1402 of file pgbench.c.

1404 {
1405  if (ss->count == 0 || val < ss->min)
1406  ss->min = val;
1407  if (ss->count == 0 || val > ss->max)
1408  ss->max = val;
1409  ss->count++;
1410  ss->sum += val;
1411  ss->sum2 += val * val;
long val
Definition: informix.c:670
int64 count
Definition: pgbench.c:357
double sum
Definition: pgbench.c:360
double min
Definition: pgbench.c:358
double max
Definition: pgbench.c:359
double sum2
Definition: pgbench.c:361

References SimpleStats::count, SimpleStats::max, SimpleStats::min, SimpleStats::sum, SimpleStats::sum2, and val.

Referenced by accumStats(), and advanceConnectionState().

◆ advanceConnectionState()

static void advanceConnectionState ( TState thread,
CState st,
StatsData agg 
)
static

Definition at line 3588 of file pgbench.c.

3590 {
3591 
3592  /*
3593  * gettimeofday() isn't free, so we get the current timestamp lazily the
3594  * first time it's needed, and reuse the same value throughout this
3595  * function after that. This also ensures that e.g. the calculated
3596  * latency reported in the log file and in the totals are the same. Zero
3597  * means "not set yet". Reset "now" when we execute shell commands or
3598  * expressions, which might take a non-negligible amount of time, though.
3599  */
3600  pg_time_usec_t now = 0;
3601 
3602  /*
3603  * Loop in the state machine, until we have to wait for a result from the
3604  * server or have to sleep for throttling or \sleep.
3605  *
3606  * Note: In the switch-statement below, 'break' will loop back here,
3607  * meaning "continue in the state machine". Return is used to return to
3608  * the caller, giving the thread the opportunity to advance another
3609  * client.
3610  */
3611  for (;;)
3612  {
3613  Command *command;
3614 
3615  switch (st->state)
3616  {
3617  /* Select transaction (script) to run. */
3618  case CSTATE_CHOOSE_SCRIPT:
3619  st->use_file = chooseScript(thread);
3621 
3622  /* reset transaction variables to default values */
3623  st->estatus = ESTATUS_NO_ERROR;
3624  st->tries = 1;
3625 
3626  pg_log_debug("client %d executing script \"%s\"",
3627  st->id, sql_script[st->use_file].desc);
3628 
3629  /*
3630  * If time is over, we're done; otherwise, get ready to start
3631  * a new transaction, or to get throttled if that's requested.
3632  */
3635  break;
3636 
3637  /* Start new transaction (script) */
3638  case CSTATE_START_TX:
3640 
3641  /* establish connection if needed, i.e. under --connect */
3642  if (st->con == NULL)
3643  {
3645 
3646  if ((st->con = doConnect()) == NULL)
3647  {
3648  /*
3649  * as the bench is already running, we do not abort
3650  * the process
3651  */
3652  pg_log_error("client %d aborted while establishing connection", st->id);
3653  st->state = CSTATE_ABORTED;
3654  break;
3655  }
3656 
3657  /* reset now after connection */
3658  now = pg_time_now();
3659 
3660  thread->conn_duration += now - start;
3661 
3662  /* Reset session-local state */
3663  pg_free(st->prepared);
3664  st->prepared = NULL;
3665  }
3666 
3667  /*
3668  * It is the first try to run this transaction. Remember the
3669  * random state: maybe it will get an error and we will need
3670  * to run it again.
3671  */
3672  st->random_state = st->cs_func_rs;
3673 
3674  /* record transaction start time */
3675  st->txn_begin = now;
3676 
3677  /*
3678  * When not throttling, this is also the transaction's
3679  * scheduled start time.
3680  */
3681  if (!throttle_delay)
3682  st->txn_scheduled = now;
3683 
3684  /* Begin with the first command */
3686  st->command = 0;
3687  break;
3688 
3689  /*
3690  * Handle throttling once per transaction by sleeping.
3691  */
3693 
3694  /*
3695  * Generate a delay such that the series of delays will
3696  * approximate a Poisson distribution centered on the
3697  * throttle_delay time.
3698  *
3699  * If transactions are too slow or a given wait is shorter
3700  * than a transaction, the next transaction will start right
3701  * away.
3702  */
3703  Assert(throttle_delay > 0);
3704 
3705  thread->throttle_trigger +=
3707  st->txn_scheduled = thread->throttle_trigger;
3708 
3709  /*
3710  * If --latency-limit is used, and this slot is already late
3711  * so that the transaction will miss the latency limit even if
3712  * it completed immediately, skip this time slot and loop to
3713  * reschedule.
3714  */
3715  if (latency_limit)
3716  {
3718 
3719  if (thread->throttle_trigger < now - latency_limit)
3720  {
3721  processXactStats(thread, st, &now, true, agg);
3722 
3723  /*
3724  * Finish client if -T or -t was exceeded.
3725  *
3726  * Stop counting skipped transactions under -T as soon
3727  * as the timer is exceeded. Because otherwise it can
3728  * take a very long time to count all of them
3729  * especially when quite a lot of them happen with
3730  * unrealistically high rate setting in -R, which
3731  * would prevent pgbench from ending immediately.
3732  * Because of this behavior, note that there is no
3733  * guarantee that all skipped transactions are counted
3734  * under -T though there is under -t. This is OK in
3735  * practice because it's very unlikely to happen with
3736  * realistic setting.
3737  */
3738  if (timer_exceeded || (nxacts > 0 && st->cnt >= nxacts))
3739  st->state = CSTATE_FINISHED;
3740 
3741  /* Go back to top of loop with CSTATE_PREPARE_THROTTLE */
3742  break;
3743  }
3744  }
3745 
3746  /*
3747  * stop client if next transaction is beyond pgbench end of
3748  * execution; otherwise, throttle it.
3749  */
3750  st->state = end_time > 0 && st->txn_scheduled > end_time ?
3752  break;
3753 
3754  /*
3755  * Wait until it's time to start next transaction.
3756  */
3757  case CSTATE_THROTTLE:
3759 
3760  if (now < st->txn_scheduled)
3761  return; /* still sleeping, nothing to do here */
3762 
3763  /* done sleeping, but don't start transaction if we're done */
3765  break;
3766 
3767  /*
3768  * Send a command to server (or execute a meta-command)
3769  */
3770  case CSTATE_START_COMMAND:
3771  command = sql_script[st->use_file].commands[st->command];
3772 
3773  /*
3774  * Transition to script end processing if done, but close up
3775  * shop if a pipeline is open at this point.
3776  */
3777  if (command == NULL)
3778  {
3779  if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
3780  st->state = CSTATE_END_TX;
3781  else
3782  {
3783  pg_log_error("client %d aborted: end of script reached with pipeline open",
3784  st->id);
3785  st->state = CSTATE_ABORTED;
3786  }
3787 
3788  break;
3789  }
3790 
3791  /* record begin time of next command, and initiate it */
3792  if (report_per_command)
3793  {
3795  st->stmt_begin = now;
3796  }
3797 
3798  /* Execute the command */
3799  if (command->type == SQL_COMMAND)
3800  {
3801  /* disallow \aset and \gset in pipeline mode */
3802  if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
3803  {
3804  if (command->meta == META_GSET)
3805  {
3806  commandFailed(st, "gset", "\\gset is not allowed in pipeline mode");
3807  st->state = CSTATE_ABORTED;
3808  break;
3809  }
3810  else if (command->meta == META_ASET)
3811  {
3812  commandFailed(st, "aset", "\\aset is not allowed in pipeline mode");
3813  st->state = CSTATE_ABORTED;
3814  break;
3815  }
3816  }
3817 
3818  if (!sendCommand(st, command))
3819  {
3820  commandFailed(st, "SQL", "SQL command send failed");
3821  st->state = CSTATE_ABORTED;
3822  }
3823  else
3824  {
3825  /* Wait for results, unless in pipeline mode */
3826  if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
3827  st->state = CSTATE_WAIT_RESULT;
3828  else
3829  st->state = CSTATE_END_COMMAND;
3830  }
3831  }
3832  else if (command->type == META_COMMAND)
3833  {
3834  /*-----
3835  * Possible state changes when executing meta commands:
3836  * - on errors CSTATE_ABORTED
3837  * - on sleep CSTATE_SLEEP
3838  * - else CSTATE_END_COMMAND
3839  */
3840  st->state = executeMetaCommand(st, &now);
3841  if (st->state == CSTATE_ABORTED)
3843  }
3844 
3845  /*
3846  * We're now waiting for an SQL command to complete, or
3847  * finished processing a metacommand, or need to sleep, or
3848  * something bad happened.
3849  */
3850  Assert(st->state == CSTATE_WAIT_RESULT ||
3851  st->state == CSTATE_END_COMMAND ||
3852  st->state == CSTATE_SLEEP ||
3853  st->state == CSTATE_ABORTED);
3854  break;
3855 
3856  /*
3857  * non executed conditional branch
3858  */
3859  case CSTATE_SKIP_COMMAND:
3861  /* quickly skip commands until something to do... */
3862  while (true)
3863  {
3864  command = sql_script[st->use_file].commands[st->command];
3865 
3866  /* cannot reach end of script in that state */
3867  Assert(command != NULL);
3868 
3869  /*
3870  * if this is conditional related, update conditional
3871  * state
3872  */
3873  if (command->type == META_COMMAND &&
3874  (command->meta == META_IF ||
3875  command->meta == META_ELIF ||
3876  command->meta == META_ELSE ||
3877  command->meta == META_ENDIF))
3878  {
3879  switch (conditional_stack_peek(st->cstack))
3880  {
3881  case IFSTATE_FALSE:
3882  if (command->meta == META_IF ||
3883  command->meta == META_ELIF)
3884  {
3885  /* we must evaluate the condition */
3887  }
3888  else if (command->meta == META_ELSE)
3889  {
3890  /* we must execute next command */
3894  st->command++;
3895  }
3896  else if (command->meta == META_ENDIF)
3897  {
3900  if (conditional_active(st->cstack))
3902 
3903  /*
3904  * else state remains in
3905  * CSTATE_SKIP_COMMAND
3906  */
3907  st->command++;
3908  }
3909  break;
3910 
3911  case IFSTATE_IGNORED:
3912  case IFSTATE_ELSE_FALSE:
3913  if (command->meta == META_IF)
3915  IFSTATE_IGNORED);
3916  else if (command->meta == META_ENDIF)
3917  {
3920  if (conditional_active(st->cstack))
3922  }
3923  /* could detect "else" & "elif" after "else" */
3924  st->command++;
3925  break;
3926 
3927  case IFSTATE_NONE:
3928  case IFSTATE_TRUE:
3929  case IFSTATE_ELSE_TRUE:
3930  default:
3931 
3932  /*
3933  * inconsistent if inactive, unreachable dead
3934  * code
3935  */
3936  Assert(false);
3937  }
3938  }
3939  else
3940  {
3941  /* skip and consider next */
3942  st->command++;
3943  }
3944 
3945  if (st->state != CSTATE_SKIP_COMMAND)
3946  /* out of quick skip command loop */
3947  break;
3948  }
3949  break;
3950 
3951  /*
3952  * Wait for the current SQL command to complete
3953  */
3954  case CSTATE_WAIT_RESULT:
3955  pg_log_debug("client %d receiving", st->id);
3956 
3957  /*
3958  * Only check for new network data if we processed all data
3959  * fetched prior. Otherwise we end up doing a syscall for each
3960  * individual pipelined query, which has a measurable
3961  * performance impact.
3962  */
3963  if (PQisBusy(st->con) && !PQconsumeInput(st->con))
3964  {
3965  /* there's something wrong */
3966  commandFailed(st, "SQL", "perhaps the backend died while processing");
3967  st->state = CSTATE_ABORTED;
3968  break;
3969  }
3970  if (PQisBusy(st->con))
3971  return; /* don't have the whole result yet */
3972 
3973  /* store or discard the query results */
3974  if (readCommandResponse(st,
3977  {
3978  /*
3979  * outside of pipeline mode: stop reading results.
3980  * pipeline mode: continue reading results until an
3981  * end-of-pipeline response.
3982  */
3983  if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
3984  st->state = CSTATE_END_COMMAND;
3985  }
3986  else if (canRetryError(st->estatus))
3987  st->state = CSTATE_ERROR;
3988  else
3989  st->state = CSTATE_ABORTED;
3990  break;
3991 
3992  /*
3993  * Wait until sleep is done. This state is entered after a
3994  * \sleep metacommand. The behavior is similar to
3995  * CSTATE_THROTTLE, but proceeds to CSTATE_START_COMMAND
3996  * instead of CSTATE_START_TX.
3997  */
3998  case CSTATE_SLEEP:
4000  if (now < st->sleep_until)
4001  return; /* still sleeping, nothing to do here */
4002  /* Else done sleeping. */
4003  st->state = CSTATE_END_COMMAND;
4004  break;
4005 
4006  /*
4007  * End of command: record stats and proceed to next command.
4008  */
4009  case CSTATE_END_COMMAND:
4010 
4011  /*
4012  * command completed: accumulate per-command execution times
4013  * in thread-local data structure, if per-command latencies
4014  * are requested.
4015  */
4016  if (report_per_command)
4017  {
4019 
4020  command = sql_script[st->use_file].commands[st->command];
4021  /* XXX could use a mutex here, but we choose not to */
4022  addToSimpleStats(&command->stats,
4024  }
4025 
4026  /* Go ahead with next command, to be executed or skipped */
4027  st->command++;
4028  st->state = conditional_active(st->cstack) ?
4030  break;
4031 
4032  /*
4033  * Clean up after an error.
4034  */
4035  case CSTATE_ERROR:
4036  {
4037  TStatus tstatus;
4038 
4040 
4041  /* Clear the conditional stack */
4043 
4044  /* Read and discard until a sync point in pipeline mode */
4045  if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
4046  {
4047  if (!discardUntilSync(st))
4048  {
4049  st->state = CSTATE_ABORTED;
4050  break;
4051  }
4052  }
4053 
4054  /*
4055  * Check if we have a (failed) transaction block or not,
4056  * and roll it back if any.
4057  */
4058  tstatus = getTransactionStatus(st->con);
4059  if (tstatus == TSTATUS_IN_BLOCK)
4060  {
4061  /* Try to rollback a (failed) transaction block. */
4062  if (!PQsendQuery(st->con, "ROLLBACK"))
4063  {
4064  pg_log_error("client %d aborted: failed to send sql command for rolling back the failed transaction",
4065  st->id);
4066  st->state = CSTATE_ABORTED;
4067  }
4068  else
4070  }
4071  else if (tstatus == TSTATUS_IDLE)
4072  {
4073  /*
4074  * If time is over, we're done; otherwise, check if we
4075  * can retry the error.
4076  */
4079  }
4080  else
4081  {
4082  if (tstatus == TSTATUS_CONN_ERROR)
4083  pg_log_error("perhaps the backend died while processing");
4084 
4085  pg_log_error("client %d aborted while receiving the transaction status", st->id);
4086  st->state = CSTATE_ABORTED;
4087  }
4088  break;
4089  }
4090 
4091  /*
4092  * Wait for the rollback command to complete
4093  */
4095  {
4096  PGresult *res;
4097 
4098  pg_log_debug("client %d receiving", st->id);
4099  if (!PQconsumeInput(st->con))
4100  {
4101  pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
4102  st->id);
4103  st->state = CSTATE_ABORTED;
4104  break;
4105  }
4106  if (PQisBusy(st->con))
4107  return; /* don't have the whole result yet */
4108 
4109  /*
4110  * Read and discard the query result;
4111  */
4112  res = PQgetResult(st->con);
4113  switch (PQresultStatus(res))
4114  {
4115  case PGRES_COMMAND_OK:
4116  /* OK */
4117  PQclear(res);
4118  /* null must be returned */
4119  res = PQgetResult(st->con);
4120  Assert(res == NULL);
4121 
4122  /*
4123  * If time is over, we're done; otherwise, check
4124  * if we can retry the error.
4125  */
4128  break;
4129  default:
4130  pg_log_error("client %d aborted while rolling back the transaction after an error; %s",
4131  st->id, PQerrorMessage(st->con));
4132  PQclear(res);
4133  st->state = CSTATE_ABORTED;
4134  break;
4135  }
4136  break;
4137  }
4138 
4139  /*
4140  * Retry the transaction after an error.
4141  */
4142  case CSTATE_RETRY:
4143  command = sql_script[st->use_file].commands[st->command];
4144 
4145  /*
4146  * Inform that the transaction will be retried after the
4147  * error.
4148  */
4149  if (verbose_errors)
4150  printVerboseErrorMessages(st, &now, true);
4151 
4152  /* Count tries and retries */
4153  st->tries++;
4154  command->retries++;
4155 
4156  /*
4157  * Reset the random state as they were at the beginning of the
4158  * transaction.
4159  */
4160  st->cs_func_rs = st->random_state;
4161 
4162  /* Process the first transaction command. */
4163  st->command = 0;
4164  st->estatus = ESTATUS_NO_ERROR;
4166  break;
4167 
4168  /*
4169  * Record a failed transaction.
4170  */
4171  case CSTATE_FAILURE:
4172  command = sql_script[st->use_file].commands[st->command];
4173 
4174  /* Accumulate the failure. */
4175  command->failures++;
4176 
4177  /*
4178  * Inform that the failed transaction will not be retried.
4179  */
4180  if (verbose_errors)
4181  printVerboseErrorMessages(st, &now, false);
4182 
4183  /* End the failed transaction. */
4184  st->state = CSTATE_END_TX;
4185  break;
4186 
4187  /*
4188  * End of transaction (end of script, really).
4189  */
4190  case CSTATE_END_TX:
4191  {
4192  TStatus tstatus;
4193 
4194  /* transaction finished: calculate latency and do log */
4195  processXactStats(thread, st, &now, false, agg);
4196 
4197  /*
4198  * missing \endif... cannot happen if CheckConditional was
4199  * okay
4200  */
4202 
4203  /*
4204  * We must complete all the transaction blocks that were
4205  * started in this script.
4206  */
4207  tstatus = getTransactionStatus(st->con);
4208  if (tstatus == TSTATUS_IN_BLOCK)
4209  {
4210  pg_log_error("client %d aborted: end of script reached without completing the last transaction",
4211  st->id);
4212  st->state = CSTATE_ABORTED;
4213  break;
4214  }
4215  else if (tstatus != TSTATUS_IDLE)
4216  {
4217  if (tstatus == TSTATUS_CONN_ERROR)
4218  pg_log_error("perhaps the backend died while processing");
4219 
4220  pg_log_error("client %d aborted while receiving the transaction status", st->id);
4221  st->state = CSTATE_ABORTED;
4222  break;
4223  }
4224 
4225  if (is_connect)
4226  {
4228 
4230  finishCon(st);
4231  now = pg_time_now();
4232  thread->conn_duration += now - start;
4233  }
4234 
4235  if ((st->cnt >= nxacts && duration <= 0) || timer_exceeded)
4236  {
4237  /* script completed */
4238  st->state = CSTATE_FINISHED;
4239  break;
4240  }
4241 
4242  /* next transaction (script) */
4244 
4245  /*
4246  * Ensure that we always return on this point, so as to
4247  * avoid an infinite loop if the script only contains meta
4248  * commands.
4249  */
4250  return;
4251  }
4252 
4253  /*
4254  * Final states. Close the connection if it's still open.
4255  */
4256  case CSTATE_ABORTED:
4257  case CSTATE_FINISHED:
4258 
4259  /*
4260  * Don't measure the disconnection delays here even if in
4261  * CSTATE_FINISHED and -C/--connect option is specified.
4262  * Because in this case all the connections that this thread
4263  * established are closed at the end of transactions and the
4264  * disconnection delays should have already been measured at
4265  * that moment.
4266  *
4267  * In CSTATE_ABORTED state, the measurement is no longer
4268  * necessary because we cannot report complete results anyways
4269  * in this case.
4270  */
4271  finishCon(st);
4272  return;
4273  }
4274  }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
#define Assert(condition)
Definition: c.h:858
ifState conditional_stack_peek(ConditionalStack cstack)
Definition: conditional.c:106
void conditional_stack_push(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:53
bool conditional_stack_pop(ConditionalStack cstack)
Definition: conditional.c:69
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:140
void conditional_stack_reset(ConditionalStack cstack)
Definition: conditional.c:30
bool conditional_stack_poke(ConditionalStack cstack, ifState new_state)
Definition: conditional.c:118
bool conditional_stack_empty(ConditionalStack cstack)
Definition: conditional.c:130
@ IFSTATE_FALSE
Definition: conditional.h:34
@ IFSTATE_ELSE_TRUE
Definition: conditional.h:40
@ IFSTATE_IGNORED
Definition: conditional.h:37
@ IFSTATE_TRUE
Definition: conditional.h:32
@ IFSTATE_NONE
Definition: conditional.h:31
@ IFSTATE_ELSE_FALSE
Definition: conditional.h:42
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7154
PGpipelineStatus PQpipelineStatus(const PGconn *conn)
Definition: fe-connect.c:7196
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1984
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1416
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
void pg_free(void *ptr)
Definition: fe_memutils.c:105
return str start
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:99
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:161
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:162
#define pg_log_debug(...)
Definition: logging.h:133
static pg_time_usec_t pg_time_now(void)
Definition: pgbench.c:850
static void printVerboseErrorMessages(CState *st, pg_time_usec_t *now, bool is_retry)
Definition: pgbench.c:3550
int64 latency_limit
Definition: pgbench.c:211
static TStatus getTransactionStatus(PGconn *con)
Definition: pgbench.c:3513
int64 end_time
Definition: pgbench.c:175
static bool doRetry(CState *st, pg_time_usec_t *now)
Definition: pgbench.c:3427
static bool sendCommand(CState *st, Command *command)
Definition: pgbench.c:3154
TStatus
Definition: pgbench.c:468
static void finishCon(CState *st)
Definition: pgbench.c:7694
int64 pg_time_usec_t
Definition: pgbench.c:369
bool is_connect
Definition: pgbench.c:265
int nxacts
Definition: pgbench.c:173
bool report_per_command
Definition: pgbench.c:266
#define PG_TIME_GET_DOUBLE(t)
Definition: pgbench.c:866
static int discardUntilSync(CState *st)
Definition: pgbench.c:3473
static ConnectionStateEnum executeMetaCommand(CState *st, pg_time_usec_t *now)
Definition: pgbench.c:4284
static bool canRetryError(EStatus estatus)
Definition: pgbench.c:3224
static void commandFailed(CState *st, const char *cmd, const char *message)
Definition: pgbench.c:3027
static int chooseScript(TState *thread)
Definition: pgbench.c:3046
#define SQL_COMMAND
Definition: pgbench.c:677
volatile sig_atomic_t timer_exceeded
Definition: pgbench.c:303
static void processXactStats(TState *thread, CState *st, pg_time_usec_t *now, bool skipped, StatsData *agg)
Definition: pgbench.c:4665
int duration
Definition: pgbench.c:174
static void pg_time_now_lazy(pg_time_usec_t *now)
Definition: pgbench.c:860
static bool verbose_errors
Definition: pgbench.c:767
static int64 getPoissonRand(pg_prng_state *state, double center)
Definition: pgbench.c:1178
static PGconn * doConnect(void)
Definition: pgbench.c:1530
#define META_COMMAND
Definition: pgbench.c:678
static bool readCommandResponse(CState *st, MetaCommand meta, char *varprefix)
Definition: pgbench.c:3240
int64 cnt
Definition: pgbench.c:636
int id
Definition: pgbench.c:598
pg_time_usec_t txn_scheduled
Definition: pgbench.c:616
pg_time_usec_t stmt_begin
Definition: pgbench.c:619
int command
Definition: pgbench.c:609
int use_file
Definition: pgbench.c:608
ConditionalStack cstack
Definition: pgbench.c:600
pg_prng_state random_state
Definition: pgbench.c:631
pg_time_usec_t txn_begin
Definition: pgbench.c:618
EStatus estatus
Definition: pgbench.c:628
PGconn * con
Definition: pgbench.c:597
pg_prng_state cs_func_rs
Definition: pgbench.c:606
uint32 tries
Definition: pgbench.c:632
bool ** prepared
Definition: pgbench.c:622
ConnectionStateEnum state
Definition: pgbench.c:599
int64 retries
Definition: pgbench.c:751
char * varprefix
Definition: pgbench.c:748
int type
Definition: pgbench.c:743
MetaCommand meta
Definition: pgbench.c:744
SimpleStats stats
Definition: pgbench.c:750
int64 failures
Definition: pgbench.c:752
int64 throttle_trigger
Definition: pgbench.c:660
pg_prng_state ts_throttle_rs
Definition: pgbench.c:657
pg_time_usec_t conn_duration
Definition: pgbench.c:667

References addToSimpleStats(), Assert, canRetryError(), chooseScript(), CState::cnt, CState::command, commandFailed(), ParsedScript::commands, CState::con, conditional_active(), conditional_stack_empty(), conditional_stack_peek(), conditional_stack_poke(), conditional_stack_pop(), conditional_stack_push(), conditional_stack_reset(), TState::conn_duration, CState::cs_func_rs, CState::cstack, CSTATE_ABORTED, CSTATE_CHOOSE_SCRIPT, CSTATE_END_COMMAND, CSTATE_END_TX, CSTATE_ERROR, CSTATE_FAILURE, CSTATE_FINISHED, CSTATE_PREPARE_THROTTLE, CSTATE_RETRY, CSTATE_SKIP_COMMAND, CSTATE_SLEEP, CSTATE_START_COMMAND, CSTATE_START_TX, CSTATE_THROTTLE, CSTATE_WAIT_RESULT, CSTATE_WAIT_ROLLBACK_RESULT, ParsedScript::desc, discardUntilSync(), doConnect(), doRetry(), duration, end_time, CState::estatus, ESTATUS_META_COMMAND_ERROR, ESTATUS_NO_ERROR, executeMetaCommand(), Command::failures, finishCon(), getPoissonRand(), getTransactionStatus(), CState::id, IFSTATE_ELSE_FALSE, IFSTATE_ELSE_TRUE, IFSTATE_FALSE, IFSTATE_IGNORED, IFSTATE_NONE, IFSTATE_TRUE, is_connect, latency_limit, Command::meta, META_ASET, META_COMMAND, META_ELIF, META_ELSE, META_ENDIF, META_GSET, META_IF, now(), nxacts, pg_free(), pg_log_debug, pg_log_error, PG_TIME_GET_DOUBLE, pg_time_now(), pg_time_now_lazy(), PGRES_COMMAND_OK, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, PQclear(), PQconsumeInput(), PQerrorMessage(), PQgetResult(), PQisBusy(), PQpipelineStatus(), PQresultStatus(), PQsendQuery(), CState::prepared, printVerboseErrorMessages(), processXactStats(), CState::random_state, readCommandResponse(), report_per_command, res, Command::retries, sendCommand(), SQL_COMMAND, sql_script, start, CState::state, Command::stats, CState::stmt_begin, throttle_delay, TState::throttle_trigger, timer_exceeded, CState::tries, TState::ts_throttle_rs, TSTATUS_CONN_ERROR, TSTATUS_IDLE, TSTATUS_IN_BLOCK, CState::txn_begin, CState::txn_scheduled, Command::type, CState::use_file, Command::varprefix, and verbose_errors.

Referenced by threadRun().

◆ alloc_socket_set()

static socket_set * alloc_socket_set ( int  count)
static

Definition at line 7859 of file pgbench.c.

7861 {
7862  return (socket_set *) pg_malloc0(sizeof(socket_set));
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53

References pg_malloc0().

Referenced by threadRun().

◆ allocCStatePrepared()

static void allocCStatePrepared ( CState st)
static

Definition at line 3068 of file pgbench.c.

3070 {
3071  Assert(st->prepared == NULL);
3072 
3073  st->prepared = pg_malloc(sizeof(bool *) * num_scripts);
3074  for (int i = 0; i < num_scripts; i++)
3075  {
3076  ParsedScript *script = &sql_script[i];
3077  int numcmds;
3078 
3079  for (numcmds = 0; script->commands[numcmds] != NULL; numcmds++)
3080  ;
3081  st->prepared[i] = pg_malloc0(sizeof(bool) * numcmds);
3082  }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
int i
Definition: isn.c:73

References Assert, ParsedScript::commands, i, num_scripts, pg_malloc(), pg_malloc0(), CState::prepared, and sql_script.

Referenced by prepareCommand(), and prepareCommandsInPipeline().

◆ assignVariables()

static char* assignVariables ( Variables variables,
char *  sql 
)
static

Definition at line 1935 of file pgbench.c.

1937 {
1938  char *p,
1939  *name,
1940  *val;
1941 
1942  p = sql;
1943  while ((p = strchr(p, ':')) != NULL)
1944  {
1945  int eaten;
1946 
1947  name = parseVariable(p, &eaten);
1948  if (name == NULL)
1949  {
1950  while (*p == ':')
1951  {
1952  p++;
1953  }
1954  continue;
1955  }
1956 
1957  val = getVariable(variables, name);
1958  free(name);
1959  if (val == NULL)
1960  {
1961  p++;
1962  continue;
1963  }
1964 
1965  p = replaceVariable(&sql, p, eaten, val);
1966  }
1967 
1968  return sql;
#define free(a)
Definition: header.h:65
static char * getVariable(Variables *variables, char *name)
Definition: pgbench.c:1630
static char * parseVariable(const char *sql, int *eaten)
Definition: pgbench.c:1888
static char * replaceVariable(char **sql, char *param, int len, char *value)
Definition: pgbench.c:1915
const char * name

References free, getVariable(), name, parseVariable(), replaceVariable(), and val.

Referenced by sendCommand().

◆ canRetryError()

static bool canRetryError ( EStatus  estatus)
static

Definition at line 3224 of file pgbench.c.

3226 {
3227  return (estatus == ESTATUS_SERIALIZATION_ERROR ||
3228  estatus == ESTATUS_DEADLOCK_ERROR);

References ESTATUS_DEADLOCK_ERROR, and ESTATUS_SERIALIZATION_ERROR.

Referenced by advanceConnectionState(), doRetry(), and readCommandResponse().

◆ CheckConditional()

static void CheckConditional ( const ParsedScript ps)
static

Definition at line 5854 of file pgbench.c.

5856 {
5857  /* statically check conditional structure */
5859  int i;
5860 
5861  for (i = 0; ps->commands[i] != NULL; i++)
5862  {
5863  Command *cmd = ps->commands[i];
5864 
5865  if (cmd->type == META_COMMAND)
5866  {
5867  switch (cmd->meta)
5868  {
5869  case META_IF:
5871  break;
5872  case META_ELIF:
5873  if (conditional_stack_empty(cs))
5874  ConditionError(ps->desc, i + 1, "\\elif without matching \\if");
5876  ConditionError(ps->desc, i + 1, "\\elif after \\else");
5877  break;
5878  case META_ELSE:
5879  if (conditional_stack_empty(cs))
5880  ConditionError(ps->desc, i + 1, "\\else without matching \\if");
5882  ConditionError(ps->desc, i + 1, "\\else after \\else");
5884  break;
5885  case META_ENDIF:
5886  if (!conditional_stack_pop(cs))
5887  ConditionError(ps->desc, i + 1, "\\endif without matching \\if");
5888  break;
5889  default:
5890  /* ignore anything else... */
5891  break;
5892  }
5893  }
5894  }
5895  if (!conditional_stack_empty(cs))
5896  ConditionError(ps->desc, i + 1, "\\if without matching \\endif");
ConditionalStack conditional_stack_create(void)
Definition: conditional.c:18
void conditional_stack_destroy(ConditionalStack cstack)
Definition: conditional.c:43
struct parser_state ps
static void ConditionError(const char *desc, int cmdn, const char *msg)
Definition: pgbench.c:5844

References conditional_stack_create(), conditional_stack_destroy(), conditional_stack_empty(), conditional_stack_peek(), conditional_stack_poke(), conditional_stack_pop(), conditional_stack_push(), ConditionError(), i, IFSTATE_ELSE_FALSE, IFSTATE_FALSE, Command::meta, META_COMMAND, META_ELIF, META_ELSE, META_ENDIF, META_IF, ps, and Command::type.

Referenced by addScript().

◆ checkInitSteps()

static void checkInitSteps ( const char *  initialize_steps)
static

Definition at line 5202 of file pgbench.c.

5204 {
5205  if (initialize_steps[0] == '\0')
5206  pg_fatal("no initialization steps specified");
5207 
5208  for (const char *step = initialize_steps; *step != '\0'; step++)
5209  {
5210  if (strchr(ALL_INIT_STEPS " ", *step) == NULL)
5211  {
5212  pg_log_error("unrecognized initialization step \"%c\"", *step);
5213  pg_log_error_detail("Allowed step characters are: \"" ALL_INIT_STEPS "\".");
5214  exit(1);
5215  }
5216  }
#define pg_log_error_detail(...)
Definition: logging.h:109
#define ALL_INIT_STEPS
Definition: pgbench.c:163

References ALL_INIT_STEPS, exit(), pg_fatal, pg_log_error, and pg_log_error_detail.

Referenced by main().

◆ chooseScript()

static int chooseScript ( TState thread)
static

Definition at line 3046 of file pgbench.c.

3048 {
3049  int i = 0;
3050  int64 w;
3051 
3052  if (num_scripts == 1)
3053  return 0;
3054 
3055  w = getrand(&thread->ts_choose_rs, 0, total_weight - 1);
3056  do
3057  {
3058  w -= sql_script[i++].weight;
3059  } while (w >= 0);
3060 
3061  return i - 1;
static int64 total_weight
Definition: pgbench.c:765
static int64 getrand(pg_prng_state *state, int64 min, int64 max)
Definition: pgbench.c:1101
int weight
Definition: pgbench.c:758
pg_prng_state ts_choose_rs
Definition: pgbench.c:656

References getrand(), i, num_scripts, sql_script, total_weight, TState::ts_choose_rs, and ParsedScript::weight.

Referenced by advanceConnectionState().

◆ clear_socket_set()

static void clear_socket_set ( socket_set sa)
static

Definition at line 7871 of file pgbench.c.

7873 {
7874  FD_ZERO(&sa->fds);
7875  sa->maxfd = -1;

Referenced by threadRun().

◆ coerceToBool()

static bool coerceToBool ( PgBenchValue pval,
bool bval 
)
static

Definition at line 2003 of file pgbench.c.

2005 {
2006  if (pval->type == PGBT_BOOLEAN)
2007  {
2008  *bval = pval->u.bval;
2009  return true;
2010  }
2011  else /* NULL, INT or DOUBLE */
2012  {
2013  pg_log_error("cannot coerce %s to boolean", valueTypeName(pval));
2014  *bval = false; /* suppress uninitialized-variable warnings */
2015  return false;
2016  }
static char * valueTypeName(PgBenchValue *pval)
Definition: pgbench.c:1981
@ PGBT_BOOLEAN
Definition: pgbench.h:40
PgBenchValueType type
Definition: pgbench.h:46
bool bval
Definition: pgbench.h:51
union PgBenchValue::@36 u

References PgBenchValue::bval, pg_log_error, PGBT_BOOLEAN, PgBenchValue::type, PgBenchValue::u, and valueTypeName().

Referenced by evalLazyFunc(), and evalStandardFunc().

◆ coerceToDouble()

static bool coerceToDouble ( PgBenchValue pval,
double *  dval 
)
static

Definition at line 2072 of file pgbench.c.

2074 {
2075  if (pval->type == PGBT_DOUBLE)
2076  {
2077  *dval = pval->u.dval;
2078  return true;
2079  }
2080  else if (pval->type == PGBT_INT)
2081  {
2082  *dval = (double) pval->u.ival;
2083  return true;
2084  }
2085  else /* BOOLEAN or NULL */
2086  {
2087  pg_log_error("cannot coerce %s to double", valueTypeName(pval));
2088  return false;
2089  }
@ PGBT_INT
Definition: pgbench.h:38
@ PGBT_DOUBLE
Definition: pgbench.h:39
int64 ival
Definition: pgbench.h:49
double dval
Definition: pgbench.h:50

References PgBenchValue::dval, PgBenchValue::ival, pg_log_error, PGBT_DOUBLE, PGBT_INT, PgBenchValue::type, PgBenchValue::u, and valueTypeName().

Referenced by evalStandardFunc().

◆ coerceToInt()

static bool coerceToInt ( PgBenchValue pval,
int64 *  ival 
)
static

Definition at line 2044 of file pgbench.c.

2046 {
2047  if (pval->type == PGBT_INT)
2048  {
2049  *ival = pval->u.ival;
2050  return true;
2051  }
2052  else if (pval->type == PGBT_DOUBLE)
2053  {
2054  double dval = rint(pval->u.dval);
2055 
2056  if (isnan(dval) || !FLOAT8_FITS_IN_INT64(dval))
2057  {
2058  pg_log_error("double to int overflow for %f", dval);
2059  return false;
2060  }
2061  *ival = (int64) dval;
2062  return true;
2063  }
2064  else /* BOOLEAN or NULL */
2065  {
2066  pg_log_error("cannot coerce %s to int", valueTypeName(pval));
2067  return false;
2068  }
#define FLOAT8_FITS_IN_INT64(num)
Definition: c.h:1092

References PgBenchValue::dval, FLOAT8_FITS_IN_INT64, PgBenchValue::ival, pg_log_error, PGBT_DOUBLE, PGBT_INT, PgBenchValue::type, PgBenchValue::u, and valueTypeName().

Referenced by evalStandardFunc().

◆ commandError()

static void commandError ( CState st,
const char *  message 
)
static

Definition at line 3037 of file pgbench.c.

3039 {
3041  pg_log_info("client %d got an error in command %d (SQL) of script %d; %s",
3042  st->id, st->command, st->use_file, message);
#define pg_log_info(...)
Definition: logging.h:124

References Assert, CState::command, ParsedScript::commands, CState::id, pg_log_info, SQL_COMMAND, sql_script, Command::type, and CState::use_file.

Referenced by readCommandResponse().

◆ commandFailed()

static void commandFailed ( CState st,
const char *  cmd,
const char *  message 
)
static

Definition at line 3027 of file pgbench.c.

3029 {
3030  pg_log_error("client %d aborted in command %d (%s) of script %d; %s",
3031  st->id, st->command, cmd, st->use_file, message);

References CState::command, CState::id, pg_log_error, and CState::use_file.

Referenced by advanceConnectionState(), and executeMetaCommand().

◆ compareVariableNames()

static int compareVariableNames ( const void *  v1,
const void *  v2 
)
static

Definition at line 1595 of file pgbench.c.

1597 {
1598  return strcmp(((const Variable *) v1)->name,
1599  ((const Variable *) v2)->name);

References name.

Referenced by lookupVariable().

◆ computeIterativeZipfian()

static int64 computeIterativeZipfian ( pg_prng_state state,
int64  n,
double  s 
)
static

Definition at line 1200 of file pgbench.c.

1202 {
1203  double b = pow(2.0, s - 1.0);
1204  double x,
1205  t,
1206  u,
1207  v;
1208 
1209  /* Ensure n is sane */
1210  if (n <= 1)
1211  return 1;
1212 
1213  while (true)
1214  {
1215  /* random variates */
1216  u = pg_prng_double(state);
1217  v = pg_prng_double(state);
1218 
1219  x = floor(pow(u, -1.0 / (s - 1.0)));
1220 
1221  t = pow(1.0 + 1.0 / x, s - 1.0);
1222  /* reject if too large or out of bound */
1223  if (v * x * (t - 1.0) / (b - 1.0) <= t / b && x <= n)
1224  break;
1225  }
1226  return (int64) x;
int b
Definition: isn.c:70
int x
Definition: isn.c:71
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:268
Definition: regguts.h:323

References b, pg_prng_double(), and x.

Referenced by getZipfianRand().

◆ ConditionError()

static void ConditionError ( const char *  desc,
int  cmdn,
const char *  msg 
)
static

Definition at line 5844 of file pgbench.c.

5846 {
5847  pg_fatal("condition error in script \"%s\" command %d: %s",
5848  desc, cmdn, msg);

References pg_fatal.

Referenced by CheckConditional().

◆ create_sql_command()

static Command* create_sql_command ( PQExpBuffer  buf,
const char *  source 
)
static

Definition at line 5548 of file pgbench.c.

5550 {
5551  Command *my_command;
5552  char *p = skip_sql_comments(buf->data);
5553 
5554  if (p == NULL)
5555  return NULL;
5556 
5557  /* Allocate and initialize Command structure */
5558  my_command = (Command *) pg_malloc(sizeof(Command));
5559  initPQExpBuffer(&my_command->lines);
5560  appendPQExpBufferStr(&my_command->lines, p);
5561  my_command->first_line = NULL; /* this is set later */
5562  my_command->type = SQL_COMMAND;
5563  my_command->meta = META_NONE;
5564  my_command->argc = 0;
5565  my_command->retries = 0;
5566  my_command->failures = 0;
5567  memset(my_command->argv, 0, sizeof(my_command->argv));
5568  my_command->varprefix = NULL; /* allocated later, if needed */
5569  my_command->expr = NULL;
5570  initSimpleStats(&my_command->stats);
5571  my_command->prepname = NULL; /* set later, if needed */
5572 
5573  return my_command;
static char * buf
Definition: pg_test_fsync.c:73
static char * skip_sql_comments(char *sql_command)
Definition: pgbench.c:5513
static void initSimpleStats(SimpleStats *ss)
Definition: pgbench.c:1393
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
PQExpBufferData lines
Definition: pgbench.c:741
PgBenchExpr * expr
Definition: pgbench.c:749
char * argv[MAX_ARGS]
Definition: pgbench.c:746
char * first_line
Definition: pgbench.c:742
int argc
Definition: pgbench.c:745
char * prepname
Definition: pgbench.c:747

References appendPQExpBufferStr(), Command::argc, Command::argv, buf, Command::expr, Command::failures, Command::first_line, initPQExpBuffer(), initSimpleStats(), Command::lines, Command::meta, META_NONE, pg_malloc(), Command::prepname, Command::retries, skip_sql_comments(), SQL_COMMAND, Command::stats, Command::type, and Command::varprefix.

Referenced by ParseScript().

◆ createPartitions()

static void createPartitions ( PGconn con)
static

Definition at line 4738 of file pgbench.c.

4740 {
4741  PQExpBufferData query;
4742 
4743  /* we must have to create some partitions */
4744  Assert(partitions > 0);
4745 
4746  fprintf(stderr, "creating %d partitions...\n", partitions);
4747 
4748  initPQExpBuffer(&query);
4749 
4750  for (int p = 1; p <= partitions; p++)
4751  {
4753  {
4754  int64 part_size = (naccounts * (int64) scale + partitions - 1) / partitions;
4755 
4756  printfPQExpBuffer(&query,
4757  "create%s table pgbench_accounts_%d\n"
4758  " partition of pgbench_accounts\n"
4759  " for values from (",
4760  unlogged_tables ? " unlogged" : "", p);
4761 
4762  /*
4763  * For RANGE, we use open-ended partitions at the beginning and
4764  * end to allow any valid value for the primary key. Although the
4765  * actual minimum and maximum values can be derived from the
4766  * scale, it is more generic and the performance is better.
4767  */
4768  if (p == 1)
4769  appendPQExpBufferStr(&query, "minvalue");
4770  else
4771  appendPQExpBuffer(&query, INT64_FORMAT, (p - 1) * part_size + 1);
4772 
4773  appendPQExpBufferStr(&query, ") to (");
4774 
4775  if (p < partitions)
4776  appendPQExpBuffer(&query, INT64_FORMAT, p * part_size + 1);
4777  else
4778  appendPQExpBufferStr(&query, "maxvalue");
4779 
4780  appendPQExpBufferChar(&query, ')');
4781  }
4782  else if (partition_method == PART_HASH)
4783  printfPQExpBuffer(&query,
4784  "create%s table pgbench_accounts_%d\n"
4785  " partition of pgbench_accounts\n"
4786  " for values with (modulus %d, remainder %d)",
4787  unlogged_tables ? " unlogged" : "", p,
4788  partitions, p - 1);
4789  else /* cannot get there */
4790  Assert(0);
4791 
4792  /*
4793  * Per ddlinfo in initCreateTables, fillfactor is needed on table
4794  * pgbench_accounts.
4795  */
4796  appendPQExpBuffer(&query, " with (fillfactor=%d)", fillfactor);
4797 
4798  executeStatement(con, query.data);
4799  }
4800 
4801  termPQExpBuffer(&query);
#define INT64_FORMAT
Definition: c.h:548
int scale
Definition: pgbench.c:181
static int partitions
Definition: pgbench.c:223
int fillfactor
Definition: pgbench.c:187
static partition_method_t partition_method
Definition: pgbench.c:233
bool unlogged_tables
Definition: pgbench.c:192
#define naccounts
Definition: pgbench.c:245
static void executeStatement(PGconn *con, const char *sql)
Definition: pgbench.c:1499
#define fprintf
Definition: port.h:242
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), Assert, PQExpBufferData::data, executeStatement(), fillfactor, fprintf, initPQExpBuffer(), INT64_FORMAT, naccounts, PART_HASH, PART_RANGE, partition_method, partitions, printfPQExpBuffer(), scale, termPQExpBuffer(), and unlogged_tables.

Referenced by initCreateTables().

◆ discardUntilSync()

static int discardUntilSync ( CState st)
static

Definition at line 3473 of file pgbench.c.

3475 {
3476  /* send a sync */
3477  if (!PQpipelineSync(st->con))
3478  {
3479  pg_log_error("client %d aborted: failed to send a pipeline sync",
3480  st->id);
3481  return 0;
3482  }
3483 
3484  /* receive PGRES_PIPELINE_SYNC and null following it */
3485  for (;;)
3486  {
3487  PGresult *res = PQgetResult(st->con);
3488 
3490  {
3491  PQclear(res);
3492  res = PQgetResult(st->con);
3493  Assert(res == NULL);
3494  break;
3495  }
3496  PQclear(res);
3497  }
3498 
3499  /* exit pipeline */
3500  if (PQexitPipelineMode(st->con) != 1)
3501  {
3502  pg_log_error("client %d aborted: failed to exit pipeline mode for rolling back the failed transaction",
3503  st->id);
3504  return 0;
3505  }
3506  return 1;
int PQexitPipelineMode(PGconn *conn)
Definition: fe-exec.c:3073
int PQpipelineSync(PGconn *conn)
Definition: fe-exec.c:3272
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:113

References Assert, CState::con, CState::id, pg_log_error, PGRES_PIPELINE_SYNC, PQclear(), PQexitPipelineMode(), PQgetResult(), PQpipelineSync(), PQresultStatus(), and res.

Referenced by advanceConnectionState().

◆ disconnect_all()

static void disconnect_all ( CState state,
int  length 
)
static

Definition at line 4704 of file pgbench.c.

4706 {
4707  int i;
4708 
4709  for (i = 0; i < length; i++)
4710  finishCon(&state[i]);

References finishCon(), and i.

Referenced by main(), and threadRun().

◆ doConnect()

static PGconn* doConnect ( void  )
static

Definition at line 1530 of file pgbench.c.

1532 {
1533  PGconn *conn;
1534  bool new_pass;
1535  static char *password = NULL;
1536 
1537  /*
1538  * Start the connection. Loop until we have a password if requested by
1539  * backend.
1540  */
1541  do
1542  {
1543 #define PARAMS_ARRAY_SIZE 7
1544 
1545  const char *keywords[PARAMS_ARRAY_SIZE];
1546  const char *values[PARAMS_ARRAY_SIZE];
1547 
1548  keywords[0] = "host";
1549  values[0] = pghost;
1550  keywords[1] = "port";
1551  values[1] = pgport;
1552  keywords[2] = "user";
1553  values[2] = username;
1554  keywords[3] = "password";
1555  values[3] = password;
1556  keywords[4] = "dbname";
1557  values[4] = dbName;
1558  keywords[5] = "fallback_application_name";
1559  values[5] = progname;
1560  keywords[6] = NULL;
1561  values[6] = NULL;
1562 
1563  new_pass = false;
1564 
1565  conn = PQconnectdbParams(keywords, values, true);
1566 
1567  if (!conn)
1568  {
1569  pg_log_error("connection to database \"%s\" failed", dbName);
1570  return NULL;
1571  }
1572 
1573  if (PQstatus(conn) == CONNECTION_BAD &&
1575  !password)
1576  {
1577  PQfinish(conn);
1578  password = simple_prompt("Password: ", false);
1579  new_pass = true;
1580  }
1581  } while (new_pass);
1582 
1583  /* check to see that the backend connection was successfully made */
1584  if (PQstatus(conn) == CONNECTION_BAD)
1585  {
1587  PQfinish(conn);
1588  return NULL;
1589  }
1590 
1591  return conn;
static Datum values[MAXATTR]
Definition: bootstrap.c:152
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:689
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7205
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7101
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4875
@ CONNECTION_BAD
Definition: libpq-fe.h:61
#define PARAMS_ARRAY_SIZE
const char * pghost
Definition: pgbench.c:294
const char * username
Definition: pgbench.c:296
const char * progname
Definition: pgbench.c:299
const char * pgport
Definition: pgbench.c:295
const char * dbName
Definition: pgbench.c:297
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static char * password
Definition: streamutil.c:54
PGconn * conn
Definition: streamutil.c:55

References conn, CONNECTION_BAD, dbName, PARAMS_ARRAY_SIZE, password, pg_log_error, pghost, pgport, PQconnectdbParams(), PQconnectionNeedsPassword(), PQerrorMessage(), PQfinish(), PQstatus(), progname, simple_prompt(), username, and values.

Referenced by advanceConnectionState(), main(), runInitSteps(), and threadRun().

◆ doLog()

static void doLog ( TState thread,
CState st,
StatsData agg,
bool  skipped,
double  latency,
double  lag 
)
static

Definition at line 4545 of file pgbench.c.

4548 {
4549  FILE *logfile = thread->logfile;
4551 
4552  Assert(use_log);
4553 
4554  /*
4555  * Skip the log entry if sampling is enabled and this row doesn't belong
4556  * to the random sample.
4557  */
4558  if (sample_rate != 0.0 &&
4560  return;
4561 
4562  /* should we aggregate the results or not? */
4563  if (agg_interval > 0)
4564  {
4566 
4567  /*
4568  * Loop until we reach the interval of the current moment, and print
4569  * any empty intervals in between (this may happen with very low tps,
4570  * e.g. --rate=0.1).
4571  */
4572 
4573  while ((next = agg->start_time + agg_interval * INT64CONST(1000000)) <= now)
4574  {
4575  double lag_sum = 0.0;
4576  double lag_sum2 = 0.0;
4577  double lag_min = 0.0;
4578  double lag_max = 0.0;
4579  int64 skipped = 0;
4580  int64 serialization_failures = 0;
4581  int64 deadlock_failures = 0;
4582  int64 retried = 0;
4583  int64 retries = 0;
4584 
4585  /* print aggregated report to logfile */
4586  fprintf(logfile, INT64_FORMAT " " INT64_FORMAT " %.0f %.0f %.0f %.0f",
4587  agg->start_time / 1000000, /* seconds since Unix epoch */
4588  agg->cnt,
4589  agg->latency.sum,
4590  agg->latency.sum2,
4591  agg->latency.min,
4592  agg->latency.max);
4593 
4594  if (throttle_delay)
4595  {
4596  lag_sum = agg->lag.sum;
4597  lag_sum2 = agg->lag.sum2;
4598  lag_min = agg->lag.min;
4599  lag_max = agg->lag.max;
4600  }
4601  fprintf(logfile, " %.0f %.0f %.0f %.0f",
4602  lag_sum,
4603  lag_sum2,
4604  lag_min,
4605  lag_max);
4606 
4607  if (latency_limit)
4608  skipped = agg->skipped;
4609  fprintf(logfile, " " INT64_FORMAT, skipped);
4610 
4611  if (max_tries != 1)
4612  {
4613  retried = agg->retried;
4614  retries = agg->retries;
4615  }
4616  fprintf(logfile, " " INT64_FORMAT " " INT64_FORMAT, retried, retries);
4617 
4618  if (failures_detailed)
4619  {
4620  serialization_failures = agg->serialization_failures;
4621  deadlock_failures = agg->deadlock_failures;
4622  }
4624  serialization_failures,
4625  deadlock_failures);
4626 
4627  fputc('\n', logfile);
4628 
4629  /* reset data and move to next interval */
4630  initStats(agg, next);
4631  }
4632 
4633  /* accumulate the current transaction */
4634  accumStats(agg, skipped, latency, lag, st->estatus, st->tries);
4635  }
4636  else
4637  {
4638  /* no, print raw transactions */
4639  if (!skipped && st->estatus == ESTATUS_NO_ERROR)
4640  fprintf(logfile, "%d " INT64_FORMAT " %.0f %d " INT64_FORMAT " "
4641  INT64_FORMAT,
4642  st->id, st->cnt, latency, st->use_file,
4643  now / 1000000, now % 1000000);
4644  else
4645  fprintf(logfile, "%d " INT64_FORMAT " %s %d " INT64_FORMAT " "
4646  INT64_FORMAT,
4647  st->id, st->cnt, getResultString(skipped, st->estatus),
4648  st->use_file, now / 1000000, now % 1000000);
4649 
4650  if (throttle_delay)
4651  fprintf(logfile, " %.0f", lag);
4652  if (max_tries != 1)
4653  fprintf(logfile, " %u", st->tries - 1);
4654  fputc('\n', logfile);
4655  }
static int32 next
Definition: blutils.c:221
static FILE * logfile
Definition: pg_regress.c:127
static void accumStats(StatsData *stats, bool skipped, double lat, double lag, EStatus estatus, int64 tries)
Definition: pgbench.c:1450
uint32 max_tries
Definition: pgbench.c:289
bool use_log
Definition: pgbench.c:256
int agg_interval
Definition: pgbench.c:258
static const char * getResultString(bool skipped, EStatus estatus)
Definition: pgbench.c:4514
static void initStats(StatsData *sd, pg_time_usec_t start)
Definition: pgbench.c:1433
double sample_rate
Definition: pgbench.c:197
bool failures_detailed
Definition: pgbench.c:291
pg_time_usec_t epoch_shift
Definition: pgbench.c:448
pg_time_usec_t start_time
Definition: pgbench.c:377
FILE * logfile
Definition: pgbench.c:661
pg_prng_state ts_sample_rs
Definition: pgbench.c:658

References accumStats(), agg_interval, Assert, StatsData::cnt, CState::cnt, StatsData::deadlock_failures, epoch_shift, CState::estatus, ESTATUS_NO_ERROR, failures_detailed, fprintf, getResultString(), CState::id, initStats(), INT64_FORMAT, StatsData::lag, StatsData::latency, latency_limit, TState::logfile, logfile, SimpleStats::max, max_tries, SimpleStats::min, next, now(), pg_prng_double(), pg_time_now(), StatsData::retried, StatsData::retries, sample_rate, StatsData::serialization_failures, StatsData::skipped, StatsData::start_time, SimpleStats::sum, SimpleStats::sum2, throttle_delay, CState::tries, TState::ts_sample_rs, CState::use_file, and use_log.

Referenced by processXactStats(), and threadRun().

◆ doRetry()

static bool doRetry ( CState st,
pg_time_usec_t now 
)
static

Definition at line 3427 of file pgbench.c.

3429 {
3431 
3432  /* We can only retry serialization or deadlock errors. */
3433  if (!canRetryError(st->estatus))
3434  return false;
3435 
3436  /*
3437  * We must have at least one option to limit the retrying of transactions
3438  * that got an error.
3439  */
3441 
3442  /*
3443  * We cannot retry the error if we have reached the maximum number of
3444  * tries.
3445  */
3446  if (max_tries && st->tries >= max_tries)
3447  return false;
3448 
3449  /*
3450  * We cannot retry the error if we spent too much time on this
3451  * transaction.
3452  */
3453  if (latency_limit)
3454  {
3456  if (*now - st->txn_scheduled > latency_limit)
3457  return false;
3458  }
3459 
3460  /*
3461  * We cannot retry the error if the benchmark duration is over.
3462  */
3463  if (timer_exceeded)
3464  return false;
3465 
3466  /* OK */
3467  return true;

References Assert, canRetryError(), duration, CState::estatus, ESTATUS_NO_ERROR, latency_limit, max_tries, now(), pg_time_now_lazy(), timer_exceeded, CState::tries, and CState::txn_scheduled.

Referenced by advanceConnectionState().

◆ enlargeVariables()

static void enlargeVariables ( Variables variables,
int  needed 
)
static

Definition at line 1772 of file pgbench.c.

1774 {
1775  /* total number of variables required now */
1776  needed += variables->nvars;
1777 
1778  if (variables->max_vars < needed)
1779  {
1780  variables->max_vars = needed + VARIABLES_ALLOC_MARGIN;
1781  variables->vars = (Variable *)
1782  pg_realloc(variables->vars, variables->max_vars * sizeof(Variable));
1783  }
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
#define VARIABLES_ALLOC_MARGIN
Definition: pgbench.c:309
Variable * vars
Definition: pgbench.c:333
int nvars
Definition: pgbench.c:334
int max_vars
Definition: pgbench.c:341

References Variables::max_vars, Variables::nvars, pg_realloc(), VARIABLES_ALLOC_MARGIN, and Variables::vars.

Referenced by lookupCreateVariable().

◆ evalFunc()

static bool evalFunc ( CState st,
PgBenchFunction  func,
PgBenchExprLink args,
PgBenchValue retval 
)
static

Definition at line 2820 of file pgbench.c.

2823 {
2824  if (isLazyFunc(func))
2825  return evalLazyFunc(st, func, args, retval);
2826  else
2827  return evalStandardFunc(st, func, args, retval);
static bool isLazyFunc(PgBenchFunction func)
Definition: pgbench.c:2124
static bool evalLazyFunc(CState *st, PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
Definition: pgbench.c:2131
static bool evalStandardFunc(CState *st, PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
Definition: pgbench.c:2248

References generate_unaccent_rules::args, evalLazyFunc(), evalStandardFunc(), and isLazyFunc().

Referenced by evaluateExpr().

◆ evalLazyFunc()

static bool evalLazyFunc ( CState st,
PgBenchFunction  func,
PgBenchExprLink args,
PgBenchValue retval 
)
static

Definition at line 2131 of file pgbench.c.

2134 {
2135  PgBenchValue a1,
2136  a2;
2137  bool ba1,
2138  ba2;
2139 
2140  Assert(isLazyFunc(func) && args != NULL && args->next != NULL);
2141 
2142  /* args points to first condition */
2143  if (!evaluateExpr(st, args->expr, &a1))
2144  return false;
2145 
2146  /* second condition for AND/OR and corresponding branch for CASE */
2147  args = args->next;
2148 
2149  switch (func)
2150  {
2151  case PGBENCH_AND:
2152  if (a1.type == PGBT_NULL)
2153  {
2154  setNullValue(retval);
2155  return true;
2156  }
2157 
2158  if (!coerceToBool(&a1, &ba1))
2159  return false;
2160 
2161  if (!ba1)
2162  {
2163  setBoolValue(retval, false);
2164  return true;
2165  }
2166 
2167  if (!evaluateExpr(st, args->expr, &a2))
2168  return false;
2169 
2170  if (a2.type == PGBT_NULL)
2171  {
2172  setNullValue(retval);
2173  return true;
2174  }
2175  else if (!coerceToBool(&a2, &ba2))
2176  return false;
2177  else
2178  {
2179  setBoolValue(retval, ba2);
2180  return true;
2181  }
2182 
2183  return true;
2184 
2185  case PGBENCH_OR:
2186 
2187  if (a1.type == PGBT_NULL)
2188  {
2189  setNullValue(retval);
2190  return true;
2191  }
2192 
2193  if (!coerceToBool(&a1, &ba1))
2194  return false;
2195 
2196  if (ba1)
2197  {
2198  setBoolValue(retval, true);
2199  return true;
2200  }
2201 
2202  if (!evaluateExpr(st, args->expr, &a2))
2203  return false;
2204 
2205  if (a2.type == PGBT_NULL)
2206  {
2207  setNullValue(retval);
2208  return true;
2209  }
2210  else if (!coerceToBool(&a2, &ba2))
2211  return false;
2212  else
2213  {
2214  setBoolValue(retval, ba2);
2215  return true;
2216  }
2217 
2218  case PGBENCH_CASE:
2219  /* when true, execute branch */
2220  if (valueTruth(&a1))
2221  return evaluateExpr(st, args->expr, retval);
2222 
2223  /* now args contains next condition or final else expression */
2224  args = args->next;
2225 
2226  /* final else case? */
2227  if (args->next == NULL)
2228  return evaluateExpr(st, args->expr, retval);
2229 
2230  /* no, another when, proceed */
2231  return evalLazyFunc(st, PGBENCH_CASE, args, retval);
2232 
2233  default:
2234  /* internal error, cannot get here */
2235  Assert(0);
2236  break;
2237  }
2238  return false;
static const FormData_pg_attribute a1
Definition: heap.c:142
static const FormData_pg_attribute a2
Definition: heap.c:156
static void setNullValue(PgBenchValue *pv)
Definition: pgbench.c:2093
static bool evaluateExpr(CState *st, PgBenchExpr *expr, PgBenchValue *retval)
Definition: pgbench.c:2836
static void setBoolValue(PgBenchValue *pv, bool bval)
Definition: pgbench.c:2101
static bool valueTruth(PgBenchValue *pval)
Definition: pgbench.c:2023
static bool coerceToBool(PgBenchValue *pval, bool *bval)
Definition: pgbench.c:2003
@ PGBT_NULL
Definition: pgbench.h:37
@ PGBENCH_AND
Definition: pgbench.h:87
@ PGBENCH_OR
Definition: pgbench.h:88
@ PGBENCH_CASE
Definition: pgbench.h:100

References a1, a2, generate_unaccent_rules::args, Assert, coerceToBool(), evaluateExpr(), isLazyFunc(), PGBENCH_AND, PGBENCH_CASE, PGBENCH_OR, PGBT_NULL, setBoolValue(), setNullValue(), and valueTruth().

Referenced by evalFunc().

◆ evalStandardFunc()

static bool evalStandardFunc ( CState st,
PgBenchFunction  func,
PgBenchExprLink args,
PgBenchValue retval 
)
static

Definition at line 2248 of file pgbench.c.

2252 {
2253  /* evaluate all function arguments */
2254  int nargs = 0;
2255  PgBenchExprLink *l = args;
2256  bool has_null = false;
2257 
2258  /*
2259  * This value is double braced to workaround GCC bug 53119, which seems to
2260  * exist at least on gcc (Debian 4.7.2-5) 4.7.2, 32-bit.
2261  */
2262  PgBenchValue vargs[MAX_FARGS] = {{0}};
2263 
2264  for (nargs = 0; nargs < MAX_FARGS && l != NULL; nargs++, l = l->next)
2265  {
2266  if (!evaluateExpr(st, l->expr, &vargs[nargs]))
2267  return false;
2268  has_null |= vargs[nargs].type == PGBT_NULL;
2269  }
2270 
2271  if (l != NULL)
2272  {
2273  pg_log_error("too many function arguments, maximum is %d", MAX_FARGS);
2274  return false;
2275  }
2276 
2277  /* NULL arguments */
2278  if (has_null && func != PGBENCH_IS && func != PGBENCH_DEBUG)
2279  {
2280  setNullValue(retval);
2281  return true;
2282  }
2283 
2284  /* then evaluate function */
2285  switch (func)
2286  {
2287  /* overloaded operators */
2288  case PGBENCH_ADD:
2289  case PGBENCH_SUB:
2290  case PGBENCH_MUL:
2291  case PGBENCH_DIV:
2292  case PGBENCH_MOD:
2293  case PGBENCH_EQ:
2294  case PGBENCH_NE:
2295  case PGBENCH_LE:
2296  case PGBENCH_LT:
2297  {
2298  PgBenchValue *lval = &vargs[0],
2299  *rval = &vargs[1];
2300 
2301  Assert(nargs == 2);
2302 
2303  /* overloaded type management, double if some double */
2304  if ((lval->type == PGBT_DOUBLE ||
2305  rval->type == PGBT_DOUBLE) && func != PGBENCH_MOD)
2306  {
2307  double ld,
2308  rd;
2309 
2310  if (!coerceToDouble(lval, &ld) ||
2311  !coerceToDouble(rval, &rd))
2312  return false;
2313 
2314  switch (func)
2315  {
2316  case PGBENCH_ADD:
2317  setDoubleValue(retval, ld + rd);
2318  return true;
2319 
2320  case PGBENCH_SUB:
2321  setDoubleValue(retval, ld - rd);
2322  return true;
2323 
2324  case PGBENCH_MUL:
2325  setDoubleValue(retval, ld * rd);
2326  return true;
2327 
2328  case PGBENCH_DIV:
2329  setDoubleValue(retval, ld / rd);
2330  return true;
2331 
2332  case PGBENCH_EQ:
2333  setBoolValue(retval, ld == rd);
2334  return true;
2335 
2336  case PGBENCH_NE:
2337  setBoolValue(retval, ld != rd);
2338  return true;
2339 
2340  case PGBENCH_LE:
2341  setBoolValue(retval, ld <= rd);
2342  return true;
2343 
2344  case PGBENCH_LT:
2345  setBoolValue(retval, ld < rd);
2346  return true;
2347 
2348  default:
2349  /* cannot get here */
2350  Assert(0);
2351  }
2352  }
2353  else /* we have integer operands, or % */
2354  {
2355  int64 li,
2356  ri,
2357  res;
2358 
2359  if (!coerceToInt(lval, &li) ||
2360  !coerceToInt(rval, &ri))
2361  return false;
2362 
2363  switch (func)
2364  {
2365  case PGBENCH_ADD:
2366  if (pg_add_s64_overflow(li, ri, &res))
2367  {
2368  pg_log_error("bigint add out of range");
2369  return false;
2370  }
2371  setIntValue(retval, res);
2372  return true;
2373 
2374  case PGBENCH_SUB:
2375  if (pg_sub_s64_overflow(li, ri, &res))
2376  {
2377  pg_log_error("bigint sub out of range");
2378  return false;
2379  }
2380  setIntValue(retval, res);
2381  return true;
2382 
2383  case PGBENCH_MUL:
2384  if (pg_mul_s64_overflow(li, ri, &res))
2385  {
2386  pg_log_error("bigint mul out of range");
2387  return false;
2388  }
2389  setIntValue(retval, res);
2390  return true;
2391 
2392  case PGBENCH_EQ:
2393  setBoolValue(retval, li == ri);
2394  return true;
2395 
2396  case PGBENCH_NE:
2397  setBoolValue(retval, li != ri);
2398  return true;
2399 
2400  case PGBENCH_LE:
2401  setBoolValue(retval, li <= ri);
2402  return true;
2403 
2404  case PGBENCH_LT:
2405  setBoolValue(retval, li < ri);
2406  return true;
2407 
2408  case PGBENCH_DIV:
2409  case PGBENCH_MOD:
2410  if (ri == 0)
2411  {
2412  pg_log_error("division by zero");
2413  return false;
2414  }
2415  /* special handling of -1 divisor */
2416  if (ri == -1)
2417  {
2418  if (func == PGBENCH_DIV)
2419  {
2420  /* overflow check (needed for INT64_MIN) */
2421  if (li == PG_INT64_MIN)
2422  {
2423  pg_log_error("bigint div out of range");
2424  return false;
2425  }
2426  else
2427  setIntValue(retval, -li);
2428  }
2429  else
2430  setIntValue(retval, 0);
2431  return true;
2432  }
2433  /* else divisor is not -1 */
2434  if (func == PGBENCH_DIV)
2435  setIntValue(retval, li / ri);
2436  else /* func == PGBENCH_MOD */
2437  setIntValue(retval, li % ri);
2438 
2439  return true;
2440 
2441  default:
2442  /* cannot get here */
2443  Assert(0);
2444  }
2445  }
2446 
2447  Assert(0);
2448  return false; /* NOTREACHED */
2449  }
2450 
2451  /* integer bitwise operators */
2452  case PGBENCH_BITAND:
2453  case PGBENCH_BITOR:
2454  case PGBENCH_BITXOR:
2455  case PGBENCH_LSHIFT:
2456  case PGBENCH_RSHIFT:
2457  {
2458  int64 li,
2459  ri;
2460 
2461  if (!coerceToInt(&vargs[0], &li) || !coerceToInt(&vargs[1], &ri))
2462  return false;
2463 
2464  if (func == PGBENCH_BITAND)
2465  setIntValue(retval, li & ri);
2466  else if (func == PGBENCH_BITOR)
2467  setIntValue(retval, li | ri);
2468  else if (func == PGBENCH_BITXOR)
2469  setIntValue(retval, li ^ ri);
2470  else if (func == PGBENCH_LSHIFT)
2471  setIntValue(retval, li << ri);
2472  else if (func == PGBENCH_RSHIFT)
2473  setIntValue(retval, li >> ri);
2474  else /* cannot get here */
2475  Assert(0);
2476 
2477  return true;
2478  }
2479 
2480  /* logical operators */
2481  case PGBENCH_NOT:
2482  {
2483  bool b;
2484 
2485  if (!coerceToBool(&vargs[0], &b))
2486  return false;
2487 
2488  setBoolValue(retval, !b);
2489  return true;
2490  }
2491 
2492  /* no arguments */
2493  case PGBENCH_PI:
2494  setDoubleValue(retval, M_PI);
2495  return true;
2496 
2497  /* 1 overloaded argument */
2498  case PGBENCH_ABS:
2499  {
2500  PgBenchValue *varg = &vargs[0];
2501 
2502  Assert(nargs == 1);
2503 
2504  if (varg->type == PGBT_INT)
2505  {
2506  int64 i = varg->u.ival;
2507 
2508  setIntValue(retval, i < 0 ? -i : i);
2509  }
2510  else
2511  {
2512  double d = varg->u.dval;
2513 
2514  Assert(varg->type == PGBT_DOUBLE);
2515  setDoubleValue(retval, d < 0.0 ? -d : d);
2516  }
2517 
2518  return true;
2519  }
2520 
2521  case PGBENCH_DEBUG:
2522  {
2523  PgBenchValue *varg = &vargs[0];
2524 
2525  Assert(nargs == 1);
2526 
2527  fprintf(stderr, "debug(script=%d,command=%d): ",
2528  st->use_file, st->command + 1);
2529 
2530  if (varg->type == PGBT_NULL)
2531  fprintf(stderr, "null\n");
2532  else if (varg->type == PGBT_BOOLEAN)
2533  fprintf(stderr, "boolean %s\n", varg->u.bval ? "true" : "false");
2534  else if (varg->type == PGBT_INT)
2535  fprintf(stderr, "int " INT64_FORMAT "\n", varg->u.ival);
2536  else if (varg->type == PGBT_DOUBLE)
2537  fprintf(stderr, "double %.*g\n", DBL_DIG, varg->u.dval);
2538  else /* internal error, unexpected type */
2539  Assert(0);
2540 
2541  *retval = *varg;
2542 
2543  return true;
2544  }
2545 
2546  /* 1 double argument */
2547  case PGBENCH_DOUBLE:
2548  case PGBENCH_SQRT:
2549  case PGBENCH_LN:
2550  case PGBENCH_EXP:
2551  {
2552  double dval;
2553 
2554  Assert(nargs == 1);
2555 
2556  if (!coerceToDouble(&vargs[0], &dval))
2557  return false;
2558 
2559  if (func == PGBENCH_SQRT)
2560  dval = sqrt(dval);
2561  else if (func == PGBENCH_LN)
2562  dval = log(dval);
2563  else if (func == PGBENCH_EXP)
2564  dval = exp(dval);
2565  /* else is cast: do nothing */
2566 
2567  setDoubleValue(retval, dval);
2568  return true;
2569  }
2570 
2571  /* 1 int argument */
2572  case PGBENCH_INT:
2573  {
2574  int64 ival;
2575 
2576  Assert(nargs == 1);
2577 
2578  if (!coerceToInt(&vargs[0], &ival))
2579  return false;
2580 
2581  setIntValue(retval, ival);
2582  return true;
2583  }
2584 
2585  /* variable number of arguments */
2586  case PGBENCH_LEAST:
2587  case PGBENCH_GREATEST:
2588  {
2589  bool havedouble;
2590  int i;
2591 
2592  Assert(nargs >= 1);
2593 
2594  /* need double result if any input is double */
2595  havedouble = false;
2596  for (i = 0; i < nargs; i++)
2597  {
2598  if (vargs[i].type == PGBT_DOUBLE)
2599  {
2600  havedouble = true;
2601  break;
2602  }
2603  }
2604  if (havedouble)
2605  {
2606  double extremum;
2607 
2608  if (!coerceToDouble(&vargs[0], &extremum))
2609  return false;
2610  for (i = 1; i < nargs; i++)
2611  {
2612  double dval;
2613 
2614  if (!coerceToDouble(&vargs[i], &dval))
2615  return false;
2616  if (func == PGBENCH_LEAST)
2617  extremum = Min(extremum, dval);
2618  else
2619  extremum = Max(extremum, dval);
2620  }
2621  setDoubleValue(retval, extremum);
2622  }
2623  else
2624  {
2625  int64 extremum;
2626 
2627  if (!coerceToInt(&vargs[0], &extremum))
2628  return false;
2629  for (i = 1; i < nargs; i++)
2630  {
2631  int64 ival;
2632 
2633  if (!coerceToInt(&vargs[i], &ival))
2634  return false;
2635  if (func == PGBENCH_LEAST)
2636  extremum = Min(extremum, ival);
2637  else
2638  extremum = Max(extremum, ival);
2639  }
2640  setIntValue(retval, extremum);
2641  }
2642  return true;
2643  }
2644 
2645  /* random functions */
2646  case PGBENCH_RANDOM:
2650  {
2651  int64 imin,
2652  imax,
2653  delta;
2654 
2655  Assert(nargs >= 2);
2656 
2657  if (!coerceToInt(&vargs[0], &imin) ||
2658  !coerceToInt(&vargs[1], &imax))
2659  return false;
2660 
2661  /* check random range */
2662  if (unlikely(imin > imax))
2663  {
2664  pg_log_error("empty range given to random");
2665  return false;
2666  }
2667  else if (unlikely(pg_sub_s64_overflow(imax, imin, &delta) ||
2668  pg_add_s64_overflow(delta, 1, &delta)))
2669  {
2670  /* prevent int overflows in random functions */
2671  pg_log_error("random range is too large");
2672  return false;
2673  }
2674 
2675  if (func == PGBENCH_RANDOM)
2676  {
2677  Assert(nargs == 2);
2678  setIntValue(retval, getrand(&st->cs_func_rs, imin, imax));
2679  }
2680  else /* gaussian & exponential */
2681  {
2682  double param;
2683 
2684  Assert(nargs == 3);
2685 
2686  if (!coerceToDouble(&vargs[2], &param))
2687  return false;
2688 
2689  if (func == PGBENCH_RANDOM_GAUSSIAN)
2690  {
2691  if (param < MIN_GAUSSIAN_PARAM)
2692  {
2693  pg_log_error("gaussian parameter must be at least %f (not %f)",
2694  MIN_GAUSSIAN_PARAM, param);
2695  return false;
2696  }
2697 
2698  setIntValue(retval,
2700  imin, imax, param));
2701  }
2702  else if (func == PGBENCH_RANDOM_ZIPFIAN)
2703  {
2704  if (param < MIN_ZIPFIAN_PARAM || param > MAX_ZIPFIAN_PARAM)
2705  {
2706  pg_log_error("zipfian parameter must be in range [%.3f, %.0f] (not %f)",
2708  return false;
2709  }
2710 
2711  setIntValue(retval,
2712  getZipfianRand(&st->cs_func_rs, imin, imax, param));
2713  }
2714  else /* exponential */
2715  {
2716  if (param <= 0.0)
2717  {
2718  pg_log_error("exponential parameter must be greater than zero (not %f)",
2719  param);
2720  return false;
2721  }
2722 
2723  setIntValue(retval,
2725  imin, imax, param));
2726  }
2727  }
2728 
2729  return true;
2730  }
2731 
2732  case PGBENCH_POW:
2733  {
2734  PgBenchValue *lval = &vargs[0];
2735  PgBenchValue *rval = &vargs[1];
2736  double ld,
2737  rd;
2738 
2739  Assert(nargs == 2);
2740 
2741  if (!coerceToDouble(lval, &ld) ||
2742  !coerceToDouble(rval, &rd))
2743  return false;
2744 
2745  setDoubleValue(retval, pow(ld, rd));
2746 
2747  return true;
2748  }
2749 
2750  case PGBENCH_IS:
2751  {
2752  Assert(nargs == 2);
2753 
2754  /*
2755  * note: this simple implementation is more permissive than
2756  * SQL
2757  */
2758  setBoolValue(retval,
2759  vargs[0].type == vargs[1].type &&
2760  vargs[0].u.bval == vargs[1].u.bval);
2761  return true;
2762  }
2763 
2764  /* hashing */
2765  case PGBENCH_HASH_FNV1A:
2766  case PGBENCH_HASH_MURMUR2:
2767  {
2768  int64 val,
2769  seed;
2770 
2771  Assert(nargs == 2);
2772 
2773  if (!coerceToInt(&vargs[0], &val) ||
2774  !coerceToInt(&vargs[1], &seed))
2775  return false;
2776 
2777  if (func == PGBENCH_HASH_MURMUR2)
2778  setIntValue(retval, getHashMurmur2(val, seed));
2779  else if (func == PGBENCH_HASH_FNV1A)
2780  setIntValue(retval, getHashFnv1a(val, seed));
2781  else
2782  /* cannot get here */
2783  Assert(0);
2784 
2785  return true;
2786  }
2787 
2788  case PGBENCH_PERMUTE:
2789  {
2790  int64 val,
2791  size,
2792  seed;
2793 
2794  Assert(nargs == 3);
2795 
2796  if (!coerceToInt(&vargs[0], &val) ||
2797  !coerceToInt(&vargs[1], &size) ||
2798  !coerceToInt(&vargs[2], &seed))
2799  return false;
2800 
2801  if (size <= 0)
2802  {
2803  pg_log_error("permute size parameter must be greater than zero");
2804  return false;
2805  }
2806 
2807  setIntValue(retval, permute(val, size, seed));
2808  return true;
2809  }
2810 
2811  default:
2812  /* cannot get here */
2813  Assert(0);
2814  /* dead code to avoid a compiler warning */
2815  return false;
2816  }
#define Min(x, y)
Definition: c.h:1004
#define Max(x, y)
Definition: c.h:998
#define PG_INT64_MIN
Definition: c.h:591
#define unlikely(x)
Definition: c.h:311
static bool pg_mul_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:219
static bool pg_sub_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:188
static bool pg_add_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:161
static int64 getZipfianRand(pg_prng_state *state, int64 min, int64 max, double s)
Definition: pgbench.c:1230
static void setIntValue(PgBenchValue *pv, int64 ival)
Definition: pgbench.c:2109
static bool coerceToInt(PgBenchValue *pval, int64 *ival)
Definition: pgbench.c:2044
static int64 getExponentialRand(pg_prng_state *state, int64 min, int64 max, double parameter)
Definition: pgbench.c:1112
static void setDoubleValue(PgBenchValue *pv, double dval)
Definition: pgbench.c:2117
#define MIN_ZIPFIAN_PARAM
Definition: pgbench.c:170
static int64 permute(const int64 val, const int64 isize, const int64 seed)
Definition: pgbench.c:1302
#define MAX_FARGS
Definition: pgbench.c:2241
static int64 getHashMurmur2(int64 val, uint64 seed)
Definition: pgbench.c:1269
static int64 getGaussianRand(pg_prng_state *state, int64 min, int64 max, double parameter)
Definition: pgbench.c:1136
#define MIN_GAUSSIAN_PARAM
Definition: pgbench.c:168
#define M_PI
Definition: pgbench.c:73
static int64 getHashFnv1a(int64 val, uint64 seed)
Definition: pgbench.c:1244
static bool coerceToDouble(PgBenchValue *pval, double *dval)
Definition: pgbench.c:2072
#define MAX_ZIPFIAN_PARAM
Definition: pgbench.c:171
@ PGBENCH_DIV
Definition: pgbench.h:70
@ PGBENCH_DOUBLE
Definition: pgbench.h:77
@ PGBENCH_LT
Definition: pgbench.h:98
@ PGBENCH_LN
Definition: pgbench.h:80
@ PGBENCH_RANDOM_EXPONENTIAL
Definition: pgbench.h:84
@ PGBENCH_RSHIFT
Definition: pgbench.h:94
@ PGBENCH_DEBUG
Definition: pgbench.h:72
@ PGBENCH_MOD
Definition: pgbench.h:71
@ PGBENCH_GREATEST
Definition: pgbench.h:75
@ PGBENCH_BITXOR
Definition: pgbench.h:92
@ PGBENCH_RANDOM_ZIPFIAN
Definition: pgbench.h:85
@ PGBENCH_INT
Definition: pgbench.h:76
@ PGBENCH_NE
Definition: pgbench.h:96
@ PGBENCH_LE
Definition: pgbench.h:97
@ PGBENCH_EXP
Definition: pgbench.h:81
@ PGBENCH_PI
Definition: pgbench.h:78
@ PGBENCH_ADD
Definition: pgbench.h:67
@ PGBENCH_EQ
Definition: pgbench.h:95
@ PGBENCH_LSHIFT
Definition: pgbench.h:93
@ PGBENCH_RANDOM
Definition: pgbench.h:82
@ PGBENCH_POW
Definition: pgbench.h:86
@ PGBENCH_IS
Definition: pgbench.h:99
@ PGBENCH_SUB
Definition: pgbench.h:68
@ PGBENCH_HASH_MURMUR2
Definition: pgbench.h:102
@ PGBENCH_ABS
Definition: pgbench.h:73
@ PGBENCH_BITOR
Definition: pgbench.h:91
@ PGBENCH_SQRT
Definition: pgbench.h:79
@ PGBENCH_LEAST
Definition: pgbench.h:74
@ PGBENCH_PERMUTE
Definition: pgbench.h:103
@ PGBENCH_HASH_FNV1A
Definition: pgbench.h:101
@ PGBENCH_NOT
Definition: pgbench.h:89
@ PGBENCH_BITAND
Definition: pgbench.h:90
@ PGBENCH_RANDOM_GAUSSIAN
Definition: pgbench.h:83
@ PGBENCH_MUL
Definition: pgbench.h:69
static pg_noinline void Size size
Definition: slab.c:607
const char * type

References generate_unaccent_rules::args, Assert, b, PgBenchValue::bval, coerceToBool(), coerceToDouble(), coerceToInt(), CState::command, CState::cs_func_rs, PgBenchValue::dval, evaluateExpr(), PgBenchExprLink::expr, fprintf, getExponentialRand(), getGaussianRand(), getHashFnv1a(), getHashMurmur2(), getrand(), getZipfianRand(), i, INT64_FORMAT, PgBenchValue::ival, M_PI, Max, MAX_FARGS, MAX_ZIPFIAN_PARAM, Min, MIN_GAUSSIAN_PARAM, MIN_ZIPFIAN_PARAM, PgBenchExprLink::next, permute(), pg_add_s64_overflow(), PG_INT64_MIN, pg_log_error, pg_mul_s64_overflow(), pg_sub_s64_overflow(), PGBENCH_ABS, PGBENCH_ADD, PGBENCH_BITAND, PGBENCH_BITOR, PGBENCH_BITXOR, PGBENCH_DEBUG, PGBENCH_DIV, PGBENCH_DOUBLE, PGBENCH_EQ, PGBENCH_EXP, PGBENCH_GREATEST, PGBENCH_HASH_FNV1A, PGBENCH_HASH_MURMUR2, PGBENCH_INT, PGBENCH_IS, PGBENCH_LE, PGBENCH_LEAST, PGBENCH_LN, PGBENCH_LSHIFT, PGBENCH_LT, PGBENCH_MOD, PGBENCH_MUL, PGBENCH_NE, PGBENCH_NOT, PGBENCH_PERMUTE, PGBENCH_PI, PGBENCH_POW, PGBENCH_RANDOM, PGBENCH_RANDOM_EXPONENTIAL, PGBENCH_RANDOM_GAUSSIAN, PGBENCH_RANDOM_ZIPFIAN, PGBENCH_RSHIFT, PGBENCH_SQRT, PGBENCH_SUB, PGBT_BOOLEAN, PGBT_DOUBLE, PGBT_INT, PGBT_NULL, res, setBoolValue(), setDoubleValue(), setIntValue(), setNullValue(), size, type, PgBenchValue::type, PgBenchValue::u, unlikely, CState::use_file, and val.

Referenced by evalFunc().

◆ evaluateExpr()

static bool evaluateExpr ( CState st,
PgBenchExpr expr,
PgBenchValue retval 
)
static

Definition at line 2836 of file pgbench.c.

2838 {
2839  switch (expr->etype)
2840  {
2841  case ENODE_CONSTANT:
2842  {
2843  *retval = expr->u.constant;
2844  return true;
2845  }
2846 
2847  case ENODE_VARIABLE:
2848  {
2849  Variable *var;
2850 
2851  if ((var = lookupVariable(&st->variables, expr->u.variable.varname)) == NULL)
2852  {
2853  pg_log_error("undefined variable \"%s\"", expr->u.variable.varname);
2854  return false;
2855  }
2856 
2857  if (!makeVariableValue(var))
2858  return false;
2859 
2860  *retval = var->value;
2861  return true;
2862  }
2863 
2864  case ENODE_FUNCTION:
2865  return evalFunc(st,
2866  expr->u.function.function,
2867  expr->u.function.args,
2868  retval);
2869 
2870  default:
2871  /* internal error which should never occur */
2872  pg_fatal("unexpected enode type in evaluation: %d", expr->etype);
2873  }
static Variable * lookupVariable(Variables *variables, char *name)
Definition: pgbench.c:1603
static bool evalFunc(CState *st, PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
Definition: pgbench.c:2820
static bool makeVariableValue(Variable *var)
Definition: pgbench.c:1663
@ ENODE_VARIABLE
Definition: pgbench.h:60
@ ENODE_CONSTANT
Definition: pgbench.h:59
@ ENODE_FUNCTION
Definition: pgbench.h:61
Variables variables
Definition: pgbench.c:613
PgBenchValue constant
Definition: pgbench.h:115
PgBenchFunction function
Definition: pgbench.h:122
PgBenchExprType etype
Definition: pgbench.h:112
union PgBenchExpr::@37 u
struct PgBenchExpr::@37::@38 variable
PgBenchValue value
Definition: pgbench.c:325

References PgBenchExpr::constant, ENODE_CONSTANT, ENODE_FUNCTION, ENODE_VARIABLE, PgBenchExpr::etype, evalFunc(), PgBenchExpr::function, lookupVariable(), makeVariableValue(), pg_fatal, pg_log_error, PgBenchExpr::u, Variable::value, PgBenchExpr::variable, and CState::variables.

Referenced by evalLazyFunc(), evalStandardFunc(), and executeMetaCommand().

◆ evaluateSleep()

static bool evaluateSleep ( Variables variables,
int  argc,
char **  argv,
int *  usecs 
)
static

Definition at line 3382 of file pgbench.c.

3384 {
3385  char *var;
3386  int usec;
3387 
3388  if (*argv[1] == ':')
3389  {
3390  if ((var = getVariable(variables, argv[1] + 1)) == NULL)
3391  {
3392  pg_log_error("%s: undefined variable \"%s\"", argv[0], argv[1] + 1);
3393  return false;
3394  }
3395 
3396  usec = atoi(var);
3397 
3398  /* Raise an error if the value of a variable is not a number */
3399  if (usec == 0 && !isdigit((unsigned char) *var))
3400  {
3401  pg_log_error("%s: invalid sleep time \"%s\" for variable \"%s\"",
3402  argv[0], var, argv[1] + 1);
3403  return false;
3404  }
3405  }
3406  else
3407  usec = atoi(argv[1]);
3408 
3409  if (argc > 2)
3410  {
3411  if (pg_strcasecmp(argv[2], "ms") == 0)
3412  usec *= 1000;
3413  else if (pg_strcasecmp(argv[2], "s") == 0)
3414  usec *= 1000000;
3415  }
3416  else
3417  usec *= 1000000;
3418 
3419  *usecs = usec;
3420  return true;
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36

References getVariable(), pg_log_error, and pg_strcasecmp().

Referenced by executeMetaCommand().

◆ executeMetaCommand()

static ConnectionStateEnum executeMetaCommand ( CState st,
pg_time_usec_t now 
)
static

Definition at line 4284 of file pgbench.c.

4286 {
4287  Command *command = sql_script[st->use_file].commands[st->command];
4288  int argc;
4289  char **argv;
4290 
4291  Assert(command != NULL && command->type == META_COMMAND);
4292 
4293  argc = command->argc;
4294  argv = command->argv;
4295 
4297  {
4299 
4300  initPQExpBuffer(&buf);
4301 
4302  printfPQExpBuffer(&buf, "client %d executing \\%s", st->id, argv[0]);
4303  for (int i = 1; i < argc; i++)
4304  appendPQExpBuffer(&buf, " %s", argv[i]);
4305 
4306  pg_log_debug("%s", buf.data);
4307 
4308  termPQExpBuffer(&buf);
4309  }
4310 
4311  if (command->meta == META_SLEEP)
4312  {
4313  int usec;
4314 
4315  /*
4316  * A \sleep doesn't execute anything, we just get the delay from the
4317  * argument, and enter the CSTATE_SLEEP state. (The per-command
4318  * latency will be recorded in CSTATE_SLEEP state, not here, after the
4319  * delay has elapsed.)
4320  */
4321  if (!evaluateSleep(&st->variables, argc, argv, &usec))
4322  {
4323  commandFailed(st, "sleep", "execution of meta-command failed");
4324  return CSTATE_ABORTED;
4325  }
4326 
4328  st->sleep_until = (*now) + usec;
4329  return CSTATE_SLEEP;
4330  }
4331  else if (command->meta == META_SET)
4332  {
4333  PgBenchExpr *expr = command->expr;
4334  PgBenchValue result;
4335 
4336  if (!evaluateExpr(st, expr, &result))
4337  {
4338  commandFailed(st, argv[0], "evaluation of meta-command failed");
4339  return CSTATE_ABORTED;
4340  }
4341 
4342  if (!putVariableValue(&st->variables, argv[0], argv[1], &result))
4343  {
4344  commandFailed(st, "set", "assignment of meta-command failed");
4345  return CSTATE_ABORTED;
4346  }
4347  }
4348  else if (command->meta == META_IF)
4349  {
4350  /* backslash commands with an expression to evaluate */
4351  PgBenchExpr *expr = command->expr;
4352  PgBenchValue result;
4353  bool cond;
4354 
4355  if (!evaluateExpr(st, expr, &result))
4356  {
4357  commandFailed(st, argv[0], "evaluation of meta-command failed");
4358  return CSTATE_ABORTED;
4359  }
4360 
4361  cond = valueTruth(&result);
4363  }
4364  else if (command->meta == META_ELIF)
4365  {
4366  /* backslash commands with an expression to evaluate */
4367  PgBenchExpr *expr = command->expr;
4368  PgBenchValue result;
4369  bool cond;
4370 
4372  {
4373  /* elif after executed block, skip eval and wait for endif. */
4375  return CSTATE_END_COMMAND;
4376  }
4377 
4378  if (!evaluateExpr(st, expr, &result))
4379  {
4380  commandFailed(st, argv[0], "evaluation of meta-command failed");
4381  return CSTATE_ABORTED;
4382  }
4383 
4384  cond = valueTruth(&result);
4387  }
4388  else if (command->meta == META_ELSE)
4389  {
4390  switch (conditional_stack_peek(st->cstack))
4391  {
4392  case IFSTATE_TRUE:
4394  break;
4395  case IFSTATE_FALSE: /* inconsistent if active */
4396  case IFSTATE_IGNORED: /* inconsistent if active */
4397  case IFSTATE_NONE: /* else without if */
4398  case IFSTATE_ELSE_TRUE: /* else after else */
4399  case IFSTATE_ELSE_FALSE: /* else after else */
4400  default:
4401  /* dead code if conditional check is ok */
4402  Assert(false);
4403  }
4404  }
4405  else if (command->meta == META_ENDIF)
4406  {
4409  }
4410  else if (command->meta == META_SETSHELL)
4411  {
4412  if (!runShellCommand(&st->variables, argv[1], argv + 2, argc - 2))
4413  {
4414  commandFailed(st, "setshell", "execution of meta-command failed");
4415  return CSTATE_ABORTED;
4416  }
4417  }
4418  else if (command->meta == META_SHELL)
4419  {
4420  if (!runShellCommand(&st->variables, NULL, argv + 1, argc - 1))
4421  {
4422  commandFailed(st, "shell", "execution of meta-command failed");
4423  return CSTATE_ABORTED;
4424  }
4425  }
4426  else if (command->meta == META_STARTPIPELINE)
4427  {
4428  /*
4429  * In pipeline mode, we use a workflow based on libpq pipeline
4430  * functions.
4431  */
4432  if (querymode == QUERY_SIMPLE)
4433  {
4434  commandFailed(st, "startpipeline", "cannot use pipeline mode with the simple query protocol");
4435  return CSTATE_ABORTED;
4436  }
4437 
4438  /*
4439  * If we're in prepared-query mode, we need to prepare all the
4440  * commands that are inside the pipeline before we actually start the
4441  * pipeline itself. This solves the problem that running BEGIN
4442  * ISOLATION LEVEL SERIALIZABLE in a pipeline would fail due to a
4443  * snapshot having been acquired by the prepare within the pipeline.
4444  */
4445  if (querymode == QUERY_PREPARED)
4447 
4448  if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
4449  {
4450  commandFailed(st, "startpipeline", "already in pipeline mode");
4451  return CSTATE_ABORTED;
4452  }
4453  if (PQenterPipelineMode(st->con) == 0)
4454  {
4455  commandFailed(st, "startpipeline", "failed to enter pipeline mode");
4456  return CSTATE_ABORTED;
4457  }
4458  }
4459  else if (command->meta == META_SYNCPIPELINE)
4460  {
4461  if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
4462  {
4463  commandFailed(st, "syncpipeline", "not in pipeline mode");
4464  return CSTATE_ABORTED;
4465  }
4466  if (PQsendPipelineSync(st->con) == 0)
4467  {
4468  commandFailed(st, "syncpipeline", "failed to send a pipeline sync");
4469  return CSTATE_ABORTED;
4470  }
4471  st->num_syncs++;
4472  }
4473  else if (command->meta == META_ENDPIPELINE)
4474  {
4475  if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
4476  {
4477  commandFailed(st, "endpipeline", "not in pipeline mode");
4478  return CSTATE_ABORTED;
4479  }
4480  if (!PQpipelineSync(st->con))
4481  {
4482  commandFailed(st, "endpipeline", "failed to send a pipeline sync");
4483  return CSTATE_ABORTED;
4484  }
4485  st->num_syncs++;
4486  /* Now wait for the PGRES_PIPELINE_SYNC and exit pipeline mode there */
4487  /* collect pending results before getting out of pipeline mode */
4488  return CSTATE_WAIT_RESULT;
4489  }
4490 
4491  /*
4492  * executing the expression or shell command might have taken a
4493  * non-negligible amount of time, so reset 'now'
4494  */
4495  *now = 0;
4496 
4497  return CSTATE_END_COMMAND;
int PQenterPipelineMode(PGconn *conn)
Definition: fe-exec.c:3042
int PQsendPipelineSync(PGconn *conn)
Definition: fe-exec.c:3282
enum pg_log_level __pg_log_level
Definition: logging.c:21
@ PG_LOG_DEBUG
Definition: logging.h:26
static QueryMode querymode
Definition: pgbench.c:712
static void prepareCommandsInPipeline(CState *st)
Definition: pgbench.c:3121
static bool runShellCommand(Variables *variables, char *variable, char **argv, int argc)
Definition: pgbench.c:2921
static bool evaluateSleep(Variables *variables, int argc, char **argv, int *usecs)
Definition: pgbench.c:3382
static bool putVariableValue(Variables *variables, const char *context, char *name, const PgBenchValue *value)
Definition: pgbench.c:1851
pg_time_usec_t sleep_until
Definition: pgbench.c:617
int num_syncs
Definition: pgbench.c:610

References __pg_log_level, appendPQExpBuffer(), Command::argc, Command::argv, Assert, buf, CState::command, commandFailed(), ParsedScript::commands, CState::con, conditional_stack_empty(), conditional_stack_peek(), conditional_stack_poke(), conditional_stack_pop(), conditional_stack_push(), CState::cstack, CSTATE_ABORTED, CSTATE_END_COMMAND, CSTATE_SLEEP, CSTATE_WAIT_RESULT, evaluateExpr(), evaluateSleep(), Command::expr, i, CState::id, IFSTATE_ELSE_FALSE, IFSTATE_ELSE_TRUE, IFSTATE_FALSE, IFSTATE_IGNORED, IFSTATE_NONE, IFSTATE_TRUE, initPQExpBuffer(), Command::meta, META_COMMAND, META_ELIF, META_ELSE, META_ENDIF, META_ENDPIPELINE, META_IF, META_SET, META_SETSHELL, META_SHELL, META_SLEEP, META_STARTPIPELINE, META_SYNCPIPELINE, now(), CState::num_syncs, PG_LOG_DEBUG, pg_log_debug, pg_time_now_lazy(), PQ_PIPELINE_OFF, PQ_PIPELINE_ON, PQenterPipelineMode(), PQpipelineStatus(), PQpipelineSync(), PQsendPipelineSync(), prepareCommandsInPipeline(), printfPQExpBuffer(), putVariableValue(), QUERY_PREPARED, QUERY_SIMPLE, querymode, runShellCommand(), CState::sleep_until, sql_script, termPQExpBuffer(), Command::type, unlikely, CState::use_file, valueTruth(), and CState::variables.

Referenced by advanceConnectionState().

◆ executeStatement()

static void executeStatement ( PGconn con,
const char *  sql 
)
static

Definition at line 1499 of file pgbench.c.

1501 {
1502  PGresult *res;
1503 
1504  res = PQexec(con, sql);
1506  {
1507  pg_log_error("query failed: %s", PQerrorMessage(con));
1508  pg_log_error_detail("Query was: %s", sql);
1509  exit(1);
1510  }
1511  PQclear(res);
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262

References exit(), pg_log_error, pg_log_error_detail, PGRES_COMMAND_OK, PQclear(), PQerrorMessage(), PQexec(), PQresultStatus(), and res.

Referenced by createPartitions(), initCreateFKeys(), initCreatePKeys(), initCreateTables(), initDropTables(), initGenerateDataClientSide(), initGenerateDataServerSide(), initTruncateTables(), and initVacuum().

◆ findBuiltin()

static const BuiltinScript* findBuiltin ( const char *  name)
static

Definition at line 6119 of file pgbench.c.

6121 {
6122  int i,
6123  found = 0,
6124  len = strlen(name);
6125  const BuiltinScript *result = NULL;
6126 
6127  for (i = 0; i < lengthof(builtin_script); i++)
6128  {
6129  if (strncmp(builtin_script[i].name, name, len) == 0)
6130  {
6131  result = &builtin_script[i];
6132  found++;
6133  }
6134  }
6135 
6136  /* ok, unambiguous result */
6137  if (found == 1)
6138  return result;
6139 
6140  /* error cases */
6141  if (found == 0)
6142  pg_log_error("no builtin script found for name \"%s\"", name);
6143  else /* found > 1 */
6144  pg_log_error("ambiguous builtin name: %d builtin scripts found for prefix \"%s\"", found, name);
6145 
6147  exit(1);
#define lengthof(array)
Definition: c.h:788
const void size_t len
static void listAvailableScripts(void)
Definition: pgbench.c:6107
static const BuiltinScript builtin_script[]
Definition: pgbench.c:779

References builtin_script, exit(), i, len, lengthof, listAvailableScripts(), name, and pg_log_error.

Referenced by main().

◆ finishCon()

static void finishCon ( CState st)
static

Definition at line 7694 of file pgbench.c.

7696 {
7697  if (st->con != NULL)
7698  {
7699  PQfinish(st->con);
7700  st->con = NULL;
7701  }

References CState::con, and PQfinish().

Referenced by advanceConnectionState(), and disconnect_all().

◆ free_command()

static void free_command ( Command command)
static

Definition at line 5577 of file pgbench.c.

5579 {
5580  termPQExpBuffer(&command->lines);
5581  pg_free(command->first_line);
5582  for (int i = 0; i < command->argc; i++)
5583  pg_free(command->argv[i]);
5584  pg_free(command->varprefix);
5585 
5586  /*
5587  * It should also free expr recursively, but this is currently not needed
5588  * as only gset commands (which do not have an expression) are freed.
5589  */
5590  pg_free(command);

References Command::argc, Command::argv, Command::first_line, i, Command::lines, pg_free(), termPQExpBuffer(), and Command::varprefix.

Referenced by ParseScript().

◆ free_socket_set()

static void free_socket_set ( socket_set sa)
static

Definition at line 7865 of file pgbench.c.

7867 {
7868  pg_free(sa);

References pg_free().

Referenced by threadRun().

◆ getExponentialRand()

static int64 getExponentialRand ( pg_prng_state state,
int64  min,
int64  max,
double  parameter 
)
static

Definition at line 1112 of file pgbench.c.

1115 {
1116  double cut,
1117  uniform,
1118  rand;
1119 
1120  /* abort if wrong parameter, but must really be checked beforehand */
1121  Assert(parameter > 0.0);
1122  cut = exp(-parameter);
1123  /* pg_prng_double value in [0, 1), uniform in (0, 1] */
1124  uniform = 1.0 - pg_prng_double(state);
1125 
1126  /*
1127  * inner expression in (cut, 1] (if parameter > 0), rand in [0, 1)
1128  */
1129  Assert((1.0 - cut) != 0.0);
1130  rand = -log(cut + (1.0 - cut) * uniform) / parameter;
1131  /* return int64 random number within between min and max */
1132  return min + (int64) ((max - min + 1) * rand);

References Assert, and pg_prng_double().

Referenced by evalStandardFunc().

◆ getFailures()

static int64 getFailures ( const StatsData stats)
static

Definition at line 4503 of file pgbench.c.

4505 {
4506  return (stats->serialization_failures +
4507  stats->deadlock_failures);

References StatsData::deadlock_failures, and StatsData::serialization_failures.

Referenced by printProgressReport(), and printResults().

◆ getGaussianRand()

static int64 getGaussianRand ( pg_prng_state state,
int64  min,
int64  max,
double  parameter 
)
static

Definition at line 1136 of file pgbench.c.

1139 {
1140  double stdev;
1141  double rand;
1142 
1143  /* abort if parameter is too low, but must really be checked beforehand */
1144  Assert(parameter >= MIN_GAUSSIAN_PARAM);
1145 
1146  /*
1147  * Get normally-distributed random number in the range -parameter <= stdev
1148  * < parameter.
1149  *
1150  * This loop is executed until the number is in the expected range.
1151  *
1152  * As the minimum parameter is 2.0, the probability of looping is low:
1153  * sqrt(-2 ln(r)) <= 2 => r >= e^{-2} ~ 0.135, then when taking the
1154  * average sinus multiplier as 2/pi, we have a 8.6% looping probability in
1155  * the worst case. For a parameter value of 5.0, the looping probability
1156  * is about e^{-5} * 2 / pi ~ 0.43%.
1157  */
1158  do
1159  {
1160  stdev = pg_prng_double_normal(state);
1161  }
1162  while (stdev < -parameter || stdev >= parameter);
1163 
1164  /* stdev is in [-parameter, parameter), normalization to [0,1) */
1165  rand = (stdev + parameter) / (parameter * 2.0);
1166 
1167  /* return int64 random number within between min and max */
1168  return min + (int64) ((max - min + 1) * rand);
double pg_prng_double_normal(pg_prng_state *state)
Definition: pg_prng.c:290

References Assert, MIN_GAUSSIAN_PARAM, and pg_prng_double_normal().

Referenced by evalStandardFunc().

◆ getHashFnv1a()

static int64 getHashFnv1a ( int64  val,
uint64  seed 
)
static

Definition at line 1244 of file pgbench.c.

1246 {
1247  int64 result;
1248  int i;
1249 
1250  result = FNV_OFFSET_BASIS ^ seed;
1251  for (i = 0; i < 8; ++i)
1252  {
1253  int32 octet = val & 0xff;
1254 
1255  val = val >> 8;
1256  result = result ^ octet;
1257  result = result * FNV_PRIME;
1258  }
1259 
1260  return result;
signed int int32
Definition: c.h:494
#define FNV_OFFSET_BASIS
Definition: pgbench.c:84
#define FNV_PRIME
Definition: pgbench.c:83

References FNV_OFFSET_BASIS, FNV_PRIME, i, and val.

Referenced by evalStandardFunc().

◆ getHashMurmur2()

static int64 getHashMurmur2 ( int64  val,
uint64  seed 
)
static

Definition at line 1269 of file pgbench.c.

1271 {
1272  uint64 result = seed ^ MM2_MUL_TIMES_8; /* sizeof(int64) */
1273  uint64 k = (uint64) val;
1274 
1275  k *= MM2_MUL;
1276  k ^= k >> MM2_ROT;
1277  k *= MM2_MUL;
1278 
1279  result ^= k;
1280  result *= MM2_MUL;
1281 
1282  result ^= result >> MM2_ROT;
1283  result *= MM2_MUL;
1284  result ^= result >> MM2_ROT;
1285 
1286  return (int64) result;
#define MM2_MUL_TIMES_8
Definition: pgbench.c:86
#define MM2_ROT
Definition: pgbench.c:87
#define MM2_MUL
Definition: pgbench.c:85

References MM2_MUL, MM2_MUL_TIMES_8, MM2_ROT, and val.

Referenced by evalStandardFunc().

◆ getMetaCommand()

static MetaCommand getMetaCommand ( const char *  cmd)
static

Definition at line 2879 of file pgbench.c.

2881 {
2882  MetaCommand mc;
2883 
2884  if (cmd == NULL)
2885  mc = META_NONE;
2886  else if (pg_strcasecmp(cmd, "set") == 0)
2887  mc = META_SET;
2888  else if (pg_strcasecmp(cmd, "setshell") == 0)
2889  mc = META_SETSHELL;
2890  else if (pg_strcasecmp(cmd, "shell") == 0)
2891  mc = META_SHELL;
2892  else if (pg_strcasecmp(cmd, "sleep") == 0)
2893  mc = META_SLEEP;
2894  else if (pg_strcasecmp(cmd, "if") == 0)
2895  mc = META_IF;
2896  else if (pg_strcasecmp(cmd, "elif") == 0)
2897  mc = META_ELIF;
2898  else if (pg_strcasecmp(cmd, "else") == 0)
2899  mc = META_ELSE;
2900  else if (pg_strcasecmp(cmd, "endif") == 0)
2901  mc = META_ENDIF;
2902  else if (pg_strcasecmp(cmd, "gset") == 0)
2903  mc = META_GSET;
2904  else if (pg_strcasecmp(cmd, "aset") == 0)
2905  mc = META_ASET;
2906  else if (pg_strcasecmp(cmd, "startpipeline") == 0)
2907  mc = META_STARTPIPELINE;
2908  else if (pg_strcasecmp(cmd, "syncpipeline") == 0)
2909  mc = META_SYNCPIPELINE;
2910  else if (pg_strcasecmp(cmd, "endpipeline") == 0)
2911  mc = META_ENDPIPELINE;
2912  else
2913  mc = META_NONE;
2914  return mc;
MetaCommand
Definition: pgbench.c:687

References META_ASET, META_ELIF, META_ELSE, META_ENDIF, META_ENDPIPELINE, META_GSET, META_IF, META_NONE, META_SET, META_SETSHELL, META_SHELL, META_SLEEP, META_STARTPIPELINE, META_SYNCPIPELINE, and pg_strcasecmp().

Referenced by process_backslash_command().

◆ getPoissonRand()

static int64 getPoissonRand ( pg_prng_state state,
double  center 
)
static

Definition at line 1178 of file pgbench.c.

1180 {
1181  /*
1182  * Use inverse transform sampling to generate a value > 0, such that the
1183  * expected (i.e. average) value is the given argument.
1184  */
1185  double uniform;
1186 
1187  /* pg_prng_double value in [0, 1), uniform in (0, 1] */
1188  uniform = 1.0 - pg_prng_double(state);
1189 
1190  return (int64) (-log(uniform) * center + 0.5);

References pg_prng_double().

Referenced by advanceConnectionState().

◆ getQueryParams()

static void getQueryParams ( Variables variables,
const Command command,
const char **  params 
)
static

Definition at line 1971 of file pgbench.c.

1974 {
1975  int i;
1976 
1977  for (i = 0; i < command->argc - 1; i++)
1978  params[i] = getVariable(variables, command->argv[i + 1]);

References Command::argc, Command::argv, getVariable(), and i.

Referenced by sendCommand().

◆ getrand()

static int64 getrand ( pg_prng_state state,
int64  min,
int64  max 
)
static

Definition at line 1101 of file pgbench.c.

1103 {
1104  return min + (int64) pg_prng_uint64_range(state, 0, max - min);
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition: pg_prng.c:144

References pg_prng_uint64_range().

Referenced by chooseScript(), and evalStandardFunc().

◆ getResultString()

static const char* getResultString ( bool  skipped,
EStatus  estatus 
)
static

Definition at line 4514 of file pgbench.c.

4516 {
4517  if (skipped)
4518  return "skipped";
4519  else if (failures_detailed)
4520  {
4521  switch (estatus)
4522  {
4524  return "serialization";
4526  return "deadlock";
4527  default:
4528  /* internal error which should never occur */
4529  pg_fatal("unexpected error status: %d", estatus);
4530  }
4531  }
4532  else
4533  return "failed";

References ESTATUS_DEADLOCK_ERROR, ESTATUS_SERIALIZATION_ERROR, failures_detailed, and pg_fatal.

Referenced by doLog().

◆ getSQLErrorStatus()

static EStatus getSQLErrorStatus ( const char *  sqlState)
static

Definition at line 3207 of file pgbench.c.

3209 {
3210  if (sqlState != NULL)
3211  {
3212  if (strcmp(sqlState, ERRCODE_T_R_SERIALIZATION_FAILURE) == 0)
3214  else if (strcmp(sqlState, ERRCODE_T_R_DEADLOCK_DETECTED) == 0)
3215  return ESTATUS_DEADLOCK_ERROR;
3216  }
3217 
3218  return ESTATUS_OTHER_SQL_ERROR;
#define ERRCODE_T_R_DEADLOCK_DETECTED
Definition: pgbench.c:77
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76

References ERRCODE_T_R_DEADLOCK_DETECTED, ERRCODE_T_R_SERIALIZATION_FAILURE, ESTATUS_DEADLOCK_ERROR, ESTATUS_OTHER_SQL_ERROR, and ESTATUS_SERIALIZATION_ERROR.

Referenced by readCommandResponse().

◆ GetTableInfo()

static void GetTableInfo ( PGconn con,
bool  scale_given 
)
static

Definition at line 5307 of file pgbench.c.

5309 {
5310  PGresult *res;
5311 
5312  /*
5313  * get the scaling factor that should be same as count(*) from
5314  * pgbench_branches if this is not a custom query
5315  */
5316  res = PQexec(con, "select count(*) from pgbench_branches");
5318  {
5319  char *sqlState = PQresultErrorField(res, PG_DIAG_SQLSTATE);
5320 
5321  pg_log_error("could not count number of branches: %s", PQerrorMessage(con));
5322 
5323  if (sqlState && strcmp(sqlState, ERRCODE_UNDEFINED_TABLE) == 0)
5324  pg_log_error_hint("Perhaps you need to do initialization (\"pgbench -i\") in database \"%s\".",
5325  PQdb(con));
5326 
5327  exit(1);
5328  }
5329  scale = atoi(PQgetvalue(res, 0, 0));
5330  if (scale < 0)
5331  pg_fatal("invalid count(*) from pgbench_branches: \"%s\"",
5332  PQgetvalue(res, 0, 0));
5333  PQclear(res);
5334 
5335  /* warn if we override user-given -s switch */
5336  if (scale_given)
5337  pg_log_warning("scale option ignored, using count from pgbench_branches table (%d)",
5338  scale);
5339 
5340  /*
5341  * Get the partition information for the first "pgbench_accounts" table
5342  * found in search_path.
5343  *
5344  * The result is empty if no "pgbench_accounts" is found.
5345  *
5346  * Otherwise, it always returns one row even if the table is not
5347  * partitioned (in which case the partition strategy is NULL).
5348  *
5349  * The number of partitions can be 0 even for partitioned tables, if no
5350  * partition is attached.
5351  *
5352  * We assume no partitioning on any failure, so as to avoid failing on an
5353  * old version without "pg_partitioned_table".
5354  */
5355  res = PQexec(con,
5356  "select o.n, p.partstrat, pg_catalog.count(i.inhparent) "
5357  "from pg_catalog.pg_class as c "
5358  "join pg_catalog.pg_namespace as n on (n.oid = c.relnamespace) "
5359  "cross join lateral (select pg_catalog.array_position(pg_catalog.current_schemas(true), n.nspname)) as o(n) "
5360  "left join pg_catalog.pg_partitioned_table as p on (p.partrelid = c.oid) "
5361  "left join pg_catalog.pg_inherits as i on (c.oid = i.inhparent) "
5362  "where c.relname = 'pgbench_accounts' and o.n is not null "
5363  "group by 1, 2 "
5364  "order by 1 asc "
5365  "limit 1");
5366 
5368  {
5369  /* probably an older version, coldly assume no partitioning */
5371  partitions = 0;
5372  }
5373  else if (PQntuples(res) == 0)
5374  {
5375  /*
5376  * This case is unlikely as pgbench already found "pgbench_branches"
5377  * above to compute the scale.
5378  */
5379  pg_log_error("no pgbench_accounts table found in \"search_path\"");
5380  pg_log_error_hint("Perhaps you need to do initialization (\"pgbench -i\") in database \"%s\".", PQdb(con));
5381  exit(1);
5382  }
5383  else /* PQntuples(res) == 1 */
5384  {
5385  /* normal case, extract partition information */
5386  if (PQgetisnull(res, 0, 1))
5388  else
5389  {
5390  char *ps = PQgetvalue(res, 0, 1);
5391 
5392  /* column must be there */
5393  Assert(ps != NULL);
5394 
5395  if (strcmp(ps, "r") == 0)
5397  else if (strcmp(ps, "h") == 0)
5399  else
5400  {
5401  /* possibly a newer version with new partition method */
5402  pg_fatal("unexpected partition method: \"%s\"", ps);
5403  }
5404  }
5405 
5406  partitions = atoi(PQgetvalue(res, 0, 2));
5407  }
5408 
5409  PQclear(res);
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:7000
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3901
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:102
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
#define pg_log_warning(...)
Definition: pgfnames.c:24
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56

References Assert, ERRCODE_UNDEFINED_TABLE, exit(), PART_HASH, PART_NONE, PART_RANGE, partition_method, partitions, PG_DIAG_SQLSTATE, pg_fatal, pg_log_error, pg_log_error_hint, pg_log_warning, PGRES_TUPLES_OK, PQclear(), PQdb(), PQerrorMessage(), PQexec(), PQgetisnull(), PQgetvalue(), PQntuples(), PQresultErrorField(), PQresultStatus(), ps, res, and scale.

Referenced by main().

◆ getTransactionStatus()

static TStatus getTransactionStatus ( PGconn con)
static

Definition at line 3513 of file pgbench.c.

3515 {
3516  PGTransactionStatusType tx_status;
3517 
3518  tx_status = PQtransactionStatus(con);
3519  switch (tx_status)
3520  {
3521  case PQTRANS_IDLE:
3522  return TSTATUS_IDLE;
3523  case PQTRANS_INTRANS:
3524  case PQTRANS_INERROR:
3525  return TSTATUS_IN_BLOCK;
3526  case PQTRANS_UNKNOWN:
3527  /* PQTRANS_UNKNOWN is expected given a broken connection */
3528  if (PQstatus(con) == CONNECTION_BAD)
3529  return TSTATUS_CONN_ERROR;
3530  /* fall through */
3531  case PQTRANS_ACTIVE:
3532  default:
3533 
3534  /*
3535  * We cannot find out whether we are in a transaction block or
3536  * not. Internal error which should never occur.
3537  */
3538  pg_log_error("unexpected transaction status %d", tx_status);
3539  return TSTATUS_OTHER_ERROR;
3540  }
3541 
3542  /* not reached */
3543  Assert(false);
3544  return TSTATUS_OTHER_ERROR;
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7109
PGTransactionStatusType
Definition: libpq-fe.h:120
@ PQTRANS_INTRANS
Definition: libpq-fe.h:123
@ PQTRANS_IDLE
Definition: libpq-fe.h:121
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:122
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:125
@ PQTRANS_INERROR
Definition: libpq-fe.h:124

References Assert, CONNECTION_BAD, pg_log_error, PQstatus(), PQTRANS_ACTIVE, PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, PQtransactionStatus(), TSTATUS_CONN_ERROR, TSTATUS_IDLE, TSTATUS_IN_BLOCK, and TSTATUS_OTHER_ERROR.

Referenced by advanceConnectionState().

◆ getVariable()

static char* getVariable ( Variables variables,
char *  name 
)
static

Definition at line 1630 of file pgbench.c.

1632 {
1633  Variable *var;
1634  char stringform[64];
1635 
1636  var = lookupVariable(variables, name);
1637  if (var == NULL)
1638  return NULL; /* not found */
1639 
1640  if (var->svalue)
1641  return var->svalue; /* we have it in string form */
1642 
1643  /* We need to produce a string equivalent of the value */
1644  Assert(var->value.type != PGBT_NO_VALUE);
1645  if (var->value.type == PGBT_NULL)
1646  snprintf(stringform, sizeof(stringform), "NULL");
1647  else if (var->value.type == PGBT_BOOLEAN)
1648  snprintf(stringform, sizeof(stringform),
1649  "%s", var->value.u.bval ? "true" : "false");
1650  else if (var->value.type == PGBT_INT)
1651  snprintf(stringform, sizeof(stringform),
1652  INT64_FORMAT, var->value.u.ival);
1653  else if (var->value.type == PGBT_DOUBLE)
1654  snprintf(stringform, sizeof(stringform),
1655  "%.*g", DBL_DIG, var->value.u.dval);
1656  else /* internal error, unexpected type */
1657  Assert(0);
1658  var->svalue = pg_strdup(stringform);
1659  return var->svalue;
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
@ PGBT_NO_VALUE
Definition: pgbench.h:36
#define snprintf
Definition: port.h:238
char * svalue
Definition: pgbench.c:324

References Assert, PgBenchValue::bval, PgBenchValue::dval, INT64_FORMAT, PgBenchValue::ival, lookupVariable(), name, pg_strdup(), PGBT_BOOLEAN, PGBT_DOUBLE, PGBT_INT, PGBT_NO_VALUE, PGBT_NULL, snprintf, Variable::svalue, PgBenchValue::type, PgBenchValue::u, and Variable::value.

Referenced by assignVariables(), evaluateSleep(), getQueryParams(), and runShellCommand().

◆ getZipfianRand()

static int64 getZipfianRand ( pg_prng_state state,
int64  min,
int64  max,
double  s 
)
static

Definition at line 1230 of file pgbench.c.

1232 {
1233  int64 n = max - min + 1;
1234 
1235  /* abort if parameter is invalid */
1237 
1238  return min - 1 + computeIterativeZipfian(state, n, s);
static int64 computeIterativeZipfian(pg_prng_state *state, int64 n, double s)
Definition: pgbench.c:1200

References Assert, computeIterativeZipfian(), MAX_ZIPFIAN_PARAM, and MIN_ZIPFIAN_PARAM.

Referenced by evalStandardFunc().

◆ handle_sig_alarm()

static void handle_sig_alarm ( SIGNAL_ARGS  )
static

Definition at line 7710 of file pgbench.c.

7712 {
7713  timer_exceeded = true;

References timer_exceeded.

Referenced by setalarm().

◆ initAccount()

static void initAccount ( PQExpBufferData sql,
int64  curr 
)
static

Definition at line 4930 of file pgbench.c.

4932 {
4933  /* "filler" column defaults to blank padded empty string */
4934  printfPQExpBuffer(sql,
4935  INT64_FORMAT "\t" INT64_FORMAT "\t0\t\n",
4936  curr + 1, curr / naccounts + 1);

References INT64_FORMAT, naccounts, and printfPQExpBuffer().

Referenced by initGenerateDataClientSide().

◆ initBranch()

static void initBranch ( PQExpBufferData sql,
int64  curr 
)
static

Definition at line 4912 of file pgbench.c.

4914 {
4915  /* "filler" column uses NULL */
4916  printfPQExpBuffer(sql,
4917  INT64_FORMAT "\t0\t\\N\n",
4918  curr + 1);

References INT64_FORMAT, and printfPQExpBuffer().

Referenced by initGenerateDataClientSide().

◆ initCreateFKeys()

static void initCreateFKeys ( PGconn con)
static

Definition at line 5176 of file pgbench.c.

5178 {
5179  static const char *const DDLKEYs[] = {
5180  "alter table pgbench_tellers add constraint pgbench_tellers_bid_fkey foreign key (bid) references pgbench_branches",
5181  "alter table pgbench_accounts add constraint pgbench_accounts_bid_fkey foreign key (bid) references pgbench_branches",
5182  "alter table pgbench_history add constraint pgbench_history_bid_fkey foreign key (bid) references pgbench_branches",
5183  "alter table pgbench_history add constraint pgbench_history_tid_fkey foreign key (tid) references pgbench_tellers",
5184  "alter table pgbench_history add constraint pgbench_history_aid_fkey foreign key (aid) references pgbench_accounts"
5185  };
5186  int i;
5187 
5188  fprintf(stderr, "creating foreign keys...\n");
5189  for (i = 0; i < lengthof(DDLKEYs); i++)
5190  {
5191  executeStatement(con, DDLKEYs[i]);
5192  }

References executeStatement(), fprintf, i, and lengthof.

Referenced by runInitSteps().

◆ initCreatePKeys()

static void initCreatePKeys ( PGconn con)
static

Definition at line 5138 of file pgbench.c.

5140 {
5141  static const char *const DDLINDEXes[] = {
5142  "alter table pgbench_branches add primary key (bid)",
5143  "alter table pgbench_tellers add primary key (tid)",
5144  "alter table pgbench_accounts add primary key (aid)"
5145  };
5146  int i;
5147  PQExpBufferData query;
5148 
5149  fprintf(stderr, "creating primary keys...\n");
5150  initPQExpBuffer(&query);
5151 
5152  for (i = 0; i < lengthof(DDLINDEXes); i++)
5153  {
5154  resetPQExpBuffer(&query);
5155  appendPQExpBufferStr(&query, DDLINDEXes[i]);
5156 
5157  if (index_tablespace != NULL)
5158  {
5159  char *escape_tablespace;
5160 
5161  escape_tablespace = PQescapeIdentifier(con, index_tablespace,
5162  strlen(index_tablespace));
5163  appendPQExpBuffer(&query, " using index tablespace %s", escape_tablespace);
5164  PQfreemem(escape_tablespace);
5165  }
5166 
5167  executeStatement(con, query.data);
5168  }
5169 
5170  termPQExpBuffer(&query);
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4310
char * index_tablespace
Definition: pgbench.c:217
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146

References appendPQExpBuffer(), appendPQExpBufferStr(), PQExpBufferData::data, executeStatement(), fprintf, i, index_tablespace, initPQExpBuffer(), lengthof, PQescapeIdentifier(), PQfreemem(), resetPQExpBuffer(), and termPQExpBuffer().

Referenced by runInitSteps().

◆ initCreateTables()

static void initCreateTables ( PGconn con)
static

Definition at line 4807 of file pgbench.c.

4809 {
4810  /*
4811  * Note: TPC-B requires at least 100 bytes per row, and the "filler"
4812  * fields in these table declarations were intended to comply with that.
4813  * The pgbench_accounts table complies with that because the "filler"
4814  * column is set to blank-padded empty string. But for all other tables
4815  * the columns default to NULL and so don't actually take any space. We
4816  * could fix that by giving them non-null default values. However, that
4817  * would completely break comparability of pgbench results with prior
4818  * versions. Since pgbench has never pretended to be fully TPC-B compliant
4819  * anyway, we stick with the historical behavior.
4820  */
4821  struct ddlinfo
4822  {
4823  const char *table; /* table name */
4824  const char *smcols; /* column decls if accountIDs are 32 bits */
4825  const char *bigcols; /* column decls if accountIDs are 64 bits */
4826  int declare_fillfactor;
4827  };
4828  static const struct ddlinfo DDLs[] = {
4829  {
4830  "pgbench_history",
4831  "tid int,bid int,aid int,delta int,mtime timestamp,filler char(22)",
4832  "tid int,bid int,aid bigint,delta int,mtime timestamp,filler char(22)",
4833  0
4834  },
4835  {
4836  "pgbench_tellers",
4837  "tid int not null,bid int,tbalance int,filler char(84)",
4838  "tid int not null,bid int,tbalance int,filler char(84)",
4839  1
4840  },
4841  {
4842  "pgbench_accounts",
4843  "aid int not null,bid int,abalance int,filler char(84)",
4844  "aid bigint not null,bid int,abalance int,filler char(84)",
4845  1
4846  },
4847  {
4848  "pgbench_branches",
4849  "bid int not null,bbalance int,filler char(88)",
4850  "bid int not null,bbalance int,filler char(88)",
4851  1
4852  }
4853  };
4854  int i;
4855  PQExpBufferData query;
4856 
4857  fprintf(stderr, "creating tables...\n");
4858 
4859  initPQExpBuffer(&query);
4860 
4861  for (i = 0; i < lengthof(DDLs); i++)
4862  {
4863  const struct ddlinfo *ddl = &DDLs[i];
4864 
4865  /* Construct new create table statement. */
4866  printfPQExpBuffer(&query, "create%s table %s(%s)",
4867  unlogged_tables ? " unlogged" : "",
4868  ddl->table,
4869  (scale >= SCALE_32BIT_THRESHOLD) ? ddl->bigcols : ddl->smcols);
4870 
4871  /* Partition pgbench_accounts table */
4872  if (partition_method != PART_NONE && strcmp(ddl->table, "pgbench_accounts") == 0)
4873  appendPQExpBuffer(&query,
4874  " partition by %s (aid)", PARTITION_METHOD[partition_method]);
4875  else if (ddl->declare_fillfactor)
4876  {
4877  /* fillfactor is only expected on actual tables */
4878  appendPQExpBuffer(&query, " with (fillfactor=%d)", fillfactor);
4879  }
4880 
4881  if (tablespace != NULL)
4882  {
4883  char *escape_tablespace;
4884 
4885  escape_tablespace = PQescapeIdentifier(con, tablespace, strlen(tablespace));
4886  appendPQExpBuffer(&query, " tablespace %s", escape_tablespace);
4887  PQfreemem(escape_tablespace);
4888  }
4889 
4890  executeStatement(con, query.data);
4891  }
4892 
4893  termPQExpBuffer(&query);
4894 
4895  if (partition_method != PART_NONE)
4896  createPartitions(con);
static void createPartitions(PGconn *con)
Definition: pgbench.c:4738
static const char *const PARTITION_METHOD[]
Definition: pgbench.c:234
#define SCALE_32BIT_THRESHOLD
Definition: pgbench.c:254
char * tablespace
Definition: pgbench.c:216

References appendPQExpBuffer(), createPartitions(), PQExpBufferData::data, executeStatement(), fillfactor, fprintf, i, initPQExpBuffer(), lengthof, PART_NONE, partition_method, PARTITION_METHOD, PQescapeIdentifier(), PQfreemem(), printfPQExpBuffer(), scale, SCALE_32BIT_THRESHOLD, tablespace, termPQExpBuffer(), and unlogged_tables.

Referenced by runInitSteps().

◆ initDropTables()

static void initDropTables ( PGconn con)
static

Definition at line 4716 of file pgbench.c.

4718 {
4719  fprintf(stderr, "dropping old tables...\n");
4720 
4721  /*
4722  * We drop all the tables in one command, so that whether there are
4723  * foreign key dependencies or not doesn't matter.
4724  */
4725  executeStatement(con, "drop table if exists "
4726  "pgbench_accounts, "
4727  "pgbench_branches, "
4728  "pgbench_history, "
4729  "pgbench_tellers");

References executeStatement(), and fprintf.

Referenced by runInitSteps().

◆ initGenerateDataClientSide()

static void initGenerateDataClientSide ( PGconn con)
static

Definition at line 5048 of file pgbench.c.

5050 {
5051  fprintf(stderr, "generating data (client-side)...\n");
5052 
5053  /*
5054  * we do all of this in one transaction to enable the backend's
5055  * data-loading optimizations
5056  */
5057  executeStatement(con, "begin");
5058 
5059  /* truncate away any old data */
5060  initTruncateTables(con);
5061 
5062  /*
5063  * fill branches, tellers, accounts in that order in case foreign keys
5064  * already exist
5065  */
5066  initPopulateTable(con, "pgbench_branches", nbranches, initBranch);
5067  initPopulateTable(con, "pgbench_tellers", ntellers, initTeller);
5068  initPopulateTable(con, "pgbench_accounts", naccounts, initAccount);
5069 
5070  executeStatement(con, "commit");
static void initTeller(PQExpBufferData *sql, int64 curr)
Definition: pgbench.c:4921
static void initBranch(PQExpBufferData *sql, int64 curr)
Definition: pgbench.c:4912
#define ntellers
Definition: pgbench.c:244
static void initTruncateTables(PGconn *con)
Definition: pgbench.c:4902
static void initAccount(PQExpBufferData *sql, int64 curr)
Definition: pgbench.c:4930
#define nbranches
Definition: pgbench.c:243
static void initPopulateTable(PGconn *con, const char *table, int64 base, initRowMethod init_row)
Definition: pgbench.c:4939

References executeStatement(), fprintf, initAccount(), initBranch(), initPopulateTable(), initTeller(), initTruncateTables(), naccounts, nbranches, and ntellers.

Referenced by runInitSteps().

◆ initGenerateDataServerSide()

static void initGenerateDataServerSide ( PGconn con)
static

Definition at line 5080 of file pgbench.c.

5082 {
5083  PQExpBufferData sql;
5084