]> granicus.if.org Git - postgresql/blobdiff - contrib/pgbench/pgbench.c
Add -M (query mode) option per ITAGAKI Takahiro
[postgresql] / contrib / pgbench / pgbench.c
index b5082e0abd62efb9d1a7e68eb7b1d1e149ce5713..41312e88c64bb10ccc652992f797bac4d2395d05 100644 (file)
@@ -1,21 +1,30 @@
 /*
- * $PostgreSQL: pgsql/contrib/pgbench/pgbench.c,v 1.76 2008/03/10 01:23:04 tgl Exp $
+ * pgbench.c
  *
- * pgbench: a simple benchmark program for PostgreSQL
- * written by Tatsuo Ishii
+ * A simple benchmark program for PostgreSQL
+ * Originally written by Tatsuo Ishii and enhanced by many contributors.
  *
- * Copyright (c) 2000-2007     Tatsuo Ishii
+ * $PostgreSQL: pgsql/contrib/pgbench/pgbench.c,v 1.79 2008/03/19 03:33:21 ishii Exp $
+ * Copyright (c) 2000-2008, PostgreSQL Global Development Group
+ * ALL RIGHTS RESERVED;
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without a written agreement
+ * is hereby granted, provided that the above copyright notice and this
+ * paragraph and the following two paragraphs appear in all copies.
+ *
+ * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
+ * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
+ * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose and without fee is hereby
- * granted, provided that the above copyright notice appear in all
- * copies and that both that copyright notice and this permission
- * notice appear in supporting documentation, and that the name of the
- * author not be used in advertising or publicity pertaining to
- * distribution of the software without specific, written prior
- * permission. The author makes no representations about the
- * suitability of this software for any purpose.  It is provided "as
- * is" without express or implied warranty.
  */
 #include "postgres_fe.h"
 
@@ -103,6 +112,8 @@ typedef struct
        char       *value;                      /* its value */
 }      Variable;
 
+#define MAX_FILES              128             /* max number of SQL script files allowed */
+
 /*
  * structures used in custom query mode
  */
@@ -122,6 +133,7 @@ typedef struct
        int                     nvariables;
        struct timeval txn_begin;       /* used for measuring latencies */
        int                     use_file;               /* index in sql_files for this client */
+       bool            prepared[MAX_FILES];
 }      CState;
 
 /*
@@ -131,6 +143,17 @@ typedef struct
 #define META_COMMAND   2
 #define MAX_ARGS               10
 
+typedef enum QueryMode
+{
+       QUERY_SIMPLE,   /* simple query */
+       QUERY_EXTENDED, /* extended query */
+       QUERY_PREPARED, /* extended query with prepared statements */
+       NUM_QUERYMODE
+} QueryMode;
+
+static QueryMode       querymode = QUERY_SIMPLE;
+static const char *QUERYMODE[] = { "simple", "extended", "prepared" };
+
 typedef struct
 {
        int                     type;                   /* command type (SQL_COMMAND or META_COMMAND) */
@@ -138,8 +161,6 @@ typedef struct
        char       *argv[MAX_ARGS]; /* command list */
 }      Command;
 
-#define MAX_FILES              128             /* max number of SQL script files allowed */
-
 Command   **sql_files[MAX_FILES];              /* SQL script files */
 int                    num_files;                      /* its number */
 
@@ -184,10 +205,43 @@ static char *select_only = {
        "SELECT abalance FROM accounts WHERE aid = :aid;\n"
 };
 
+/* Connection overhead time */
+static struct timeval conn_total_time = {0, 0};
+
+/* Calculate total time */
+static void
+addTime(struct timeval *t1, struct timeval *t2, struct timeval *result)
+{
+       int sec = t1->tv_sec + t2->tv_sec;
+       int usec = t1->tv_usec + t2->tv_usec;
+       if (usec >= 1000000)
+       {
+               usec -= 1000000;
+               sec++;
+       }
+       result->tv_sec = sec;
+       result->tv_usec = usec;
+}
+
+/* Calculate time difference */
+static void
+diffTime(struct timeval *t1, struct timeval *t2, struct timeval *result)
+{
+       int sec = t1->tv_sec - t2->tv_sec;
+       int usec = t1->tv_usec - t2->tv_usec;
+       if (usec < 0)
+       {
+               usec += 1000000;
+               sec--;
+       }
+       result->tv_sec = sec;
+       result->tv_usec = usec;
+}
+
 static void
 usage(void)
 {
-       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");
+       fprintf(stderr, "usage: pgbench [-h hostname][-p port][-c nclients][-t ntransactions][-s scaling_factor][-D varname=value][-n][-C][-v][-S][-N][-M querymode][-f filename][-l][-U login][-d][dbname]\n");
        fprintf(stderr, "(initialize mode): pgbench -i [-h hostname][-p port][-s scaling_factor] [-F fillfactor] [-U login][-d][dbname]\n");
 }
 
