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