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