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