OSDN Git Service

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