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