2 * $PostgreSQL: pgsql/contrib/pgbench/pgbench.c,v 1.76 2008/03/10 01:23:04 tgl Exp $
4 * pgbench: a simple benchmark program for PostgreSQL
5 * written by Tatsuo Ishii
7 * Copyright (c) 2000-2007 Tatsuo Ishii
9 * Permission to use, copy, modify, and distribute this software and
10 * its documentation for any purpose and without fee is hereby
11 * granted, provided that the above copyright notice appear in all
12 * copies and that both that copyright notice and this permission
13 * notice appear in supporting documentation, and that the name of the
14 * author not be used in advertising or publicity pertaining to
15 * distribution of the software without specific, written prior
16 * permission. The author makes no representations about the
17 * suitability of this software for any purpose. It is provided "as
18 * is" without express or implied warranty.
20 #include "postgres_fe.h"
28 #define FD_SETSIZE 1024
39 #ifdef HAVE_SYS_SELECT_H
40 #include <sys/select.h>
43 #ifdef HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h> /* for getrlimit */
51 /********************************************************************
52 * some configurable parameters */
54 /* max number of clients allowed */
56 #define MAXCLIENTS (FD_SETSIZE - 10)
58 #define MAXCLIENTS 1024
61 int nclients = 1; /* default number of simulated clients */
62 int nxacts = 10; /* default number of transactions per clients */
65 * scaling factor. for example, scale = 10 will make 1000000 tuples of
71 * fillfactor. for example, fillfactor = 90 will use only 90 percent
72 * space during inserts and leave 10 percent free.
77 * end of configurable parameters
78 *********************************************************************/
82 #define naccounts 100000
86 bool use_log; /* log transaction latencies to a file */
88 int remains; /* number of remaining clients */
90 int is_connect; /* establish connection for each transaction */
94 char *pgoptions = NULL;
99 /* variable definitions */
102 char *name; /* variable name */
103 char *value; /* its value */
107 * structures used in custom query mode
112 PGconn *con; /* connection handle to DB */
113 int id; /* client No. */
114 int state; /* state No. */
115 int cnt; /* xacts count */
116 int ecnt; /* error count */
117 int listen; /* 0 indicates that an async query has been
119 int sleeping; /* 1 indicates that the client is napping */
120 struct timeval until; /* napping until */
121 Variable *variables; /* array of variable definitions */
123 struct timeval txn_begin; /* used for measuring latencies */
124 int use_file; /* index in sql_files for this client */
128 * queries read from files
130 #define SQL_COMMAND 1
131 #define META_COMMAND 2
136 int type; /* command type (SQL_COMMAND or META_COMMAND) */
137 int argc; /* number of commands */
138 char *argv[MAX_ARGS]; /* command list */
141 #define MAX_FILES 128 /* max number of SQL script files allowed */
143 Command **sql_files[MAX_FILES]; /* SQL script files */
144 int num_files; /* its number */
146 /* default scenario */
147 static char *tpc_b = {
148 "\\set nbranches :scale\n"
149 "\\set ntellers 10 * :scale\n"
150 "\\set naccounts 100000 * :scale\n"
151 "\\setrandom aid 1 :naccounts\n"
152 "\\setrandom bid 1 :nbranches\n"
153 "\\setrandom tid 1 :ntellers\n"
154 "\\setrandom delta -5000 5000\n"
156 "UPDATE accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
157 "SELECT abalance FROM accounts WHERE aid = :aid;\n"
158 "UPDATE tellers SET tbalance = tbalance + :delta WHERE tid = :tid;\n"
159 "UPDATE branches SET bbalance = bbalance + :delta WHERE bid = :bid;\n"
160 "INSERT INTO history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
165 static char *simple_update = {
166 "\\set nbranches :scale\n"
167 "\\set ntellers 10 * :scale\n"
168 "\\set naccounts 100000 * :scale\n"
169 "\\setrandom aid 1 :naccounts\n"
170 "\\setrandom bid 1 :nbranches\n"
171 "\\setrandom tid 1 :ntellers\n"
172 "\\setrandom delta -5000 5000\n"
174 "UPDATE accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
175 "SELECT abalance FROM accounts WHERE aid = :aid;\n"
176 "INSERT INTO history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
181 static char *select_only = {
182 "\\set naccounts 100000 * :scale\n"
183 "\\setrandom aid 1 :naccounts\n"
184 "SELECT abalance FROM accounts WHERE aid = :aid;\n"
190 fprintf(stderr, "usage: pgbench [-h hostname][-p port][-c nclients][-t ntransactions][-s scaling_factor][-D varname=value][-n][-C][-v][-S][-N][-f filename][-l][-U login][-d][dbname]\n");
191 fprintf(stderr, "(initialize mode): pgbench -i [-h hostname][-p port][-s scaling_factor] [-F fillfactor] [-U login][-d][dbname]\n");
194 /* random number generator: uniform distribution from min to max inclusive */
196 getrand(int min, int max)
199 * Odd coding is so that min and max have approximately the same chance of
200 * being selected as do numbers between them.
202 return min + (int) (((max - min + 1) * (double) random()) / (MAX_RANDOM_VALUE + 1.0));
205 /* call PQexec() and exit() on failure */
207 executeStatement(PGconn *con, const char *sql)
211 res = PQexec(con, sql);
212 if (PQresultStatus(res) != PGRES_COMMAND_OK)
214 fprintf(stderr, "%s", PQerrorMessage(con));
220 /* set up a connection to the backend */
225 static char *password = NULL;
229 * Start the connection. Loop until we have a password if requested by
236 conn = PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName,
240 fprintf(stderr, "Connection to database \"%s\" failed\n",
245 if (PQstatus(conn) == CONNECTION_BAD &&
246 PQconnectionNeedsPassword(conn) &&
251 password = simple_prompt("Password: ", 100, false);
256 /* check to see that the backend connection was successfully made */
257 if (PQstatus(conn) == CONNECTION_BAD)
259 fprintf(stderr, "Connection to database \"%s\" failed:\n%s",
260 dbName, PQerrorMessage(conn));
265 executeStatement(conn, "SET search_path = public");
270 /* throw away response from backend */
272 discard_response(CState * state)
278 res = PQgetResult(state->con);
284 /* check to see if the SQL result was good */
286 check(CState * state, PGresult *res, int n)
288 CState *st = &state[n];
290 switch (PQresultStatus(res))
292 case PGRES_COMMAND_OK:
293 case PGRES_TUPLES_OK:
297 fprintf(stderr, "Client %d aborted in state %d: %s",
298 n, st->state, PQerrorMessage(st->con));
299 remains--; /* I've aborted */
308 compareVariables(const void *v1, const void *v2)
310 return strcmp(((const Variable *) v1)->name,
311 ((const Variable *) v2)->name);
315 getVariable(CState * st, char *name)
320 /* On some versions of Solaris, bsearch of zero items dumps core */
321 if (st->nvariables <= 0)
325 var = (Variable *) bsearch((void *) &key,
326 (void *) st->variables,
337 putVariable(CState * st, char *name, char *value)
343 /* On some versions of Solaris, bsearch of zero items dumps core */
344 if (st->nvariables > 0)
345 var = (Variable *) bsearch((void *) &key,
346 (void *) st->variables,
358 newvars = (Variable *) realloc(st->variables,
359 (st->nvariables + 1) * sizeof(Variable));
361 newvars = (Variable *) malloc(sizeof(Variable));
366 st->variables = newvars;
368 var = &newvars[st->nvariables];
373 if ((var->name = strdup(name)) == NULL
374 || (var->value = strdup(value)) == NULL)
383 qsort((void *) st->variables, st->nvariables, sizeof(Variable),
390 if ((val = strdup(value)) == NULL)
401 assignVariables(CState * st, char *sql)
411 while ((p = strchr(&sql[i], ':')) != NULL)
417 } while (isalnum((unsigned char) sql[i]) || sql[i] == '_');
421 name = malloc(i - j);
424 memcpy(name, &sql[j + 1], i - (j + 1));
425 name[i - (j + 1)] = '\0';
426 val = getVariable(st, name);
431 if (strlen(val) > i - j)
433 tmp = realloc(sql, strlen(sql) - (i - j) + strlen(val) + 1);
442 if (strlen(val) != i - j)
443 memmove(&sql[j + strlen(val)], &sql[i], strlen(&sql[i]) + 1);
445 strncpy(&sql[j], val, strlen(val));
447 if (strlen(val) < i - j)
449 tmp = realloc(sql, strlen(sql) + 1);
465 doCustom(CState * state, int n, int debug)
468 CState *st = &state[n];
472 commands = sql_files[st->use_file];
475 { /* are we sleeping? */
479 gettimeofday(&now, NULL);
480 usec = (st->until.tv_sec - now.tv_sec) * 1000000 +
481 st->until.tv_usec - now.tv_usec;
483 st->sleeping = 0; /* Done sleeping, go ahead with next command */
485 return; /* Still sleeping, nothing to do here */
489 { /* are we receiver? */
490 if (commands[st->state]->type == SQL_COMMAND)
493 fprintf(stderr, "client %d receiving\n", n);
494 if (!PQconsumeInput(st->con))
495 { /* there's something wrong */
496 fprintf(stderr, "Client %d aborted in state %d. Probably the backend died while processing.\n", n, st->state);
497 remains--; /* I've aborted */
502 if (PQisBusy(st->con))
503 return; /* don't have the whole result yet */
507 * transaction finished: record the time it took in the log
509 if (use_log && commands[st->state + 1] == NULL)
514 gettimeofday(&now, NULL);
515 diff = (int) (now.tv_sec - st->txn_begin.tv_sec) * 1000000.0 +
516 (int) (now.tv_usec - st->txn_begin.tv_usec);
518 fprintf(LOGFILE, "%d %d %.0f %d %ld %ld\n",
519 st->id, st->cnt, diff, st->use_file,
520 (long) now.tv_sec, (long) now.tv_usec);
523 if (commands[st->state]->type == SQL_COMMAND)
525 res = PQgetResult(st->con);
526 if (check(state, res, n))
532 discard_response(st);
535 if (commands[st->state + 1] == NULL)
543 if (++st->cnt >= nxacts)
545 remains--; /* I've done */
555 /* increment state counter */
557 if (commands[st->state] == NULL)
560 st->use_file = getrand(0, num_files - 1);
561 commands = sql_files[st->use_file];
567 if ((st->con = doConnect()) == NULL)
569 fprintf(stderr, "Client %d aborted in establishing connection.\n",
571 remains--; /* I've aborted */
578 if (use_log && st->state == 0)
579 gettimeofday(&(st->txn_begin), NULL);
581 if (commands[st->state]->type == SQL_COMMAND)
585 if ((sql = strdup(commands[st->state]->argv[0])) == NULL
586 || (sql = assignVariables(st, sql)) == NULL)
588 fprintf(stderr, "out of memory\n");
594 fprintf(stderr, "client %d sending %s\n", n, sql);
595 if (PQsendQuery(st->con, sql) == 0)
598 fprintf(stderr, "PQsendQuery(%s)failed\n", sql);
603 st->listen = 1; /* flags that should be listened */
607 else if (commands[st->state]->type == META_COMMAND)
609 int argc = commands[st->state]->argc,
611 char **argv = commands[st->state]->argv;
615 fprintf(stderr, "client %d executing \\%s", n, argv[0]);
616 for (i = 1; i < argc; i++)
617 fprintf(stderr, " %s", argv[i]);
618 fprintf(stderr, "\n");
621 if (pg_strcasecmp(argv[0], "setrandom") == 0)
630 if ((var = getVariable(st, argv[2] + 1)) == NULL)
632 fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[2]);
644 fprintf(stderr, "%s: invalid minimum number %d\n", argv[0], min);
652 if ((var = getVariable(st, argv[3] + 1)) == NULL)
654 fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[3]);
663 if (max < min || max > MAX_RANDOM_VALUE)
665 fprintf(stderr, "%s: invalid maximum number %d\n", argv[0], max);
671 printf("min: %d max: %d random: %d\n", min, max, getrand(min, max));
673 snprintf(res, sizeof(res), "%d", getrand(min, max));
675 if (putVariable(st, argv[1], res) == false)
677 fprintf(stderr, "%s: out of memory\n", argv[0]);
684 else if (pg_strcasecmp(argv[0], "set") == 0)
693 if ((var = getVariable(st, argv[2] + 1)) == NULL)
695 fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[2]);
702 ope1 = atoi(argv[2]);
705 snprintf(res, sizeof(res), "%d", ope1);
710 if ((var = getVariable(st, argv[4] + 1)) == NULL)
712 fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[4]);
719 ope2 = atoi(argv[4]);
721 if (strcmp(argv[3], "+") == 0)
722 snprintf(res, sizeof(res), "%d", ope1 + ope2);
723 else if (strcmp(argv[3], "-") == 0)
724 snprintf(res, sizeof(res), "%d", ope1 - ope2);
725 else if (strcmp(argv[3], "*") == 0)
726 snprintf(res, sizeof(res), "%d", ope1 * ope2);
727 else if (strcmp(argv[3], "/") == 0)
731 fprintf(stderr, "%s: division by zero\n", argv[0]);
735 snprintf(res, sizeof(res), "%d", ope1 / ope2);
739 fprintf(stderr, "%s: unsupported operator %s\n", argv[0], argv[3]);
745 if (putVariable(st, argv[1], res) == false)
747 fprintf(stderr, "%s: out of memory\n", argv[0]);
754 else if (pg_strcasecmp(argv[0], "sleep") == 0)
762 if ((var = getVariable(st, argv[1] + 1)) == NULL)
764 fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[1]);
771 usec = atoi(argv[1]);
775 if (pg_strcasecmp(argv[2], "ms") == 0)
777 else if (pg_strcasecmp(argv[2], "s") == 0)
783 gettimeofday(&now, NULL);
784 st->until.tv_sec = now.tv_sec + (now.tv_usec + usec) / 1000000;
785 st->until.tv_usec = (now.tv_usec + usec) % 1000000;
795 /* discard connections */
797 disconnect_all(CState * state)
801 for (i = 0; i < nclients; i++)
804 PQfinish(state[i].con);
808 /* create tables and setup data */
814 static char *DDLs[] = {
815 "drop table if exists branches",
816 "create table branches(bid int not null,bbalance int,filler char(88)) with (fillfactor=%d)",
817 "drop table if exists tellers",
818 "create table tellers(tid int not null,bid int,tbalance int,filler char(84)) with (fillfactor=%d)",
819 "drop table if exists accounts",
820 "create table accounts(aid int not null,bid int,abalance int,filler char(84)) with (fillfactor=%d)",
821 "drop table if exists history",
822 "create table history(tid int,bid int,aid int,delta int,mtime timestamp,filler char(22))"};
823 static char *DDLAFTERs[] = {
824 "alter table branches add primary key (bid)",
825 "alter table tellers add primary key (tid)",
826 "alter table accounts add primary key (aid)"};
833 if ((con = doConnect()) == NULL)
836 for (i = 0; i < lengthof(DDLs); i++)
839 * set fillfactor for branches, tellers and accounts tables
841 if ((strstr(DDLs[i], "create table branches") == DDLs[i]) ||
842 (strstr(DDLs[i], "create table tellers") == DDLs[i]) ||
843 (strstr(DDLs[i], "create table accounts") == DDLs[i]))
847 snprintf(ddl_stmt, 128, DDLs[i], fillfactor);
848 executeStatement(con, ddl_stmt);
852 executeStatement(con, DDLs[i]);
855 executeStatement(con, "begin");
857 for (i = 0; i < nbranches * scale; i++)
859 snprintf(sql, 256, "insert into branches(bid,bbalance) values(%d,0)", i + 1);
860 executeStatement(con, sql);
863 for (i = 0; i < ntellers * scale; i++)
865 snprintf(sql, 256, "insert into tellers(tid,bid,tbalance) values (%d,%d,0)"
866 ,i + 1, i / ntellers + 1);
867 executeStatement(con, sql);
870 executeStatement(con, "commit");
873 * fill the accounts table with some data
875 fprintf(stderr, "creating tables...\n");
877 executeStatement(con, "begin");
878 executeStatement(con, "truncate accounts");
880 res = PQexec(con, "copy accounts from stdin");
881 if (PQresultStatus(res) != PGRES_COPY_IN)
883 fprintf(stderr, "%s", PQerrorMessage(con));
888 for (i = 0; i < naccounts * scale; i++)
892 snprintf(sql, 256, "%d\t%d\t%d\t\n", j, i / naccounts + 1, 0);
893 if (PQputline(con, sql))
895 fprintf(stderr, "PQputline failed\n");
900 fprintf(stderr, "%d tuples done.\n", j);
902 if (PQputline(con, "\\.\n"))
904 fprintf(stderr, "very last PQputline failed\n");
909 fprintf(stderr, "PQendcopy failed\n");
912 executeStatement(con, "commit");
917 fprintf(stderr, "set primary key...\n");
918 for (i = 0; i < lengthof(DDLAFTERs); i++)
919 executeStatement(con, DDLAFTERs[i]);
922 fprintf(stderr, "vacuum...");
923 executeStatement(con, "vacuum analyze");
925 fprintf(stderr, "done.\n");
930 process_commands(char *buf)
932 const char delim[] = " \f\n\r\t\v";
934 Command *my_commands;
939 if ((p = strchr(buf, '\n')) != NULL)
943 while (isspace((unsigned char) *p))
946 if (*p == '\0' || strncmp(p, "--", 2) == 0)
951 my_commands = (Command *) malloc(sizeof(Command));
952 if (my_commands == NULL)
957 my_commands->argc = 0;
961 my_commands->type = META_COMMAND;
964 tok = strtok(++p, delim);
968 if ((my_commands->argv[j] = strdup(tok)) == NULL)
974 tok = strtok(NULL, delim);
977 if (pg_strcasecmp(my_commands->argv[0], "setrandom") == 0)
979 if (my_commands->argc < 4)
981 fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
985 for (j = 4; j < my_commands->argc; j++)
986 fprintf(stderr, "%s: extra argument \"%s\" ignored\n",
987 my_commands->argv[0], my_commands->argv[j]);
989 else if (pg_strcasecmp(my_commands->argv[0], "set") == 0)
991 if (my_commands->argc < 3)
993 fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
997 for (j = my_commands->argc < 5 ? 3 : 5; j < my_commands->argc; j++)
998 fprintf(stderr, "%s: extra argument \"%s\" ignored\n",
999 my_commands->argv[0], my_commands->argv[j]);
1001 else if (pg_strcasecmp(my_commands->argv[0], "sleep") == 0)
1003 if (my_commands->argc < 2)
1005 fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
1009 if (my_commands->argc >= 3)
1011 if (pg_strcasecmp(my_commands->argv[2], "us") != 0 &&
1012 pg_strcasecmp(my_commands->argv[2], "ms") != 0 &&
1013 pg_strcasecmp(my_commands->argv[2], "s"))
1015 fprintf(stderr, "%s: unknown time unit '%s' - must be us, ms or s\n",
1016 my_commands->argv[0], my_commands->argv[2]);
1021 for (j = 3; j < my_commands->argc; j++)
1022 fprintf(stderr, "%s: extra argument \"%s\" ignored\n",
1023 my_commands->argv[0], my_commands->argv[j]);
1027 fprintf(stderr, "Invalid command %s\n", my_commands->argv[0]);
1033 my_commands->type = SQL_COMMAND;
1035 if ((my_commands->argv[0] = strdup(p)) == NULL)
1038 my_commands->argc++;
1045 process_file(char *filename)
1047 #define COMMANDS_ALLOC_NUM 128
1049 Command **my_commands;
1055 if (num_files >= MAX_FILES)
1057 fprintf(stderr, "Up to only %d SQL files are allowed\n", MAX_FILES);
1061 alloc_num = COMMANDS_ALLOC_NUM;
1062 my_commands = (Command **) malloc(sizeof(Command *) * alloc_num);
1063 if (my_commands == NULL)
1066 if (strcmp(filename, "-") == 0)
1068 else if ((fd = fopen(filename, "r")) == NULL)
1070 fprintf(stderr, "%s: %s\n", filename, strerror(errno));
1076 while (fgets(buf, sizeof(buf), fd) != NULL)
1082 while (isspace((unsigned char) buf[i]))
1085 if (buf[i] != '\0' && strncmp(&buf[i], "--", 2) != 0)
1087 commands = process_commands(&buf[i]);
1088 if (commands == NULL)
1097 my_commands[lineno] = commands;
1100 if (lineno >= alloc_num)
1102 alloc_num += COMMANDS_ALLOC_NUM;
1103 my_commands = realloc(my_commands, sizeof(Command *) * alloc_num);
1104 if (my_commands == NULL)
1113 my_commands[lineno] = NULL;
1115 sql_files[num_files++] = my_commands;
1121 process_builtin(char *tb)
1123 #define COMMANDS_ALLOC_NUM 128
1125 Command **my_commands;
1133 alloc_num = COMMANDS_ALLOC_NUM;
1134 my_commands = (Command **) malloc(sizeof(Command *) * alloc_num);
1135 if (my_commands == NULL)
1146 while (*tb && *tb != '\n')
1157 commands = process_commands(buf);
1158 if (commands == NULL)
1163 my_commands[lineno] = commands;
1166 if (lineno >= alloc_num)
1168 alloc_num += COMMANDS_ALLOC_NUM;
1169 my_commands = realloc(my_commands, sizeof(Command *) * alloc_num);
1170 if (my_commands == NULL)
1177 my_commands[lineno] = NULL;
1182 /* print out results */
1185 int ttype, CState * state,
1186 struct timeval * tv1, struct timeval * tv2,
1187 struct timeval * tv3)
1192 int normal_xacts = 0;
1195 for (i = 0; i < nclients; i++)
1196 normal_xacts += state[i].cnt;
1198 t1 = (tv3->tv_sec - tv1->tv_sec) * 1000000.0 + (tv3->tv_usec - tv1->tv_usec);
1199 t1 = normal_xacts * 1000000.0 / t1;
1201 t2 = (tv3->tv_sec - tv2->tv_sec) * 1000000.0 + (tv3->tv_usec - tv2->tv_usec);
1202 t2 = normal_xacts * 1000000.0 / t2;
1205 s = "TPC-B (sort of)";
1206 else if (ttype == 2)
1207 s = "Update only accounts";
1208 else if (ttype == 1)
1213 printf("transaction type: %s\n", s);
1214 printf("scaling factor: %d\n", scale);
1215 printf("number of clients: %d\n", nclients);
1216 printf("number of transactions per client: %d\n", nxacts);
1217 printf("number of transactions actually processed: %d/%d\n", normal_xacts, nxacts * nclients);
1218 printf("tps = %f (including connections establishing)\n", t1);
1219 printf("tps = %f (excluding connections establishing)\n", t2);
1224 main(int argc, char **argv)
1227 int is_init_mode = 0; /* initialize mode? */
1228 int is_no_vacuum = 0; /* no vacuum at all before testing? */
1229 int do_vacuum_accounts = 0; /* do vacuum accounts before testing? */
1230 int debug = 0; /* debug flag */
1231 int ttype = 0; /* transaction type. 0: TPC-B, 1: SELECT only,
1232 * 2: skip update of branches and tellers */
1233 char *filename = NULL;
1235 CState *state; /* status of clients */
1237 struct timeval tv1; /* start up time */
1238 struct timeval tv2; /* after establishing all connections to the
1240 struct timeval tv3; /* end time */
1245 int nsocks; /* return from select(2) */
1246 int maxsock; /* max socket number to be waited */
1248 struct timeval timeout;
1251 #ifdef HAVE_GETRLIMIT
1262 /* stderr is buffered on Win32. */
1263 setvbuf(stderr, NULL, _IONBF, 0);
1266 if ((env = getenv("PGHOST")) != NULL && *env != '\0')
1268 if ((env = getenv("PGPORT")) != NULL && *env != '\0')
1270 else if ((env = getenv("PGUSER")) != NULL && *env != '\0')
1273 state = (CState *) malloc(sizeof(CState));
1276 fprintf(stderr, "Couldn't allocate memory for state\n");
1280 memset(state, 0, sizeof(*state));
1282 while ((c = getopt(argc, argv, "ih:nvp:dc:t:s:U:CNSlf:D:F:")) != -1)
1296 do_vacuum_accounts++;
1311 nclients = atoi(optarg);
1312 if (nclients <= 0 || nclients > MAXCLIENTS)
1314 fprintf(stderr, "invalid number of clients: %d\n", nclients);
1317 #ifdef HAVE_GETRLIMIT
1318 #ifdef RLIMIT_NOFILE /* most platforms use RLIMIT_NOFILE */
1319 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1320 #else /* but BSD doesn't ... */
1321 if (getrlimit(RLIMIT_OFILE, &rlim) == -1)
1322 #endif /* RLIMIT_NOFILE */
1324 fprintf(stderr, "getrlimit failed: %s\n", strerror(errno));
1327 if (rlim.rlim_cur <= (nclients + 2))
1329 fprintf(stderr, "You need at least %d open files but you are only allowed to use %ld.\n", nclients + 2, (long) rlim.rlim_cur);
1330 fprintf(stderr, "Use limit/ulimit to increase the limit before using pgbench.\n");
1333 #endif /* HAVE_GETRLIMIT */
1339 scale = atoi(optarg);
1342 fprintf(stderr, "invalid scaling factor: %d\n", scale);
1347 nxacts = atoi(optarg);
1350 fprintf(stderr, "invalid number of transactions: %d\n", nxacts);
1363 if (process_file(filename) == false || *sql_files[num_files - 1] == NULL)
1370 if ((p = strchr(optarg, '=')) == NULL || p == optarg || *(p + 1) == '\0')
1372 fprintf(stderr, "invalid variable definition: %s\n", optarg);
1377 if (putVariable(&state[0], optarg, p) == false)
1379 fprintf(stderr, "Couldn't allocate memory for variable\n");
1385 fillfactor = atoi(optarg);
1386 if ((fillfactor < 10) || (fillfactor > 100))
1388 fprintf(stderr, "invalid fillfactor: %d\n", fillfactor);
1400 dbName = argv[optind];
1403 if ((env = getenv("PGDATABASE")) != NULL && *env != '\0')
1405 else if (login != NULL && *login != '\0')
1419 if (getVariable(&state[0], "scale") == NULL)
1421 snprintf(val, sizeof(val), "%d", scale);
1422 if (putVariable(&state[0], "scale", val) == false)
1424 fprintf(stderr, "Couldn't allocate memory for variable\n");
1431 state = (CState *) realloc(state, sizeof(CState) * nclients);
1434 fprintf(stderr, "Couldn't allocate memory for state\n");
1438 memset(state + 1, 0, sizeof(*state) * (nclients - 1));
1440 snprintf(val, sizeof(val), "%d", scale);
1442 for (i = 1; i < nclients; i++)
1446 for (j = 0; j < state[0].nvariables; j++)
1448 if (putVariable(&state[i], state[0].variables[j].name, state[0].variables[j].value) == false)
1450 fprintf(stderr, "Couldn't allocate memory for variable\n");
1455 if (putVariable(&state[i], "scale", val) == false)
1457 fprintf(stderr, "Couldn't allocate memory for variable\n");
1467 snprintf(logpath, 64, "pgbench_log.%d", (int) getpid());
1468 LOGFILE = fopen(logpath, "w");
1470 if (LOGFILE == NULL)
1472 fprintf(stderr, "Couldn't open logfile \"%s\": %s", logpath, strerror(errno));
1479 printf("pghost: %s pgport: %s nclients: %d nxacts: %d dbName: %s\n",
1480 pghost, pgport, nclients, nxacts, dbName);
1483 /* opening connection... */
1488 if (PQstatus(con) == CONNECTION_BAD)
1490 fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
1491 fprintf(stderr, "%s", PQerrorMessage(con));
1498 * get the scaling factor that should be same as count(*) from
1499 * branches if this is not a custom query
1501 res = PQexec(con, "select count(*) from branches");
1502 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1504 fprintf(stderr, "%s", PQerrorMessage(con));
1507 scale = atoi(PQgetvalue(res, 0, 0));
1510 fprintf(stderr, "count(*) from branches invalid (%d)\n", scale);
1515 snprintf(val, sizeof(val), "%d", scale);
1516 if (putVariable(&state[0], "scale", val) == false)
1518 fprintf(stderr, "Couldn't allocate memory for variable\n");
1524 for (i = 1; i < nclients; i++)
1526 if (putVariable(&state[i], "scale", val) == false)
1528 fprintf(stderr, "Couldn't allocate memory for variable\n");
1537 fprintf(stderr, "starting vacuum...");
1538 executeStatement(con, "vacuum branches");
1539 executeStatement(con, "vacuum tellers");
1540 executeStatement(con, "delete from history");
1541 executeStatement(con, "vacuum history");
1542 fprintf(stderr, "end.\n");
1544 if (do_vacuum_accounts)
1546 fprintf(stderr, "starting vacuum accounts...");
1547 executeStatement(con, "vacuum analyze accounts");
1548 fprintf(stderr, "end.\n");
1553 /* set random seed */
1554 gettimeofday(&tv1, NULL);
1555 srandom((unsigned int) tv1.tv_usec);
1557 /* get start up time */
1558 gettimeofday(&tv1, NULL);
1560 if (is_connect == 0)
1562 /* make connections to the database */
1563 for (i = 0; i < nclients; i++)
1566 if ((state[i].con = doConnect()) == NULL)
1571 /* time after connections set up */
1572 gettimeofday(&tv2, NULL);
1574 /* process bultin SQL scripts */
1578 sql_files[0] = process_builtin(tpc_b);
1583 sql_files[0] = process_builtin(select_only);
1588 sql_files[0] = process_builtin(simple_update);
1596 /* send start up queries in async manner */
1597 for (i = 0; i < nclients; i++)
1599 Command **commands = sql_files[state[i].use_file];
1600 int prev_ecnt = state[i].ecnt;
1602 state[i].use_file = getrand(0, num_files - 1);
1603 doCustom(state, i, debug);
1605 if (state[i].ecnt > prev_ecnt && commands[state[i].state]->type == META_COMMAND)
1607 fprintf(stderr, "Client %d aborted in state %d. Execution meta-command failed.\n", i, state[i].state);
1608 remains--; /* I've aborted */
1609 PQfinish(state[i].con);
1610 state[i].con = NULL;
1618 disconnect_all(state);
1620 gettimeofday(&tv3, NULL);
1621 printResults(ttype, state, &tv1, &tv2, &tv3);
1627 FD_ZERO(&input_mask);
1631 for (i = 0; i < nclients; i++)
1633 Command **commands = sql_files[state[i].use_file];
1635 if (state[i].sleeping)
1638 int sock = PQsocket(state[i].con);
1642 gettimeofday(&now, NULL);
1646 this_usec = (state[i].until.tv_sec - now.tv_sec) * 1000000 +
1647 state[i].until.tv_usec - now.tv_usec;
1649 if (this_usec > 0 && (min_usec == 0 || this_usec < min_usec))
1650 min_usec = this_usec;
1652 FD_SET(sock, &input_mask);
1656 else if (state[i].con && commands[state[i].state]->type != META_COMMAND)
1658 int sock = PQsocket(state[i].con);
1662 disconnect_all(state);
1665 FD_SET(sock, &input_mask);
1675 timeout.tv_sec = min_usec / 1000000;
1676 timeout.tv_usec = min_usec % 1000000;
1678 nsocks = select(maxsock + 1, &input_mask, (fd_set *) NULL,
1679 (fd_set *) NULL, &timeout);
1682 nsocks = select(maxsock + 1, &input_mask, (fd_set *) NULL,
1683 (fd_set *) NULL, (struct timeval *) NULL);
1688 /* must be something wrong */
1689 disconnect_all(state);
1690 fprintf(stderr, "select failed: %s\n", strerror(errno));
1694 else if (nsocks == 0)
1696 fprintf(stderr, "select timeout\n");
1697 for (i = 0; i < nclients; i++)
1699 fprintf(stderr, "client %d:state %d cnt %d ecnt %d listen %d\n",
1700 i, state[i].state, state[i].cnt, state[i].ecnt, state[i].listen);
1707 /* ok, backend returns reply */
1708 for (i = 0; i < nclients; i++)
1710 Command **commands = sql_files[state[i].use_file];
1711 int prev_ecnt = state[i].ecnt;
1713 if (state[i].con && (FD_ISSET(PQsocket(state[i].con), &input_mask)
1714 || commands[state[i].state]->type == META_COMMAND))
1716 doCustom(state, i, debug);
1719 if (state[i].ecnt > prev_ecnt && commands[state[i].state]->type == META_COMMAND)
1721 fprintf(stderr, "Client %d aborted in state %d. Execution meta-command failed.\n", i, state[i].state);
1722 remains--; /* I've aborted */
1723 PQfinish(state[i].con);
1724 state[i].con = NULL;