]> granicus.if.org Git - postgresql/blob - src/backend/tcop/postgres.c
e276083788daf17eced61bd5868d83fe3a20affe
[postgresql] / src / backend / tcop / postgres.c
1 /*-------------------------------------------------------------------------
2  *
3  * postgres.c
4  *        POSTGRES C Backend Interface
5  *
6  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
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.179 2000/10/07 04:00:41 tgl Exp $
12  *
13  * NOTES
14  *        this is the "main" module of the postgres backend and
15  *        hence the main module of the "traffic cop".
16  *
17  *-------------------------------------------------------------------------
18  */
19
20 #include "postgres.h"
21
22 #include <unistd.h>
23 #include <signal.h>
24 #include <time.h>
25 #include <sys/time.h>
26 #include <sys/types.h>
27 #include <fcntl.h>
28 #include <sys/socket.h>
29 #include <errno.h>
30 #if HAVE_SYS_SELECT_H
31 #include <sys/select.h>
32 #endif   /* aix */
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <netdb.h>
36 #ifdef HAVE_GETOPT_H
37 #include <getopt.h>
38 #endif
39
40 #include "commands/async.h"
41 #include "commands/trigger.h"
42 #include "commands/variable.h"
43 #include "libpq/libpq.h"
44 #include "libpq/pqformat.h"
45 #include "libpq/pqsignal.h"
46 #include "miscadmin.h"
47 #include "nodes/print.h"
48 #include "optimizer/cost.h"
49 #include "optimizer/planner.h"
50 #include "parser/analyze.h"
51 #include "parser/parse.h"
52 #include "parser/parser.h"
53 #include "rewrite/rewriteHandler.h"
54 #include "tcop/fastpath.h"
55 #include "tcop/pquery.h"
56 #include "tcop/tcopprot.h"
57 #include "tcop/utility.h"
58 #include "storage/proc.h"
59 #include "utils/exc.h"
60 #include "utils/guc.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #include "utils/temprel.h"
64 #ifdef MULTIBYTE
65 #include "mb/pg_wchar.h"
66 #endif
67
68
69 /* ----------------
70  *              global variables
71  * ----------------
72  */
73
74 /*
75  * XXX For ps display. That stuff needs to be cleaned up.
76  */
77 bool HostnameLookup;
78 bool ShowPortNumber;
79
80 bool Log_connections = false;
81
82 CommandDest whereToSendOutput = Debug;
83
84
85 extern void StartupXLOG(void);
86 extern void ShutdownXLOG(void);
87
88 extern void HandleDeadLock(SIGNAL_ARGS);
89
90 extern char XLogDir[];
91 extern char ControlFilePath[];
92
93 static bool     dontExecute = false;
94
95 /* note: these declarations had better match tcopprot.h */
96 DLLIMPORT sigjmp_buf Warn_restart;
97
98 bool            Warn_restart_ready = false;
99 bool            InError = false;
100 bool            ExitAfterAbort = false;
101
102 static bool EchoQuery = false;  /* default don't echo */
103 char            pg_pathname[MAXPGPATH];
104 FILE       *StatFp = NULL;
105
106 /* ----------------
107  *              people who want to use EOF should #define DONTUSENEWLINE in
108  *              tcop/tcopdebug.h
109  * ----------------
110  */
111 #ifndef TCOP_DONTUSENEWLINE
112 int                     UseNewLine = 1;         /* Use newlines query delimiters (the
113                                                                  * default) */
114
115 #else
116 int                     UseNewLine = 0;         /* Use EOF as query delimiters */
117
118 #endif   /* TCOP_DONTUSENEWLINE */
119
120 /*
121 ** Flags for expensive function optimization -- JMH 3/9/92
122 */
123 int                     XfuncMode = 0;
124
125 /* ----------------------------------------------------------------
126  *              decls for routines only used in this file
127  * ----------------------------------------------------------------
128  */
129 static int      InteractiveBackend(StringInfo inBuf);
130 static int      SocketBackend(StringInfo inBuf);
131 static int      ReadCommand(StringInfo inBuf);
132 static List *pg_parse_query(char *query_string, Oid *typev, int nargs);
133 static List *pg_analyze_and_rewrite(Node *parsetree);
134 static void start_xact_command(void);
135 static void finish_xact_command(void);
136 static void SigHupHandler(SIGNAL_ARGS);
137 static void FloatExceptionHandler(SIGNAL_ARGS);
138 static void quickdie(SIGNAL_ARGS);
139
140 /*
141  * Flag to mark SIGHUP. Whenever the main loop comes around it
142  * will reread the configuration file. (Better than doing the
143  * reading in the signal handler, ey?)
144  */
145 static volatile bool got_SIGHUP = false;
146
147
148 /* ----------------------------------------------------------------
149  *              routines to obtain user input
150  * ----------------------------------------------------------------
151  */
152
153 /* ----------------
154  *      InteractiveBackend() is called for user interactive connections
155  *      the string entered by the user is placed in its parameter inBuf.
156  *
157  *      EOF is returned if end-of-file input is seen; time to shut down.
158  * ----------------
159  */
160
161 static int
162 InteractiveBackend(StringInfo inBuf)
163 {
164         int                     c;                              /* character read from getc() */
165         bool            end = false;    /* end-of-input flag */
166         bool            backslashSeen = false;  /* have we seen a \ ? */
167
168         /* ----------------
169          *      display a prompt and obtain input from the user
170          * ----------------
171          */
172         printf("backend> ");
173         fflush(stdout);
174
175         /* Reset inBuf to empty */
176         inBuf->len = 0;
177         inBuf->data[0] = '\0';
178
179         for (;;)
180         {
181                 if (UseNewLine)
182                 {
183                         /* ----------------
184                          *      if we are using \n as a delimiter, then read
185                          *      characters until the \n.
186                          * ----------------
187                          */
188                         while ((c = getc(stdin)) != EOF)
189                         {
190                                 if (c == '\n')
191                                 {
192                                         if (backslashSeen)
193                                         {
194                                                 /* discard backslash from inBuf */
195                                                 inBuf->data[--inBuf->len] = '\0';
196                                                 backslashSeen = false;
197                                                 continue;
198                                         }
199                                         else
200                                         {
201                                                 /* keep the newline character */
202                                                 appendStringInfoChar(inBuf, '\n');
203                                                 break;
204                                         }
205                                 }
206                                 else if (c == '\\')
207                                         backslashSeen = true;
208                                 else
209                                         backslashSeen = false;
210
211                                 appendStringInfoChar(inBuf, (char) c);
212                         }
213
214                         if (c == EOF)
215                                 end = true;
216                 }
217                 else
218                 {
219                         /* ----------------
220                          *      otherwise read characters until EOF.
221                          * ----------------
222                          */
223                         while ((c = getc(stdin)) != EOF)
224                                 appendStringInfoChar(inBuf, (char) c);
225
226                         if (inBuf->len == 0)
227                                 end = true;
228                 }
229
230                 if (end)
231                         return EOF;
232
233                 /* ----------------
234                  *      otherwise we have a user query so process it.
235                  * ----------------
236                  */
237                 break;
238         }
239
240         /* ----------------
241          *      if the query echo flag was given, print the query..
242          * ----------------
243          */
244         if (EchoQuery)
245                 printf("query: %s\n", inBuf->data);
246         fflush(stdout);
247
248         return 'Q';
249 }
250
251 /* ----------------
252  *      SocketBackend()         Is called for frontend-backend connections
253  *
254  *      If the input is a query (case 'Q') then the string entered by
255  *      the user is placed in its parameter inBuf.
256  *
257  *      If the input is a fastpath function call (case 'F') then
258  *      the function call is processed in HandleFunctionRequest()
259  *      (now called from PostgresMain()).
260  *
261  *      EOF is returned if the connection is lost.
262  * ----------------
263  */
264
265 static int
266 SocketBackend(StringInfo inBuf)
267 {
268         char            qtype;
269         char            result = '\0';
270
271         /* ----------------
272          *      get input from the frontend
273          * ----------------
274          */
275         qtype = '?';
276         if (pq_getbytes(&qtype, 1) == EOF)
277                 return EOF;
278
279         switch (qtype)
280         {
281                         /* ----------------
282                          *      'Q': user entered a query
283                          * ----------------
284                          */
285                 case 'Q':
286                         if (pq_getstr(inBuf))
287                                 return EOF;
288                         result = 'Q';
289                         break;
290
291                         /* ----------------
292                          *      'F':  calling user/system functions
293                          * ----------------
294                          */
295                 case 'F':
296                         if (pq_getstr(inBuf))
297                                 return EOF;             /* ignore "string" at start of F message */
298                         result = 'F';
299                         break;
300
301                         /* ----------------
302                          *      'X':  frontend is exiting
303                          * ----------------
304                          */
305                 case 'X':
306                         result = 'X';
307                         break;
308
309                         /* ----------------
310                          *      otherwise we got garbage from the frontend.
311                          *
312                          *      XXX are we certain that we want to do an elog(FATAL) here?
313                          *              -cim 1/24/90
314                          * ----------------
315                          */
316                 default:
317                         elog(FATAL, "Socket command type %c unknown", qtype);
318                         break;
319         }
320         return result;
321 }
322
323 /* ----------------
324  *              ReadCommand reads a command from either the frontend or
325  *              standard input, places it in inBuf, and returns a char
326  *              representing whether the string is a 'Q'uery or a 'F'astpath
327  *              call.  EOF is returned if end of file.
328  * ----------------
329  */
330 static int
331 ReadCommand(StringInfo inBuf)
332 {
333         int                     result;
334
335         if (IsUnderPostmaster)
336                 result = SocketBackend(inBuf);
337         else
338                 result = InteractiveBackend(inBuf);
339         return result;
340 }
341
342
343 /*
344  * Parse a query string and pass it through the rewriter.
345  *
346  * A list of Query nodes is returned, since the string might contain
347  * multiple queries and/or the rewriter might expand one query to several.
348  *
349  * NOTE: this routine is no longer used for processing interactive queries,
350  * but it is still needed for parsing of SQL function bodies.
351  */
352 List *
353 pg_parse_and_rewrite(char *query_string,        /* string to execute */
354                                          Oid *typev,                    /* parameter types */
355                                          int nargs)                             /* number of parameters */
356 {
357         List       *raw_parsetree_list;
358         List       *querytree_list;
359         List       *list_item;
360
361         /* ----------------
362          *      (1) parse the request string into a list of raw parse trees.
363          * ----------------
364          */
365         raw_parsetree_list = pg_parse_query(query_string, typev, nargs);
366
367         /* ----------------
368          *      (2) Do parse analysis and rule rewrite.
369          * ----------------
370          */
371         querytree_list = NIL;
372         foreach(list_item, raw_parsetree_list)
373         {
374                 Node   *parsetree = (Node *) lfirst(list_item);
375
376                 querytree_list = nconc(querytree_list,
377                                                            pg_analyze_and_rewrite(parsetree));
378         }
379
380         return querytree_list;
381 }
382
383 /*
384  * Do raw parsing (only).
385  *
386  * A list of parsetrees is returned, since there might be multiple
387  * commands in the given string.
388  *
389  * NOTE: for interactive queries, it is important to keep this routine
390  * separate from the analysis & rewrite stages.  Analysis and rewriting
391  * cannot be done in an aborted transaction, since they require access to
392  * database tables.  So, we rely on the raw parser to determine whether
393  * we've seen a COMMIT or ABORT command; when we are in abort state, other
394  * commands are not processed any further than the raw parse stage.
395  */
396 static List *
397 pg_parse_query(char *query_string, Oid *typev, int nargs)
398 {
399         List       *raw_parsetree_list;
400
401         if (Debug_print_query)
402                 elog(DEBUG, "query: %s", query_string);
403
404         if (Show_parser_stats)
405                 ResetUsage();
406
407         raw_parsetree_list = parser(query_string, typev, nargs);
408
409         if (Show_parser_stats)
410         {
411                 fprintf(StatFp, "PARSER STATISTICS\n");
412                 ShowUsage();
413         }
414
415         return raw_parsetree_list;
416 }
417
418 /*
419  * Given a raw parsetree (gram.y output), perform parse analysis and
420  * rule rewriting.
421  *
422  * A list of Query nodes is returned, since either the analyzer or the
423  * rewriter might expand one query to several.
424  *
425  * NOTE: for reasons mentioned above, this must be separate from raw parsing.
426  */
427 static List *
428 pg_analyze_and_rewrite(Node *parsetree)
429 {
430         List       *querytree_list;
431         List       *list_item;
432         Query      *querytree;
433         List       *new_list;
434
435         /* ----------------
436          *      (1) Perform parse analysis.
437          * ----------------
438          */
439         if (Show_parser_stats)
440                 ResetUsage();
441
442         querytree_list = parse_analyze(parsetree, NULL);
443
444         if (Show_parser_stats)
445         {
446                 fprintf(StatFp, "PARSE ANALYSIS STATISTICS\n");
447                 ShowUsage();
448                 ResetUsage();
449         }
450
451         /* ----------------
452          *      (2) Rewrite the queries, as necessary
453          *
454          *      rewritten queries are collected in new_list.  Note there may be
455          *      more or fewer than in the original list.
456          * ----------------
457          */
458         new_list = NIL;
459         foreach(list_item, querytree_list)
460         {
461                 querytree = (Query *) lfirst(list_item);
462
463                 if (Debug_print_parse)
464                 {
465                         if (Debug_pretty_print)
466                         {
467                                 elog(DEBUG, "parse tree:");
468                                 nodeDisplay(querytree);
469                         }
470                         else
471                                 elog(DEBUG, "parse tree: %s", nodeToString(querytree));
472                 }
473
474                 if (querytree->commandType == CMD_UTILITY)
475                 {
476                         /* don't rewrite utilities, just dump 'em into new_list */
477                         new_list = lappend(new_list, querytree);
478                 }
479                 else
480                 {
481                         /* rewrite regular queries */
482                         List       *rewritten = QueryRewrite(querytree);
483
484                         new_list = nconc(new_list, rewritten);
485                 }
486         }
487
488         querytree_list = new_list;
489
490         if (Show_parser_stats)
491         {
492                 fprintf(StatFp, "REWRITER STATISTICS\n");
493                 ShowUsage();
494         }
495
496 #ifdef COPY_PARSE_PLAN_TREES
497         /* Optional debugging check: pass querytree output through copyObject() */
498         new_list = (List *) copyObject(querytree_list);
499         /* This checks both copyObject() and the equal() routines... */
500         if (! equal(new_list, querytree_list))
501                 elog(NOTICE, "pg_analyze_and_rewrite: copyObject failed on parse tree");
502         else
503                 querytree_list = new_list;
504 #endif
505
506         if (Debug_print_rewritten)
507         {
508                 if (Debug_pretty_print)
509                 {
510                         elog(DEBUG, "rewritten parse tree:");
511                         foreach(list_item, querytree_list)
512                         {
513                                 querytree = (Query *) lfirst(list_item);
514                                 nodeDisplay(querytree);
515                                 printf("\n");
516                         }
517                 }
518                 else
519                 {
520                         elog(DEBUG, "rewritten parse tree:");
521                         foreach(list_item, querytree_list)
522                         {
523                                 querytree = (Query *) lfirst(list_item);
524                                 elog(DEBUG, "%s", nodeToString(querytree));
525                         }
526                 }
527         }
528
529         return querytree_list;
530 }
531
532
533 /* Generate a plan for a single query. */
534 Plan *
535 pg_plan_query(Query *querytree)
536 {
537         Plan       *plan;
538
539         /* Utility commands have no plans. */
540         if (querytree->commandType == CMD_UTILITY)
541                 return NULL;
542
543         if (Show_planner_stats)
544                 ResetUsage();
545
546         /* call that optimizer */
547         plan = planner(querytree);
548
549         if (Show_planner_stats)
550         {
551                 fprintf(stderr, "PLANNER STATISTICS\n");
552                 ShowUsage();
553         }
554
555 #ifdef COPY_PARSE_PLAN_TREES
556         /* Optional debugging check: pass plan output through copyObject() */
557         {
558                 Plan   *new_plan = (Plan *) copyObject(plan);
559
560                 /* equal() currently does not have routines to compare Plan nodes,
561                  * so don't try to test equality here.  Perhaps fix someday?
562                  */
563 #ifdef NOT_USED
564                 /* This checks both copyObject() and the equal() routines... */
565                 if (! equal(new_plan, plan))
566                         elog(NOTICE, "pg_plan_query: copyObject failed on plan tree");
567                 else
568 #endif
569                         plan = new_plan;
570         }
571 #endif
572
573         /* ----------------
574          *      Print plan if debugging.
575          * ----------------
576          */
577         if (Debug_print_plan)
578         {
579                 if (Debug_pretty_print)
580                 {
581                         elog(DEBUG, "plan:");
582                         nodeDisplay(plan);
583                 }
584                 else
585                         elog(DEBUG, "plan: %s", nodeToString(plan));
586         }
587
588         return plan;
589 }
590
591
592 /* ----------------------------------------------------------------
593  *              pg_exec_query_string()
594  *
595  *              Takes a querystring, runs the parser/utilities or
596  *              parser/planner/executor over it as necessary.
597  *
598  * Assumptions:
599  *
600  * At call, we are not inside a transaction command.
601  *
602  * The CurrentMemoryContext after starting a transaction command must be
603  * appropriate for execution of individual queries (typically this will be
604  * TransactionCommandContext).  Note that this routine resets that context
605  * after each individual query, so don't store anything there that
606  * must outlive the call!
607  *
608  * parse_context references a context suitable for holding the
609  * parse/rewrite trees (typically this will be QueryContext).
610  * This context *must* be longer-lived than the transaction context!
611  * In fact, if the query string might contain BEGIN/COMMIT commands,
612  * parse_context had better outlive TopTransactionContext!
613  *
614  * We could have hard-wired knowledge about QueryContext and
615  * TransactionCommandContext into this routine, but it seems better
616  * not to, in case callers from outside this module need to use some
617  * other contexts.
618  *
619  * ----------------------------------------------------------------
620  */
621
622 void
623 pg_exec_query_string(char *query_string,        /* string to execute */
624                                          CommandDest dest,              /* where results should go */
625                                          MemoryContext parse_context) /* context for parsetrees */
626 {
627         bool            xact_started;
628         MemoryContext oldcontext;
629         List       *parsetree_list,
630                            *parsetree_item;
631
632         /*
633          * Start up a transaction command.  All queries generated by the
634          * query_string will be in this same command block, *unless* we find
635          * a BEGIN/COMMIT/ABORT statement; we have to force a new xact command
636          * after one of those, else bad things will happen in xact.c.
637          * (Note that this will possibly change current memory context.)
638          */
639         start_xact_command();
640         xact_started = true;
641
642         /*
643          * parse_context *must* be different from the execution memory context,
644          * else the context reset at the bottom of the loop will destroy the
645          * parsetree list.  (We really ought to check that parse_context isn't a
646          * child of CurrentMemoryContext either, but that would take more cycles
647          * than it's likely to be worth.)
648          */
649         Assert(parse_context != CurrentMemoryContext);
650
651         /*
652          * Switch to appropriate context for constructing parsetrees.
653          */
654         oldcontext = MemoryContextSwitchTo(parse_context);
655
656         /*
657          * Do basic parsing of the query or queries (this should be safe
658          * even if we are in aborted transaction state!)
659          */
660         parsetree_list = pg_parse_query(query_string, NULL, 0);
661
662         /*
663          * Switch back to execution context to enter the loop.
664          */
665         MemoryContextSwitchTo(oldcontext);
666
667         /*
668          * Run through the parsetree(s) and process each one.
669          */
670         foreach(parsetree_item, parsetree_list)
671         {
672                 Node   *parsetree = (Node *) lfirst(parsetree_item);
673                 bool    isTransactionStmt;
674                 List   *querytree_list,
675                            *querytree_item;
676
677                 /* Transaction control statements need some special handling */
678                 isTransactionStmt = IsA(parsetree, TransactionStmt);
679
680                 /*
681                  * If we are in an aborted transaction, ignore all commands except
682                  * COMMIT/ABORT.  It is important that this test occur before we
683                  * try to do parse analysis, rewrite, or planning, since all those
684                  * phases try to do database accesses, which may fail in abort state.
685                  * (It might be safe to allow some additional utility commands in
686                  * this state, but not many...)
687                  */
688                 if (IsAbortedTransactionBlockState())
689                 {
690                         bool    allowit = false;
691
692                         if (isTransactionStmt)
693                         {
694                                 TransactionStmt *stmt = (TransactionStmt *) parsetree;
695
696                                 switch (stmt->command)
697                                 {
698                                         case COMMIT:
699                                         case ROLLBACK:
700                                                 allowit = true;
701                                                 break;
702                                         default:
703                                                 break;
704                                 }
705                         }
706
707                         if (! allowit)
708                         {
709                                 /* ----------------
710                                  *       the EndCommand() stuff is to tell the frontend
711                                  *       that the command ended. -cim 6/1/90
712                                  * ----------------
713                                  */
714                                 char       *tag = "*ABORT STATE*";
715
716                                 elog(NOTICE, "current transaction is aborted, "
717                                          "queries ignored until end of transaction block");
718
719                                 EndCommand(tag, dest);
720
721                                 /*
722                                  * We continue in the loop, on the off chance that there
723                                  * is a COMMIT or ROLLBACK utility command later in the
724                                  * query string.
725                                  */
726                                 continue;
727                         }
728                 }
729
730                 /* Make sure we are in a transaction command */
731                 if (! xact_started)
732                 {
733                         start_xact_command();
734                         xact_started = true;
735                 }
736
737                 /* If we got a cancel signal in parsing or prior command, quit */
738                 if (QueryCancel)
739                         CancelQuery();
740
741                 /*
742                  * OK to analyze and rewrite this query.
743                  *
744                  * Switch to appropriate context for constructing querytrees
745                  * (again, these must outlive the execution context).
746                  */
747                 oldcontext = MemoryContextSwitchTo(parse_context);
748
749                 querytree_list = pg_analyze_and_rewrite(parsetree);
750
751                 /*
752                  * Switch back to execution context for planning and execution.
753                  */
754                 MemoryContextSwitchTo(oldcontext);
755
756                 /*
757                  * Inner loop handles the individual queries generated from a
758                  * single parsetree by analysis and rewrite.
759                  */
760                 foreach(querytree_item, querytree_list)
761                 {
762                         Query      *querytree = (Query *) lfirst(querytree_item);
763
764                         /* Make sure we are in a transaction command */
765                         if (! xact_started)
766                         {
767                                 start_xact_command();
768                                 xact_started = true;
769                         }
770
771                         /* If we got a cancel signal in analysis or prior command, quit */
772                         if (QueryCancel)
773                                 CancelQuery();
774
775                         if (querytree->commandType == CMD_UTILITY)
776                         {
777                                 /* ----------------
778                                  *       process utility functions (create, destroy, etc..)
779                                  * ----------------
780                                  */
781                                 if (Debug_print_query)
782                                         elog(DEBUG, "ProcessUtility: %s", query_string);
783                                 else if (DebugLvl > 1)
784                                         elog(DEBUG, "ProcessUtility");
785
786                                 ProcessUtility(querytree->utilityStmt, dest);
787                         }
788                         else
789                         {
790                                 /* ----------------
791                                  *       process a plannable query.
792                                  * ----------------
793                                  */
794                                 Plan       *plan;
795
796                                 plan = pg_plan_query(querytree);
797
798                                 /* if we got a cancel signal whilst planning, quit */
799                                 if (QueryCancel)
800                                         CancelQuery();
801
802                                 /* Initialize snapshot state for query */
803                                 SetQuerySnapshot();
804
805                                 /*
806                                  * execute the plan
807                                  */
808                                 if (Show_executor_stats)
809                                         ResetUsage();
810
811                                 if (dontExecute)
812                                 {
813                                         /* don't execute it, just show the query plan */
814                                         print_plan(plan, querytree);
815                                 }
816                                 else
817                                 {
818                                         if (DebugLvl > 1)
819                                                 elog(DEBUG, "ProcessQuery");
820                                         ProcessQuery(querytree, plan, dest);
821                                 }
822
823                                 if (Show_executor_stats)
824                                 {
825                                         fprintf(stderr, "EXECUTOR STATISTICS\n");
826                                         ShowUsage();
827                                 }
828                         }
829
830                         /*
831                          * In a query block, we want to increment the command counter
832                          * between queries so that the effects of early queries are
833                          * visible to subsequent ones.  In particular we'd better
834                          * do so before checking constraints.
835                          */
836                         if (!isTransactionStmt)
837                                 CommandCounterIncrement();
838
839                         /*
840                          * Clear the execution context to recover temporary
841                          * memory used by the query.  NOTE: if query string contains
842                          * BEGIN/COMMIT transaction commands, execution context may
843                          * now be different from what we were originally passed;
844                          * so be careful to clear current context not "oldcontext".
845                          */
846                         Assert(parse_context != CurrentMemoryContext);
847
848                         MemoryContextResetAndDeleteChildren(CurrentMemoryContext);
849
850                         /*
851                          * If this was a transaction control statement, commit it
852                          * and arrange to start a new xact command for the next
853                          * command (if any).
854                          */
855                         if (isTransactionStmt)
856                         {
857                                 finish_xact_command();
858                                 xact_started = false;
859                         }
860
861                 } /* end loop over queries generated from a parsetree */
862         } /* end loop over parsetrees */
863
864         /*
865          * Close down transaction statement, if one is open.
866          */
867         if (xact_started)
868                 finish_xact_command();
869 }
870
871 /*
872  * Convenience routines for starting/committing a single command.
873  */
874 static void
875 start_xact_command(void)
876 {
877         if (DebugLvl >= 1)
878                 elog(DEBUG, "StartTransactionCommand");
879         StartTransactionCommand();
880 }
881
882 static void
883 finish_xact_command(void)
884 {
885         /* Invoke IMMEDIATE constraint triggers */
886         DeferredTriggerEndQuery();
887
888         /* Now commit the command */
889         if (DebugLvl >= 1)
890                 elog(DEBUG, "CommitTransactionCommand");
891         set_ps_display("commit");       /* XXX probably the wrong place to do this */
892         CommitTransactionCommand();
893
894 #ifdef SHOW_MEMORY_STATS
895         /* Print mem stats at each commit for leak tracking */
896         if (ShowStats)
897                 MemoryContextStats(TopMemoryContext);
898 #endif
899 }
900
901
902 /* --------------------------------
903  *              signal handler routines used in PostgresMain()
904  *
905  *              handle_warn() catches SIGQUIT.  It forces control back to the main
906  *              loop, just as if an internal error (elog(ERROR,...)) had occurred.
907  *              elog() used to actually use kill(2) to induce a SIGQUIT to get here!
908  *              But that's not 100% reliable on some systems, so now it does its own
909  *              siglongjmp() instead.
910  *              We still provide the signal catcher so that an error quit can be
911  *              forced externally.      This should be done only with great caution,
912  *              however, since an asynchronous signal could leave the system in
913  *              who-knows-what inconsistent state.
914  *
915  *              quickdie() occurs when signalled by the postmaster.
916  *              Some backend has bought the farm,
917  *              so we need to stop what we're doing and exit.
918  *
919  *              die() performs an orderly cleanup via proc_exit()
920  * --------------------------------
921  */
922
923 void
924 handle_warn(SIGNAL_ARGS)
925 {
926         siglongjmp(Warn_restart, 1);
927 }
928
929 static void
930 quickdie(SIGNAL_ARGS)
931 {
932         PG_SETMASK(&BlockSig);
933         elog(NOTICE, "Message from PostgreSQL backend:"
934                  "\n\tThe Postmaster has informed me that some other backend"
935                  " died abnormally and possibly corrupted shared memory."
936                  "\n\tI have rolled back the current transaction and am"
937                  " going to terminate your database system connection and exit."
938         "\n\tPlease reconnect to the database system and repeat your query.");
939
940
941         /*
942          * DO NOT proc_exit(0) -- we're here because shared memory may be
943          * corrupted, so we don't want to flush any shared state to stable
944          * storage.  Just nail the windows shut and get out of town.
945          */
946
947         exit(1);
948 }
949
950 /*
951  * Abort transaction and exit
952  */
953 void
954 die(SIGNAL_ARGS)
955 {
956         PG_SETMASK(&BlockSig);
957
958         /*
959          * If ERROR/FATAL is in progress...
960          */
961         if (InError)
962         {
963                 ExitAfterAbort = true;
964                 return;
965         }
966         elog(FATAL, "The system is shutting down");
967 }
968
969 /* signal handler for floating point exception */
970 static void
971 FloatExceptionHandler(SIGNAL_ARGS)
972 {
973         elog(ERROR, "floating point exception!"
974                  " The last floating point operation either exceeded legal ranges"
975                  " or was a divide by zero");
976 }
977
978 /* signal handler for query cancel signal from postmaster */
979 static void
980 QueryCancelHandler(SIGNAL_ARGS)
981 {
982         QueryCancel = true;
983         LockWaitCancel();
984 }
985
986 void
987 CancelQuery(void)
988 {
989
990         /*
991          * QueryCancel flag will be reset in main loop, which we reach by
992          * longjmp from elog().
993          */
994         elog(ERROR, "Query was cancelled.");
995 }
996
997 static void
998 SigHupHandler(SIGNAL_ARGS)
999 {
1000         got_SIGHUP = true;
1001 }
1002
1003
1004 static void
1005 usage(char *progname)
1006 {
1007         fprintf(stderr,
1008                         "Usage: %s [options] [dbname]\n", progname);
1009 #ifdef USE_ASSERT_CHECKING
1010         fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
1011 #endif
1012         fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
1013         fprintf(stderr, "\t-C \t\tsuppress version info\n");
1014         fprintf(stderr, "\t-D dir\t\tdata directory\n");
1015         fprintf(stderr, "\t-E \t\techo query before execution\n");
1016         fprintf(stderr, "\t-F \t\tturn fsync off\n");
1017         fprintf(stderr, "\t-L \t\tturn off locking\n");
1018         fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
1019         fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
1020         fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
1021         fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
1022         fprintf(stderr, "\t-T options\tspecify pg_options\n");
1023         fprintf(stderr, "\t-W sec\t\twait N seconds to allow attach from a debugger\n");
1024         fprintf(stderr, "\t-d [1-5]\tset debug level\n");
1025         fprintf(stderr, "\t-e \t\tturn on European date format\n");
1026         fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
1027         fprintf(stderr, "\t-i \t\tdon't execute queries\n");
1028         fprintf(stderr, "\t-o file\t\tsend stdout and stderr to given filename\n");
1029         fprintf(stderr, "\t-p database\tbackend is started under a postmaster\n");
1030         fprintf(stderr, "\t-s \t\tshow stats after each query\n");
1031         fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
1032         fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
1033 }
1034
1035 /* ----------------------------------------------------------------
1036  * PostgresMain
1037  *     postgres main loop -- all backends, interactive or otherwise start here
1038  *
1039  * argc/argv are the command line arguments to be used.  When being forked
1040  * by the postmaster, these are not the original argv array of the process.
1041  * real_argc/real_argv point to the original argv array, which is needed by
1042  * `ps' display on some platforms. username is the (possibly authenticated)
1043  * PostgreSQL user name to be used for the session.
1044  * ----------------------------------------------------------------
1045  */
1046 int
1047 PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[], const char * username)
1048 {
1049         int                     flag;
1050
1051         const char         *DBName = NULL;
1052         bool            secure = true;
1053         int                     errs = 0;
1054
1055         int                     firstchar;
1056         StringInfo      parser_input;
1057
1058         char       *remote_host;
1059         unsigned short remote_port;
1060
1061         extern int      optind;
1062         extern char *optarg;
1063         extern int      DebugLvl;
1064
1065         /*
1066          * Fire up essential subsystems: error and memory management
1067          *
1068          * If we are running under the postmaster, this is done already.
1069          */
1070         if (!IsUnderPostmaster)
1071         {
1072                 EnableExceptionHandling(true);
1073                 MemoryContextInit();
1074         }
1075
1076         /*
1077          * Set default values for command-line options.
1078          */
1079         Noversion = false;
1080         EchoQuery = false;
1081
1082         if (!IsUnderPostmaster)
1083         {
1084                 ResetAllOptions();
1085                 if (getenv("PGDATA"))
1086                         DataDir = strdup(getenv("PGDATA"));
1087         }
1088         StatFp = stderr;
1089
1090         SetProcessingMode(InitProcessing);
1091
1092         /* Check for PGDATESTYLE environment variable */
1093         set_default_datestyle();
1094
1095         /* ----------------
1096          *      parse command line arguments
1097          *
1098          *      There are now two styles of command line layout for the backend:
1099          *
1100          *      For interactive use (not started from postmaster) the format is
1101          *              postgres [switches] [databasename]
1102          *      If the databasename is omitted it is taken to be the user name.
1103          *
1104          *      When started from the postmaster, the format is
1105          *              postgres [secure switches] -p databasename [insecure switches]
1106          *      Switches appearing after -p came from the client (via "options"
1107          *      field of connection request).  For security reasons we restrict
1108          *      what these switches can do.
1109          * ----------------
1110          */
1111
1112         optind = 1;                                     /* reset after postmaster's usage */
1113
1114         while ((flag = getopt(argc, argv,  "A:B:CD:d:Eef:FiLNOPo:p:S:st:v:W:x:-:")) != EOF)
1115                 switch (flag)
1116                 {
1117                         case 'A':
1118 #ifdef USE_ASSERT_CHECKING
1119                                 assert_enabled = atoi(optarg);
1120 #else
1121                                 fprintf(stderr, "Assert checking is not compiled in\n");
1122 #endif
1123                                 break;
1124
1125                         case 'B':
1126                                 /* ----------------
1127                                  *      specify the size of buffer pool
1128                                  * ----------------
1129                                  */
1130                                 if (secure)
1131                                         NBuffers = atoi(optarg);
1132                                 break;
1133
1134                         case 'C':
1135                                 /* ----------------
1136                                  *      don't print version string
1137                                  * ----------------
1138                                  */
1139                                 Noversion = true;
1140                                 break;
1141
1142                         case 'D':                       /* PGDATA directory */
1143                                 if (secure)
1144                                 {
1145                                         if (DataDir)
1146                                                 free(DataDir);
1147                                         DataDir = strdup(optarg);
1148                                 }
1149                                 break;
1150
1151                         case 'd':                       /* debug level */
1152                                 DebugLvl = atoi(optarg);
1153                                 if (DebugLvl >= 1);
1154                                         Log_connections = true;
1155                                 if (DebugLvl >= 2)
1156                                         Debug_print_query = true;
1157                                 if (DebugLvl >= 3)
1158                                         Debug_print_parse = true;
1159                                 if (DebugLvl >= 4)
1160                                         Debug_print_plan = true;
1161                                 if (DebugLvl >= 5)
1162                                         Debug_print_rewritten = true;
1163                                 break;
1164
1165                         case 'E':
1166                                 /* ----------------
1167                                  *      E - echo the query the user entered
1168                                  * ----------------
1169                                  */
1170                                 EchoQuery = true;
1171                                 break;
1172
1173                         case 'e':
1174                                 /* --------------------------
1175                                  * Use european date formats.
1176                                  * --------------------------
1177                                  */
1178                                 EuroDates = true;
1179                                 break;
1180
1181                         case 'F':
1182                                 /* --------------------
1183                                  *      turn off fsync
1184                                  *
1185                                  *      7.0 buffer manager can support different backends running
1186                                  *      with different fsync settings, so this no longer needs
1187                                  *      to be "if (secure)".
1188                                  * --------------------
1189                                  */
1190                                 enableFsync = false;
1191                                 break;
1192
1193                         case 'f':
1194                                 /* -----------------
1195                                  *        f - forbid generation of certain plans
1196                                  * -----------------
1197                                  */
1198                                 switch (optarg[0])
1199                                 {
1200                                         case 's':       /* seqscan */
1201                                                 enable_seqscan = false;
1202                                                 break;
1203                                         case 'i':       /* indexscan */
1204                                                 enable_indexscan = false;
1205                                                 break;
1206                                         case 't':       /* tidscan */
1207                                                 enable_tidscan = false;
1208                                                 break;
1209                                         case 'n':       /* nestloop */
1210                                                 enable_nestloop = false;
1211                                                 break;
1212                                         case 'm':       /* mergejoin */
1213                                                 enable_mergejoin = false;
1214                                                 break;
1215                                         case 'h':       /* hashjoin */
1216                                                 enable_hashjoin = false;
1217                                                 break;
1218                                         default:
1219                                                 errs++;
1220                                 }
1221                                 break;
1222
1223                         case 'i':
1224                                 dontExecute = true;
1225                                 break;
1226
1227                         case 'L':
1228                                 /* --------------------
1229                                  *      turn off locking
1230                                  * --------------------
1231                                  */
1232                                 if (secure)
1233                                         lockingOff = 1;
1234                                 break;
1235
1236                         case 'N':
1237                                 /* ----------------
1238                                  *      N - Don't use newline as a query delimiter
1239                                  * ----------------
1240                                  */
1241                                 UseNewLine = 0;
1242                                 break;
1243
1244                         case 'O':
1245                                 /* --------------------
1246                                  *      allow system table structure modifications
1247                                  * --------------------
1248                                  */
1249                                 if (secure)             /* XXX safe to allow from client??? */
1250                                         allowSystemTableMods = true;
1251                                 break;
1252
1253                         case 'P':
1254                                 /* --------------------
1255                                  *      ignore system indexes
1256                                  * --------------------
1257                                  */
1258                                 if (secure)             /* XXX safe to allow from client??? */
1259                                         IgnoreSystemIndexes(true);
1260                                 break;
1261
1262                         case 'o':
1263                                 /* ----------------
1264                                  *      o - send output (stdout and stderr) to the given file
1265                                  * ----------------
1266                                  */
1267                                 if (secure)
1268                                         StrNCpy(OutputFileName, optarg, MAXPGPATH);
1269                                 break;
1270
1271                         case 'p':
1272                                 /* ----------------
1273                                  *      p - special flag passed if backend was forked
1274                                  *              by a postmaster.
1275                                  * ----------------
1276                                  */
1277                                 if (secure)
1278                                 {
1279                                         DBName = strdup(optarg);
1280                                         secure = false;         /* subsequent switches are NOT
1281                                                                                  * secure */
1282                                 }
1283                                 break;
1284
1285                         case 'S':
1286                                 /* ----------------
1287                                  *      S - amount of sort memory to use in 1k bytes
1288                                  * ----------------
1289                                  */
1290                                 {
1291                                         int                     S;
1292
1293                                         S = atoi(optarg);
1294                                         if (S >= 4 * BLCKSZ / 1024)
1295                                                 SortMem = S;
1296                                 }
1297                                 break;
1298
1299                         case 's':
1300                                 /* ----------------
1301                                  *        s - report usage statistics (timings) after each query
1302                                  * ----------------
1303                                  */
1304                                 Show_query_stats = 1;
1305                                 break;
1306
1307                         case 't':
1308                                 /* ----------------
1309                                  *      tell postgres to report usage statistics (timings) for
1310                                  *      each query
1311                                  *
1312                                  *      -tpa[rser] = print stats for parser time of each query
1313                                  *      -tpl[anner] = print stats for planner time of each query
1314                                  *      -te[xecutor] = print stats for executor time of each query
1315                                  *      caution: -s can not be used together with -t.
1316                                  * ----------------
1317                                  */
1318                                 switch (optarg[0])
1319                                 {
1320                                         case 'p':
1321                                                 if (optarg[1] == 'a')
1322                                                         Show_parser_stats = 1;
1323                                                 else if (optarg[1] == 'l')
1324                                                         Show_planner_stats = 1;
1325                                                 else
1326                                                         errs++;
1327                                                 break;
1328                                         case 'e':
1329                                                 Show_executor_stats = 1;
1330                                                 break;
1331                                         default:
1332                                                 errs++;
1333                                                 break;
1334                                 }
1335                                 break;
1336
1337                         case 'v':
1338                                 if (secure)
1339                                         FrontendProtocol = (ProtocolVersion) atoi(optarg);
1340                                 break;
1341
1342                         case 'W':
1343                                 /* ----------------
1344                                  *      wait N seconds to allow attach from a debugger
1345                                  * ----------------
1346                                  */
1347                                 sleep(atoi(optarg));
1348                                 break;
1349
1350                         case 'x':
1351 #ifdef NOT_USED                                 /* planner/xfunc.h */
1352
1353                                 /*
1354                                  * control joey hellerstein's expensive function
1355                                  * optimization
1356                                  */
1357                                 if (XfuncMode != 0)
1358                                 {
1359                                         fprintf(stderr, "only one -x flag is allowed\n");
1360                                         errs++;
1361                                         break;
1362                                 }
1363                                 if (strcmp(optarg, "off") == 0)
1364                                         XfuncMode = XFUNC_OFF;
1365                                 else if (strcmp(optarg, "nor") == 0)
1366                                         XfuncMode = XFUNC_NOR;
1367                                 else if (strcmp(optarg, "nopull") == 0)
1368                                         XfuncMode = XFUNC_NOPULL;
1369                                 else if (strcmp(optarg, "nopm") == 0)
1370                                         XfuncMode = XFUNC_NOPM;
1371                                 else if (strcmp(optarg, "pullall") == 0)
1372                                         XfuncMode = XFUNC_PULLALL;
1373                                 else if (strcmp(optarg, "wait") == 0)
1374                                         XfuncMode = XFUNC_WAIT;
1375                                 else
1376                                 {
1377                                         fprintf(stderr, "use -x {off,nor,nopull,nopm,pullall,wait}\n");
1378                                         errs++;
1379                                 }
1380 #endif
1381                                 break;
1382
1383                         case '-':
1384                         {
1385                                 char *name, *value;
1386
1387                                 ParseLongOption(optarg, &name, &value);
1388                                 if (!value)
1389                                         elog(ERROR, "--%s requires argument", optarg);
1390
1391                                 SetConfigOption(name, value, PGC_BACKEND);
1392                                 free(name);
1393                                 if (value)
1394                                         free(value);
1395                                 break;
1396                         }
1397
1398                         default:
1399                                 /* ----------------
1400                                  *      default: bad command line option
1401                                  * ----------------
1402                                  */
1403                                 errs++;
1404                                 break;
1405                 }
1406
1407         if (Show_query_stats &&
1408                 (Show_parser_stats || Show_planner_stats || Show_executor_stats))
1409         {
1410                 elog(NOTICE, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1411                 Show_query_stats = false;
1412         }
1413
1414         if (!DataDir)
1415         {
1416                 fprintf(stderr, "%s does not know where to find the database system "
1417                                 "data.  You must specify the directory that contains the "
1418                                 "database system either by specifying the -D invocation "
1419                          "option or by setting the PGDATA environment variable.\n\n",
1420                                 argv[0]);
1421                 proc_exit(1);
1422         }
1423
1424         /*
1425          * 1. Set BlockSig and UnBlockSig masks. 2. Set up signal handlers. 3.
1426          * Allow only SIGUSR1 signal (we never block it) during
1427          * initialization.
1428          *
1429          * Note that postmaster already blocked ALL signals to make us happy.
1430          */
1431         pqinitmask();
1432
1433 #ifdef HAVE_SIGPROCMASK
1434         sigdelset(&BlockSig, SIGUSR1);
1435 #else
1436         BlockSig &= ~(sigmask(SIGUSR1));
1437 #endif
1438
1439         PG_SETMASK(&BlockSig);          /* block everything except SIGUSR1 */
1440
1441         pqsignal(SIGHUP, SigHupHandler);        /* set flag to read config file */
1442         pqsignal(SIGINT, QueryCancelHandler);           /* cancel current query */
1443         pqsignal(SIGQUIT, handle_warn);         /* handle error */
1444         pqsignal(SIGTERM, die);
1445         pqsignal(SIGALRM, HandleDeadLock);
1446
1447         /*
1448          * Ignore failure to write to frontend. Note: if frontend closes
1449          * connection, we will notice it and exit cleanly when control next
1450          * returns to outer loop.  This seems safer than forcing exit in the
1451          * midst of output during who-knows-what operation...
1452          */
1453         pqsignal(SIGPIPE, SIG_IGN);
1454         pqsignal(SIGUSR1, quickdie);
1455         pqsignal(SIGUSR2, Async_NotifyHandler);         /* flush also sinval cache */
1456         pqsignal(SIGFPE, FloatExceptionHandler);
1457         pqsignal(SIGCHLD, SIG_IGN); /* ignored, sent by LockOwners */
1458         pqsignal(SIGTTIN, SIG_DFL);
1459         pqsignal(SIGTTOU, SIG_DFL);
1460         pqsignal(SIGCONT, SIG_DFL);
1461
1462
1463         if (IsUnderPostmaster)
1464         {
1465                 /* noninteractive case: nothing should be left after switches */
1466                 if (errs || argc != optind || DBName == NULL)
1467                 {
1468                         usage(argv[0]);
1469                         proc_exit(0);
1470                 }
1471                 pq_init();                              /* initialize libpq at backend startup */
1472                 whereToSendOutput = Remote;
1473                 BaseInit();
1474         }
1475         else
1476         {
1477                 /* interactive case: database name can be last arg on command line */
1478                 whereToSendOutput = Debug;
1479                 if (errs || argc - optind > 1)
1480                 {
1481                         usage(argv[0]);
1482                         proc_exit(0);
1483                 }
1484                 else if (argc - optind == 1)
1485                         DBName = argv[optind];
1486                 else if ((DBName = username) == NULL)
1487                 {
1488                         fprintf(stderr, "%s: user name undefined and no database specified\n",
1489                                         argv[0]);
1490                         proc_exit(0);
1491                 }
1492
1493                 /*
1494                  * Try to create pid file.
1495                  */
1496                 SetPidFname(DataDir);
1497                 if (SetPidFile(-getpid()))
1498                         proc_exit(0);
1499
1500                 /*
1501                  * Register clean up proc.
1502                  */
1503                 on_proc_exit(UnlinkPidFile, 0);
1504
1505                 BaseInit();
1506                 snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
1507                 snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
1508                 StartupXLOG();
1509         }
1510
1511         /*
1512          * Set up additional info.
1513          */
1514
1515 #ifdef CYR_RECODE
1516         SetCharSet();
1517 #endif
1518
1519         /* On some systems our dynloader code needs the executable's pathname */
1520         if (FindExec(pg_pathname, real_argv[0], "postgres") < 0)
1521                 elog(FATAL, "%s: could not locate executable, bailing out...",
1522                          real_argv[0]);
1523
1524         /*
1525          * Find remote host name or address.
1526          */
1527         remote_host = NULL;
1528
1529         if (IsUnderPostmaster)
1530         {
1531                 if (MyProcPort->raddr.sa.sa_family == AF_INET)
1532                 {
1533                         struct hostent *host_ent;
1534                         char * host_addr;
1535
1536                         remote_port = ntohs(MyProcPort->raddr.in.sin_port);
1537                         host_addr = inet_ntoa(MyProcPort->raddr.in.sin_addr);
1538
1539                         if (HostnameLookup)
1540                         {
1541                                 host_ent = gethostbyaddr((char *) &MyProcPort->raddr.in.sin_addr, sizeof(MyProcPort->raddr.in.sin_addr), AF_INET);
1542
1543                                 if (host_ent)
1544                                 {
1545                                         remote_host = palloc(strlen(host_addr) + strlen(host_ent->h_name) + 3);
1546                                         sprintf(remote_host, "%s[%s]", host_ent->h_name, host_addr);
1547                                 }
1548                         }
1549
1550                         if (remote_host == NULL)
1551                                 remote_host = pstrdup(host_addr);
1552
1553                         if (ShowPortNumber)
1554                         {
1555                                 char * str = palloc(strlen(remote_host) + 7);
1556                                 sprintf(str, "%s:%hu", remote_host, remote_port);
1557                                 pfree(remote_host);
1558                                 remote_host = str;
1559                         }
1560                 }
1561                 else /* not AF_INET */
1562                         remote_host = "[local]";
1563
1564
1565                 /*
1566                  * Set process parameters for ps
1567                  *
1568                  * WARNING: On some platforms the environment will be moved
1569                  * around to make room for the ps display string. So any
1570                  * references to optarg or getenv() from above will be invalid
1571                  * after this call. Better use strdup or something similar.
1572                  */
1573                 init_ps_display(real_argc, real_argv, username, DBName, remote_host);
1574                 set_ps_display("startup");
1575         }
1576
1577         if (Log_connections)
1578                 elog(DEBUG, "connection: host=%s user=%s database=%s",
1579                          remote_host, username, DBName);
1580
1581         /*
1582          * general initialization
1583          */
1584         if (DebugLvl > 1)
1585                 elog(DEBUG, "InitPostgres");
1586         InitPostgres(DBName, username);
1587
1588 #ifdef MULTIBYTE
1589         /* set default client encoding */
1590         if (DebugLvl > 1)
1591                 elog(DEBUG, "reset_client_encoding");
1592         reset_client_encoding();
1593 #endif
1594
1595         on_shmem_exit(remove_all_temp_relations, 0);
1596
1597         /*
1598          * Send this backend's cancellation info to the frontend.
1599          */
1600         if (whereToSendOutput == Remote &&
1601                 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
1602         {
1603                 StringInfoData buf;
1604
1605                 pq_beginmessage(&buf);
1606                 pq_sendbyte(&buf, 'K');
1607                 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
1608                 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
1609                 pq_endmessage(&buf);
1610                 /* Need not flush since ReadyForQuery will do it. */
1611         }
1612
1613         if (!IsUnderPostmaster)
1614         {
1615                 puts("\nPOSTGRES backend interactive interface ");
1616                 puts("$Revision: 1.179 $ $Date: 2000/10/07 04:00:41 $\n");
1617         }
1618
1619         /*
1620          * Initialize the deferred trigger manager
1621          */
1622         if (DeferredTriggerInit() != 0)
1623                 goto normalexit;
1624
1625         SetProcessingMode(NormalProcessing);
1626
1627         /*
1628          * Create the memory context we will use in the main loop.
1629          *
1630          * QueryContext is reset once per iteration of the main loop,
1631          * ie, upon completion of processing of each supplied query string.
1632          * It can therefore be used for any data that should live just as
1633          * long as the query string --- parse trees, for example.
1634          */
1635         QueryContext = AllocSetContextCreate(TopMemoryContext,
1636                                                                                  "QueryContext",
1637                                                                                  ALLOCSET_DEFAULT_MINSIZE,
1638                                                                                  ALLOCSET_DEFAULT_INITSIZE,
1639                                                                                  ALLOCSET_DEFAULT_MAXSIZE);
1640
1641         /*
1642          * POSTGRES main processing loop begins here
1643          *
1644          * If an exception is encountered, processing resumes here so we abort
1645          * the current transaction and start a new one.
1646          */
1647
1648         if (sigsetjmp(Warn_restart, 1) != 0)
1649         {
1650                 /*
1651                  * Make sure we are in a valid memory context during recovery.
1652                  *
1653                  * We use ErrorContext in hopes that it will have some free space
1654                  * even if we're otherwise up against it...
1655                  */
1656                 MemoryContextSwitchTo(ErrorContext);
1657
1658                 if (DebugLvl >= 1)
1659                         elog(DEBUG, "AbortCurrentTransaction");
1660                 AbortCurrentTransaction();
1661
1662                 if (ExitAfterAbort)
1663                         goto errorexit;
1664
1665                 /*
1666                  * If we recovered successfully, return to normal top-level context
1667                  * and clear ErrorContext for next time.
1668                  */
1669                 MemoryContextSwitchTo(TopMemoryContext);
1670                 MemoryContextResetAndDeleteChildren(ErrorContext);
1671                 InError = false;
1672         }
1673
1674         Warn_restart_ready = true;      /* we can now handle elog(ERROR) */
1675
1676         PG_SETMASK(&UnBlockSig);
1677
1678         /*
1679          * Non-error queries loop here.
1680          */
1681
1682         for (;;)
1683         {
1684                 /*
1685                  * Release storage left over from prior query cycle, and
1686                  * create a new query input buffer in the cleared QueryContext.
1687                  */
1688                 MemoryContextSwitchTo(QueryContext);
1689                 MemoryContextResetAndDeleteChildren(QueryContext);
1690
1691                 parser_input = makeStringInfo();
1692
1693                 /* XXX this could be moved after ReadCommand below to get more
1694                  * sensical behaviour */
1695                 if (got_SIGHUP)
1696                 {
1697                         got_SIGHUP = false;
1698                         ProcessConfigFile(PGC_SIGHUP);
1699                 }
1700
1701                 /* ----------------
1702                  *       (1) tell the frontend we're ready for a new query.
1703                  *
1704                  *       Note: this includes fflush()'ing the last of the prior output.
1705                  * ----------------
1706                  */
1707                 ReadyForQuery(whereToSendOutput);
1708
1709                 /* ----------------
1710                  *       (2) deal with pending asynchronous NOTIFY from other backends,
1711                  *       and enable async.c's signal handler to execute NOTIFY directly.
1712                  * ----------------
1713                  */
1714                 QueryCancel = false;    /* forget any earlier CANCEL signal */
1715                 SetWaitingForLock(false);
1716
1717                 EnableNotifyInterrupt();
1718
1719                 /* ----------------
1720                  *       (3) read a command (loop blocks here)
1721                  * ----------------
1722                  */
1723                 set_ps_display("idle");
1724
1725                 firstchar = ReadCommand(parser_input);
1726
1727                 QueryCancel = false;    /* forget any earlier CANCEL signal */
1728
1729                 /* ----------------
1730                  *       (4) disable async.c's signal handler.
1731                  * ----------------
1732                  */
1733                 DisableNotifyInterrupt();
1734
1735                 /* ----------------
1736                  *       (5) process the command.
1737                  * ----------------
1738                  */
1739                 switch (firstchar)
1740                 {
1741                                 /* ----------------
1742                                  *      'F' indicates a fastpath call.
1743                                  * ----------------
1744                                  */
1745                         case 'F':
1746                                 /* start an xact for this function invocation */
1747                                 start_xact_command();
1748
1749                                 if (HandleFunctionRequest() == EOF)
1750                                 {
1751                                         /* lost frontend connection during F message input */
1752                                         goto normalexit;
1753                                 }
1754
1755                                 /* commit the function-invocation transaction */
1756                                 finish_xact_command();
1757                                 break;
1758
1759                                 /* ----------------
1760                                  *      'Q' indicates a user query
1761                                  * ----------------
1762                                  */
1763                         case 'Q':
1764                                 if (strspn(parser_input->data, " \t\n") == parser_input->len)
1765                                 {
1766                                         /* ----------------
1767                                          *      if there is nothing in the input buffer, don't bother
1768                                          *      trying to parse and execute anything; just send
1769                                          *      back a quick NullCommand response.
1770                                          * ----------------
1771                                          */
1772                                         if (IsUnderPostmaster)
1773                                                 NullCommand(Remote);
1774                                 }
1775                                 else
1776                                 {
1777                                         /* ----------------
1778                                          *      otherwise, process the input string.
1779                                          *
1780                                          * Note: transaction command start/end is now done
1781                                          * within pg_exec_query_string(), not here.
1782                                          * ----------------
1783                                          */
1784                                         if (Show_query_stats)
1785                                                 ResetUsage();
1786
1787                                         pg_exec_query_string(parser_input->data,
1788                                                                                  whereToSendOutput,
1789                                                                                  QueryContext);
1790
1791                                         if (Show_query_stats)
1792                                         {
1793                                                 fprintf(StatFp, "QUERY STATISTICS\n");
1794                                                 ShowUsage();
1795                                         }
1796                                 }
1797                                 break;
1798
1799                                 /* ----------------
1800                                  *      'X' means that the frontend is closing down the socket.
1801                                  *      EOF means unexpected loss of frontend connection.
1802                                  *      Either way, perform normal shutdown.
1803                                  * ----------------
1804                                  */
1805                         case 'X':
1806                         case EOF:
1807                                 goto normalexit;
1808
1809                         default:
1810                                 elog(ERROR, "unknown frontend message was received");
1811                 }
1812
1813 #ifdef MEMORY_CONTEXT_CHECKING
1814                 /*
1815                  * Check all memory after each backend loop.  This is a rather
1816                  * weird place to do it, perhaps.
1817                  */
1818                 MemoryContextCheck(TopMemoryContext);   
1819 #endif
1820         }                                                       /* end of input-reading loop */
1821
1822 normalexit:
1823         ExitAfterAbort = true;          /* ensure we will exit if elog during abort */
1824         AbortOutOfAnyTransaction();
1825         if (!IsUnderPostmaster)
1826                 ShutdownXLOG();
1827
1828 errorexit:
1829         pq_close();
1830         ProcReleaseLocks();                     /* Just to be sure... */
1831         proc_exit(0);
1832
1833         return 1;                                       /* keep compiler quiet */
1834 }
1835
1836 #ifndef HAVE_GETRUSAGE
1837 #include "rusagestub.h"
1838 #else
1839 #include <sys/resource.h>
1840 #endif   /* HAVE_GETRUSAGE */
1841
1842 struct rusage Save_r;
1843 struct timeval Save_t;
1844
1845 void
1846 ResetUsage(void)
1847 {
1848         struct timezone tz;
1849
1850         getrusage(RUSAGE_SELF, &Save_r);
1851         gettimeofday(&Save_t, &tz);
1852         ResetBufferUsage();
1853 /*        ResetTupleCount(); */
1854 }
1855
1856 void
1857 ShowUsage(void)
1858 {
1859         struct timeval user,
1860                                 sys;
1861         struct timeval elapse_t;
1862         struct timezone tz;
1863         struct rusage r;
1864
1865         getrusage(RUSAGE_SELF, &r);
1866         gettimeofday(&elapse_t, &tz);
1867         memmove((char *) &user, (char *) &r.ru_utime, sizeof(user));
1868         memmove((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
1869         if (elapse_t.tv_usec < Save_t.tv_usec)
1870         {
1871                 elapse_t.tv_sec--;
1872                 elapse_t.tv_usec += 1000000;
1873         }
1874         if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
1875         {
1876                 r.ru_utime.tv_sec--;
1877                 r.ru_utime.tv_usec += 1000000;
1878         }
1879         if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
1880         {
1881                 r.ru_stime.tv_sec--;
1882                 r.ru_stime.tv_usec += 1000000;
1883         }
1884
1885         /*
1886          * Set output destination if not otherwise set
1887          */
1888         if (StatFp == NULL)
1889                 StatFp = stderr;
1890
1891         /*
1892          * the only stats we don't show here are for memory usage -- i can't
1893          * figure out how to interpret the relevant fields in the rusage
1894          * struct, and they change names across o/s platforms, anyway. if you
1895          * can figure out what the entries mean, you can somehow extract
1896          * resident set size, shared text size, and unshared data and stack
1897          * sizes.
1898          */
1899
1900         fprintf(StatFp, "! system usage stats:\n");
1901         fprintf(StatFp,
1902                         "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
1903                         (long int) elapse_t.tv_sec - Save_t.tv_sec,
1904                         (long int) elapse_t.tv_usec - Save_t.tv_usec,
1905                         (long int) r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec,
1906                         (long int) r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec,
1907                         (long int) r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec,
1908                         (long int) r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec);
1909         fprintf(StatFp,
1910                         "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
1911                         (long int) user.tv_sec,
1912                         (long int) user.tv_usec,
1913                         (long int) sys.tv_sec,
1914                         (long int) sys.tv_usec);
1915 /* BeOS has rusage but only has some fields, and not these... */
1916 #if defined(HAVE_GETRUSAGE) && !defined(__BEOS__)
1917         fprintf(StatFp,
1918                         "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
1919                         r.ru_inblock - Save_r.ru_inblock,
1920         /* they only drink coffee at dec */
1921                         r.ru_oublock - Save_r.ru_oublock,
1922                         r.ru_inblock, r.ru_oublock);
1923         fprintf(StatFp,
1924                   "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
1925                         r.ru_majflt - Save_r.ru_majflt,
1926                         r.ru_minflt - Save_r.ru_minflt,
1927                         r.ru_majflt, r.ru_minflt,
1928                         r.ru_nswap - Save_r.ru_nswap,
1929                         r.ru_nswap);
1930         fprintf(StatFp,
1931          "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
1932                         r.ru_nsignals - Save_r.ru_nsignals,
1933                         r.ru_nsignals,
1934                         r.ru_msgrcv - Save_r.ru_msgrcv,
1935                         r.ru_msgsnd - Save_r.ru_msgsnd,
1936                         r.ru_msgrcv, r.ru_msgsnd);
1937         fprintf(StatFp,
1938                  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
1939                         r.ru_nvcsw - Save_r.ru_nvcsw,
1940                         r.ru_nivcsw - Save_r.ru_nivcsw,
1941                         r.ru_nvcsw, r.ru_nivcsw);
1942 #endif   /* HAVE_GETRUSAGE */
1943         fprintf(StatFp, "! postgres usage stats:\n");
1944         PrintBufferUsage(StatFp);
1945 /*         DisplayTupleCount(StatFp); */
1946 }
1947
1948 #ifdef NOT_USED
1949 static int
1950 assertEnable(int val)
1951 {
1952         assert_enabled = val;
1953         return val;
1954 }
1955
1956 #ifdef ASSERT_CHECKING_TEST
1957 int
1958 assertTest(int val)
1959 {
1960         Assert(val == 0);
1961
1962         if (assert_enabled)
1963         {
1964                 /* val != 0 should be trapped by previous Assert */
1965                 elog(NOTICE, "Assert test successfull (val = %d)", val);
1966         }
1967         else
1968                 elog(NOTICE, "Assert checking is disabled (val = %d)", val);
1969
1970         return val;
1971 }
1972
1973 #endif
1974 #endif