OSDN Git Service

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