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