@@ -397,68 +451,104 @@ putVariable(CState * st, char *name, char *value)
        return true;
 }
 
+static char *
+parseVariable(const char *sql, int *eaten)
+{
+       int             i = 0;
+       char   *name;
+
+       do
+       {
+               i++;
+       } while (isalnum((unsigned char) sql[i]) || sql[i] == '_');
+       if (i == 1)
+               return NULL;
+
+       name = malloc(i);
+       if (name == NULL)
+               return NULL;
+       memcpy(name, &sql[1], i - 1);
+       name[i - 1] = '\0';
+
+       *eaten = i;
+       return name;
+}
+
+static char *
+replaceVariable(char **sql, char *param, int len, char *value)
+{
+       int     valueln = strlen(value);
+
+       if (valueln > len)
+       {
+               char   *tmp;
+               size_t  offset = param - *sql;
+
+               tmp = realloc(*sql, strlen(*sql) - len + valueln + 1);
+               if (tmp == NULL)
+               {
+                       free(*sql);
+                       return NULL;
+               }
+               *sql = tmp;
+               param = *sql + offset;
+       }
+
+       if (valueln != len)
+               memmove(param + valueln, param + len, strlen(param + len) + 1);
+       strncpy(param, value, valueln);
+
+       return param + valueln;
+}
+
 static char *
 assignVariables(CState * st, char *sql)
 {
-       int                     i,
-                               j;
        char       *p,
                           *name,
                           *val;
-       void       *tmp;
 
-       i = 0;
-       while ((p = strchr(&sql[i], ':')) != NULL)
+       p = sql;
+       while ((p = strchr(p, ':')) != NULL)
        {
-               i = j = p - sql;
-               do
+               int             eaten;
+
+               name = parseVariable(p, &eaten);
+               if (name == NULL)
                {
-                       i++;
-               } while (isalnum((unsigned char) sql[i]) || sql[i] == '_');
-               if (i == j + 1)
+                       while (*p == ':') { p++; }
                        continue;
+               }
 
-               name = malloc(i - j);
-               if (name == NULL)
-                       return NULL;
-               memcpy(name, &sql[j + 1], i - (j + 1));
-               name[i - (j + 1)] = '\0';
                val = getVariable(st, name);
                free(name);
                if (val == NULL)
-                       continue;
-
-               if (strlen(val) > i - j)
                {
-                       tmp = realloc(sql, strlen(sql) - (i - j) + strlen(val) + 1);
-                       if (tmp == NULL)
-                       {
-                               free(sql);
-                               return NULL;
-                       }
-                       sql = tmp;
+                       p++;
+                       continue;
                }
 
-               if (strlen(val) != i - j)
-                       memmove(&sql[j + strlen(val)], &sql[i], strlen(&sql[i]) + 1);
+               if ((p = replaceVariable(&sql, p, eaten, val)) == NULL)
+                       return NULL;
+       }
 
-               strncpy(&sql[j], val, strlen(val));
+       return sql;
+}
 
-               if (strlen(val) < i - j)
-               {
-                       tmp = realloc(sql, strlen(sql) + 1);
-                       if (tmp == NULL)
-                       {
-                               free(sql);
-                               return NULL;
-                       }
-                       sql = tmp;
-               }
+static void
+getQueryParams(CState *st, const Command *command, const char **params)
+{
+       int             i;
 
-               i = j + strlen(val);
-       }
+       for (i = 0; i < command->argc - 1; i++)
+               params[i] = getVariable(st, command->argv[i+1]);
+}
 
