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