]> granicus.if.org Git - postgresql/blob - src/backend/tcop/postgres.c
Put back encoding-conversion step in processing of incoming queries;
[postgresql] / src / backend / tcop / postgres.c
1 /*-------------------------------------------------------------------------
2  *
3  * postgres.c
4  *        POSTGRES C Backend Interface
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.325 2003/04/27 20:09:44 tgl Exp $
12  *
13  * NOTES
14  *        this is the "main" module of the postgres backend and
15  *        hence the main module of the "traffic cop".
16  *
17  *-------------------------------------------------------------------------
18  */
19
20 #include "postgres.h"
21
22 #include <unistd.h>
23 #include <signal.h>
24 #include <time.h>
25 #include <sys/time.h>
26 #include <fcntl.h>
27 #include <sys/socket.h>
28 #include <errno.h>
29 #if HAVE_SYS_SELECT_H
30 #include <sys/select.h>
31 #endif
32 #ifdef HAVE_GETOPT_H
33 #include <getopt.h>
34 #endif
35
36 #include "access/xlog.h"
37 #include "commands/async.h"
38 #include "commands/trigger.h"
39 #include "libpq/libpq.h"
40 #include "libpq/pqformat.h"
41 #include "libpq/pqsignal.h"
42 #include "miscadmin.h"
43 #include "nodes/print.h"
44 #include "optimizer/cost.h"
45 #include "optimizer/planner.h"
46 #include "parser/analyze.h"
47 #include "parser/parser.h"
48 #include "rewrite/rewriteHandler.h"
49 #include "storage/freespace.h"
50 #include "storage/ipc.h"
51 #include "storage/proc.h"
52 #include "tcop/fastpath.h"
53 #include "tcop/pquery.h"
54 #include "tcop/tcopprot.h"
55 #include "tcop/utility.h"
56 #include "utils/guc.h"
57 #include "utils/memutils.h"
58 #include "utils/ps_status.h"
59 #include "mb/pg_wchar.h"
60
61 #include "pgstat.h"
62
63 extern int      optind;
64 extern char *optarg;
65
66
67 /* ----------------
68  *              global variables
69  * ----------------
70  */
71 const char *debug_query_string; /* for pgmonitor and
72                                                                  * log_min_error_statement */
73
74 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
75 CommandDest whereToSendOutput = Debug;
76
77 static bool dontExecute = false;
78
79 /* note: these declarations had better match tcopprot.h */
80 sigjmp_buf      Warn_restart;
81
82 bool            Warn_restart_ready = false;
83 bool            InError = false;
84
85 extern bool     autocommit;
86
87 static bool EchoQuery = false;  /* default don't echo */
88
89 /*
90  * Flag to mark SIGHUP. Whenever the main loop comes around it
91  * will reread the configuration file. (Better than doing the
92  * reading in the signal handler, ey?)
93  */
94 static volatile bool got_SIGHUP = false;
95
96 /* ----------------
97  *              people who want to use EOF should #define DONTUSENEWLINE in
98  *              tcop/tcopdebug.h
99  * ----------------
100  */
101 #ifndef TCOP_DONTUSENEWLINE
102 int                     UseNewLine = 1;         /* Use newlines query delimiters (the
103                                                                  * default) */
104
105 #else
106 int                     UseNewLine = 0;         /* Use EOF as query delimiters */
107 #endif   /* TCOP_DONTUSENEWLINE */
108
109 /*
110 ** Flags for expensive function optimization -- JMH 3/9/92
111 */
112 int                     XfuncMode = 0;
113
114 /* ----------------------------------------------------------------
115  *              decls for routines only used in this file
116  * ----------------------------------------------------------------
117  */
118 static int      InteractiveBackend(StringInfo inBuf);
119 static int      SocketBackend(StringInfo inBuf);
120 static int      ReadCommand(StringInfo inBuf);
121 static void start_xact_command(void);
122 static void finish_xact_command(bool forceCommit);
123 static void SigHupHandler(SIGNAL_ARGS);
124 static void FloatExceptionHandler(SIGNAL_ARGS);
125 static const char *CreateCommandTag(Node *parsetree);
126
127
128 /* ----------------------------------------------------------------
129  *              routines to obtain user input
130  * ----------------------------------------------------------------
131  */
132
133 /* ----------------
134  *      InteractiveBackend() is called for user interactive connections
135  *
136  *      the string entered by the user is placed in its parameter inBuf,
137  *      and we act like a Q message was received.
138  *
139  *      EOF is returned if end-of-file input is seen; time to shut down.
140  * ----------------
141  */
142
143 static int
144 InteractiveBackend(StringInfo inBuf)
145 {
146         int                     c;                              /* character read from getc() */
147         bool            end = false;    /* end-of-input flag */
148         bool            backslashSeen = false;  /* have we seen a \ ? */
149
150         /*
151          * display a prompt and obtain input from the user
152          */
153         printf("backend> ");
154         fflush(stdout);
155
156         /* Reset inBuf to empty */
157         inBuf->len = 0;
158         inBuf->data[0] = '\0';
159         inBuf->cursor = 0;
160
161         for (;;)
162         {
163                 if (UseNewLine)
164                 {
165                         /*
166                          * if we are using \n as a delimiter, then read characters
167                          * until the \n.
168                          */
169                         while ((c = getc(stdin)) != EOF)
170                         {
171                                 if (c == '\n')
172                                 {
173                                         if (backslashSeen)
174                                         {
175                                                 /* discard backslash from inBuf */
176                                                 inBuf->data[--inBuf->len] = '\0';
177                                                 backslashSeen = false;
178                                                 continue;
179                                         }
180                                         else
181                                         {
182                                                 /* keep the newline character */
183                                                 appendStringInfoChar(inBuf, '\n');
184                                                 break;
185                                         }
186                                 }
187                                 else if (c == '\\')
188                                         backslashSeen = true;
189                                 else
190                                         backslashSeen = false;
191
192                                 appendStringInfoChar(inBuf, (char) c);
193                         }
194
195                         if (c == EOF)
196                                 end = true;
197                 }
198                 else
199                 {
200                         /*
201                          * otherwise read characters until EOF.
202                          */
203                         while ((c = getc(stdin)) != EOF)
204                                 appendStringInfoChar(inBuf, (char) c);
205
206                         if (inBuf->len == 0)
207                                 end = true;
208                 }
209
210                 if (end)
211                         return EOF;
212
213                 /*
214                  * otherwise we have a user query so process it.
215                  */
216                 break;
217         }
218
219         /* Add '\0' to make it look the same as message case. */
220         appendStringInfoChar(inBuf, (char) '\0');
221
222         /*
223          * if the query echo flag was given, print the query..
224          */
225         if (EchoQuery)
226                 printf("statement: %s\n", inBuf->data);
227         fflush(stdout);
228
229         return 'Q';
230 }
231
232 /* ----------------
233  *      SocketBackend()         Is called for frontend-backend connections
234  *
235  *      Returns the message type code, and loads message body data into inBuf.
236  *
237  *      EOF is returned if the connection is lost.
238  * ----------------
239  */
240 static int
241 SocketBackend(StringInfo inBuf)
242 {
243         int                     qtype;
244
245         /*
246          * Get message type code from the frontend.
247          */
248         qtype = pq_getbyte();
249
250         if (qtype == EOF)                       /* frontend disconnected */
251         {
252                 elog(COMMERROR, "unexpected EOF on client connection");
253                 return qtype;
254         }
255
256         /*
257          * Validate message type code before trying to read body; if we have
258          * lost sync, better to say "command unknown" than to run out of memory
259          * because we used garbage as a length word.
260          */
261         switch (qtype)
262         {
263                 case 'Q':                               /* simple query */
264                         if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
265                         {
266                                 /* old style without length word; convert */
267                                 if (pq_getstring(inBuf))
268                                 {
269                                         elog(COMMERROR, "unexpected EOF on client connection");
270                                         return EOF;
271                                 }
272                         }
273                         break;
274
275                 case 'F':                               /* fastpath function call */
276                         break;
277
278                 case 'X':                               /* terminate */
279                         break;
280
281                 case 'd':                               /* copy data */
282                 case 'c':                               /* copy done */
283                 case 'f':                               /* copy fail */
284                         /* Accept but ignore these messages, per protocol spec */
285                         break;
286
287                 default:
288                         /*
289                          * Otherwise we got garbage from the frontend.  We treat this
290                          * as fatal because we have probably lost message boundary sync,
291                          * and there's no good way to recover.
292                          */
293                         elog(FATAL, "Socket command type %c unknown", qtype);
294                         break;
295         }
296
297         /*
298          * In protocol version 3, all frontend messages have a length word
299          * next after the type code; we can read the message contents
300          * independently of the type.
301          */
302         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
303         {
304                 if (pq_getmessage(inBuf, 0))
305                         return EOF;                     /* suitable message already logged */
306         }
307
308         return qtype;
309 }
310
311 /* ----------------
312  *              ReadCommand reads a command from either the frontend or
313  *              standard input, places it in inBuf, and returns a char
314  *              representing whether the string is a 'Q'uery or a 'F'astpath
315  *              call.  EOF is returned if end of file.
316  * ----------------
317  */
318 static int
319 ReadCommand(StringInfo inBuf)
320 {
321         int                     result;
322
323         if (IsUnderPostmaster)
324                 result = SocketBackend(inBuf);
325         else
326                 result = InteractiveBackend(inBuf);
327         return result;
328 }
329
330
331 /*
332  * Parse a query string and pass it through the rewriter.
333  *
334  * A list of Query nodes is returned, since the string might contain
335  * multiple queries and/or the rewriter might expand one query to several.
336  *
337  * NOTE: this routine is no longer used for processing interactive queries,
338  * but it is still needed for parsing of SQL function bodies.
339  */
340 List *
341 pg_parse_and_rewrite(const char *query_string, /* string to execute */
342                                          Oid *typev,    /* parameter types */
343                                          int nargs) /* number of parameters */
344 {
345         List       *raw_parsetree_list;
346         List       *querytree_list;
347         List       *list_item;
348
349         /*
350          * (1) parse the request string into a list of raw parse trees.
351          */
352         raw_parsetree_list = pg_parse_query(query_string, typev, nargs);
353
354         /*
355          * (2) Do parse analysis and rule rewrite.
356          */
357         querytree_list = NIL;
358         foreach(list_item, raw_parsetree_list)
359         {
360                 Node       *parsetree = (Node *) lfirst(list_item);
361
362                 querytree_list = nconc(querytree_list,
363                                                            pg_analyze_and_rewrite(parsetree));
364         }
365
366         return querytree_list;
367 }
368
369 /*
370  * Do raw parsing (only).
371  *
372  * A list of parsetrees is returned, since there might be multiple
373  * commands in the given string.
374  *
375  * NOTE: for interactive queries, it is important to keep this routine
376  * separate from the analysis & rewrite stages.  Analysis and rewriting
377  * cannot be done in an aborted transaction, since they require access to
378  * database tables.  So, we rely on the raw parser to determine whether
379  * we've seen a COMMIT or ABORT command; when we are in abort state, other
380  * commands are not processed any further than the raw parse stage.
381  */
382 List *
383 pg_parse_query(const char *query_string, Oid *typev, int nargs)
384 {
385         List       *raw_parsetree_list;
386
387         if (log_statement)
388                 elog(LOG, "query: %s", query_string);
389
390         if (log_parser_stats)
391                 ResetUsage();
392
393         raw_parsetree_list = parser(query_string, typev, nargs);
394
395         if (log_parser_stats)
396                 ShowUsage("PARSER STATISTICS");
397
398         return raw_parsetree_list;
399 }
400
401 /*
402  * Given a raw parsetree (gram.y output), perform parse analysis and
403  * rule rewriting.
404  *
405  * A list of Query nodes is returned, since either the analyzer or the
406  * rewriter might expand one query to several.
407  *
408  * NOTE: for reasons mentioned above, this must be separate from raw parsing.
409  */
410 List *
411 pg_analyze_and_rewrite(Node *parsetree)
412 {
413         List       *querytree_list;
414         List       *list_item;
415         Query      *querytree;
416         List       *new_list;
417
418         /*
419          * (1) Perform parse analysis.
420          */
421         if (log_parser_stats)
422                 ResetUsage();
423
424         querytree_list = parse_analyze(parsetree, NULL);
425
426         if (log_parser_stats)
427         {
428                 ShowUsage("PARSE ANALYSIS STATISTICS");
429                 ResetUsage();
430         }
431
432         /*
433          * (2) Rewrite the queries, as necessary
434          *
435          * rewritten queries are collected in new_list.  Note there may be more
436          * or fewer than in the original list.
437          */
438         new_list = NIL;
439         foreach(list_item, querytree_list)
440         {
441                 querytree = (Query *) lfirst(list_item);
442
443                 if (Debug_print_parse)
444                         elog_node_display(LOG, "parse tree", querytree,
445                                                           Debug_pretty_print);
446
447                 if (querytree->commandType == CMD_UTILITY)
448                 {
449                         /* don't rewrite utilities, just dump 'em into new_list */
450                         new_list = lappend(new_list, querytree);
451                 }
452                 else
453                 {
454                         /* rewrite regular queries */
455                         List       *rewritten = QueryRewrite(querytree);
456
457                         new_list = nconc(new_list, rewritten);
458                 }
459         }
460
461         querytree_list = new_list;
462
463         if (log_parser_stats)
464                 ShowUsage("REWRITER STATISTICS");
465
466 #ifdef COPY_PARSE_PLAN_TREES
467
468         /*
469          * Optional debugging check: pass querytree output through
470          * copyObject()
471          */
472         new_list = (List *) copyObject(querytree_list);
473         /* This checks both copyObject() and the equal() routines... */
474         if (!equal(new_list, querytree_list))
475                 elog(WARNING, "pg_analyze_and_rewrite: copyObject failed on parse tree");
476         else
477                 querytree_list = new_list;
478 #endif
479
480         if (Debug_print_rewritten)
481                 elog_node_display(LOG, "rewritten parse tree", querytree_list,
482                                                   Debug_pretty_print);
483
484         return querytree_list;
485 }
486
487
488 /* Generate a plan for a single query. */
489 Plan *
490 pg_plan_query(Query *querytree)
491 {
492         Plan       *plan;
493
494         /* Utility commands have no plans. */
495         if (querytree->commandType == CMD_UTILITY)
496                 return NULL;
497
498         if (log_planner_stats)
499                 ResetUsage();
500
501         /* call the optimizer */
502         plan = planner(querytree, false, 0);
503
504         if (log_planner_stats)
505                 ShowUsage("PLANNER STATISTICS");
506
507 #ifdef COPY_PARSE_PLAN_TREES
508         /* Optional debugging check: pass plan output through copyObject() */
509         {
510                 Plan       *new_plan = (Plan *) copyObject(plan);
511
512                 /*
513                  * equal() currently does not have routines to compare Plan nodes,
514                  * so don't try to test equality here.  Perhaps fix someday?
515                  */
516 #ifdef NOT_USED
517                 /* This checks both copyObject() and the equal() routines... */
518                 if (!equal(new_plan, plan))
519                         elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
520                 else
521 #endif
522                         plan = new_plan;
523         }
524 #endif
525
526         /*
527          * Print plan if debugging.
528          */
529         if (Debug_print_plan)
530                 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
531
532         return plan;
533 }
534
535
536 /* ----------------------------------------------------------------
537  *              pg_exec_query_string()
538  *
539  *              Takes a querystring, runs the parser/utilities or
540  *              parser/planner/executor over it as necessary.
541  *
542  * Assumptions:
543  *
544  * At call, we are not inside a transaction command.
545  *
546  * The CurrentMemoryContext after starting a transaction command must be
547  * appropriate for execution of individual queries (typically this will be
548  * TransactionCommandContext).  Note that this routine resets that context
549  * after each individual query, so don't store anything there that
550  * must outlive the call!
551  *
552  * parse_context references a context suitable for holding the
553  * parse/rewrite trees (typically this will be QueryContext).
554  * This context *must* be longer-lived than the transaction context!
555  * In fact, if the query string might contain BEGIN/COMMIT commands,
556  * parse_context had better outlive TopTransactionContext!
557  *
558  * We could have hard-wired knowledge about QueryContext and
559  * TransactionCommandContext into this routine, but it seems better
560  * not to, in case callers from outside this module need to use some
561  * other contexts.
562  *
563  * ----------------------------------------------------------------
564  */
565
566 void
567 pg_exec_query_string(const char *query_string,  /* string to execute */
568                                          CommandDest dest,      /* where results should go */
569                                          MemoryContext parse_context)           /* context for
570                                                                                                                  * parsetrees */
571 {
572         bool            xact_started;
573         MemoryContext oldcontext;
574         List       *parsetree_list,
575                            *parsetree_item;
576         struct timeval start_t,
577                                 stop_t;
578         bool            save_log_duration = log_duration;
579
580         debug_query_string = query_string;
581
582         /*
583          * We use save_log_duration so "SET log_duration = true" doesn't
584          * report incorrect time because gettimeofday() wasn't called.
585          */
586         if (save_log_duration)
587                 gettimeofday(&start_t, NULL);
588
589         /*
590          * Start up a transaction command.      All queries generated by the
591          * query_string will be in this same command block, *unless* we find a
592          * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
593          * after one of those, else bad things will happen in xact.c. (Note
594          * that this will possibly change current memory context.)
595          */
596         start_xact_command();
597         xact_started = true;
598
599         /*
600          * parse_context *must* be different from the execution memory
601          * context, else the context reset at the bottom of the loop will
602          * destroy the parsetree list.  (We really ought to check that
603          * parse_context isn't a child of CurrentMemoryContext either, but
604          * that would take more cycles than it's likely to be worth.)
605          */
606         Assert(parse_context != CurrentMemoryContext);
607
608         /*
609          * Switch to appropriate context for constructing parsetrees.
610          */
611         oldcontext = MemoryContextSwitchTo(parse_context);
612
613         /*
614          * Do basic parsing of the query or queries (this should be safe even
615          * if we are in aborted transaction state!)
616          */
617         parsetree_list = pg_parse_query(query_string, NULL, 0);
618
619         /*
620          * Switch back to execution context to enter the loop.
621          */
622         MemoryContextSwitchTo(oldcontext);
623
624         /*
625          * Run through the parsetree(s) and process each one.
626          */
627         foreach(parsetree_item, parsetree_list)
628         {
629                 Node       *parsetree = (Node *) lfirst(parsetree_item);
630                 const char *commandTag;
631                 char            completionTag[COMPLETION_TAG_BUFSIZE];
632                 CmdType         origCmdType;
633                 bool            foundOriginalQuery = false;
634                 List       *querytree_list,
635                                    *querytree_item;
636
637                 /*
638                  * First we set the command-completion tag to the main query (as
639                  * opposed to each of the others that may be generated by analyze
640                  * and rewrite).  Also set ps_status and do any special
641                  * start-of-SQL-command processing needed by the destination.
642                  */
643                 commandTag = CreateCommandTag(parsetree);
644
645                 switch (nodeTag(parsetree))
646                 {
647                         case T_InsertStmt:
648                                 origCmdType = CMD_INSERT;
649                                 break;
650                         case T_DeleteStmt:
651                                 origCmdType = CMD_DELETE;
652                                 break;
653                         case T_UpdateStmt:
654                                 origCmdType = CMD_UPDATE;
655                                 break;
656                         case T_SelectStmt:
657                                 origCmdType = CMD_SELECT;
658                                 break;
659                         default:
660                                 /* Otherwise, never match commandType */
661                                 origCmdType = CMD_UNKNOWN;
662                                 break;
663                 }
664
665                 set_ps_display(commandTag);
666
667                 BeginCommand(commandTag, dest);
668
669                 /*
670                  * If we are in an aborted transaction, ignore all commands except
671                  * COMMIT/ABORT.  It is important that this test occur before we
672                  * try to do parse analysis, rewrite, or planning, since all those
673                  * phases try to do database accesses, which may fail in abort
674                  * state. (It might be safe to allow some additional utility
675                  * commands in this state, but not many...)
676                  */
677                 if (IsAbortedTransactionBlockState())
678                 {
679                         bool            allowit = false;
680
681                         if (IsA(parsetree, TransactionStmt))
682                         {
683                                 TransactionStmt *stmt = (TransactionStmt *) parsetree;
684
685                                 if (stmt->kind == TRANS_STMT_COMMIT ||
686                                         stmt->kind == TRANS_STMT_ROLLBACK)
687                                         allowit = true;
688                         }
689
690                         if (!allowit)
691                                 elog(ERROR, "current transaction is aborted, "
692                                          "queries ignored until end of transaction block");
693                 }
694
695                 /* Make sure we are in a transaction command */
696                 if (!xact_started)
697                 {
698                         start_xact_command();
699                         xact_started = true;
700                 }
701
702                 /* If we got a cancel signal in parsing or prior command, quit */
703                 CHECK_FOR_INTERRUPTS();
704
705                 /*
706                  * OK to analyze and rewrite this query.
707                  *
708                  * Switch to appropriate context for constructing querytrees (again,
709                  * these must outlive the execution context).
710                  */
711                 oldcontext = MemoryContextSwitchTo(parse_context);
712
713                 querytree_list = pg_analyze_and_rewrite(parsetree);
714
715                 /*
716                  * Switch back to execution context for planning and execution.
717                  */
718                 MemoryContextSwitchTo(oldcontext);
719
720                 /*
721                  * Inner loop handles the individual queries generated from a
722                  * single parsetree by analysis and rewrite.
723                  */
724                 foreach(querytree_item, querytree_list)
725                 {
726                         Query      *querytree = (Query *) lfirst(querytree_item);
727                         bool            endTransactionBlock = false;
728                         bool            canSetTag;
729
730                         /* Make sure we are in a transaction command */
731                         if (!xact_started)
732                         {
733                                 start_xact_command();
734                                 xact_started = true;
735                         }
736
737                         /*
738                          * If we got a cancel signal in analysis or prior command,
739                          * quit
740                          */
741                         CHECK_FOR_INTERRUPTS();
742
743                         /*
744                          * This query can set the completion tag if it is the original
745                          * query, or if it is an INSTEAD query of the same kind as the
746                          * original and we haven't yet seen the original query.
747                          */
748                         if (querytree->querySource == QSRC_ORIGINAL)
749                         {
750                                 canSetTag = true;
751                                 foundOriginalQuery = true;
752                         }
753                         else if (!foundOriginalQuery &&
754                                          querytree->commandType == origCmdType &&
755                                          (querytree->querySource == QSRC_INSTEAD_RULE ||
756                                           querytree->querySource == QSRC_QUAL_INSTEAD_RULE))
757                                 canSetTag = true;
758                         else
759                                 canSetTag = false;
760
761                         if (querytree->commandType == CMD_UTILITY)
762                         {
763                                 /*
764                                  * process utility functions (create, destroy, etc..)
765                                  */
766                                 Node   *utilityStmt = querytree->utilityStmt;
767
768                                 elog(DEBUG2, "ProcessUtility");
769
770                                 /*
771                                  * Set snapshot if utility stmt needs one.  Most reliable
772                                  * way to do this seems to be to enumerate those that do not
773                                  * need one; this is a short list.  Transaction control,
774                                  * LOCK, and SET must *not* set a snapshot since they need
775                                  * to be executable at the start of a serializable transaction
776                                  * without freezing a snapshot.  By extension we allow SHOW
777                                  * not to set a snapshot.  The other stmts listed are just
778                                  * efficiency hacks.  Beware of listing anything that can
779                                  * modify the database --- if, say, it has to update a
780                                  * functional index, then it had better have a snapshot.
781                                  */
782                                 if (! (IsA(utilityStmt, TransactionStmt) ||
783                                            IsA(utilityStmt, LockStmt) ||
784                                            IsA(utilityStmt, VariableSetStmt) ||
785                                            IsA(utilityStmt, VariableShowStmt) ||
786                                            IsA(utilityStmt, VariableResetStmt) ||
787                                            IsA(utilityStmt, ConstraintsSetStmt) ||
788                                            /* efficiency hacks from here down */
789                                            IsA(utilityStmt, FetchStmt) ||
790                                            IsA(utilityStmt, ListenStmt) ||
791                                            IsA(utilityStmt, NotifyStmt) ||
792                                            IsA(utilityStmt, UnlistenStmt) ||
793                                            IsA(utilityStmt, CheckPointStmt)))
794                                         SetQuerySnapshot();
795
796                                 /* end transaction block if transaction or variable stmt */
797                                 if (IsA(utilityStmt, TransactionStmt) ||
798                                         IsA(utilityStmt, VariableSetStmt) ||
799                                         IsA(utilityStmt, VariableShowStmt) ||
800                                         IsA(utilityStmt, VariableResetStmt))
801                                         endTransactionBlock = true;
802
803                                 if (canSetTag)
804                                 {
805                                         /* utility statement can override default tag string */
806                                         ProcessUtility(utilityStmt, dest, completionTag);
807                                         if (completionTag[0])
808                                                 commandTag = completionTag;
809                                 }
810                                 else
811                                 {
812                                         /* utility added by rewrite cannot override tag */
813                                         ProcessUtility(utilityStmt, dest, NULL);
814                                 }
815                         }
816                         else
817                         {
818                                 /*
819                                  * process a plannable query.
820                                  */
821                                 Plan       *plan;
822
823                                 /*
824                                  * Initialize snapshot state for query.  This has to
825                                  * be done before running the planner, because it might
826                                  * try to evaluate immutable or stable functions, which
827                                  * in turn might run queries.
828                                  */
829                                 SetQuerySnapshot();
830
831                                 /* Make the plan */
832                                 plan = pg_plan_query(querytree);
833
834                                 /* if we got a cancel signal whilst planning, quit */
835                                 CHECK_FOR_INTERRUPTS();
836
837                                 /*
838                                  * execute the plan
839                                  */
840                                 if (log_executor_stats)
841                                         ResetUsage();
842
843                                 if (dontExecute)
844                                 {
845                                         /* don't execute it, just show the query plan */
846                                         print_plan(plan, querytree);
847                                 }
848                                 else
849                                 {
850                                         elog(DEBUG2, "ProcessQuery");
851
852                                         if (canSetTag)
853                                         {
854                                                 /* statement can override default tag string */
855                                                 ProcessQuery(querytree, plan, dest, completionTag);
856                                                 commandTag = completionTag;
857                                         }
858                                         else
859                                         {
860                                                 /* stmt added by rewrite cannot override tag */
861                                                 ProcessQuery(querytree, plan, dest, NULL);
862                                         }
863                                 }
864
865                                 if (log_executor_stats)
866                                         ShowUsage("EXECUTOR STATISTICS");
867                         }
868
869                         /*
870                          * In a query block, we want to increment the command counter
871                          * between queries so that the effects of early queries are
872                          * visible to subsequent ones.  In particular we'd better do
873                          * so before checking constraints.
874                          */
875                         if (!endTransactionBlock)
876                                 CommandCounterIncrement();
877
878                         /*
879                          * Clear the execution context to recover temporary memory
880                          * used by the query.  NOTE: if query string contains
881                          * BEGIN/COMMIT transaction commands, execution context may
882                          * now be different from what we were originally passed; so be
883                          * careful to clear current context not "oldcontext".
884                          */
885                         Assert(parse_context != CurrentMemoryContext);
886
887                         MemoryContextResetAndDeleteChildren(CurrentMemoryContext);
888
889                         /*
890                          * If this was a transaction control statement or a variable
891                          * set/show/reset statement, commit it and arrange to start a
892                          * new xact command for the next command (if any).
893                          */
894                         if (endTransactionBlock)
895                         {
896                                 finish_xact_command(true);
897                                 xact_started = false;
898                         }
899                 }                                               /* end loop over queries generated from a
900                                                                  * parsetree */
901
902                 /*
903                  * If this is the last parsetree of the query string, close down
904                  * transaction statement before reporting command-complete.  This
905                  * is so that any end-of-transaction errors are reported before
906                  * the command-complete message is issued, to avoid confusing
907                  * clients who will expect either a command-complete message or an
908                  * error, not one and then the other.  But for compatibility with
909                  * historical Postgres behavior, we do not force a transaction
910                  * boundary between queries appearing in a single query string.
911                  */
912                 if ((lnext(parsetree_item) == NIL || !autocommit) && xact_started)
913                 {
914                         finish_xact_command(false);
915                         xact_started = false;
916                 }
917
918                 /*
919                  * It is possible that the original query was removed due to a DO
920                  * INSTEAD rewrite rule.  If so, and if we found no INSTEAD query
921                  * matching the command type, we will still have the default
922                  * completion tag.  This is fine for most purposes, but it
923                  * may confuse clients if it's INSERT/UPDATE/DELETE. Clients
924                  * expect those tags to have counts after them (cf. ProcessQuery).
925                  */
926                 if (!foundOriginalQuery)
927                 {
928                         if (strcmp(commandTag, "INSERT") == 0)
929                                 commandTag = "INSERT 0 0";
930                         else if (strcmp(commandTag, "UPDATE") == 0)
931                                 commandTag = "UPDATE 0";
932                         else if (strcmp(commandTag, "DELETE") == 0)
933                                 commandTag = "DELETE 0";
934                 }
935
936                 /*
937                  * Tell client that we're done with this query.  Note we emit
938                  * exactly one EndCommand report for each raw parsetree, thus one
939                  * for each SQL command the client sent, regardless of rewriting.
940                  * (But a command aborted by error will not send an EndCommand
941                  * report at all.)
942                  */
943                 EndCommand(commandTag, dest);
944         }                                                       /* end loop over parsetrees */
945
946         /* No parsetree - return empty result */
947         if (!parsetree_list)
948                 NullCommand(dest);
949
950         /*
951          * Close down transaction statement, if one is open. (Note that this
952          * will only happen if the querystring was empty.)
953          */
954         if (xact_started)
955                 finish_xact_command(false);
956
957         if (save_log_duration)
958         {
959                 gettimeofday(&stop_t, NULL);
960                 if (stop_t.tv_usec < start_t.tv_usec)
961                 {
962                         stop_t.tv_sec--;
963                         stop_t.tv_usec += 1000000;
964                 }
965                 elog(LOG, "duration: %ld.%06ld sec",
966                          (long) (stop_t.tv_sec - start_t.tv_sec),
967                          (long) (stop_t.tv_usec - start_t.tv_usec));
968         }
969
970         debug_query_string = NULL;
971 }
972
973 /*
974  * Convenience routines for starting/committing a single command.
975  */
976 static void
977 start_xact_command(void)
978 {
979         elog(DEBUG1, "StartTransactionCommand");
980         StartTransactionCommand(false);
981
982         /* Set statement timeout running, if any */
983         if (StatementTimeout > 0)
984                 enable_sig_alarm(StatementTimeout, true);
985 }
986
987 static void
988 finish_xact_command(bool forceCommit)
989 {
990         /* Invoke IMMEDIATE constraint triggers */
991         DeferredTriggerEndQuery();
992
993         /* Cancel any active statement timeout before committing */
994         disable_sig_alarm(true);
995
996         /* Now commit the command */
997         elog(DEBUG1, "CommitTransactionCommand");
998
999         CommitTransactionCommand(forceCommit);
1000
1001 #ifdef SHOW_MEMORY_STATS
1002         /* Print mem stats at each commit for leak tracking */
1003         if (ShowStats)
1004                 MemoryContextStats(TopMemoryContext);
1005 #endif
1006 }
1007
1008
1009 /* --------------------------------
1010  *              signal handler routines used in PostgresMain()
1011  * --------------------------------
1012  */
1013
1014 /*
1015  * quickdie() occurs when signalled SIGQUIT by the postmaster.
1016  *
1017  * Some backend has bought the farm,
1018  * so we need to stop what we're doing and exit.
1019  */
1020 void
1021 quickdie(SIGNAL_ARGS)
1022 {
1023         PG_SETMASK(&BlockSig);
1024         elog(WARNING, "Message from PostgreSQL backend:"
1025                  "\n\tThe Postmaster has informed me that some other backend"
1026                  "\n\tdied abnormally and possibly corrupted shared memory."
1027                  "\n\tI have rolled back the current transaction and am"
1028            "\n\tgoing to terminate your database system connection and exit."
1029         "\n\tPlease reconnect to the database system and repeat your query.");
1030
1031         /*
1032          * DO NOT proc_exit() -- we're here because shared memory may be
1033          * corrupted, so we don't want to try to clean up our transaction.
1034          * Just nail the windows shut and get out of town.
1035          *
1036          * Note we do exit(1) not exit(0).      This is to force the postmaster into
1037          * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1038          * random backend.      This is necessary precisely because we don't clean
1039          * up our shared memory state.
1040          */
1041
1042         exit(1);
1043 }
1044
1045 /*
1046  * Shutdown signal from postmaster: abort transaction and exit
1047  * at soonest convenient time
1048  */
1049 void
1050 die(SIGNAL_ARGS)
1051 {
1052         int                     save_errno = errno;
1053
1054         /* Don't joggle the elbow of proc_exit */
1055         if (!proc_exit_inprogress)
1056         {
1057                 InterruptPending = true;
1058                 ProcDiePending = true;
1059
1060                 /*
1061                  * If it's safe to interrupt, and we're waiting for input or a
1062                  * lock, service the interrupt immediately
1063                  */
1064                 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1065                         CritSectionCount == 0)
1066                 {
1067                         /* bump holdoff count to make ProcessInterrupts() a no-op */
1068                         /* until we are done getting ready for it */
1069                         InterruptHoldoffCount++;
1070                         DisableNotifyInterrupt();
1071                         /* Make sure CheckDeadLock won't run while shutting down... */
1072                         LockWaitCancel();
1073                         InterruptHoldoffCount--;
1074                         ProcessInterrupts();
1075                 }
1076         }
1077
1078         errno = save_errno;
1079 }
1080
1081 /*
1082  * Timeout or shutdown signal from postmaster during client authentication.
1083  * Simply exit(0).
1084  *
1085  * XXX: possible future improvement: try to send a message indicating
1086  * why we are disconnecting.  Problem is to be sure we don't block while
1087  * doing so, nor mess up the authentication message exchange.
1088  */
1089 void
1090 authdie(SIGNAL_ARGS)
1091 {
1092         exit(0);
1093 }
1094
1095 /*
1096  * Query-cancel signal from postmaster: abort current transaction
1097  * at soonest convenient time
1098  */
1099 static void
1100 StatementCancelHandler(SIGNAL_ARGS)
1101 {
1102         int                     save_errno = errno;
1103
1104         /*
1105          * Don't joggle the elbow of proc_exit, nor an already-in-progress
1106          * abort
1107          */
1108         if (!proc_exit_inprogress && !InError)
1109         {
1110                 InterruptPending = true;
1111                 QueryCancelPending = true;
1112
1113                 /*
1114                  * If it's safe to interrupt, and we're waiting for a lock,
1115                  * service the interrupt immediately.  No point in interrupting if
1116                  * we're waiting for input, however.
1117                  */
1118                 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1119                         CritSectionCount == 0)
1120                 {
1121                         /* bump holdoff count to make ProcessInterrupts() a no-op */
1122                         /* until we are done getting ready for it */
1123                         InterruptHoldoffCount++;
1124                         if (LockWaitCancel())
1125                         {
1126                                 DisableNotifyInterrupt();
1127                                 InterruptHoldoffCount--;
1128                                 ProcessInterrupts();
1129                         }
1130                         else
1131                                 InterruptHoldoffCount--;
1132                 }
1133         }
1134
1135         errno = save_errno;
1136 }
1137
1138 /* signal handler for floating point exception */
1139 static void
1140 FloatExceptionHandler(SIGNAL_ARGS)
1141 {
1142         elog(ERROR, "floating point exception!"
1143                  " The last floating point operation either exceeded legal ranges"
1144                  " or was a divide by zero");
1145 }
1146
1147 /* SIGHUP: set flag to re-read config file at next convenient time */
1148 static void
1149 SigHupHandler(SIGNAL_ARGS)
1150 {
1151         got_SIGHUP = true;
1152 }
1153
1154
1155 /*
1156  * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1157  *
1158  * If an interrupt condition is pending, and it's safe to service it,
1159  * then clear the flag and accept the interrupt.  Called only when
1160  * InterruptPending is true.
1161  */
1162 void
1163 ProcessInterrupts(void)
1164 {
1165         /* OK to accept interrupt now? */
1166         if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1167                 return;
1168         InterruptPending = false;
1169         if (ProcDiePending)
1170         {
1171                 ProcDiePending = false;
1172                 QueryCancelPending = false;             /* ProcDie trumps QueryCancel */
1173                 ImmediateInterruptOK = false;   /* not idle anymore */
1174                 DisableNotifyInterrupt();
1175                 elog(FATAL, "This connection has been terminated by the administrator.");
1176         }
1177         if (QueryCancelPending)
1178         {
1179                 QueryCancelPending = false;
1180                 ImmediateInterruptOK = false;   /* not idle anymore */
1181                 DisableNotifyInterrupt();
1182                 elog(ERROR, "Query was canceled.");
1183         }
1184         /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1185 }
1186
1187
1188 static void
1189 usage(char *progname)
1190 {
1191         printf("%s is the PostgreSQL stand-alone backend.  It is not\nintended to be used by normal users.\n\n", progname);
1192
1193         printf("Usage:\n  %s [OPTION]... [DBNAME]\n\n", progname);
1194         printf("Options:\n");
1195 #ifdef USE_ASSERT_CHECKING
1196         printf("  -A 1|0          enable/disable run-time assert checking\n");
1197 #endif
1198         printf("  -B NBUFFERS     number of shared buffers (default %d)\n", DEF_NBUFFERS);
1199         printf("  -c NAME=VALUE   set run-time parameter\n");
1200         printf("  -d 0-5          debugging level (0 is off)\n");
1201         printf("  -D DATADIR      database directory\n");
1202         printf("  -e              use European date format\n");
1203         printf("  -E              echo query before execution\n");
1204         printf("  -F              turn fsync off\n");
1205         printf("  -N              do not use newline as interactive query delimiter\n");
1206         printf("  -o FILENAME     send stdout and stderr to given file\n");
1207         printf("  -P              disable system indexes\n");
1208         printf("  -s              show statistics after each query\n");
1209         printf("  -S SORT-MEM     set amount of memory for sorts (in kbytes)\n");
1210         printf("  --help          show this help, then exit\n");
1211         printf("  --version       output version information, then exit\n");
1212         printf("\nDeveloper options:\n");
1213         printf("  -f s|i|n|m|h    forbid use of some plan types\n");
1214         printf("  -i              do not execute queries\n");
1215         printf("  -O              allow system table structure changes\n");
1216         printf("  -t pa|pl|ex     show timings after each query\n");
1217         printf("  -W NUM          wait NUM seconds to allow attach from a debugger\n");
1218         printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1219 }
1220
1221
1222
1223 /* ----------------------------------------------------------------
1224  * PostgresMain
1225  *         postgres main loop -- all backends, interactive or otherwise start here
1226  *
1227  * argc/argv are the command line arguments to be used.  (When being forked
1228  * by the postmaster, these are not the original argv array of the process.)
1229  * username is the (possibly authenticated) PostgreSQL user name to be used
1230  * for the session.
1231  * ----------------------------------------------------------------
1232  */
1233 int
1234 PostgresMain(int argc, char *argv[], const char *username)
1235 {
1236         int                     flag;
1237         const char *DBName = NULL;
1238         char       *potential_DataDir = NULL;
1239         bool            secure;
1240         int                     errs = 0;
1241         int                     debug_flag = 0;
1242         GucContext      ctx;
1243         GucSource       gucsource;
1244         char       *tmp;
1245         int                     firstchar;
1246         StringInfo      input_message;
1247         bool            send_rfq;
1248
1249         /*
1250          * Catch standard options before doing much else.  This even works on
1251          * systems without getopt_long.
1252          */
1253         if (!IsUnderPostmaster && argc > 1)
1254         {
1255                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1256                 {
1257                         usage(argv[0]);
1258                         exit(0);
1259                 }
1260                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1261                 {
1262                         puts("postgres (PostgreSQL) " PG_VERSION);
1263                         exit(0);
1264                 }
1265         }
1266
1267         /*
1268          * initialize globals (already done if under postmaster, but not if
1269          * standalone; cheap enough to do over)
1270          */
1271
1272         MyProcPid = getpid();
1273
1274         /*
1275          * Fire up essential subsystems: error and memory management
1276          *
1277          * If we are running under the postmaster, this is done already.
1278          */
1279         if (!IsUnderPostmaster)
1280                 MemoryContextInit();
1281
1282         set_ps_display("startup");
1283
1284         SetProcessingMode(InitProcessing);
1285
1286         /*
1287          * Set default values for command-line options.
1288          */
1289         Noversion = false;
1290         EchoQuery = false;
1291
1292         if (!IsUnderPostmaster)
1293         {
1294                 InitializeGUCOptions();
1295                 potential_DataDir = getenv("PGDATA");
1296         }
1297
1298         /* ----------------
1299          *      parse command line arguments
1300          *
1301          *      There are now two styles of command line layout for the backend:
1302          *
1303          *      For interactive use (not started from postmaster) the format is
1304          *              postgres [switches] [databasename]
1305          *      If the databasename is omitted it is taken to be the user name.
1306          *
1307          *      When started from the postmaster, the format is
1308          *              postgres [secure switches] -p databasename [insecure switches]
1309          *      Switches appearing after -p came from the client (via "options"
1310          *      field of connection request).  For security reasons we restrict
1311          *      what these switches can do.
1312          * ----------------
1313          */
1314
1315         /* all options are allowed until '-p' */
1316         secure = true;
1317         ctx = PGC_POSTMASTER;
1318         gucsource = PGC_S_ARGV;         /* initial switches came from command line */
1319
1320         while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1321                 switch (flag)
1322                 {
1323                         case 'A':
1324 #ifdef USE_ASSERT_CHECKING
1325                                 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
1326 #else
1327                                 elog(WARNING, "Assert checking is not compiled in");
1328 #endif
1329                                 break;
1330
1331                         case 'B':
1332
1333                                 /*
1334                                  * specify the size of buffer pool
1335                                  */
1336                                 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1337                                 break;
1338
1339                         case 'C':
1340
1341                                 /*
1342                                  * don't print version string
1343                                  */
1344                                 Noversion = true;
1345                                 break;
1346
1347                         case 'D':                       /* PGDATA directory */
1348                                 if (secure)
1349                                         potential_DataDir = optarg;
1350                                 break;
1351
1352                         case 'd':                       /* debug level */
1353                                 {
1354                                         debug_flag = atoi(optarg);
1355                                         /* Set server debugging level. */
1356                                         if (atoi(optarg) != 0)
1357                                         {
1358                                                 char       *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
1359
1360                                                 sprintf(debugstr, "debug%s", optarg);
1361                                                 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
1362                                                 pfree(debugstr);
1363
1364                                         }
1365                                         else
1366                                                 /*
1367                                                  * -d0 allows user to prevent postmaster debug
1368                                                  * from propagating to backend.  It would be nice
1369                                                  * to set it to the postgresql.conf value here.
1370                                                  */
1371                                                 SetConfigOption("log_min_messages", "notice",
1372                                                                                 ctx, gucsource);
1373                                 }
1374                                 break;
1375
1376                         case 'E':
1377
1378                                 /*
1379                                  * E - echo the query the user entered
1380                                  */
1381                                 EchoQuery = true;
1382                                 break;
1383
1384                         case 'e':
1385
1386                                 /*
1387                                  * Use european date formats.
1388                                  */
1389                                 SetConfigOption("datestyle", "euro", ctx, gucsource);
1390                                 break;
1391
1392                         case 'F':
1393
1394                                 /*
1395                                  * turn off fsync
1396                                  */
1397                                 SetConfigOption("fsync", "false", ctx, gucsource);
1398                                 break;
1399
1400                         case 'f':
1401
1402                                 /*
1403                                  * f - forbid generation of certain plans
1404                                  */
1405                                 tmp = NULL;
1406                                 switch (optarg[0])
1407                                 {
1408                                         case 's':       /* seqscan */
1409                                                 tmp = "enable_seqscan";
1410                                                 break;
1411                                         case 'i':       /* indexscan */
1412                                                 tmp = "enable_indexscan";
1413                                                 break;
1414                                         case 't':       /* tidscan */
1415                                                 tmp = "enable_tidscan";
1416                                                 break;
1417                                         case 'n':       /* nestloop */
1418                                                 tmp = "enable_nestloop";
1419                                                 break;
1420                                         case 'm':       /* mergejoin */
1421                                                 tmp = "enable_mergejoin";
1422                                                 break;
1423                                         case 'h':       /* hashjoin */
1424                                                 tmp = "enable_hashjoin";
1425                                                 break;
1426                                         default:
1427                                                 errs++;
1428                                 }
1429                                 if (tmp)
1430                                         SetConfigOption(tmp, "false", ctx, gucsource);
1431                                 break;
1432
1433                         case 'i':
1434                                 dontExecute = true;
1435                                 break;
1436
1437                         case 'N':
1438
1439                                 /*
1440                                  * N - Don't use newline as a query delimiter
1441                                  */
1442                                 UseNewLine = 0;
1443                                 break;
1444
1445                         case 'O':
1446
1447                                 /*
1448                                  * allow system table structure modifications
1449                                  */
1450                                 if (secure)             /* XXX safe to allow from client??? */
1451                                         allowSystemTableMods = true;
1452                                 break;
1453
1454                         case 'P':
1455
1456                                 /*
1457                                  * ignore system indexes
1458                                  */
1459                                 if (secure)             /* XXX safe to allow from client??? */
1460                                         IgnoreSystemIndexes(true);
1461                                 break;
1462
1463                         case 'o':
1464
1465                                 /*
1466                                  * o - send output (stdout and stderr) to the given file
1467                                  */
1468                                 if (secure)
1469                                         StrNCpy(OutputFileName, optarg, MAXPGPATH);
1470                                 break;
1471
1472                         case 'p':
1473
1474                                 /*
1475                                  * p - special flag passed if backend was forked by a
1476                                  * postmaster.
1477                                  */
1478                                 if (secure)
1479                                 {
1480                                         DBName = strdup(optarg);
1481                                         secure = false;         /* subsequent switches are NOT
1482                                                                                  * secure */
1483                                         ctx = PGC_BACKEND;
1484                                         gucsource = PGC_S_CLIENT;
1485                                 }
1486                                 break;
1487
1488                         case 'S':
1489
1490                                 /*
1491                                  * S - amount of sort memory to use in 1k bytes
1492                                  */
1493                                 SetConfigOption("sort_mem", optarg, ctx, gucsource);
1494                                 break;
1495
1496                         case 's':
1497
1498                                 /*
1499                                  * s - report usage statistics (timings) after each query
1500                                  */
1501                                 SetConfigOption("show_statement_stats", "true", ctx, gucsource);
1502                                 break;
1503
1504                         case 't':
1505                                 /* ---------------
1506                                  *      tell postgres to report usage statistics (timings) for
1507                                  *      each query
1508                                  *
1509                                  *      -tpa[rser] = print stats for parser time of each query
1510                                  *      -tpl[anner] = print stats for planner time of each query
1511                                  *      -te[xecutor] = print stats for executor time of each query
1512                                  *      caution: -s can not be used together with -t.
1513                                  * ----------------
1514                                  */
1515                                 tmp = NULL;
1516                                 switch (optarg[0])
1517                                 {
1518                                         case 'p':
1519                                                 if (optarg[1] == 'a')
1520                                                         tmp = "log_parser_stats";
1521                                                 else if (optarg[1] == 'l')
1522                                                         tmp = "log_planner_stats";
1523                                                 else
1524                                                         errs++;
1525                                                 break;
1526                                         case 'e':
1527                                                 tmp = "show_executor_stats";
1528                                                 break;
1529                                         default:
1530                                                 errs++;
1531                                                 break;
1532                                 }
1533                                 if (tmp)
1534                                         SetConfigOption(tmp, "true", ctx, gucsource);
1535                                 break;
1536
1537                         case 'v':
1538                                 if (secure)
1539                                         FrontendProtocol = (ProtocolVersion) atoi(optarg);
1540                                 break;
1541
1542                         case 'W':
1543
1544                                 /*
1545                                  * wait N seconds to allow attach from a debugger
1546                                  */
1547                                 sleep(atoi(optarg));
1548                                 break;
1549
1550                         case 'x':
1551 #ifdef NOT_USED                                 /* planner/xfunc.h */
1552
1553                                 /*
1554                                  * control joey hellerstein's expensive function
1555                                  * optimization
1556                                  */
1557                                 if (XfuncMode != 0)
1558                                 {
1559                                         elog(WARNING, "only one -x flag is allowed");
1560                                         errs++;
1561                                         break;
1562                                 }
1563                                 if (strcmp(optarg, "off") == 0)
1564                                         XfuncMode = XFUNC_OFF;
1565                                 else if (strcmp(optarg, "nor") == 0)
1566                                         XfuncMode = XFUNC_NOR;
1567                                 else if (strcmp(optarg, "nopull") == 0)
1568                                         XfuncMode = XFUNC_NOPULL;
1569                                 else if (strcmp(optarg, "nopm") == 0)
1570                                         XfuncMode = XFUNC_NOPM;
1571                                 else if (strcmp(optarg, "pullall") == 0)
1572                                         XfuncMode = XFUNC_PULLALL;
1573                                 else if (strcmp(optarg, "wait") == 0)
1574                                         XfuncMode = XFUNC_WAIT;
1575                                 else
1576                                 {
1577                                         elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
1578                                         errs++;
1579                                 }
1580 #endif
1581                                 break;
1582
1583                         case 'c':
1584                         case '-':
1585                                 {
1586                                         char       *name,
1587                                                            *value;
1588
1589                                         ParseLongOption(optarg, &name, &value);
1590                                         if (!value)
1591                                         {
1592                                                 if (flag == '-')
1593                                                         elog(ERROR, "--%s requires argument", optarg);
1594                                                 else
1595                                                         elog(ERROR, "-c %s requires argument", optarg);
1596                                         }
1597
1598                                         SetConfigOption(name, value, ctx, gucsource);
1599                                         free(name);
1600                                         if (value)
1601                                                 free(value);
1602                                         break;
1603                                 }
1604
1605                         default:
1606                                 errs++;
1607                                 break;
1608                 }
1609
1610         /*
1611          * -d is not the same as setting
1612          * log_min_messages because it enables other
1613          * output options.
1614          */
1615         if (debug_flag >= 1)
1616                 SetConfigOption("log_connections", "true", ctx, gucsource);
1617         if (debug_flag >= 2)
1618                 SetConfigOption("log_statement", "true", ctx, gucsource);
1619         if (debug_flag >= 3)
1620                 SetConfigOption("debug_print_parse", "true", ctx, gucsource);
1621         if (debug_flag >= 4)
1622                 SetConfigOption("debug_print_plan", "true", ctx, gucsource);
1623         if (debug_flag >= 5)
1624                 SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);
1625
1626         /*
1627          * Process any additional GUC variable settings passed in startup packet.
1628          */
1629         if (MyProcPort != NULL)
1630         {
1631                 List   *gucopts = MyProcPort->guc_options;
1632
1633                 while (gucopts)
1634                 {
1635                         char       *name,
1636                                            *value;
1637
1638                         name = lfirst(gucopts);
1639                         gucopts = lnext(gucopts);
1640                         value = lfirst(gucopts);
1641                         gucopts = lnext(gucopts);
1642                         SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
1643                 }
1644         }
1645
1646         /*
1647          * Post-processing for command line options.
1648          */
1649         if (log_statement_stats &&
1650                 (log_parser_stats || log_planner_stats || log_executor_stats))
1651         {
1652                 elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1653                 SetConfigOption("show_statement_stats", "false", ctx, gucsource);
1654         }
1655
1656         if (!IsUnderPostmaster)
1657         {
1658                 if (!potential_DataDir)
1659                 {
1660                         fprintf(stderr, "%s does not know where to find the database system "
1661                            "data.  You must specify the directory that contains the "
1662                                 "database system either by specifying the -D invocation "
1663                          "option or by setting the PGDATA environment variable.\n\n",
1664                                         argv[0]);
1665                         proc_exit(1);
1666                 }
1667                 SetDataDir(potential_DataDir);
1668         }
1669         Assert(DataDir);
1670
1671         /*
1672          * Set up signal handlers and masks.
1673          *
1674          * Note that postmaster blocked all signals before forking child process,
1675          * so there is no race condition whereby we might receive a signal
1676          * before we have set up the handler.
1677          *
1678          * Also note: it's best not to use any signals that are SIG_IGNored in
1679          * the postmaster.      If such a signal arrives before we are able to
1680          * change the handler to non-SIG_IGN, it'll get dropped.  Instead,
1681          * make a dummy handler in the postmaster to reserve the signal. (Of
1682          * course, this isn't an issue for signals that are locally generated,
1683          * such as SIGALRM and SIGPIPE.)
1684          */
1685
1686         pqsignal(SIGHUP, SigHupHandler);        /* set flag to read config file */
1687         pqsignal(SIGINT, StatementCancelHandler);       /* cancel current query */
1688         pqsignal(SIGTERM, die);         /* cancel current query and exit */
1689         pqsignal(SIGQUIT, quickdie);    /* hard crash time */
1690         pqsignal(SIGALRM, handle_sig_alarm);    /* timeout conditions */
1691
1692         /*
1693          * Ignore failure to write to frontend. Note: if frontend closes
1694          * connection, we will notice it and exit cleanly when control next
1695          * returns to outer loop.  This seems safer than forcing exit in the
1696          * midst of output during who-knows-what operation...
1697          */
1698         pqsignal(SIGPIPE, SIG_IGN);
1699         pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
1700
1701         pqsignal(SIGUSR2, Async_NotifyHandler);         /* flush also sinval cache */
1702         pqsignal(SIGFPE, FloatExceptionHandler);
1703
1704         /*
1705          * Reset some signals that are accepted by postmaster but not by
1706          * backend
1707          */
1708         pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
1709                                                                  * platforms */
1710
1711         pqinitmask();
1712
1713         /* We allow SIGQUIT (quickdie) at all times */
1714 #ifdef HAVE_SIGPROCMASK
1715         sigdelset(&BlockSig, SIGQUIT);
1716 #else
1717         BlockSig &= ~(sigmask(SIGQUIT));
1718 #endif
1719
1720         PG_SETMASK(&BlockSig);          /* block everything except SIGQUIT */
1721
1722
1723         if (IsUnderPostmaster)
1724         {
1725                 /* noninteractive case: nothing should be left after switches */
1726                 if (errs || argc != optind || DBName == NULL)
1727                 {
1728                         elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1729                                  argv[0]);
1730                         proc_exit(0);           /* not 1, that causes system-wide
1731                                                                  * restart... */
1732                 }
1733                 BaseInit();
1734         }
1735         else
1736         {
1737                 /* interactive case: database name can be last arg on command line */
1738                 if (errs || argc - optind > 1)
1739                 {
1740                         elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1741                                  argv[0]);
1742                         proc_exit(1);
1743                 }
1744                 else if (argc - optind == 1)
1745                         DBName = argv[optind];
1746                 else if ((DBName = username) == NULL)
1747                 {
1748                         elog(WARNING, "%s: user name undefined and no database specified",
1749                                  argv[0]);
1750                         proc_exit(1);
1751                 }
1752
1753                 /*
1754                  * On some systems our dynloader code needs the executable's
1755                  * pathname.  (If under postmaster, this was done already.)
1756                  */
1757                 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
1758                         elog(FATAL, "%s: could not locate executable, bailing out...",
1759                                  argv[0]);
1760
1761                 /*
1762                  * Validate we have been given a reasonable-looking DataDir (if
1763                  * under postmaster, assume postmaster did this already).
1764                  */
1765                 ValidatePgVersion(DataDir);
1766
1767                 /*
1768                  * Create lockfile for data directory.
1769                  */
1770                 if (!CreateDataDirLockFile(DataDir, false))
1771                         proc_exit(1);
1772
1773                 XLOGPathInit();
1774                 BaseInit();
1775
1776                 /*
1777                  * Start up xlog for standalone backend, and register to have it
1778                  * closed down at exit.
1779                  */
1780                 StartupXLOG();
1781                 on_shmem_exit(ShutdownXLOG, 0);
1782
1783                 /*
1784                  * Read any existing FSM cache file, and register to write one out
1785                  * at exit.
1786                  */
1787                 LoadFreeSpaceMap();
1788                 on_shmem_exit(DumpFreeSpaceMap, 0);
1789         }
1790
1791         /*
1792          * Set up additional info.
1793          */
1794
1795 #ifdef CYR_RECODE
1796         SetCharSet();
1797 #endif
1798
1799         /*
1800          * General initialization.
1801          *
1802          * NOTE: if you are tempted to add code in this vicinity, consider
1803          * putting it inside InitPostgres() instead.  In particular, anything
1804          * that involves database access should be there, not here.
1805          */
1806         elog(DEBUG2, "InitPostgres");
1807         InitPostgres(DBName, username);
1808
1809         SetProcessingMode(NormalProcessing);
1810
1811         /*
1812          * Send this backend's cancellation info to the frontend.
1813          */
1814         if (whereToSendOutput == Remote &&
1815                 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
1816         {
1817                 StringInfoData buf;
1818
1819                 pq_beginmessage(&buf, 'K');
1820                 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
1821                 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
1822                 pq_endmessage(&buf);
1823                 /* Need not flush since ReadyForQuery will do it. */
1824         }
1825
1826         if (!IsUnderPostmaster)
1827         {
1828                 puts("\nPOSTGRES backend interactive interface ");
1829                 puts("$Revision: 1.325 $ $Date: 2003/04/27 20:09:44 $\n");
1830         }
1831
1832         /*
1833          * Create the memory context we will use in the main loop.
1834          *
1835          * QueryContext is reset once per iteration of the main loop, ie, upon
1836          * completion of processing of each supplied query string. It can
1837          * therefore be used for any data that should live just as long as the
1838          * query string --- parse trees, for example.
1839          */
1840         QueryContext = AllocSetContextCreate(TopMemoryContext,
1841                                                                                  "QueryContext",
1842                                                                                  ALLOCSET_DEFAULT_MINSIZE,
1843                                                                                  ALLOCSET_DEFAULT_INITSIZE,
1844                                                                                  ALLOCSET_DEFAULT_MAXSIZE);
1845
1846         /* ----------
1847          * Tell the statistics collector that we're alive and
1848          * to which database we belong.
1849          * ----------
1850          */
1851         pgstat_bestart();
1852
1853         /*
1854          * POSTGRES main processing loop begins here
1855          *
1856          * If an exception is encountered, processing resumes here so we abort
1857          * the current transaction and start a new one.
1858          */
1859
1860         if (sigsetjmp(Warn_restart, 1) != 0)
1861         {
1862                 /*
1863                  * NOTE: if you are tempted to add more code in this if-block,
1864                  * consider the probability that it should be in
1865                  * AbortTransaction() instead.
1866                  *
1867                  * Make sure we're not interrupted while cleaning up.  Also forget
1868                  * any pending QueryCancel request, since we're aborting anyway.
1869                  * Force InterruptHoldoffCount to a known state in case we elog'd
1870                  * from inside a holdoff section.
1871                  */
1872                 ImmediateInterruptOK = false;
1873                 QueryCancelPending = false;
1874                 InterruptHoldoffCount = 1;
1875                 CritSectionCount = 0;   /* should be unnecessary, but... */
1876                 disable_sig_alarm(true);
1877                 QueryCancelPending = false;     /* again in case timeout occurred */
1878                 DisableNotifyInterrupt();
1879                 debug_query_string = NULL;
1880
1881                 /*
1882                  * Make sure we are in a valid memory context during recovery.
1883                  *
1884                  * We use ErrorContext in hopes that it will have some free space
1885                  * even if we're otherwise up against it...
1886                  */
1887                 MemoryContextSwitchTo(ErrorContext);
1888
1889                 /* Do the recovery */
1890                 elog(DEBUG1, "AbortCurrentTransaction");
1891                 AbortCurrentTransaction();
1892
1893                 /*
1894                  * Now return to normal top-level context and clear ErrorContext
1895                  * for next time.
1896                  */
1897                 MemoryContextSwitchTo(TopMemoryContext);
1898                 MemoryContextResetAndDeleteChildren(ErrorContext);
1899
1900                 /*
1901                  * Clear flag to indicate that we got out of error recovery mode
1902                  * successfully.  (Flag was set in elog.c before longjmp().)
1903                  */
1904                 InError = false;
1905
1906                 /*
1907                  * Exit interrupt holdoff section we implicitly established above.
1908                  */
1909                 RESUME_INTERRUPTS();
1910         }
1911
1912         Warn_restart_ready = true;      /* we can now handle elog(ERROR) */
1913
1914         PG_SETMASK(&UnBlockSig);
1915
1916         send_rfq = true;                        /* initially, or after error */
1917
1918         /*
1919          * Non-error queries loop here.
1920          */
1921
1922         for (;;)
1923         {
1924                 /*
1925                  * Release storage left over from prior query cycle, and create a
1926                  * new query input buffer in the cleared QueryContext.
1927                  */
1928                 MemoryContextSwitchTo(QueryContext);
1929                 MemoryContextResetAndDeleteChildren(QueryContext);
1930
1931                 input_message = makeStringInfo();
1932
1933                 /*
1934                  * (1) tell the frontend we're ready for a new query.
1935                  *
1936                  * Note: this includes fflush()'ing the last of the prior output.
1937                  */
1938                 if (send_rfq)
1939                 {
1940                         ReadyForQuery(whereToSendOutput);
1941                         send_rfq = false;
1942                 }
1943
1944                 /* ----------
1945                  * Tell the statistics collector what we've collected
1946                  * so far.
1947                  * ----------
1948                  */
1949                 pgstat_report_tabstat();
1950
1951                 if (IsTransactionBlock())
1952                 {
1953                         set_ps_display("idle in transaction");
1954                         pgstat_report_activity("<IDLE> in transaction");
1955                 }
1956                 else
1957                 {
1958                         set_ps_display("idle");
1959                         pgstat_report_activity("<IDLE>");
1960                 }
1961
1962                 /*
1963                  * (2) deal with pending asynchronous NOTIFY from other backends,
1964                  * and enable async.c's signal handler to execute NOTIFY directly.
1965                  * Then set up other stuff needed before blocking for input.
1966                  */
1967                 QueryCancelPending = false;             /* forget any earlier CANCEL
1968                                                                                  * signal */
1969
1970                 EnableNotifyInterrupt();
1971
1972                 /* Allow "die" interrupt to be processed while waiting */
1973                 ImmediateInterruptOK = true;
1974                 /* and don't forget to detect one that already arrived */
1975                 QueryCancelPending = false;
1976                 CHECK_FOR_INTERRUPTS();
1977
1978                 /*
1979                  * (3) read a command (loop blocks here)
1980                  */
1981                 firstchar = ReadCommand(input_message);
1982
1983                 /*
1984                  * (4) disable async signal conditions again.
1985                  */
1986                 ImmediateInterruptOK = false;
1987                 QueryCancelPending = false;             /* forget any CANCEL signal */
1988
1989                 DisableNotifyInterrupt();
1990
1991                 /*
1992                  * (5) check for any other interesting events that happened while
1993                  * we slept.
1994                  */
1995                 if (got_SIGHUP)
1996                 {
1997                         got_SIGHUP = false;
1998                         ProcessConfigFile(PGC_SIGHUP);
1999                 }
2000
2001                 /*
2002                  * (6) process the command.
2003                  */
2004                 switch (firstchar)
2005                 {
2006                         case 'Q':                       /* simple query */
2007                                 {
2008                                         /*
2009                                          * Process the query string.
2010                                          *
2011                                          * Note: transaction command start/end is now done within
2012                                          * pg_exec_query_string(), not here.
2013                                          */
2014                                         const char *query_string = pq_getmsgstring(input_message);
2015
2016                                         if (log_statement_stats)
2017                                                 ResetUsage();
2018
2019                                         pgstat_report_activity(query_string);
2020
2021                                         pg_exec_query_string(query_string,
2022                                                                                  whereToSendOutput,
2023                                                                                  QueryContext);
2024
2025                                         if (log_statement_stats)
2026                                                 ShowUsage("QUERY STATISTICS");
2027
2028                                         send_rfq = true;
2029                                 }
2030                                 break;
2031
2032                         case 'F':                       /* fastpath function call */
2033                                 /* Tell the collector what we're doing */
2034                                 pgstat_report_activity("<FASTPATH> function call");
2035
2036                                 /* start an xact for this function invocation */
2037                                 start_xact_command();
2038
2039                                 if (HandleFunctionRequest(input_message) == EOF)
2040                                 {
2041                                         /* lost frontend connection during F message input */
2042
2043                                         /*
2044                                          * Reset whereToSendOutput to prevent elog from
2045                                          * attempting to send any more messages to client.
2046                                          */
2047                                         if (whereToSendOutput == Remote)
2048                                                 whereToSendOutput = None;
2049
2050                                         proc_exit(0);
2051                                 }
2052
2053                                 /* commit the function-invocation transaction */
2054                                 finish_xact_command(false);
2055
2056                                 send_rfq = true;
2057                                 break;
2058
2059                                 /*
2060                                  * 'X' means that the frontend is closing down the socket.
2061                                  * EOF means unexpected loss of frontend connection.
2062                                  * Either way, perform normal shutdown.
2063                                  */
2064                         case 'X':
2065                         case EOF:
2066
2067                                 /*
2068                                  * Reset whereToSendOutput to prevent elog from attempting
2069                                  * to send any more messages to client.
2070                                  */
2071                                 if (whereToSendOutput == Remote)
2072                                         whereToSendOutput = None;
2073
2074                                 /*
2075                                  * NOTE: if you are tempted to add more code here, DON'T!
2076                                  * Whatever you had in mind to do should be set up as an
2077                                  * on_proc_exit or on_shmem_exit callback, instead.
2078                                  * Otherwise it will fail to be called during other
2079                                  * backend-shutdown scenarios.
2080                                  */
2081                                 proc_exit(0);
2082
2083                         case 'd':                               /* copy data */
2084                         case 'c':                               /* copy done */
2085                         case 'f':                               /* copy fail */
2086                                 /*
2087                                  * Accept but ignore these messages, per protocol spec;
2088                                  * we probably got here because a COPY failed, and the
2089                                  * frontend is still sending data.
2090                                  */
2091                                 break;
2092
2093                         default:
2094                                 elog(FATAL, "Socket command type %c unknown", firstchar);
2095                 }
2096
2097 #ifdef MEMORY_CONTEXT_CHECKING
2098
2099                 /*
2100                  * Check all memory after each backend loop.  This is a rather
2101                  * weird place to do it, perhaps.
2102                  */
2103                 MemoryContextCheck(TopMemoryContext);
2104 #endif
2105         }                                                       /* end of input-reading loop */
2106
2107         /* can't get here because the above loop never exits */
2108         Assert(false);
2109
2110         return 1;                                       /* keep compiler quiet */
2111 }
2112
2113 #ifndef HAVE_GETRUSAGE
2114 #include "rusagestub.h"
2115 #else
2116 #include <sys/resource.h>
2117 #endif   /* HAVE_GETRUSAGE */
2118
2119 struct rusage Save_r;
2120 struct timeval Save_t;
2121
2122 void
2123 ResetUsage(void)
2124 {
2125         getrusage(RUSAGE_SELF, &Save_r);
2126         gettimeofday(&Save_t, NULL);
2127         ResetBufferUsage();
2128         /* ResetTupleCount(); */
2129 }
2130
2131 void
2132 ShowUsage(const char *title)
2133 {
2134         StringInfoData str;
2135         struct timeval user,
2136                                 sys;
2137         struct timeval elapse_t;
2138         struct rusage r;
2139         char       *bufusage;
2140
2141         getrusage(RUSAGE_SELF, &r);
2142         gettimeofday(&elapse_t, NULL);
2143         memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
2144         memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2145         if (elapse_t.tv_usec < Save_t.tv_usec)
2146         {
2147                 elapse_t.tv_sec--;
2148                 elapse_t.tv_usec += 1000000;
2149         }
2150         if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
2151         {
2152                 r.ru_utime.tv_sec--;
2153                 r.ru_utime.tv_usec += 1000000;
2154         }
2155         if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
2156         {
2157                 r.ru_stime.tv_sec--;
2158                 r.ru_stime.tv_usec += 1000000;
2159         }
2160
2161         /*
2162          * the only stats we don't show here are for memory usage -- i can't
2163          * figure out how to interpret the relevant fields in the rusage
2164          * struct, and they change names across o/s platforms, anyway. if you
2165          * can figure out what the entries mean, you can somehow extract
2166          * resident set size, shared text size, and unshared data and stack
2167          * sizes.
2168          */
2169         initStringInfo(&str);
2170
2171         appendStringInfo(&str, "! system usage stats:\n");
2172         appendStringInfo(&str,
2173                         "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
2174                                          (long) (elapse_t.tv_sec - Save_t.tv_sec),
2175                                          (long) (elapse_t.tv_usec - Save_t.tv_usec),
2176                                          (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
2177                                          (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
2178                                          (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
2179                                          (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
2180         appendStringInfo(&str,
2181                                          "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
2182                                          (long) user.tv_sec,
2183                                          (long) user.tv_usec,
2184                                          (long) sys.tv_sec,
2185                                          (long) sys.tv_usec);
2186 /* BeOS has rusage but only has some fields, and not these... */
2187 #if defined(HAVE_GETRUSAGE)
2188         appendStringInfo(&str,
2189                                          "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
2190                                          r.ru_inblock - Save_r.ru_inblock,
2191         /* they only drink coffee at dec */
2192                                          r.ru_oublock - Save_r.ru_oublock,
2193                                          r.ru_inblock, r.ru_oublock);
2194         appendStringInfo(&str,
2195                   "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
2196                                          r.ru_majflt - Save_r.ru_majflt,
2197                                          r.ru_minflt - Save_r.ru_minflt,
2198                                          r.ru_majflt, r.ru_minflt,
2199                                          r.ru_nswap - Save_r.ru_nswap,
2200                                          r.ru_nswap);
2201         appendStringInfo(&str,
2202          "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
2203                                          r.ru_nsignals - Save_r.ru_nsignals,
2204                                          r.ru_nsignals,
2205                                          r.ru_msgrcv - Save_r.ru_msgrcv,
2206                                          r.ru_msgsnd - Save_r.ru_msgsnd,
2207                                          r.ru_msgrcv, r.ru_msgsnd);
2208         appendStringInfo(&str,
2209                  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
2210                                          r.ru_nvcsw - Save_r.ru_nvcsw,
2211                                          r.ru_nivcsw - Save_r.ru_nivcsw,
2212                                          r.ru_nvcsw, r.ru_nivcsw);
2213 #endif   /* HAVE_GETRUSAGE */
2214
2215         bufusage = ShowBufferUsage();
2216         appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
2217         pfree(bufusage);
2218
2219         /* remove trailing newline */
2220         if (str.data[str.len - 1] == '\n')
2221                 str.data[--str.len] = '\0';
2222
2223         elog(LOG, "%s\n%s", title, str.data);
2224
2225         pfree(str.data);
2226 }
2227
2228 /* ----------------------------------------------------------------
2229  *              CreateCommandTag
2230  *
2231  *              utility to get a string representation of the
2232  *              command operation.
2233  * ----------------------------------------------------------------
2234  */
2235 static const char *
2236 CreateCommandTag(Node *parsetree)
2237 {
2238         const char *tag;
2239
2240         switch (nodeTag(parsetree))
2241         {
2242                 case T_InsertStmt:
2243                         tag = "INSERT";
2244                         break;
2245
2246                 case T_DeleteStmt:
2247                         tag = "DELETE";
2248                         break;
2249
2250                 case T_UpdateStmt:
2251                         tag = "UPDATE";
2252                         break;
2253
2254                 case T_SelectStmt:
2255                         tag = "SELECT";
2256                         break;
2257
2258                 case T_TransactionStmt:
2259                         {
2260                                 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2261
2262                                 switch (stmt->kind)
2263                                 {
2264                                         case TRANS_STMT_BEGIN:
2265                                                 tag = "BEGIN";
2266                                                 break;
2267
2268                                         case TRANS_STMT_START:
2269                                                 tag = "START TRANSACTION";
2270                                                 break;
2271
2272                                         case TRANS_STMT_COMMIT:
2273                                                 tag = "COMMIT";
2274                                                 break;
2275
2276                                         case TRANS_STMT_ROLLBACK:
2277                                                 tag = "ROLLBACK";
2278                                                 break;
2279
2280                                         default:
2281                                                 tag = "???";
2282                                                 break;
2283                                 }
2284                         }
2285                         break;
2286
2287                 case T_DeclareCursorStmt:
2288                         tag = "DECLARE CURSOR";
2289                         break;
2290
2291                 case T_ClosePortalStmt:
2292                         tag = "CLOSE CURSOR";
2293                         break;
2294
2295                 case T_FetchStmt:
2296                         {
2297                                 FetchStmt  *stmt = (FetchStmt *) parsetree;
2298
2299                                 tag = (stmt->ismove) ? "MOVE" : "FETCH";
2300                         }
2301                         break;
2302
2303                 case T_CreateDomainStmt:
2304                         tag = "CREATE DOMAIN";
2305                         break;
2306
2307                 case T_CreateSchemaStmt:
2308                         tag = "CREATE SCHEMA";
2309                         break;
2310
2311                 case T_CreateStmt:
2312                         tag = "CREATE TABLE";
2313                         break;
2314
2315                 case T_DropStmt:
2316                         switch (((DropStmt *) parsetree)->removeType)
2317                         {
2318                                 case DROP_TABLE:
2319                                         tag = "DROP TABLE";
2320                                         break;
2321                                 case DROP_SEQUENCE:
2322                                         tag = "DROP SEQUENCE";
2323                                         break;
2324                                 case DROP_VIEW:
2325                                         tag = "DROP VIEW";
2326                                         break;
2327                                 case DROP_INDEX:
2328                                         tag = "DROP INDEX";
2329                                         break;
2330                                 case DROP_TYPE:
2331                                         tag = "DROP TYPE";
2332                                         break;
2333                                 case DROP_DOMAIN:
2334                                         tag = "DROP DOMAIN";
2335                                         break;
2336                                 case DROP_CONVERSION:
2337                                         tag = "DROP CONVERSION";
2338                                         break;
2339                                 case DROP_SCHEMA:
2340                                         tag = "DROP SCHEMA";
2341                                         break;
2342                                 default:
2343                                         tag = "???";
2344                         }
2345                         break;
2346
2347                 case T_TruncateStmt:
2348                         tag = "TRUNCATE TABLE";
2349                         break;
2350
2351                 case T_CommentStmt:
2352                         tag = "COMMENT";
2353                         break;
2354
2355                 case T_CopyStmt:
2356                         tag = "COPY";
2357                         break;
2358
2359                 case T_RenameStmt:
2360                         if (((RenameStmt *) parsetree)->renameType == RENAME_TRIGGER)
2361                                 tag = "ALTER TRIGGER";
2362                         else
2363                                 tag = "ALTER TABLE";
2364                         break;
2365
2366                 case T_AlterTableStmt:
2367                         tag = "ALTER TABLE";
2368                         break;
2369
2370                 case T_AlterDomainStmt:
2371                         tag = "ALTER DOMAIN";
2372                         break;
2373
2374                 case T_GrantStmt:
2375                         {
2376                                 GrantStmt  *stmt = (GrantStmt *) parsetree;
2377
2378                                 tag = (stmt->is_grant) ? "GRANT" : "REVOKE";
2379                         }
2380                         break;
2381
2382                 case T_DefineStmt:
2383                         switch (((DefineStmt *) parsetree)->kind)
2384                         {
2385                                 case DEFINE_STMT_AGGREGATE:
2386                                         tag = "CREATE AGGREGATE";
2387                                         break;
2388                                 case DEFINE_STMT_OPERATOR:
2389                                         tag = "CREATE OPERATOR";
2390                                         break;
2391                                 case DEFINE_STMT_TYPE:
2392                                         tag = "CREATE TYPE";
2393                                         break;
2394                                 default:
2395                                         tag = "???";
2396                         }
2397                         break;
2398
2399                 case T_CompositeTypeStmt:
2400                         tag = "CREATE TYPE";
2401                         break;
2402
2403                 case T_ViewStmt:
2404                         tag = "CREATE VIEW";
2405                         break;
2406
2407                 case T_CreateFunctionStmt:
2408                         tag = "CREATE FUNCTION";
2409                         break;
2410
2411                 case T_IndexStmt:
2412                         tag = "CREATE INDEX";
2413                         break;
2414
2415                 case T_RuleStmt:
2416                         tag = "CREATE RULE";
2417                         break;
2418
2419                 case T_CreateSeqStmt:
2420                         tag = "CREATE SEQUENCE";
2421                         break;
2422
2423                 case T_AlterSeqStmt:
2424                         tag = "ALTER SEQUENCE";
2425                         break;
2426
2427                 case T_RemoveAggrStmt:
2428                         tag = "DROP AGGREGATE";
2429                         break;
2430
2431                 case T_RemoveFuncStmt:
2432                         tag = "DROP FUNCTION";
2433                         break;
2434
2435                 case T_RemoveOperStmt:
2436                         tag = "DROP OPERATOR";
2437                         break;
2438
2439                 case T_CreatedbStmt:
2440                         tag = "CREATE DATABASE";
2441                         break;
2442
2443                 case T_AlterDatabaseSetStmt:
2444                         tag = "ALTER DATABASE";
2445                         break;
2446
2447                 case T_DropdbStmt:
2448                         tag = "DROP DATABASE";
2449                         break;
2450
2451                 case T_NotifyStmt:
2452                         tag = "NOTIFY";
2453                         break;
2454
2455                 case T_ListenStmt:
2456                         tag = "LISTEN";
2457                         break;
2458
2459                 case T_UnlistenStmt:
2460                         tag = "UNLISTEN";
2461                         break;
2462
2463                 case T_LoadStmt:
2464                         tag = "LOAD";
2465                         break;
2466
2467                 case T_ClusterStmt:
2468                         tag = "CLUSTER";
2469                         break;
2470
2471                 case T_VacuumStmt:
2472                         if (((VacuumStmt *) parsetree)->vacuum)
2473                                 tag = "VACUUM";
2474                         else
2475                                 tag = "ANALYZE";
2476                         break;
2477
2478                 case T_ExplainStmt:
2479                         tag = "EXPLAIN";
2480                         break;
2481
2482                 case T_VariableSetStmt:
2483                         tag = "SET";
2484                         break;
2485
2486                 case T_VariableShowStmt:
2487                         tag = "SHOW";
2488                         break;
2489
2490                 case T_VariableResetStmt:
2491                         tag = "RESET";
2492                         break;
2493
2494                 case T_CreateTrigStmt:
2495                         tag = "CREATE TRIGGER";
2496                         break;
2497
2498                 case T_DropPropertyStmt:
2499                         switch (((DropPropertyStmt *) parsetree)->removeType)
2500                         {
2501                                 case DROP_TRIGGER:
2502                                         tag = "DROP TRIGGER";
2503                                         break;
2504                                 case DROP_RULE:
2505                                         tag = "DROP RULE";
2506                                         break;
2507                                 default:
2508                                         tag = "???";
2509                         }
2510                         break;
2511
2512                 case T_CreatePLangStmt:
2513                         tag = "CREATE LANGUAGE";
2514                         break;
2515
2516                 case T_DropPLangStmt:
2517                         tag = "DROP LANGUAGE";
2518                         break;
2519
2520                 case T_CreateUserStmt:
2521                         tag = "CREATE USER";
2522                         break;
2523
2524                 case T_AlterUserStmt:
2525                         tag = "ALTER USER";
2526                         break;
2527
2528                 case T_AlterUserSetStmt:
2529                         tag = "ALTER USER";
2530                         break;
2531
2532                 case T_DropUserStmt:
2533                         tag = "DROP USER";
2534                         break;
2535
2536                 case T_LockStmt:
2537                         tag = "LOCK TABLE";
2538                         break;
2539
2540                 case T_ConstraintsSetStmt:
2541                         tag = "SET CONSTRAINTS";
2542                         break;
2543
2544                 case T_CreateGroupStmt:
2545                         tag = "CREATE GROUP";
2546                         break;
2547
2548                 case T_AlterGroupStmt:
2549                         tag = "ALTER GROUP";
2550                         break;
2551
2552                 case T_DropGroupStmt:
2553                         tag = "DROP GROUP";
2554                         break;
2555
2556                 case T_CheckPointStmt:
2557                         tag = "CHECKPOINT";
2558                         break;
2559
2560                 case T_ReindexStmt:
2561                         tag = "REINDEX";
2562                         break;
2563
2564                 case T_CreateConversionStmt:
2565                         tag = "CREATE CONVERSION";
2566                         break;
2567
2568                 case T_CreateCastStmt:
2569                         tag = "CREATE CAST";
2570                         break;
2571
2572                 case T_DropCastStmt:
2573                         tag = "DROP CAST";
2574                         break;
2575
2576                 case T_CreateOpClassStmt:
2577                         tag = "CREATE OPERATOR CLASS";
2578                         break;
2579
2580                 case T_RemoveOpClassStmt:
2581                         tag = "DROP OPERATOR CLASS";
2582                         break;
2583
2584                 case T_PrepareStmt:
2585                         tag = "PREPARE";
2586                         break;
2587
2588                 case T_ExecuteStmt:
2589                         tag = "EXECUTE";
2590                         break;
2591
2592                 case T_DeallocateStmt:
2593                         tag = "DEALLOCATE";
2594                         break;
2595
2596                 default:
2597                         elog(LOG, "CreateCommandTag: unknown parse node type %d",
2598                                  nodeTag(parsetree));
2599                         tag = "???";
2600                         break;
2601         }
2602
2603         return tag;
2604 }