-       return sql;
+#define MAX_PREPARE_NAME               32
+static void
+preparedStatementName(char *buffer, int file, int state)
+{
+       sprintf(buffer, "P%d_%d", file, state);
 }
 
 static void
@@ -564,6 +654,9 @@ top:
 
        if (st->con == NULL)
        {
+               struct timeval t1, t2, t3;
+
+               gettimeofday(&t1, NULL);
                if ((st->con = doConnect()) == NULL)
                {
                        fprintf(stderr, "Client %d aborted in establishing connection.\n",
@@ -573,6 +666,9 @@ top:
                        st->con = NULL;
                        return;
                }
+               gettimeofday(&t2, NULL);
+               diffTime(&t2, &t1, &t3);
+               addTime(&conn_total_time, &t3, &conn_total_time);
        }
 
        if (use_log && st->state == 0)
@@ -580,29 +676,83 @@ top:
 
        if (commands[st->state]->type == SQL_COMMAND)
        {
-               char       *sql;
+               const Command  *command = commands[st->state];
+               int                             r;
 
-               if ((sql = strdup(commands[st->state]->argv[0])) == NULL
-                       || (sql = assignVariables(st, sql)) == NULL)
+               if (querymode == QUERY_SIMPLE)
                {
-                       fprintf(stderr, "out of memory\n");
-                       st->ecnt++;
-                       return;
+                       char       *sql;
+
+                       if ((sql = strdup(command->argv[0])) == NULL
+                               || (sql = assignVariables(st, sql)) == NULL)
+                       {
+                               fprintf(stderr, "out of memory\n");
+                               st->ecnt++;
+                               return;
+                       }
+
+                       if (debug)
+                               fprintf(stderr, "client %d sending %s\n", n, sql);
+                       r = PQsendQuery(st->con, sql);
+                       free(sql);
                }
+               else if (querymode == QUERY_EXTENDED)
+               {
+                       const char               *sql = command->argv[0];
+                       const char               *params[MAX_ARGS];
 
-               if (debug)
-                       fprintf(stderr, "client %d sending %s\n", n, sql);
-               if (PQsendQuery(st->con, sql) == 0)
+                       getQueryParams(st, command, params);
+
+                       if (debug)
+                               fprintf(stderr, "client %d sending %s\n", n, sql);
+                       r = PQsendQueryParams(st->con, sql, command->argc - 1,
+                               NULL, params, NULL, NULL, 0);
+               }
+               else if (querymode == QUERY_PREPARED)
+               {
+                       char            name[MAX_PREPARE_NAME];
+                       const char *params[MAX_ARGS];
+
+                       if (!st->prepared[st->use_file])
+                       {
+                               int             j;
+
+                               for (j = 0; commands[j] != NULL; j++)
+                               {
+                                       PGresult   *res;
+                                       char            name[MAX_PREPARE_NAME];
+
+                                       if (commands[j]->type != SQL_COMMAND)
+                                               continue;
+                                       preparedStatementName(name, st->use_file, j);
+                                       res = PQprepare(st->con, name,
+                                               commands[j]->argv[0], commands[j]->argc - 1, NULL);
+                                       if (PQresultStatus(res) != PGRES_COMMAND_OK)
+                                               fprintf(stderr, "%s", PQerrorMessage(st->con));
+                                       PQclear(res);
+                               }
+                               st->prepared[st->use_file] = true;
+                       }
+
+                       getQueryParams(st, command, params);
+                       preparedStatementName(name, st->use_file, st->state);
+
+                       if (debug)
+                               fprintf(stderr, "client %d sending %s\n", n, name);
+                       r = PQsendQueryPrepared(st->con, name, command->argc - 1,
+                               params, NULL, NULL, 0);
+               }
+               else /* unknown sql mode */
+                       r = 0;
+
+               if (r == 0)
                {
                        if (debug)
-                               fprintf(stderr, "PQsendQuery(%s)failed\n", sql);
+                               fprintf(stderr, "client %d cannot send %s\n", n, command->argv[0]);
                        st->ecnt++;
                }
                else
-               {
                        st->listen = 1;         /* flags that should be listened */
-               }
-               free(sql);
        }
        else if (commands[st->state]->type == META_COMMAND)
        {
@@ -811,6 +961,16 @@ init(void)
 {
        PGconn     *con;
        PGresult   *res;
+       /*
+        * Note: TPC-B requires at least 100 bytes per row, and the "filler"
+        * fields in these table declarations were intended to comply with that.
+        * But because they default to NULLs, they don't actually take any
+        * space.  We could fix that by giving them non-null default values.
+        * However, that would completely break comparability of pgbench
+        * results with prior versions.  Since pgbench has never pretended
+        * to be fully TPC-B compliant anyway, we stick with the historical
+        * behavior.
+        */
        static char *DDLs[] = {
                "drop table if exists branches",
                "create table branches(bid int not null,bbalance int,filler char(88)) with (fillfactor=%d)",
@@ -926,6 +1086,52 @@ init(void)
        PQfinish(con);
 }
 
+/*
+ * Parse the raw sql and replace :param to $n.
+ */
+static bool
+parseQuery(Command *cmd, const char *raw_sql)
+{
+       char       *sql,
+                          *p;
+
+       sql = strdup(raw_sql);
+       if (sql == NULL)
+               return false;
+       cmd->argc = 1;
+
+       p = sql;
+       while ((p = strchr(p, ':')) != NULL)
+       {
+               char    var[12];
+               char   *name;
+               int             eaten;
+
+               name = parseVariable(p, &eaten);
+               if (name == NULL)
+               {
+                       while (*p == ':') { p++; }
+                       continue;
+               }
+
+               if (cmd->argc >= MAX_ARGS)
+               {
+                       fprintf(stderr, "statement has too many arguments (maximum is %d): %s\n", MAX_ARGS - 1, raw_sql);
+                       return false;
+               }
+
+               sprintf(var, "$%d", cmd->argc);
+               if ((p = replaceVariable(&sql, p, eaten, var)) == NULL)
+                       return false;
+
+               cmd->argv[cmd->argc] = name;
+               cmd->argc++;
+       }
+
+       cmd->argv[0] = sql;
+       return true;
+}
+
 static Command *
 process_commands(char *buf)
 {
@@ -1032,10 +1238,21 @@ process_commands(char *buf)
        {
                my_commands->type = SQL_COMMAND;
 
-               if ((my_commands->argv[0] = strdup(p)) == NULL)
-                       return NULL;
-
-               my_commands->argc++;
+               switch (querymode)
+               {
+                       case QUERY_SIMPLE:
+                               if ((my_commands->argv[0] = strdup(p)) == NULL)
+                                       return NULL;
+                               my_commands->argc++;
+                               break;
+                       case QUERY_EXTENDED:
+                       case QUERY_PREPARED:
+                               if (!parseQuery(my_commands, p))
+                                       return NULL;
+                               break;
+                       default:
+                               return NULL;
+               }
        }
 
        return my_commands;
@@ -1183,8 +1400,7 @@ process_builtin(char *tb)
 static void
 printResults(
                         int ttype, CState * state,
-                        struct timeval * tv1, struct timeval * tv2,
-                        struct timeval * tv3)
+                        struct timeval * start_time, struct timeval * end_time)
 {
        double          t1,
                                t2;
@@ -1195,10 +1411,11 @@ printResults(
        for (i = 0; i < nclients; i++)
                normal_xacts += state[i].cnt;
 
-       t1 = (tv3->tv_sec - tv1->tv_sec) * 1000000.0 + (tv3->tv_usec - tv1->tv_usec);
+       t1 = (end_time->tv_sec - start_time->tv_sec) * 1000000.0 + (end_time->tv_usec - start_time->tv_usec);
        t1 = normal_xacts * 1000000.0 / t1;
 
-       t2 = (tv3->tv_sec - tv2->tv_sec) * 1000000.0 + (tv3->tv_usec - tv2->tv_usec);
+       t2 = (end_time->tv_sec - start_time->tv_sec - conn_total_time.tv_sec) * 1000000.0 +
+               (end_time->tv_usec - start_time->tv_usec - conn_total_time.tv_usec);
        t2 = normal_xacts * 1000000.0 / t2;
 
        if (ttype == 0)
@@ -1212,6 +1429,7 @@ printResults(
 
        printf("transaction type: %s\n", s);
        printf("scaling factor: %d\n", scale);
+       printf("query mode: %s\n", QUERYMODE[querymode]);
        printf("number of clients: %d\n", nclients);
        printf("number of transactions per client: %d\n", nxacts);
        printf("number of transactions actually processed: %d/%d\n", normal_xacts, nxacts * nclients);
@@ -1234,10 +1452,8 @@ main(int argc, char **argv)
 
        CState     *state;                      /* status of clients */
 
-       struct timeval tv1;                     /* start up time */
-       struct timeval tv2;                     /* after establishing all connections to the
-                                                                * backend */
-       struct timeval tv3;                     /* end time */
+       struct timeval start_time;                      /* start up time */
+       struct timeval end_time;                        /* end time */
 
        int                     i;
 
@@ -1279,7 +1495,7 @@ main(int argc, char **argv)
 
        memset(state, 0, sizeof(*state));
 
-       while ((c = getopt(argc, argv, "ih:nvp:dc:t:s:U:CNSlf:D:F:")) != -1)
+       while ((c = getopt(argc, argv, "ih:nvp:dc:t:s:U:CNSlf:D:F:M:")) != -1)
        {
                switch (c)
                {
@@ -1389,6 +1605,21 @@ main(int argc, char **argv)
                                        exit(1);
                                }
                                break;
+                       case 'M':
+                               if (num_files > 0)
+                               {
+                                       fprintf(stderr, "querymode(-M) should be specifiled before transaction scripts(-f)\n");
+                                       exit(1);
+                               }
+                               for (querymode = 0; querymode < NUM_QUERYMODE; querymode++)
+                                       if (strcmp(optarg, QUERYMODE[querymode]) == 0)
+                                               break;
+                               if (querymode >= NUM_QUERYMODE)
+                               {
+                                       fprintf(stderr, "invalid querymode(-M): %s\n", optarg);
+                                       exit(1);
+                               }
+                               break;
                        default:
                                usage();
                                exit(1);
@@ -1551,14 +1782,16 @@ main(int argc, char **argv)
        PQfinish(con);
 
        /* set random seed */
-       gettimeofday(&tv1, NULL);
-       srandom((unsigned int) tv1.tv_usec);
+       gettimeofday(&start_time, NULL);
+       srandom((unsigned int) start_time.tv_usec);
 
        /* get start up time */
-       gettimeofday(&tv1, NULL);
+       gettimeofday(&start_time, NULL);
 
        if (is_connect == 0)
        {
+               struct timeval t, now;
+
                /* make connections to the database */
                for (i = 0; i < nclients; i++)
                {
@@ -1566,11 +1799,12 @@ main(int argc, char **argv)
                        if ((state[i].con = doConnect()) == NULL)
                                exit(1);
                }
+               /* time after connections set up */
+               gettimeofday(&now, NULL);
+               diffTime(&now, &start_time, &t);
+               addTime(&conn_total_time, &t, &conn_total_time);
        }
 
-       /* time after connections set up */
-       gettimeofday(&tv2, NULL);
-
        /* process bultin SQL scripts */
        switch (ttype)
        {
@@ -1617,8 +1851,8 @@ main(int argc, char **argv)
                {                                               /* all done ? */
                        disconnect_all(state);
                        /* get end time */
-                       gettimeofday(&tv3, NULL);
-                       printResults(ttype, state, &tv1, &tv2, &tv3);
+                       gettimeofday(&end_time, NULL);
+                       printResults(ttype, state, &start_time, &end_time);
                        if (LOGFILE)
                                fclose(LOGFILE);
                        exit(0);
@@ -1718,7 +1952,7 @@ main(int argc, char **argv)
 
                        if (state[i].ecnt > prev_ecnt && commands[state[i].state]->type == META_COMMAND)
                        {
-                               fprintf(stderr, "Client %d aborted in state %d. Execution meta-command failed.\n", i, state[i].state);
+                               fprintf(stderr, "Client %d aborted in state %d. Execution of meta-command failed.\n", i, state[i].state);
                                remains--;              /* I've aborted */
                                PQfinish(state[i].con);
                                state[i].con = NULL;