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