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