LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1148 1559 73.6 %
Date: 2025-10-10 17:18:49 Functions: 51 58 87.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * postgres.c
       4             :  *    POSTGRES C Backend Interface
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/tcop/postgres.c
      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 <fcntl.h>
      23             : #include <limits.h>
      24             : #include <signal.h>
      25             : #include <unistd.h>
      26             : #include <sys/resource.h>
      27             : #include <sys/socket.h>
      28             : #include <sys/time.h>
      29             : 
      30             : #ifdef USE_VALGRIND
      31             : #include <valgrind/valgrind.h>
      32             : #endif
      33             : 
      34             : #include "access/parallel.h"
      35             : #include "access/printtup.h"
      36             : #include "access/xact.h"
      37             : #include "catalog/pg_type.h"
      38             : #include "commands/async.h"
      39             : #include "commands/event_trigger.h"
      40             : #include "commands/explain_state.h"
      41             : #include "commands/prepare.h"
      42             : #include "common/pg_prng.h"
      43             : #include "jit/jit.h"
      44             : #include "libpq/libpq.h"
      45             : #include "libpq/pqformat.h"
      46             : #include "libpq/pqsignal.h"
      47             : #include "mb/pg_wchar.h"
      48             : #include "mb/stringinfo_mb.h"
      49             : #include "miscadmin.h"
      50             : #include "nodes/print.h"
      51             : #include "optimizer/optimizer.h"
      52             : #include "parser/analyze.h"
      53             : #include "parser/parser.h"
      54             : #include "pg_getopt.h"
      55             : #include "pg_trace.h"
      56             : #include "pgstat.h"
      57             : #include "postmaster/interrupt.h"
      58             : #include "postmaster/postmaster.h"
      59             : #include "replication/logicallauncher.h"
      60             : #include "replication/logicalworker.h"
      61             : #include "replication/slot.h"
      62             : #include "replication/walsender.h"
      63             : #include "rewrite/rewriteHandler.h"
      64             : #include "storage/bufmgr.h"
      65             : #include "storage/ipc.h"
      66             : #include "storage/pmsignal.h"
      67             : #include "storage/proc.h"
      68             : #include "storage/procsignal.h"
      69             : #include "storage/sinval.h"
      70             : #include "tcop/backend_startup.h"
      71             : #include "tcop/fastpath.h"
      72             : #include "tcop/pquery.h"
      73             : #include "tcop/tcopprot.h"
      74             : #include "tcop/utility.h"
      75             : #include "utils/guc_hooks.h"
      76             : #include "utils/injection_point.h"
      77             : #include "utils/lsyscache.h"
      78             : #include "utils/memutils.h"
      79             : #include "utils/ps_status.h"
      80             : #include "utils/snapmgr.h"
      81             : #include "utils/timeout.h"
      82             : #include "utils/timestamp.h"
      83             : #include "utils/varlena.h"
      84             : 
      85             : /* ----------------
      86             :  *      global variables
      87             :  * ----------------
      88             :  */
      89             : const char *debug_query_string; /* client-supplied query string */
      90             : 
      91             : /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
      92             : CommandDest whereToSendOutput = DestDebug;
      93             : 
      94             : /* flag for logging end of session */
      95             : bool        Log_disconnections = false;
      96             : 
      97             : int         log_statement = LOGSTMT_NONE;
      98             : 
      99             : /* wait N seconds to allow attach from a debugger */
     100             : int         PostAuthDelay = 0;
     101             : 
     102             : /* Time between checks that the client is still connected. */
     103             : int         client_connection_check_interval = 0;
     104             : 
     105             : /* flags for non-system relation kinds to restrict use */
     106             : int         restrict_nonsystem_relation_kind;
     107             : 
     108             : /* ----------------
     109             :  *      private typedefs etc
     110             :  * ----------------
     111             :  */
     112             : 
     113             : /* type of argument for bind_param_error_callback */
     114             : typedef struct BindParamCbData
     115             : {
     116             :     const char *portalName;
     117             :     int         paramno;        /* zero-based param number, or -1 initially */
     118             :     const char *paramval;       /* textual input string, if available */
     119             : } BindParamCbData;
     120             : 
     121             : /* ----------------
     122             :  *      private variables
     123             :  * ----------------
     124             :  */
     125             : 
     126             : /*
     127             :  * Flag to keep track of whether we have started a transaction.
     128             :  * For extended query protocol this has to be remembered across messages.
     129             :  */
     130             : static bool xact_started = false;
     131             : 
     132             : /*
     133             :  * Flag to indicate that we are doing the outer loop's read-from-client,
     134             :  * as opposed to any random read from client that might happen within
     135             :  * commands like COPY FROM STDIN.
     136             :  */
     137             : static bool DoingCommandRead = false;
     138             : 
     139             : /*
     140             :  * Flags to implement skip-till-Sync-after-error behavior for messages of
     141             :  * the extended query protocol.
     142             :  */
     143             : static bool doing_extended_query_message = false;
     144             : static bool ignore_till_sync = false;
     145             : 
     146             : /*
     147             :  * If an unnamed prepared statement exists, it's stored here.
     148             :  * We keep it separate from the hashtable kept by commands/prepare.c
     149             :  * in order to reduce overhead for short-lived queries.
     150             :  */
     151             : static CachedPlanSource *unnamed_stmt_psrc = NULL;
     152             : 
     153             : /* assorted command-line switches */
     154             : static const char *userDoption = NULL;  /* -D switch */
     155             : static bool EchoQuery = false;  /* -E switch */
     156             : static bool UseSemiNewlineNewline = false;  /* -j switch */
     157             : 
     158             : /* whether or not, and why, we were canceled by conflict with recovery */
     159             : static volatile sig_atomic_t RecoveryConflictPending = false;
     160             : static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS];
     161             : 
     162             : /* reused buffer to pass to SendRowDescriptionMessage() */
     163             : static MemoryContext row_description_context = NULL;
     164             : static StringInfoData row_description_buf;
     165             : 
     166             : /* ----------------------------------------------------------------
     167             :  *      decls for routines only used in this file
     168             :  * ----------------------------------------------------------------
     169             :  */
     170             : static int  InteractiveBackend(StringInfo inBuf);
     171             : static int  interactive_getc(void);
     172             : static int  SocketBackend(StringInfo inBuf);
     173             : static int  ReadCommand(StringInfo inBuf);
     174             : static void forbidden_in_wal_sender(char firstchar);
     175             : static bool check_log_statement(List *stmt_list);
     176             : static int  errdetail_execute(List *raw_parsetree_list);
     177             : static int  errdetail_params(ParamListInfo params);
     178             : static int  errdetail_abort(void);
     179             : static void bind_param_error_callback(void *arg);
     180             : static void start_xact_command(void);
     181             : static void finish_xact_command(void);
     182             : static bool IsTransactionExitStmt(Node *parsetree);
     183             : static bool IsTransactionExitStmtList(List *pstmts);
     184             : static bool IsTransactionStmtList(List *pstmts);
     185             : static void drop_unnamed_stmt(void);
     186             : static void log_disconnections(int code, Datum arg);
     187             : static void enable_statement_timeout(void);
     188             : static void disable_statement_timeout(void);
     189             : 
     190             : 
     191             : /* ----------------------------------------------------------------
     192             :  *      infrastructure for valgrind debugging
     193             :  * ----------------------------------------------------------------
     194             :  */
     195             : #ifdef USE_VALGRIND
     196             : /* This variable should be set at the top of the main loop. */
     197             : static unsigned int old_valgrind_error_count;
     198             : 
     199             : /*
     200             :  * If Valgrind detected any errors since old_valgrind_error_count was updated,
     201             :  * report the current query as the cause.  This should be called at the end
     202             :  * of message processing.
     203             :  */
     204             : static void
     205             : valgrind_report_error_query(const char *query)
     206             : {
     207             :     unsigned int valgrind_error_count = VALGRIND_COUNT_ERRORS;
     208             : 
     209             :     if (unlikely(valgrind_error_count != old_valgrind_error_count) &&
     210             :         query != NULL)
     211             :         VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
     212             :                         valgrind_error_count - old_valgrind_error_count,
     213             :                         query);
     214             : }
     215             : 
     216             : #else                           /* !USE_VALGRIND */
     217             : #define valgrind_report_error_query(query) ((void) 0)
     218             : #endif                          /* USE_VALGRIND */
     219             : 
     220             : 
     221             : /* ----------------------------------------------------------------
     222             :  *      routines to obtain user input
     223             :  * ----------------------------------------------------------------
     224             :  */
     225             : 
     226             : /* ----------------
     227             :  *  InteractiveBackend() is called for user interactive connections
     228             :  *
     229             :  *  the string entered by the user is placed in its parameter inBuf,
     230             :  *  and we act like a Q message was received.
     231             :  *
     232             :  *  EOF is returned if end-of-file input is seen; time to shut down.
     233             :  * ----------------
     234             :  */
     235             : 
     236             : static int
     237       69758 : InteractiveBackend(StringInfo inBuf)
     238             : {
     239             :     int         c;              /* character read from getc() */
     240             : 
     241             :     /*
     242             :      * display a prompt and obtain input from the user
     243             :      */
     244       69758 :     printf("backend> ");
     245       69758 :     fflush(stdout);
     246             : 
     247       69758 :     resetStringInfo(inBuf);
     248             : 
     249             :     /*
     250             :      * Read characters until EOF or the appropriate delimiter is seen.
     251             :      */
     252    24309488 :     while ((c = interactive_getc()) != EOF)
     253             :     {
     254    24309336 :         if (c == '\n')
     255             :         {
     256      653670 :             if (UseSemiNewlineNewline)
     257             :             {
     258             :                 /*
     259             :                  * In -j mode, semicolon followed by two newlines ends the
     260             :                  * command; otherwise treat newline as regular character.
     261             :                  */
     262      653664 :                 if (inBuf->len > 1 &&
     263      645888 :                     inBuf->data[inBuf->len - 1] == '\n' &&
     264      103296 :                     inBuf->data[inBuf->len - 2] == ';')
     265             :                 {
     266             :                     /* might as well drop the second newline */
     267       69600 :                     break;
     268             :                 }
     269             :             }
     270             :             else
     271             :             {
     272             :                 /*
     273             :                  * In plain mode, newline ends the command unless preceded by
     274             :                  * backslash.
     275             :                  */
     276           6 :                 if (inBuf->len > 0 &&
     277           4 :                     inBuf->data[inBuf->len - 1] == '\\')
     278             :                 {
     279             :                     /* discard backslash from inBuf */
     280           0 :                     inBuf->data[--inBuf->len] = '\0';
     281             :                     /* discard newline too */
     282           0 :                     continue;
     283             :                 }
     284             :                 else
     285             :                 {
     286             :                     /* keep the newline character, but end the command */
     287           6 :                     appendStringInfoChar(inBuf, '\n');
     288           6 :                     break;
     289             :                 }
     290             :             }
     291             :         }
     292             : 
     293             :         /* Not newline, or newline treated as regular character */
     294    24239730 :         appendStringInfoChar(inBuf, (char) c);
     295             :     }
     296             : 
     297             :     /* No input before EOF signal means time to quit. */
     298       69758 :     if (c == EOF && inBuf->len == 0)
     299         134 :         return EOF;
     300             : 
     301             :     /*
     302             :      * otherwise we have a user query so process it.
     303             :      */
     304             : 
     305             :     /* Add '\0' to make it look the same as message case. */
     306       69624 :     appendStringInfoChar(inBuf, (char) '\0');
     307             : 
     308             :     /*
     309             :      * if the query echo flag was given, print the query..
     310             :      */
     311       69624 :     if (EchoQuery)
     312           0 :         printf("statement: %s\n", inBuf->data);
     313       69624 :     fflush(stdout);
     314             : 
     315       69624 :     return PqMsg_Query;
     316             : }
     317             : 
     318             : /*
     319             :  * interactive_getc -- collect one character from stdin
     320             :  *
     321             :  * Even though we are not reading from a "client" process, we still want to
     322             :  * respond to signals, particularly SIGTERM/SIGQUIT.
     323             :  */
     324             : static int
     325    24309488 : interactive_getc(void)
     326             : {
     327             :     int         c;
     328             : 
     329             :     /*
     330             :      * This will not process catchup interrupts or notifications while
     331             :      * reading. But those can't really be relevant for a standalone backend
     332             :      * anyway. To properly handle SIGTERM there's a hack in die() that
     333             :      * directly processes interrupts at this stage...
     334             :      */
     335    24309488 :     CHECK_FOR_INTERRUPTS();
     336             : 
     337    24309488 :     c = getc(stdin);
     338             : 
     339    24309488 :     ProcessClientReadInterrupt(false);
     340             : 
     341    24309488 :     return c;
     342             : }
     343             : 
     344             : /* ----------------
     345             :  *  SocketBackend()     Is called for frontend-backend connections
     346             :  *
     347             :  *  Returns the message type code, and loads message body data into inBuf.
     348             :  *
     349             :  *  EOF is returned if the connection is lost.
     350             :  * ----------------
     351             :  */
     352             : static int
     353      723640 : SocketBackend(StringInfo inBuf)
     354             : {
     355             :     int         qtype;
     356             :     int         maxmsglen;
     357             : 
     358             :     /*
     359             :      * Get message type code from the frontend.
     360             :      */
     361      723640 :     HOLD_CANCEL_INTERRUPTS();
     362      723640 :     pq_startmsgread();
     363      723640 :     qtype = pq_getbyte();
     364             : 
     365      723558 :     if (qtype == EOF)           /* frontend disconnected */
     366             :     {
     367          86 :         if (IsTransactionState())
     368           8 :             ereport(COMMERROR,
     369             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
     370             :                      errmsg("unexpected EOF on client connection with an open transaction")));
     371             :         else
     372             :         {
     373             :             /*
     374             :              * Can't send DEBUG log messages to client at this point. Since
     375             :              * we're disconnecting right away, we don't need to restore
     376             :              * whereToSendOutput.
     377             :              */
     378          78 :             whereToSendOutput = DestNone;
     379          78 :             ereport(DEBUG1,
     380             :                     (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
     381             :                      errmsg_internal("unexpected EOF on client connection")));
     382             :         }
     383          86 :         return qtype;
     384             :     }
     385             : 
     386             :     /*
     387             :      * Validate message type code before trying to read body; if we have lost
     388             :      * sync, better to say "command unknown" than to run out of memory because
     389             :      * we used garbage as a length word.  We can also select a type-dependent
     390             :      * limit on what a sane length word could be.  (The limit could be chosen
     391             :      * more granularly, but it's not clear it's worth fussing over.)
     392             :      *
     393             :      * This also gives us a place to set the doing_extended_query_message flag
     394             :      * as soon as possible.
     395             :      */
     396      723472 :     switch (qtype)
     397             :     {
     398      593258 :         case PqMsg_Query:
     399      593258 :             maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
     400      593258 :             doing_extended_query_message = false;
     401      593258 :             break;
     402             : 
     403        2168 :         case PqMsg_FunctionCall:
     404        2168 :             maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
     405        2168 :             doing_extended_query_message = false;
     406        2168 :             break;
     407             : 
     408       25054 :         case PqMsg_Terminate:
     409       25054 :             maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
     410       25054 :             doing_extended_query_message = false;
     411       25054 :             ignore_till_sync = false;
     412       25054 :             break;
     413             : 
     414       33828 :         case PqMsg_Bind:
     415             :         case PqMsg_Parse:
     416       33828 :             maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
     417       33828 :             doing_extended_query_message = true;
     418       33828 :             break;
     419             : 
     420       45550 :         case PqMsg_Close:
     421             :         case PqMsg_Describe:
     422             :         case PqMsg_Execute:
     423             :         case PqMsg_Flush:
     424       45550 :             maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
     425       45550 :             doing_extended_query_message = true;
     426       45550 :             break;
     427             : 
     428       23374 :         case PqMsg_Sync:
     429       23374 :             maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
     430             :             /* stop any active skip-till-Sync */
     431       23374 :             ignore_till_sync = false;
     432             :             /* mark not-extended, so that a new error doesn't begin skip */
     433       23374 :             doing_extended_query_message = false;
     434       23374 :             break;
     435             : 
     436          32 :         case PqMsg_CopyData:
     437          32 :             maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
     438          32 :             doing_extended_query_message = false;
     439          32 :             break;
     440             : 
     441         208 :         case PqMsg_CopyDone:
     442             :         case PqMsg_CopyFail:
     443         208 :             maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
     444         208 :             doing_extended_query_message = false;
     445         208 :             break;
     446             : 
     447           0 :         default:
     448             : 
     449             :             /*
     450             :              * Otherwise we got garbage from the frontend.  We treat this as
     451             :              * fatal because we have probably lost message boundary sync, and
     452             :              * there's no good way to recover.
     453             :              */
     454           0 :             ereport(FATAL,
     455             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
     456             :                      errmsg("invalid frontend message type %d", qtype)));
     457             :             maxmsglen = 0;      /* keep compiler quiet */
     458             :             break;
     459             :     }
     460             : 
     461             :     /*
     462             :      * In protocol version 3, all frontend messages have a length word next
     463             :      * after the type code; we can read the message contents independently of
     464             :      * the type.
     465             :      */
     466      723472 :     if (pq_getmessage(inBuf, maxmsglen))
     467           0 :         return EOF;             /* suitable message already logged */
     468      723472 :     RESUME_CANCEL_INTERRUPTS();
     469             : 
     470      723472 :     return qtype;
     471             : }
     472             : 
     473             : /* ----------------
     474             :  *      ReadCommand reads a command from either the frontend or
     475             :  *      standard input, places it in inBuf, and returns the
     476             :  *      message type code (first byte of the message).
     477             :  *      EOF is returned if end of file.
     478             :  * ----------------
     479             :  */
     480             : static int
     481      793398 : ReadCommand(StringInfo inBuf)
     482             : {
     483             :     int         result;
     484             : 
     485      793398 :     if (whereToSendOutput == DestRemote)
     486      723640 :         result = SocketBackend(inBuf);
     487             :     else
     488       69758 :         result = InteractiveBackend(inBuf);
     489      793316 :     return result;
     490             : }
     491             : 
     492             : /*
     493             :  * ProcessClientReadInterrupt() - Process interrupts specific to client reads
     494             :  *
     495             :  * This is called just before and after low-level reads.
     496             :  * 'blocked' is true if no data was available to read and we plan to retry,
     497             :  * false if about to read or done reading.
     498             :  *
     499             :  * Must preserve errno!
     500             :  */
     501             : void
     502    29534648 : ProcessClientReadInterrupt(bool blocked)
     503             : {
     504    29534648 :     int         save_errno = errno;
     505             : 
     506    29534648 :     if (DoingCommandRead)
     507             :     {
     508             :         /* Check for general interrupts that arrived before/while reading */
     509    25613360 :         CHECK_FOR_INTERRUPTS();
     510             : 
     511             :         /* Process sinval catchup interrupts, if any */
     512    25613278 :         if (catchupInterruptPending)
     513         744 :             ProcessCatchupInterrupt();
     514             : 
     515             :         /* Process notify interrupts, if any */
     516    25613278 :         if (notifyInterruptPending)
     517         130 :             ProcessNotifyInterrupt(true);
     518             :     }
     519     3921288 :     else if (ProcDiePending)
     520             :     {
     521             :         /*
     522             :          * We're dying.  If there is no data available to read, then it's safe
     523             :          * (and sane) to handle that now.  If we haven't tried to read yet,
     524             :          * make sure the process latch is set, so that if there is no data
     525             :          * then we'll come back here and die.  If we're done reading, also
     526             :          * make sure the process latch is set, as we might've undesirably
     527             :          * cleared it while reading.
     528             :          */
     529           0 :         if (blocked)
     530           0 :             CHECK_FOR_INTERRUPTS();
     531             :         else
     532           0 :             SetLatch(MyLatch);
     533             :     }
     534             : 
     535    29534566 :     errno = save_errno;
     536    29534566 : }
     537             : 
     538             : /*
     539             :  * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
     540             :  *
     541             :  * This is called just before and after low-level writes.
     542             :  * 'blocked' is true if no data could be written and we plan to retry,
     543             :  * false if about to write or done writing.
     544             :  *
     545             :  * Must preserve errno!
     546             :  */
     547             : void
     548     4357422 : ProcessClientWriteInterrupt(bool blocked)
     549             : {
     550     4357422 :     int         save_errno = errno;
     551             : 
     552     4357422 :     if (ProcDiePending)
     553             :     {
     554             :         /*
     555             :          * We're dying.  If it's not possible to write, then we should handle
     556             :          * that immediately, else a stuck client could indefinitely delay our
     557             :          * response to the signal.  If we haven't tried to write yet, make
     558             :          * sure the process latch is set, so that if the write would block
     559             :          * then we'll come back here and die.  If we're done writing, also
     560             :          * make sure the process latch is set, as we might've undesirably
     561             :          * cleared it while writing.
     562             :          */
     563          10 :         if (blocked)
     564             :         {
     565             :             /*
     566             :              * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
     567             :              * service ProcDiePending.
     568             :              */
     569           0 :             if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
     570             :             {
     571             :                 /*
     572             :                  * We don't want to send the client the error message, as a)
     573             :                  * that would possibly block again, and b) it would likely
     574             :                  * lead to loss of protocol sync because we may have already
     575             :                  * sent a partial protocol message.
     576             :                  */
     577           0 :                 if (whereToSendOutput == DestRemote)
     578           0 :                     whereToSendOutput = DestNone;
     579             : 
     580           0 :                 CHECK_FOR_INTERRUPTS();
     581             :             }
     582             :         }
     583             :         else
     584          10 :             SetLatch(MyLatch);
     585             :     }
     586             : 
     587     4357422 :     errno = save_errno;
     588     4357422 : }
     589             : 
     590             : /*
     591             :  * Do raw parsing (only).
     592             :  *
     593             :  * A list of parsetrees (RawStmt nodes) is returned, since there might be
     594             :  * multiple commands in the given string.
     595             :  *
     596             :  * NOTE: for interactive queries, it is important to keep this routine
     597             :  * separate from the analysis & rewrite stages.  Analysis and rewriting
     598             :  * cannot be done in an aborted transaction, since they require access to
     599             :  * database tables.  So, we rely on the raw parser to determine whether
     600             :  * we've seen a COMMIT or ABORT command; when we are in abort state, other
     601             :  * commands are not processed any further than the raw parse stage.
     602             :  */
     603             : List *
     604      676298 : pg_parse_query(const char *query_string)
     605             : {
     606             :     List       *raw_parsetree_list;
     607             : 
     608             :     TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
     609             : 
     610      676298 :     if (log_parser_stats)
     611           0 :         ResetUsage();
     612             : 
     613      676298 :     raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
     614             : 
     615      675084 :     if (log_parser_stats)
     616           0 :         ShowUsage("PARSER STATISTICS");
     617             : 
     618             : #ifdef DEBUG_NODE_TESTS_ENABLED
     619             : 
     620             :     /* Optional debugging check: pass raw parsetrees through copyObject() */
     621      675084 :     if (Debug_copy_parse_plan_trees)
     622             :     {
     623      675084 :         List       *new_list = copyObject(raw_parsetree_list);
     624             : 
     625             :         /* This checks both copyObject() and the equal() routines... */
     626      675084 :         if (!equal(new_list, raw_parsetree_list))
     627           0 :             elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
     628             :         else
     629      675084 :             raw_parsetree_list = new_list;
     630             :     }
     631             : 
     632             :     /*
     633             :      * Optional debugging check: pass raw parsetrees through
     634             :      * outfuncs/readfuncs
     635             :      */
     636      675084 :     if (Debug_write_read_parse_plan_trees)
     637             :     {
     638           0 :         char       *str = nodeToStringWithLocations(raw_parsetree_list);
     639           0 :         List       *new_list = stringToNodeWithLocations(str);
     640             : 
     641           0 :         pfree(str);
     642             :         /* This checks both outfuncs/readfuncs and the equal() routines... */
     643           0 :         if (!equal(new_list, raw_parsetree_list))
     644           0 :             elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
     645             :         else
     646           0 :             raw_parsetree_list = new_list;
     647             :     }
     648             : 
     649             : #endif                          /* DEBUG_NODE_TESTS_ENABLED */
     650             : 
     651             :     TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
     652             : 
     653      675084 :     if (Debug_print_raw_parse)
     654           0 :         elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
     655             :                           Debug_pretty_print);
     656             : 
     657      675084 :     return raw_parsetree_list;
     658             : }
     659             : 
     660             : /*
     661             :  * Given a raw parsetree (gram.y output), and optionally information about
     662             :  * types of parameter symbols ($n), perform parse analysis and rule rewriting.
     663             :  *
     664             :  * A list of Query nodes is returned, since either the analyzer or the
     665             :  * rewriter might expand one query to several.
     666             :  *
     667             :  * NOTE: for reasons mentioned above, this must be separate from raw parsing.
     668             :  */
     669             : List *
     670      749428 : pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree,
     671             :                                    const char *query_string,
     672             :                                    const Oid *paramTypes,
     673             :                                    int numParams,
     674             :                                    QueryEnvironment *queryEnv)
     675             : {
     676             :     Query      *query;
     677             :     List       *querytree_list;
     678             : 
     679             :     TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
     680             : 
     681             :     /*
     682             :      * (1) Perform parse analysis.
     683             :      */
     684      749428 :     if (log_parser_stats)
     685           0 :         ResetUsage();
     686             : 
     687      749428 :     query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
     688             :                                       queryEnv);
     689             : 
     690      741714 :     if (log_parser_stats)
     691           0 :         ShowUsage("PARSE ANALYSIS STATISTICS");
     692             : 
     693             :     /*
     694             :      * (2) Rewrite the queries, as necessary
     695             :      */
     696      741714 :     querytree_list = pg_rewrite_query(query);
     697             : 
     698             :     TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
     699             : 
     700      741036 :     return querytree_list;
     701             : }
     702             : 
     703             : /*
     704             :  * Do parse analysis and rewriting.  This is the same as
     705             :  * pg_analyze_and_rewrite_fixedparams except that it's okay to deduce
     706             :  * information about $n symbol datatypes from context.
     707             :  */
     708             : List *
     709       13090 : pg_analyze_and_rewrite_varparams(RawStmt *parsetree,
     710             :                                  const char *query_string,
     711             :                                  Oid **paramTypes,
     712             :                                  int *numParams,
     713             :                                  QueryEnvironment *queryEnv)
     714             : {
     715             :     Query      *query;
     716             :     List       *querytree_list;
     717             : 
     718             :     TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
     719             : 
     720             :     /*
     721             :      * (1) Perform parse analysis.
     722             :      */
     723       13090 :     if (log_parser_stats)
     724           0 :         ResetUsage();
     725             : 
     726       13090 :     query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
     727             :                                     queryEnv);
     728             : 
     729             :     /*
     730             :      * Check all parameter types got determined.
     731             :      */
     732       27998 :     for (int i = 0; i < *numParams; i++)
     733             :     {
     734       14930 :         Oid         ptype = (*paramTypes)[i];
     735             : 
     736       14930 :         if (ptype == InvalidOid || ptype == UNKNOWNOID)
     737           6 :             ereport(ERROR,
     738             :                     (errcode(ERRCODE_INDETERMINATE_DATATYPE),
     739             :                      errmsg("could not determine data type of parameter $%d",
     740             :                             i + 1)));
     741             :     }
     742             : 
     743       13068 :     if (log_parser_stats)
     744           0 :         ShowUsage("PARSE ANALYSIS STATISTICS");
     745             : 
     746             :     /*
     747             :      * (2) Rewrite the queries, as necessary
     748             :      */
     749       13068 :     querytree_list = pg_rewrite_query(query);
     750             : 
     751             :     TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
     752             : 
     753       13068 :     return querytree_list;
     754             : }
     755             : 
     756             : /*
     757             :  * Do parse analysis and rewriting.  This is the same as
     758             :  * pg_analyze_and_rewrite_fixedparams except that, instead of a fixed list of
     759             :  * parameter datatypes, a parser callback is supplied that can do
     760             :  * external-parameter resolution and possibly other things.
     761             :  */
     762             : List *
     763       38194 : pg_analyze_and_rewrite_withcb(RawStmt *parsetree,
     764             :                               const char *query_string,
     765             :                               ParserSetupHook parserSetup,
     766             :                               void *parserSetupArg,
     767             :                               QueryEnvironment *queryEnv)
     768             : {
     769             :     Query      *query;
     770             :     List       *querytree_list;
     771             : 
     772             :     TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
     773             : 
     774             :     /*
     775             :      * (1) Perform parse analysis.
     776             :      */
     777       38194 :     if (log_parser_stats)
     778           0 :         ResetUsage();
     779             : 
     780       38194 :     query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
     781             :                                  queryEnv);
     782             : 
     783       38076 :     if (log_parser_stats)
     784           0 :         ShowUsage("PARSE ANALYSIS STATISTICS");
     785             : 
     786             :     /*
     787             :      * (2) Rewrite the queries, as necessary
     788             :      */
     789       38076 :     querytree_list = pg_rewrite_query(query);
     790             : 
     791             :     TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
     792             : 
     793       38076 :     return querytree_list;
     794             : }
     795             : 
     796             : /*
     797             :  * Perform rewriting of a query produced by parse analysis.
     798             :  *
     799             :  * Note: query must just have come from the parser, because we do not do
     800             :  * AcquireRewriteLocks() on it.
     801             :  */
     802             : List *
     803      799450 : pg_rewrite_query(Query *query)
     804             : {
     805             :     List       *querytree_list;
     806             : 
     807      799450 :     if (Debug_print_parse)
     808           0 :         elog_node_display(LOG, "parse tree", query,
     809             :                           Debug_pretty_print);
     810             : 
     811      799450 :     if (log_parser_stats)
     812           0 :         ResetUsage();
     813             : 
     814      799450 :     if (query->commandType == CMD_UTILITY)
     815             :     {
     816             :         /* don't rewrite utilities, just dump 'em into result list */
     817      386290 :         querytree_list = list_make1(query);
     818             :     }
     819             :     else
     820             :     {
     821             :         /* rewrite regular queries */
     822      413160 :         querytree_list = QueryRewrite(query);
     823             :     }
     824             : 
     825      798760 :     if (log_parser_stats)
     826           0 :         ShowUsage("REWRITER STATISTICS");
     827             : 
     828             : #ifdef DEBUG_NODE_TESTS_ENABLED
     829             : 
     830             :     /* Optional debugging check: pass querytree through copyObject() */
     831      798760 :     if (Debug_copy_parse_plan_trees)
     832             :     {
     833             :         List       *new_list;
     834             : 
     835      798760 :         new_list = copyObject(querytree_list);
     836             :         /* This checks both copyObject() and the equal() routines... */
     837      798760 :         if (!equal(new_list, querytree_list))
     838           0 :             elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
     839             :         else
     840      798760 :             querytree_list = new_list;
     841             :     }
     842             : 
     843             :     /* Optional debugging check: pass querytree through outfuncs/readfuncs */
     844      798760 :     if (Debug_write_read_parse_plan_trees)
     845             :     {
     846           0 :         List       *new_list = NIL;
     847             :         ListCell   *lc;
     848             : 
     849           0 :         foreach(lc, querytree_list)
     850             :         {
     851           0 :             Query      *curr_query = lfirst_node(Query, lc);
     852           0 :             char       *str = nodeToStringWithLocations(curr_query);
     853           0 :             Query      *new_query = stringToNodeWithLocations(str);
     854             : 
     855             :             /*
     856             :              * queryId is not saved in stored rules, but we must preserve it
     857             :              * here to avoid breaking pg_stat_statements.
     858             :              */
     859           0 :             new_query->queryId = curr_query->queryId;
     860             : 
     861           0 :             new_list = lappend(new_list, new_query);
     862           0 :             pfree(str);
     863             :         }
     864             : 
     865             :         /* This checks both outfuncs/readfuncs and the equal() routines... */
     866           0 :         if (!equal(new_list, querytree_list))
     867           0 :             elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
     868             :         else
     869           0 :             querytree_list = new_list;
     870             :     }
     871             : 
     872             : #endif                          /* DEBUG_NODE_TESTS_ENABLED */
     873             : 
     874      798760 :     if (Debug_print_rewritten)
     875           0 :         elog_node_display(LOG, "rewritten parse tree", querytree_list,
     876             :                           Debug_pretty_print);
     877             : 
     878      798760 :     return querytree_list;
     879             : }
     880             : 
     881             : 
     882             : /*
     883             :  * Generate a plan for a single already-rewritten query.
     884             :  * This is a thin wrapper around planner() and takes the same parameters.
     885             :  */
     886             : PlannedStmt *
     887      451924 : pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
     888             :               ParamListInfo boundParams, ExplainState *es)
     889             : {
     890             :     PlannedStmt *plan;
     891             : 
     892             :     /* Utility commands have no plans. */
     893      451924 :     if (querytree->commandType == CMD_UTILITY)
     894           0 :         return NULL;
     895             : 
     896             :     /* Planner must have a snapshot in case it calls user-defined functions. */
     897             :     Assert(ActiveSnapshotSet());
     898             : 
     899             :     TRACE_POSTGRESQL_QUERY_PLAN_START();
     900             : 
     901      451924 :     if (log_planner_stats)
     902           0 :         ResetUsage();
     903             : 
     904             :     /* call the optimizer */
     905      451924 :     plan = planner(querytree, query_string, cursorOptions, boundParams, es);
     906             : 
     907      447120 :     if (log_planner_stats)
     908           0 :         ShowUsage("PLANNER STATISTICS");
     909             : 
     910             : #ifdef DEBUG_NODE_TESTS_ENABLED
     911             : 
     912             :     /* Optional debugging check: pass plan tree through copyObject() */
     913      447120 :     if (Debug_copy_parse_plan_trees)
     914             :     {
     915      447120 :         PlannedStmt *new_plan = copyObject(plan);
     916             : 
     917             :         /*
     918             :          * equal() currently does not have routines to compare Plan nodes, so
     919             :          * don't try to test equality here.  Perhaps fix someday?
     920             :          */
     921             : #ifdef NOT_USED
     922             :         /* This checks both copyObject() and the equal() routines... */
     923             :         if (!equal(new_plan, plan))
     924             :             elog(WARNING, "copyObject() failed to produce an equal plan tree");
     925             :         else
     926             : #endif
     927      447120 :             plan = new_plan;
     928             :     }
     929             : 
     930             :     /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
     931      447120 :     if (Debug_write_read_parse_plan_trees)
     932             :     {
     933             :         char       *str;
     934             :         PlannedStmt *new_plan;
     935             : 
     936           0 :         str = nodeToStringWithLocations(plan);
     937           0 :         new_plan = stringToNodeWithLocations(str);
     938           0 :         pfree(str);
     939             : 
     940             :         /*
     941             :          * equal() currently does not have routines to compare Plan nodes, so
     942             :          * don't try to test equality here.  Perhaps fix someday?
     943             :          */
     944             : #ifdef NOT_USED
     945             :         /* This checks both outfuncs/readfuncs and the equal() routines... */
     946             :         if (!equal(new_plan, plan))
     947             :             elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
     948             :         else
     949             : #endif
     950           0 :             plan = new_plan;
     951             :     }
     952             : 
     953             : #endif                          /* DEBUG_NODE_TESTS_ENABLED */
     954             : 
     955             :     /*
     956             :      * Print plan if debugging.
     957             :      */
     958      447120 :     if (Debug_print_plan)
     959           0 :         elog_node_display(LOG, "plan", plan, Debug_pretty_print);
     960             : 
     961             :     TRACE_POSTGRESQL_QUERY_PLAN_DONE();
     962             : 
     963      447120 :     return plan;
     964             : }
     965             : 
     966             : /*
     967             :  * Generate plans for a list of already-rewritten queries.
     968             :  *
     969             :  * For normal optimizable statements, invoke the planner.  For utility
     970             :  * statements, just make a wrapper PlannedStmt node.
     971             :  *
     972             :  * The result is a list of PlannedStmt nodes.
     973             :  */
     974             : List *
     975      806948 : pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions,
     976             :                 ParamListInfo boundParams)
     977             : {
     978      806948 :     List       *stmt_list = NIL;
     979             :     ListCell   *query_list;
     980             : 
     981     1609758 :     foreach(query_list, querytrees)
     982             :     {
     983      807554 :         Query      *query = lfirst_node(Query, query_list);
     984             :         PlannedStmt *stmt;
     985             : 
     986      807554 :         if (query->commandType == CMD_UTILITY)
     987             :         {
     988             :             /* Utility commands require no planning. */
     989      386268 :             stmt = makeNode(PlannedStmt);
     990      386268 :             stmt->commandType = CMD_UTILITY;
     991      386268 :             stmt->canSetTag = query->canSetTag;
     992      386268 :             stmt->utilityStmt = query->utilityStmt;
     993      386268 :             stmt->stmt_location = query->stmt_location;
     994      386268 :             stmt->stmt_len = query->stmt_len;
     995      386268 :             stmt->queryId = query->queryId;
     996      386268 :             stmt->planOrigin = PLAN_STMT_INTERNAL;
     997             :         }
     998             :         else
     999             :         {
    1000      421286 :             stmt = pg_plan_query(query, query_string, cursorOptions,
    1001             :                                  boundParams, NULL);
    1002             :         }
    1003             : 
    1004      802810 :         stmt_list = lappend(stmt_list, stmt);
    1005             :     }
    1006             : 
    1007      802204 :     return stmt_list;
    1008             : }
    1009             : 
    1010             : 
    1011             : /*
    1012             :  * exec_simple_query
    1013             :  *
    1014             :  * Execute a "simple Query" protocol message.
    1015             :  */
    1016             : static void
    1017      657062 : exec_simple_query(const char *query_string)
    1018             : {
    1019      657062 :     CommandDest dest = whereToSendOutput;
    1020             :     MemoryContext oldcontext;
    1021             :     List       *parsetree_list;
    1022             :     ListCell   *parsetree_item;
    1023      657062 :     bool        save_log_statement_stats = log_statement_stats;
    1024      657062 :     bool        was_logged = false;
    1025             :     bool        use_implicit_block;
    1026             :     char        msec_str[32];
    1027             : 
    1028             :     /*
    1029             :      * Report query to various monitoring facilities.
    1030             :      */
    1031      657062 :     debug_query_string = query_string;
    1032             : 
    1033      657062 :     pgstat_report_activity(STATE_RUNNING, query_string);
    1034             : 
    1035             :     TRACE_POSTGRESQL_QUERY_START(query_string);
    1036             : 
    1037             :     /*
    1038             :      * We use save_log_statement_stats so ShowUsage doesn't report incorrect
    1039             :      * results because ResetUsage wasn't called.
    1040             :      */
    1041      657062 :     if (save_log_statement_stats)
    1042           0 :         ResetUsage();
    1043             : 
    1044             :     /*
    1045             :      * Start up a transaction command.  All queries generated by the
    1046             :      * query_string will be in this same command block, *unless* we find a
    1047             :      * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
    1048             :      * one of those, else bad things will happen in xact.c. (Note that this
    1049             :      * will normally change current memory context.)
    1050             :      */
    1051      657062 :     start_xact_command();
    1052             : 
    1053             :     /*
    1054             :      * Zap any pre-existing unnamed statement.  (While not strictly necessary,
    1055             :      * it seems best to define simple-Query mode as if it used the unnamed
    1056             :      * statement and portal; this ensures we recover any storage used by prior
    1057             :      * unnamed operations.)
    1058             :      */
    1059      657062 :     drop_unnamed_stmt();
    1060             : 
    1061             :     /*
    1062             :      * Switch to appropriate context for constructing parsetrees.
    1063             :      */
    1064      657062 :     oldcontext = MemoryContextSwitchTo(MessageContext);
    1065             : 
    1066             :     /*
    1067             :      * Do basic parsing of the query or queries (this should be safe even if
    1068             :      * we are in aborted transaction state!)
    1069             :      */
    1070      657062 :     parsetree_list = pg_parse_query(query_string);
    1071             : 
    1072             :     /* Log immediately if dictated by log_statement */
    1073      655872 :     if (check_log_statement(parsetree_list))
    1074             :     {
    1075      251824 :         ereport(LOG,
    1076             :                 (errmsg("statement: %s", query_string),
    1077             :                  errhidestmt(true),
    1078             :                  errdetail_execute(parsetree_list)));
    1079      251824 :         was_logged = true;
    1080             :     }
    1081             : 
    1082             :     /*
    1083             :      * Switch back to transaction context to enter the loop.
    1084             :      */
    1085      655872 :     MemoryContextSwitchTo(oldcontext);
    1086             : 
    1087             :     /*
    1088             :      * For historical reasons, if multiple SQL statements are given in a
    1089             :      * single "simple Query" message, we execute them as a single transaction,
    1090             :      * unless explicit transaction control commands are included to make
    1091             :      * portions of the list be separate transactions.  To represent this
    1092             :      * behavior properly in the transaction machinery, we use an "implicit"
    1093             :      * transaction block.
    1094             :      */
    1095      655872 :     use_implicit_block = (list_length(parsetree_list) > 1);
    1096             : 
    1097             :     /*
    1098             :      * Run through the raw parsetree(s) and process each one.
    1099             :      */
    1100     1313834 :     foreach(parsetree_item, parsetree_list)
    1101             :     {
    1102      700424 :         RawStmt    *parsetree = lfirst_node(RawStmt, parsetree_item);
    1103      700424 :         bool        snapshot_set = false;
    1104             :         CommandTag  commandTag;
    1105             :         QueryCompletion qc;
    1106      700424 :         MemoryContext per_parsetree_context = NULL;
    1107             :         List       *querytree_list,
    1108             :                    *plantree_list;
    1109             :         Portal      portal;
    1110             :         DestReceiver *receiver;
    1111             :         int16       format;
    1112             :         const char *cmdtagname;
    1113             :         size_t      cmdtaglen;
    1114             : 
    1115      700424 :         pgstat_report_query_id(0, true);
    1116      700424 :         pgstat_report_plan_id(0, true);
    1117             : 
    1118             :         /*
    1119             :          * Get the command name for use in status display (it also becomes the
    1120             :          * default completion tag, down inside PortalRun).  Set ps_status and
    1121             :          * do any special start-of-SQL-command processing needed by the
    1122             :          * destination.
    1123             :          */
    1124      700424 :         commandTag = CreateCommandTag(parsetree->stmt);
    1125      700424 :         cmdtagname = GetCommandTagNameAndLen(commandTag, &cmdtaglen);
    1126             : 
    1127      700424 :         set_ps_display_with_len(cmdtagname, cmdtaglen);
    1128             : 
    1129      700424 :         BeginCommand(commandTag, dest);
    1130             : 
    1131             :         /*
    1132             :          * If we are in an aborted transaction, reject all commands except
    1133             :          * COMMIT/ABORT.  It is important that this test occur before we try
    1134             :          * to do parse analysis, rewrite, or planning, since all those phases
    1135             :          * try to do database accesses, which may fail in abort state. (It
    1136             :          * might be safe to allow some additional utility commands in this
    1137             :          * state, but not many...)
    1138             :          */
    1139      700424 :         if (IsAbortedTransactionBlockState() &&
    1140        1796 :             !IsTransactionExitStmt(parsetree->stmt))
    1141          92 :             ereport(ERROR,
    1142             :                     (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    1143             :                      errmsg("current transaction is aborted, "
    1144             :                             "commands ignored until end of transaction block"),
    1145             :                      errdetail_abort()));
    1146             : 
    1147             :         /* Make sure we are in a transaction command */
    1148      700332 :         start_xact_command();
    1149             : 
    1150             :         /*
    1151             :          * If using an implicit transaction block, and we're not already in a
    1152             :          * transaction block, start an implicit block to force this statement
    1153             :          * to be grouped together with any following ones.  (We must do this
    1154             :          * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
    1155             :          * list would cause later statements to not be grouped.)
    1156             :          */
    1157      700332 :         if (use_implicit_block)
    1158       59548 :             BeginImplicitTransactionBlock();
    1159             : 
    1160             :         /* If we got a cancel signal in parsing or prior command, quit */
    1161      700332 :         CHECK_FOR_INTERRUPTS();
    1162             : 
    1163             :         /*
    1164             :          * Set up a snapshot if parse analysis/planning will need one.
    1165             :          */
    1166      700332 :         if (analyze_requires_snapshot(parsetree))
    1167             :         {
    1168      367586 :             PushActiveSnapshot(GetTransactionSnapshot());
    1169      367586 :             snapshot_set = true;
    1170             :         }
    1171             : 
    1172             :         /*
    1173             :          * OK to analyze, rewrite, and plan this query.
    1174             :          *
    1175             :          * Switch to appropriate context for constructing query and plan trees
    1176             :          * (these can't be in the transaction context, as that will get reset
    1177             :          * when the command is COMMIT/ROLLBACK).  If we have multiple
    1178             :          * parsetrees, we use a separate context for each one, so that we can
    1179             :          * free that memory before moving on to the next one.  But for the
    1180             :          * last (or only) parsetree, just use MessageContext, which will be
    1181             :          * reset shortly after completion anyway.  In event of an error, the
    1182             :          * per_parsetree_context will be deleted when MessageContext is reset.
    1183             :          */
    1184      700332 :         if (lnext(parsetree_list, parsetree_item) != NULL)
    1185             :         {
    1186             :             per_parsetree_context =
    1187       45850 :                 AllocSetContextCreate(MessageContext,
    1188             :                                       "per-parsetree message context",
    1189             :                                       ALLOCSET_DEFAULT_SIZES);
    1190       45850 :             oldcontext = MemoryContextSwitchTo(per_parsetree_context);
    1191             :         }
    1192             :         else
    1193      654482 :             oldcontext = MemoryContextSwitchTo(MessageContext);
    1194             : 
    1195      700332 :         querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
    1196             :                                                             NULL, 0, NULL);
    1197             : 
    1198      691986 :         plantree_list = pg_plan_queries(querytree_list, query_string,
    1199             :                                         CURSOR_OPT_PARALLEL_OK, NULL);
    1200             : 
    1201             :         /*
    1202             :          * Done with the snapshot used for parsing/planning.
    1203             :          *
    1204             :          * While it looks promising to reuse the same snapshot for query
    1205             :          * execution (at least for simple protocol), unfortunately it causes
    1206             :          * execution to use a snapshot that has been acquired before locking
    1207             :          * any of the tables mentioned in the query.  This creates user-
    1208             :          * visible anomalies, so refrain.  Refer to
    1209             :          * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
    1210             :          */
    1211      687452 :         if (snapshot_set)
    1212      354706 :             PopActiveSnapshot();
    1213             : 
    1214             :         /* If we got a cancel signal in analysis or planning, quit */
    1215      687452 :         CHECK_FOR_INTERRUPTS();
    1216             : 
    1217             :         /*
    1218             :          * Create unnamed portal to run the query or queries in. If there
    1219             :          * already is one, silently drop it.
    1220             :          */
    1221      687452 :         portal = CreatePortal("", true, true);
    1222             :         /* Don't display the portal in pg_cursors */
    1223      687452 :         portal->visible = false;
    1224             : 
    1225             :         /*
    1226             :          * We don't have to copy anything into the portal, because everything
    1227             :          * we are passing here is in MessageContext or the
    1228             :          * per_parsetree_context, and so will outlive the portal anyway.
    1229             :          */
    1230      687452 :         PortalDefineQuery(portal,
    1231             :                           NULL,
    1232             :                           query_string,
    1233             :                           commandTag,
    1234             :                           plantree_list,
    1235             :                           NULL);
    1236             : 
    1237             :         /*
    1238             :          * Start the portal.  No parameters here.
    1239             :          */
    1240      687452 :         PortalStart(portal, NULL, 0, InvalidSnapshot);
    1241             : 
    1242             :         /*
    1243             :          * Select the appropriate output format: text unless we are doing a
    1244             :          * FETCH from a binary cursor.  (Pretty grotty to have to do this here
    1245             :          * --- but it avoids grottiness in other places.  Ah, the joys of
    1246             :          * backward compatibility...)
    1247             :          */
    1248      686804 :         format = 0;             /* TEXT is default */
    1249      686804 :         if (IsA(parsetree->stmt, FetchStmt))
    1250             :         {
    1251        5978 :             FetchStmt  *stmt = (FetchStmt *) parsetree->stmt;
    1252             : 
    1253        5978 :             if (!stmt->ismove)
    1254             :             {
    1255        5910 :                 Portal      fportal = GetPortalByName(stmt->portalname);
    1256             : 
    1257        5910 :                 if (PortalIsValid(fportal) &&
    1258        5876 :                     (fportal->cursorOptions & CURSOR_OPT_BINARY))
    1259           8 :                     format = 1; /* BINARY */
    1260             :             }
    1261             :         }
    1262      686804 :         PortalSetResultFormat(portal, 1, &format);
    1263             : 
    1264             :         /*
    1265             :          * Now we can create the destination receiver object.
    1266             :          */
    1267      686804 :         receiver = CreateDestReceiver(dest);
    1268      686804 :         if (dest == DestRemote)
    1269      607966 :             SetRemoteDestReceiverParams(receiver, portal);
    1270             : 
    1271             :         /*
    1272             :          * Switch back to transaction context for execution.
    1273             :          */
    1274      686804 :         MemoryContextSwitchTo(oldcontext);
    1275             : 
    1276             :         /*
    1277             :          * Run the portal to completion, and then drop it (and the receiver).
    1278             :          */
    1279      686804 :         (void) PortalRun(portal,
    1280             :                          FETCH_ALL,
    1281             :                          true,  /* always top level */
    1282             :                          receiver,
    1283             :                          receiver,
    1284             :                          &qc);
    1285             : 
    1286      658514 :         receiver->rDestroy(receiver);
    1287             : 
    1288      658514 :         PortalDrop(portal, false);
    1289             : 
    1290      658514 :         if (lnext(parsetree_list, parsetree_item) == NULL)
    1291             :         {
    1292             :             /*
    1293             :              * If this is the last parsetree of the query string, close down
    1294             :              * transaction statement before reporting command-complete.  This
    1295             :              * is so that any end-of-transaction errors are reported before
    1296             :              * the command-complete message is issued, to avoid confusing
    1297             :              * clients who will expect either a command-complete message or an
    1298             :              * error, not one and then the other.  Also, if we're using an
    1299             :              * implicit transaction block, we must close that out first.
    1300             :              */
    1301      612708 :             if (use_implicit_block)
    1302       13606 :                 EndImplicitTransactionBlock();
    1303      612708 :             finish_xact_command();
    1304             :         }
    1305       45806 :         else if (IsA(parsetree->stmt, TransactionStmt))
    1306             :         {
    1307             :             /*
    1308             :              * If this was a transaction control statement, commit it. We will
    1309             :              * start a new xact command for the next command.
    1310             :              */
    1311        1058 :             finish_xact_command();
    1312             :         }
    1313             :         else
    1314             :         {
    1315             :             /*
    1316             :              * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
    1317             :              * we're not calling finish_xact_command().  (The implicit
    1318             :              * transaction block should have prevented it from getting set.)
    1319             :              */
    1320             :             Assert(!(MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT));
    1321             : 
    1322             :             /*
    1323             :              * We need a CommandCounterIncrement after every query, except
    1324             :              * those that start or end a transaction block.
    1325             :              */
    1326       44748 :             CommandCounterIncrement();
    1327             : 
    1328             :             /*
    1329             :              * Disable statement timeout between queries of a multi-query
    1330             :              * string, so that the timeout applies separately to each query.
    1331             :              * (Our next loop iteration will start a fresh timeout.)
    1332             :              */
    1333       44748 :             disable_statement_timeout();
    1334             :         }
    1335             : 
    1336             :         /*
    1337             :          * Tell client that we're done with this query.  Note we emit exactly
    1338             :          * one EndCommand report for each raw parsetree, thus one for each SQL
    1339             :          * command the client sent, regardless of rewriting. (But a command
    1340             :          * aborted by error will not send an EndCommand report at all.)
    1341             :          */
    1342      657962 :         EndCommand(&qc, dest, false);
    1343             : 
    1344             :         /* Now we may drop the per-parsetree context, if one was created. */
    1345      657962 :         if (per_parsetree_context)
    1346       45806 :             MemoryContextDelete(per_parsetree_context);
    1347             :     }                           /* end loop over parsetrees */
    1348             : 
    1349             :     /*
    1350             :      * Close down transaction statement, if one is open.  (This will only do
    1351             :      * something if the parsetree list was empty; otherwise the last loop
    1352             :      * iteration already did it.)
    1353             :      */
    1354      613410 :     finish_xact_command();
    1355             : 
    1356             :     /*
    1357             :      * If there were no parsetrees, return EmptyQueryResponse message.
    1358             :      */
    1359      613410 :     if (!parsetree_list)
    1360        1254 :         NullCommand(dest);
    1361             : 
    1362             :     /*
    1363             :      * Emit duration logging if appropriate.
    1364             :      */
    1365      613410 :     switch (check_log_duration(msec_str, was_logged))
    1366             :     {
    1367          36 :         case 1:
    1368          36 :             ereport(LOG,
    1369             :                     (errmsg("duration: %s ms", msec_str),
    1370             :                      errhidestmt(true)));
    1371          36 :             break;
    1372           0 :         case 2:
    1373           0 :             ereport(LOG,
    1374             :                     (errmsg("duration: %s ms  statement: %s",
    1375             :                             msec_str, query_string),
    1376             :                      errhidestmt(true),
    1377             :                      errdetail_execute(parsetree_list)));
    1378           0 :             break;
    1379             :     }
    1380             : 
    1381      613410 :     if (save_log_statement_stats)
    1382           0 :         ShowUsage("QUERY STATISTICS");
    1383             : 
    1384             :     TRACE_POSTGRESQL_QUERY_DONE(query_string);
    1385             : 
    1386      613410 :     debug_query_string = NULL;
    1387      613410 : }
    1388             : 
    1389             : /*
    1390             :  * exec_parse_message
    1391             :  *
    1392             :  * Execute a "Parse" protocol message.
    1393             :  */
    1394             : static void
    1395       11082 : exec_parse_message(const char *query_string,    /* string to execute */
    1396             :                    const char *stmt_name,   /* name for prepared stmt */
    1397             :                    Oid *paramTypes, /* parameter types */
    1398             :                    int numParams)   /* number of parameters */
    1399             : {
    1400       11082 :     MemoryContext unnamed_stmt_context = NULL;
    1401             :     MemoryContext oldcontext;
    1402             :     List       *parsetree_list;
    1403             :     RawStmt    *raw_parse_tree;
    1404             :     List       *querytree_list;
    1405             :     CachedPlanSource *psrc;
    1406             :     bool        is_named;
    1407       11082 :     bool        save_log_statement_stats = log_statement_stats;
    1408             :     char        msec_str[32];
    1409             : 
    1410             :     /*
    1411             :      * Report query to various monitoring facilities.
    1412             :      */
    1413       11082 :     debug_query_string = query_string;
    1414             : 
    1415       11082 :     pgstat_report_activity(STATE_RUNNING, query_string);
    1416             : 
    1417       11082 :     set_ps_display("PARSE");
    1418             : 
    1419       11082 :     if (save_log_statement_stats)
    1420           0 :         ResetUsage();
    1421             : 
    1422       11082 :     ereport(DEBUG2,
    1423             :             (errmsg_internal("parse %s: %s",
    1424             :                              *stmt_name ? stmt_name : "<unnamed>",
    1425             :                              query_string)));
    1426             : 
    1427             :     /*
    1428             :      * Start up a transaction command so we can run parse analysis etc. (Note
    1429             :      * that this will normally change current memory context.) Nothing happens
    1430             :      * if we are already in one.  This also arms the statement timeout if
    1431             :      * necessary.
    1432             :      */
    1433       11082 :     start_xact_command();
    1434             : 
    1435             :     /*
    1436             :      * Switch to appropriate context for constructing parsetrees.
    1437             :      *
    1438             :      * We have two strategies depending on whether the prepared statement is
    1439             :      * named or not.  For a named prepared statement, we do parsing in
    1440             :      * MessageContext and copy the finished trees into the prepared
    1441             :      * statement's plancache entry; then the reset of MessageContext releases
    1442             :      * temporary space used by parsing and rewriting. For an unnamed prepared
    1443             :      * statement, we assume the statement isn't going to hang around long, so
    1444             :      * getting rid of temp space quickly is probably not worth the costs of
    1445             :      * copying parse trees.  So in this case, we create the plancache entry's
    1446             :      * query_context here, and do all the parsing work therein.
    1447             :      */
    1448       11082 :     is_named = (stmt_name[0] != '\0');
    1449       11082 :     if (is_named)
    1450             :     {
    1451             :         /* Named prepared statement --- parse in MessageContext */
    1452        4372 :         oldcontext = MemoryContextSwitchTo(MessageContext);
    1453             :     }
    1454             :     else
    1455             :     {
    1456             :         /* Unnamed prepared statement --- release any prior unnamed stmt */
    1457        6710 :         drop_unnamed_stmt();
    1458             :         /* Create context for parsing */
    1459             :         unnamed_stmt_context =
    1460        6710 :             AllocSetContextCreate(MessageContext,
    1461             :                                   "unnamed prepared statement",
    1462             :                                   ALLOCSET_DEFAULT_SIZES);
    1463        6710 :         oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
    1464             :     }
    1465             : 
    1466             :     /*
    1467             :      * Do basic parsing of the query or queries (this should be safe even if
    1468             :      * we are in aborted transaction state!)
    1469             :      */
    1470       11082 :     parsetree_list = pg_parse_query(query_string);
    1471             : 
    1472             :     /*
    1473             :      * We only allow a single user statement in a prepared statement. This is
    1474             :      * mainly to keep the protocol simple --- otherwise we'd need to worry
    1475             :      * about multiple result tupdescs and things like that.
    1476             :      */
    1477       11068 :     if (list_length(parsetree_list) > 1)
    1478           8 :         ereport(ERROR,
    1479             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1480             :                  errmsg("cannot insert multiple commands into a prepared statement")));
    1481             : 
    1482       11060 :     if (parsetree_list != NIL)
    1483             :     {
    1484       11054 :         bool        snapshot_set = false;
    1485             : 
    1486       11054 :         raw_parse_tree = linitial_node(RawStmt, parsetree_list);
    1487             : 
    1488             :         /*
    1489             :          * If we are in an aborted transaction, reject all commands except
    1490             :          * COMMIT/ROLLBACK.  It is important that this test occur before we
    1491             :          * try to do parse analysis, rewrite, or planning, since all those
    1492             :          * phases try to do database accesses, which may fail in abort state.
    1493             :          * (It might be safe to allow some additional utility commands in this
    1494             :          * state, but not many...)
    1495             :          */
    1496       11054 :         if (IsAbortedTransactionBlockState() &&
    1497           2 :             !IsTransactionExitStmt(raw_parse_tree->stmt))
    1498           2 :             ereport(ERROR,
    1499             :                     (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    1500             :                      errmsg("current transaction is aborted, "
    1501             :                             "commands ignored until end of transaction block"),
    1502             :                      errdetail_abort()));
    1503             : 
    1504             :         /*
    1505             :          * Create the CachedPlanSource before we do parse analysis, since it
    1506             :          * needs to see the unmodified raw parse tree.
    1507             :          */
    1508       11052 :         psrc = CreateCachedPlan(raw_parse_tree, query_string,
    1509             :                                 CreateCommandTag(raw_parse_tree->stmt));
    1510             : 
    1511             :         /*
    1512             :          * Set up a snapshot if parse analysis will need one.
    1513             :          */
    1514       11052 :         if (analyze_requires_snapshot(raw_parse_tree))
    1515             :         {
    1516       10338 :             PushActiveSnapshot(GetTransactionSnapshot());
    1517       10338 :             snapshot_set = true;
    1518             :         }
    1519             : 
    1520             :         /*
    1521             :          * Analyze and rewrite the query.  Note that the originally specified
    1522             :          * parameter set is not required to be complete, so we have to use
    1523             :          * pg_analyze_and_rewrite_varparams().
    1524             :          */
    1525       11052 :         querytree_list = pg_analyze_and_rewrite_varparams(raw_parse_tree,
    1526             :                                                           query_string,
    1527             :                                                           &paramTypes,
    1528             :                                                           &numParams,
    1529             :                                                           NULL);
    1530             : 
    1531             :         /* Done with the snapshot used for parsing */
    1532       11030 :         if (snapshot_set)
    1533       10316 :             PopActiveSnapshot();
    1534             :     }
    1535             :     else
    1536             :     {
    1537             :         /* Empty input string.  This is legal. */
    1538           6 :         raw_parse_tree = NULL;
    1539           6 :         psrc = CreateCachedPlan(raw_parse_tree, query_string,
    1540             :                                 CMDTAG_UNKNOWN);
    1541           6 :         querytree_list = NIL;
    1542             :     }
    1543             : 
    1544             :     /*
    1545             :      * CachedPlanSource must be a direct child of MessageContext before we
    1546             :      * reparent unnamed_stmt_context under it, else we have a disconnected
    1547             :      * circular subgraph.  Klugy, but less so than flipping contexts even more
    1548             :      * above.
    1549             :      */
    1550       11036 :     if (unnamed_stmt_context)
    1551        6672 :         MemoryContextSetParent(psrc->context, MessageContext);
    1552             : 
    1553             :     /* Finish filling in the CachedPlanSource */
    1554       11036 :     CompleteCachedPlan(psrc,
    1555             :                        querytree_list,
    1556             :                        unnamed_stmt_context,
    1557             :                        paramTypes,
    1558             :                        numParams,
    1559             :                        NULL,
    1560             :                        NULL,
    1561             :                        CURSOR_OPT_PARALLEL_OK,  /* allow parallel mode */
    1562             :                        true);   /* fixed result */
    1563             : 
    1564             :     /* If we got a cancel signal during analysis, quit */
    1565       11036 :     CHECK_FOR_INTERRUPTS();
    1566             : 
    1567       11036 :     if (is_named)
    1568             :     {
    1569             :         /*
    1570             :          * Store the query as a prepared statement.
    1571             :          */
    1572        4364 :         StorePreparedStatement(stmt_name, psrc, false);
    1573             :     }
    1574             :     else
    1575             :     {
    1576             :         /*
    1577             :          * We just save the CachedPlanSource into unnamed_stmt_psrc.
    1578             :          */
    1579        6672 :         SaveCachedPlan(psrc);
    1580        6672 :         unnamed_stmt_psrc = psrc;
    1581             :     }
    1582             : 
    1583       11036 :     MemoryContextSwitchTo(oldcontext);
    1584             : 
    1585             :     /*
    1586             :      * We do NOT close the open transaction command here; that only happens
    1587             :      * when the client sends Sync.  Instead, do CommandCounterIncrement just
    1588             :      * in case something happened during parse/plan.
    1589             :      */
    1590       11036 :     CommandCounterIncrement();
    1591             : 
    1592             :     /*
    1593             :      * Send ParseComplete.
    1594             :      */
    1595       11036 :     if (whereToSendOutput == DestRemote)
    1596       11036 :         pq_putemptymessage(PqMsg_ParseComplete);
    1597             : 
    1598             :     /*
    1599             :      * Emit duration logging if appropriate.
    1600             :      */
    1601       11036 :     switch (check_log_duration(msec_str, false))
    1602             :     {
    1603           0 :         case 1:
    1604           0 :             ereport(LOG,
    1605             :                     (errmsg("duration: %s ms", msec_str),
    1606             :                      errhidestmt(true)));
    1607           0 :             break;
    1608          26 :         case 2:
    1609          26 :             ereport(LOG,
    1610             :                     (errmsg("duration: %s ms  parse %s: %s",
    1611             :                             msec_str,
    1612             :                             *stmt_name ? stmt_name : "<unnamed>",
    1613             :                             query_string),
    1614             :                      errhidestmt(true)));
    1615          26 :             break;
    1616             :     }
    1617             : 
    1618       11036 :     if (save_log_statement_stats)
    1619           0 :         ShowUsage("PARSE MESSAGE STATISTICS");
    1620             : 
    1621       11036 :     debug_query_string = NULL;
    1622       11036 : }
    1623             : 
    1624             : /*
    1625             :  * exec_bind_message
    1626             :  *
    1627             :  * Process a "Bind" message to create a portal from a prepared statement
    1628             :  */
    1629             : static void
    1630       22142 : exec_bind_message(StringInfo input_message)
    1631             : {
    1632             :     const char *portal_name;
    1633             :     const char *stmt_name;
    1634             :     int         numPFormats;
    1635       22142 :     int16      *pformats = NULL;
    1636             :     int         numParams;
    1637             :     int         numRFormats;
    1638       22142 :     int16      *rformats = NULL;
    1639             :     CachedPlanSource *psrc;
    1640             :     CachedPlan *cplan;
    1641             :     Portal      portal;
    1642             :     char       *query_string;
    1643             :     char       *saved_stmt_name;
    1644             :     ParamListInfo params;
    1645             :     MemoryContext oldContext;
    1646       22142 :     bool        save_log_statement_stats = log_statement_stats;
    1647       22142 :     bool        snapshot_set = false;
    1648             :     char        msec_str[32];
    1649             :     ParamsErrorCbData params_data;
    1650             :     ErrorContextCallback params_errcxt;
    1651             :     ListCell   *lc;
    1652             : 
    1653             :     /* Get the fixed part of the message */
    1654       22142 :     portal_name = pq_getmsgstring(input_message);
    1655       22142 :     stmt_name = pq_getmsgstring(input_message);
    1656             : 
    1657       22142 :     ereport(DEBUG2,
    1658             :             (errmsg_internal("bind %s to %s",
    1659             :                              *portal_name ? portal_name : "<unnamed>",
    1660             :                              *stmt_name ? stmt_name : "<unnamed>")));
    1661             : 
    1662             :     /* Find prepared statement */
    1663       22142 :     if (stmt_name[0] != '\0')
    1664             :     {
    1665             :         PreparedStatement *pstmt;
    1666             : 
    1667       15542 :         pstmt = FetchPreparedStatement(stmt_name, true);
    1668       15534 :         psrc = pstmt->plansource;
    1669             :     }
    1670             :     else
    1671             :     {
    1672             :         /* special-case the unnamed statement */
    1673        6600 :         psrc = unnamed_stmt_psrc;
    1674        6600 :         if (!psrc)
    1675           0 :             ereport(ERROR,
    1676             :                     (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
    1677             :                      errmsg("unnamed prepared statement does not exist")));
    1678             :     }
    1679             : 
    1680             :     /*
    1681             :      * Report query to various monitoring facilities.
    1682             :      */
    1683       22134 :     debug_query_string = psrc->query_string;
    1684             : 
    1685       22134 :     pgstat_report_activity(STATE_RUNNING, psrc->query_string);
    1686             : 
    1687       44008 :     foreach(lc, psrc->query_list)
    1688             :     {
    1689       22134 :         Query      *query = lfirst_node(Query, lc);
    1690             : 
    1691       22134 :         if (query->queryId != INT64CONST(0))
    1692             :         {
    1693         260 :             pgstat_report_query_id(query->queryId, false);
    1694         260 :             break;
    1695             :         }
    1696             :     }
    1697             : 
    1698       22134 :     set_ps_display("BIND");
    1699             : 
    1700       22134 :     if (save_log_statement_stats)
    1701           0 :         ResetUsage();
    1702             : 
    1703             :     /*
    1704             :      * Start up a transaction command so we can call functions etc. (Note that
    1705             :      * this will normally change current memory context.) Nothing happens if
    1706             :      * we are already in one.  This also arms the statement timeout if
    1707             :      * necessary.
    1708             :      */
    1709       22134 :     start_xact_command();
    1710             : 
    1711             :     /* Switch back to message context */
    1712       22134 :     MemoryContextSwitchTo(MessageContext);
    1713             : 
    1714             :     /* Get the parameter format codes */
    1715       22134 :     numPFormats = pq_getmsgint(input_message, 2);
    1716       22134 :     if (numPFormats > 0)
    1717             :     {
    1718        5108 :         pformats = palloc_array(int16, numPFormats);
    1719       12036 :         for (int i = 0; i < numPFormats; i++)
    1720        6928 :             pformats[i] = pq_getmsgint(input_message, 2);
    1721             :     }
    1722             : 
    1723             :     /* Get the parameter value count */
    1724       22134 :     numParams = pq_getmsgint(input_message, 2);
    1725             : 
    1726       22134 :     if (numPFormats > 1 && numPFormats != numParams)
    1727           0 :         ereport(ERROR,
    1728             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1729             :                  errmsg("bind message has %d parameter formats but %d parameters",
    1730             :                         numPFormats, numParams)));
    1731             : 
    1732       22134 :     if (numParams != psrc->num_params)
    1733          54 :         ereport(ERROR,
    1734             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1735             :                  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
    1736             :                         numParams, stmt_name, psrc->num_params)));
    1737             : 
    1738             :     /*
    1739             :      * If we are in aborted transaction state, the only portals we can
    1740             :      * actually run are those containing COMMIT or ROLLBACK commands. We
    1741             :      * disallow binding anything else to avoid problems with infrastructure
    1742             :      * that expects to run inside a valid transaction.  We also disallow
    1743             :      * binding any parameters, since we can't risk calling user-defined I/O
    1744             :      * functions.
    1745             :      */
    1746       22080 :     if (IsAbortedTransactionBlockState() &&
    1747           4 :         (!(psrc->raw_parse_tree &&
    1748           4 :            IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
    1749             :          numParams != 0))
    1750           0 :         ereport(ERROR,
    1751             :                 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    1752             :                  errmsg("current transaction is aborted, "
    1753             :                         "commands ignored until end of transaction block"),
    1754             :                  errdetail_abort()));
    1755             : 
    1756             :     /*
    1757             :      * Create the portal.  Allow silent replacement of an existing portal only
    1758             :      * if the unnamed portal is specified.
    1759             :      */
    1760       22080 :     if (portal_name[0] == '\0')
    1761       22080 :         portal = CreatePortal(portal_name, true, true);
    1762             :     else
    1763           0 :         portal = CreatePortal(portal_name, false, false);
    1764             : 
    1765             :     /*
    1766             :      * Prepare to copy stuff into the portal's memory context.  We do all this
    1767             :      * copying first, because it could possibly fail (out-of-memory) and we
    1768             :      * don't want a failure to occur between GetCachedPlan and
    1769             :      * PortalDefineQuery; that would result in leaking our plancache refcount.
    1770             :      */
    1771       22080 :     oldContext = MemoryContextSwitchTo(portal->portalContext);
    1772             : 
    1773             :     /* Copy the plan's query string into the portal */
    1774       22080 :     query_string = pstrdup(psrc->query_string);
    1775             : 
    1776             :     /* Likewise make a copy of the statement name, unless it's unnamed */
    1777       22080 :     if (stmt_name[0])
    1778       15528 :         saved_stmt_name = pstrdup(stmt_name);
    1779             :     else
    1780        6552 :         saved_stmt_name = NULL;
    1781             : 
    1782             :     /*
    1783             :      * Set a snapshot if we have parameters to fetch (since the input
    1784             :      * functions might need it) or the query isn't a utility command (and
    1785             :      * hence could require redoing parse analysis and planning).  We keep the
    1786             :      * snapshot active till we're done, so that plancache.c doesn't have to
    1787             :      * take new ones.
    1788             :      */
    1789       22080 :     if (numParams > 0 ||
    1790        8528 :         (psrc->raw_parse_tree &&
    1791        4264 :          analyze_requires_snapshot(psrc->raw_parse_tree)))
    1792             :     {
    1793       20010 :         PushActiveSnapshot(GetTransactionSnapshot());
    1794       20010 :         snapshot_set = true;
    1795             :     }
    1796             : 
    1797             :     /*
    1798             :      * Fetch parameters, if any, and store in the portal's memory context.
    1799             :      */
    1800       22080 :     if (numParams > 0)
    1801             :     {
    1802       17816 :         char      **knownTextValues = NULL; /* allocate on first use */
    1803             :         BindParamCbData one_param_data;
    1804             : 
    1805             :         /*
    1806             :          * Set up an error callback so that if there's an error in this phase,
    1807             :          * we can report the specific parameter causing the problem.
    1808             :          */
    1809       17816 :         one_param_data.portalName = portal->name;
    1810       17816 :         one_param_data.paramno = -1;
    1811       17816 :         one_param_data.paramval = NULL;
    1812       17816 :         params_errcxt.previous = error_context_stack;
    1813       17816 :         params_errcxt.callback = bind_param_error_callback;
    1814       17816 :         params_errcxt.arg = &one_param_data;
    1815       17816 :         error_context_stack = &params_errcxt;
    1816             : 
    1817       17816 :         params = makeParamList(numParams);
    1818             : 
    1819       46778 :         for (int paramno = 0; paramno < numParams; paramno++)
    1820             :         {
    1821       28964 :             Oid         ptype = psrc->param_types[paramno];
    1822             :             int32       plength;
    1823             :             Datum       pval;
    1824             :             bool        isNull;
    1825             :             StringInfoData pbuf;
    1826             :             char        csave;
    1827             :             int16       pformat;
    1828             : 
    1829       28964 :             one_param_data.paramno = paramno;
    1830       28964 :             one_param_data.paramval = NULL;
    1831             : 
    1832       28964 :             plength = pq_getmsgint(input_message, 4);
    1833       28964 :             isNull = (plength == -1);
    1834             : 
    1835       28964 :             if (!isNull)
    1836             :             {
    1837             :                 char       *pvalue;
    1838             : 
    1839             :                 /*
    1840             :                  * Rather than copying data around, we just initialize a
    1841             :                  * StringInfo pointing to the correct portion of the message
    1842             :                  * buffer.  We assume we can scribble on the message buffer to
    1843             :                  * add a trailing NUL which is required for the input function
    1844             :                  * call.
    1845             :                  */
    1846       27746 :                 pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
    1847       27746 :                 csave = pvalue[plength];
    1848       27746 :                 pvalue[plength] = '\0';
    1849       27746 :                 initReadOnlyStringInfo(&pbuf, pvalue, plength);
    1850             :             }
    1851             :             else
    1852             :             {
    1853        1218 :                 pbuf.data = NULL;   /* keep compiler quiet */
    1854        1218 :                 csave = 0;
    1855             :             }
    1856             : 
    1857       28964 :             if (numPFormats > 1)
    1858        3544 :                 pformat = pformats[paramno];
    1859       25420 :             else if (numPFormats > 0)
    1860        3384 :                 pformat = pformats[0];
    1861             :             else
    1862       22036 :                 pformat = 0;    /* default = text */
    1863             : 
    1864       28964 :             if (pformat == 0)   /* text mode */
    1865             :             {
    1866             :                 Oid         typinput;
    1867             :                 Oid         typioparam;
    1868             :                 char       *pstring;
    1869             : 
    1870       28912 :                 getTypeInputInfo(ptype, &typinput, &typioparam);
    1871             : 
    1872             :                 /*
    1873             :                  * We have to do encoding conversion before calling the
    1874             :                  * typinput routine.
    1875             :                  */
    1876       28912 :                 if (isNull)
    1877        1218 :                     pstring = NULL;
    1878             :                 else
    1879       27694 :                     pstring = pg_client_to_server(pbuf.data, plength);
    1880             : 
    1881             :                 /* Now we can log the input string in case of error */
    1882       28912 :                 one_param_data.paramval = pstring;
    1883             : 
    1884       28912 :                 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
    1885             : 
    1886       28910 :                 one_param_data.paramval = NULL;
    1887             : 
    1888             :                 /*
    1889             :                  * If we might need to log parameters later, save a copy of
    1890             :                  * the converted string in MessageContext; then free the
    1891             :                  * result of encoding conversion, if any was done.
    1892             :                  */
    1893       28910 :                 if (pstring)
    1894             :                 {
    1895       27692 :                     if (log_parameter_max_length_on_error != 0)
    1896             :                     {
    1897             :                         MemoryContext oldcxt;
    1898             : 
    1899          14 :                         oldcxt = MemoryContextSwitchTo(MessageContext);
    1900             : 
    1901          14 :                         if (knownTextValues == NULL)
    1902          10 :                             knownTextValues = palloc0_array(char *, numParams);
    1903             : 
    1904          14 :                         if (log_parameter_max_length_on_error < 0)
    1905           8 :                             knownTextValues[paramno] = pstrdup(pstring);
    1906             :                         else
    1907             :                         {
    1908             :                             /*
    1909             :                              * We can trim the saved string, knowing that we
    1910             :                              * won't print all of it.  But we must copy at
    1911             :                              * least two more full characters than
    1912             :                              * BuildParamLogString wants to use; otherwise it
    1913             :                              * might fail to include the trailing ellipsis.
    1914             :                              */
    1915           6 :                             knownTextValues[paramno] =
    1916           6 :                                 pnstrdup(pstring,
    1917             :                                          log_parameter_max_length_on_error
    1918           6 :                                          + 2 * MAX_MULTIBYTE_CHAR_LEN);
    1919             :                         }
    1920             : 
    1921          14 :                         MemoryContextSwitchTo(oldcxt);
    1922             :                     }
    1923       27692 :                     if (pstring != pbuf.data)
    1924           0 :                         pfree(pstring);
    1925             :                 }
    1926             :             }
    1927          52 :             else if (pformat == 1)  /* binary mode */
    1928             :             {
    1929             :                 Oid         typreceive;
    1930             :                 Oid         typioparam;
    1931             :                 StringInfo  bufptr;
    1932             : 
    1933             :                 /*
    1934             :                  * Call the parameter type's binary input converter
    1935             :                  */
    1936          52 :                 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
    1937             : 
    1938          52 :                 if (isNull)
    1939           0 :                     bufptr = NULL;
    1940             :                 else
    1941          52 :                     bufptr = &pbuf;
    1942             : 
    1943          52 :                 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
    1944             : 
    1945             :                 /* Trouble if it didn't eat the whole buffer */
    1946          52 :                 if (!isNull && pbuf.cursor != pbuf.len)
    1947           0 :                     ereport(ERROR,
    1948             :                             (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1949             :                              errmsg("incorrect binary data format in bind parameter %d",
    1950             :                                     paramno + 1)));
    1951             :             }
    1952             :             else
    1953             :             {
    1954           0 :                 ereport(ERROR,
    1955             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1956             :                          errmsg("unsupported format code: %d",
    1957             :                                 pformat)));
    1958             :                 pval = 0;       /* keep compiler quiet */
    1959             :             }
    1960             : 
    1961             :             /* Restore message buffer contents */
    1962       28962 :             if (!isNull)
    1963       27744 :                 pbuf.data[plength] = csave;
    1964             : 
    1965       28962 :             params->params[paramno].value = pval;
    1966       28962 :             params->params[paramno].isnull = isNull;
    1967             : 
    1968             :             /*
    1969             :              * We mark the params as CONST.  This ensures that any custom plan
    1970             :              * makes full use of the parameter values.
    1971             :              */
    1972       28962 :             params->params[paramno].pflags = PARAM_FLAG_CONST;
    1973       28962 :             params->params[paramno].ptype = ptype;
    1974             :         }
    1975             : 
    1976             :         /* Pop the per-parameter error callback */
    1977       17814 :         error_context_stack = error_context_stack->previous;
    1978             : 
    1979             :         /*
    1980             :          * Once all parameters have been received, prepare for printing them
    1981             :          * in future errors, if configured to do so.  (This is saved in the
    1982             :          * portal, so that they'll appear when the query is executed later.)
    1983             :          */
    1984       17814 :         if (log_parameter_max_length_on_error != 0)
    1985           8 :             params->paramValuesStr =
    1986           8 :                 BuildParamLogString(params,
    1987             :                                     knownTextValues,
    1988             :                                     log_parameter_max_length_on_error);
    1989             :     }
    1990             :     else
    1991        4264 :         params = NULL;
    1992             : 
    1993             :     /* Done storing stuff in portal's context */
    1994       22078 :     MemoryContextSwitchTo(oldContext);
    1995             : 
    1996             :     /*
    1997             :      * Set up another error callback so that all the parameters are logged if
    1998             :      * we get an error during the rest of the BIND processing.
    1999             :      */
    2000       22078 :     params_data.portalName = portal->name;
    2001       22078 :     params_data.params = params;
    2002       22078 :     params_errcxt.previous = error_context_stack;
    2003       22078 :     params_errcxt.callback = ParamsErrorCallback;
    2004       22078 :     params_errcxt.arg = &params_data;
    2005       22078 :     error_context_stack = &params_errcxt;
    2006             : 
    2007             :     /* Get the result format codes */
    2008       22078 :     numRFormats = pq_getmsgint(input_message, 2);
    2009       22078 :     if (numRFormats > 0)
    2010             :     {
    2011       22078 :         rformats = palloc_array(int16, numRFormats);
    2012       44156 :         for (int i = 0; i < numRFormats; i++)
    2013       22078 :             rformats[i] = pq_getmsgint(input_message, 2);
    2014             :     }
    2015             : 
    2016       22078 :     pq_getmsgend(input_message);
    2017             : 
    2018             :     /*
    2019             :      * Obtain a plan from the CachedPlanSource.  Any cruft from (re)planning
    2020             :      * will be generated in MessageContext.  The plan refcount will be
    2021             :      * assigned to the Portal, so it will be released at portal destruction.
    2022             :      */
    2023       22078 :     cplan = GetCachedPlan(psrc, params, NULL, NULL);
    2024             : 
    2025             :     /*
    2026             :      * Now we can define the portal.
    2027             :      *
    2028             :      * DO NOT put any code that could possibly throw an error between the
    2029             :      * above GetCachedPlan call and here.
    2030             :      */
    2031       22076 :     PortalDefineQuery(portal,
    2032             :                       saved_stmt_name,
    2033             :                       query_string,
    2034             :                       psrc->commandTag,
    2035             :                       cplan->stmt_list,
    2036             :                       cplan);
    2037             : 
    2038             :     /* Portal is defined, set the plan ID based on its contents. */
    2039       44152 :     foreach(lc, portal->stmts)
    2040             :     {
    2041       22076 :         PlannedStmt *plan = lfirst_node(PlannedStmt, lc);
    2042             : 
    2043       22076 :         if (plan->planId != INT64CONST(0))
    2044             :         {
    2045           0 :             pgstat_report_plan_id(plan->planId, false);
    2046           0 :             break;
    2047             :         }
    2048             :     }
    2049             : 
    2050             :     /* Done with the snapshot used for parameter I/O and parsing/planning */
    2051       22076 :     if (snapshot_set)
    2052       20006 :         PopActiveSnapshot();
    2053             : 
    2054             :     /*
    2055             :      * And we're ready to start portal execution.
    2056             :      */
    2057       22076 :     PortalStart(portal, params, 0, InvalidSnapshot);
    2058             : 
    2059             :     /*
    2060             :      * Apply the result format requests to the portal.
    2061             :      */
    2062       22076 :     PortalSetResultFormat(portal, numRFormats, rformats);
    2063             : 
    2064             :     /*
    2065             :      * Done binding; remove the parameters error callback.  Entries emitted
    2066             :      * later determine independently whether to log the parameters or not.
    2067             :      */
    2068       22076 :     error_context_stack = error_context_stack->previous;
    2069             : 
    2070             :     /*
    2071             :      * Send BindComplete.
    2072             :      */
    2073       22076 :     if (whereToSendOutput == DestRemote)
    2074       22076 :         pq_putemptymessage(PqMsg_BindComplete);
    2075             : 
    2076             :     /*
    2077             :      * Emit duration logging if appropriate.
    2078             :      */
    2079       22076 :     switch (check_log_duration(msec_str, false))
    2080             :     {
    2081           0 :         case 1:
    2082           0 :             ereport(LOG,
    2083             :                     (errmsg("duration: %s ms", msec_str),
    2084             :                      errhidestmt(true)));
    2085           0 :             break;
    2086          24 :         case 2:
    2087          24 :             ereport(LOG,
    2088             :                     (errmsg("duration: %s ms  bind %s%s%s: %s",
    2089             :                             msec_str,
    2090             :                             *stmt_name ? stmt_name : "<unnamed>",
    2091             :                             *portal_name ? "/" : "",
    2092             :                             *portal_name ? portal_name : "",
    2093             :                             psrc->query_string),
    2094             :                      errhidestmt(true),
    2095             :                      errdetail_params(params)));
    2096          24 :             break;
    2097             :     }
    2098             : 
    2099       22076 :     if (save_log_statement_stats)
    2100           0 :         ShowUsage("BIND MESSAGE STATISTICS");
    2101             : 
    2102             :     valgrind_report_error_query(debug_query_string);
    2103             : 
    2104       22076 :     debug_query_string = NULL;
    2105       22076 : }
    2106             : 
    2107             : /*
    2108             :  * exec_execute_message
    2109             :  *
    2110             :  * Process an "Execute" message for a portal
    2111             :  */
    2112             : static void
    2113       22076 : exec_execute_message(const char *portal_name, long max_rows)
    2114             : {
    2115             :     CommandDest dest;
    2116             :     DestReceiver *receiver;
    2117             :     Portal      portal;
    2118             :     bool        completed;
    2119             :     QueryCompletion qc;
    2120             :     const char *sourceText;
    2121             :     const char *prepStmtName;
    2122             :     ParamListInfo portalParams;
    2123       22076 :     bool        save_log_statement_stats = log_statement_stats;
    2124             :     bool        is_xact_command;
    2125             :     bool        execute_is_fetch;
    2126       22076 :     bool        was_logged = false;
    2127             :     char        msec_str[32];
    2128             :     ParamsErrorCbData params_data;
    2129             :     ErrorContextCallback params_errcxt;
    2130             :     const char *cmdtagname;
    2131             :     size_t      cmdtaglen;
    2132             :     ListCell   *lc;
    2133             : 
    2134             :     /* Adjust destination to tell printtup.c what to do */
    2135       22076 :     dest = whereToSendOutput;
    2136       22076 :     if (dest == DestRemote)
    2137       22076 :         dest = DestRemoteExecute;
    2138             : 
    2139       22076 :     portal = GetPortalByName(portal_name);
    2140       22076 :     if (!PortalIsValid(portal))
    2141           0 :         ereport(ERROR,
    2142             :                 (errcode(ERRCODE_UNDEFINED_CURSOR),
    2143             :                  errmsg("portal \"%s\" does not exist", portal_name)));
    2144             : 
    2145             :     /*
    2146             :      * If the original query was a null string, just return
    2147             :      * EmptyQueryResponse.
    2148             :      */
    2149       22076 :     if (portal->commandTag == CMDTAG_UNKNOWN)
    2150             :     {
    2151             :         Assert(portal->stmts == NIL);
    2152           0 :         NullCommand(dest);
    2153           0 :         return;
    2154             :     }
    2155             : 
    2156             :     /* Does the portal contain a transaction command? */
    2157       22076 :     is_xact_command = IsTransactionStmtList(portal->stmts);
    2158             : 
    2159             :     /*
    2160             :      * We must copy the sourceText and prepStmtName into MessageContext in
    2161             :      * case the portal is destroyed during finish_xact_command.  We do not
    2162             :      * make a copy of the portalParams though, preferring to just not print
    2163             :      * them in that case.
    2164             :      */
    2165       22076 :     sourceText = pstrdup(portal->sourceText);
    2166       22076 :     if (portal->prepStmtName)
    2167       15526 :         prepStmtName = pstrdup(portal->prepStmtName);
    2168             :     else
    2169        6550 :         prepStmtName = "<unnamed>";
    2170       22076 :     portalParams = portal->portalParams;
    2171             : 
    2172             :     /*
    2173             :      * Report query to various monitoring facilities.
    2174             :      */
    2175       22076 :     debug_query_string = sourceText;
    2176             : 
    2177       22076 :     pgstat_report_activity(STATE_RUNNING, sourceText);
    2178             : 
    2179       43910 :     foreach(lc, portal->stmts)
    2180             :     {
    2181       22076 :         PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
    2182             : 
    2183       22076 :         if (stmt->queryId != INT64CONST(0))
    2184             :         {
    2185         242 :             pgstat_report_query_id(stmt->queryId, false);
    2186         242 :             break;
    2187             :         }
    2188             :     }
    2189             : 
    2190       44152 :     foreach(lc, portal->stmts)
    2191             :     {
    2192       22076 :         PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
    2193             : 
    2194       22076 :         if (stmt->planId != INT64CONST(0))
    2195             :         {
    2196           0 :             pgstat_report_plan_id(stmt->planId, false);
    2197           0 :             break;
    2198             :         }
    2199             :     }
    2200             : 
    2201       22076 :     cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
    2202             : 
    2203       22076 :     set_ps_display_with_len(cmdtagname, cmdtaglen);
    2204             : 
    2205       22076 :     if (save_log_statement_stats)
    2206           0 :         ResetUsage();
    2207             : 
    2208       22076 :     BeginCommand(portal->commandTag, dest);
    2209             : 
    2210             :     /*
    2211             :      * Create dest receiver in MessageContext (we don't want it in transaction
    2212             :      * context, because that may get deleted if portal contains VACUUM).
    2213             :      */
    2214       22076 :     receiver = CreateDestReceiver(dest);
    2215       22076 :     if (dest == DestRemoteExecute)
    2216       22076 :         SetRemoteDestReceiverParams(receiver, portal);
    2217             : 
    2218             :     /*
    2219             :      * Ensure we are in a transaction command (this should normally be the
    2220             :      * case already due to prior BIND).
    2221             :      */
    2222       22076 :     start_xact_command();
    2223             : 
    2224             :     /*
    2225             :      * If we re-issue an Execute protocol request against an existing portal,
    2226             :      * then we are only fetching more rows rather than completely re-executing
    2227             :      * the query from the start. atStart is never reset for a v3 portal, so we
    2228             :      * are safe to use this check.
    2229             :      */
    2230       22076 :     execute_is_fetch = !portal->atStart;
    2231             : 
    2232             :     /* Log immediately if dictated by log_statement */
    2233       22076 :     if (check_log_statement(portal->stmts))
    2234             :     {
    2235        7706 :         ereport(LOG,
    2236             :                 (errmsg("%s %s%s%s: %s",
    2237             :                         execute_is_fetch ?
    2238             :                         _("execute fetch from") :
    2239             :                         _("execute"),
    2240             :                         prepStmtName,
    2241             :                         *portal_name ? "/" : "",
    2242             :                         *portal_name ? portal_name : "",
    2243             :                         sourceText),
    2244             :                  errhidestmt(true),
    2245             :                  errdetail_params(portalParams)));
    2246        7706 :         was_logged = true;
    2247             :     }
    2248             : 
    2249             :     /*
    2250             :      * If we are in aborted transaction state, the only portals we can
    2251             :      * actually run are those containing COMMIT or ROLLBACK commands.
    2252             :      */
    2253       22076 :     if (IsAbortedTransactionBlockState() &&
    2254           2 :         !IsTransactionExitStmtList(portal->stmts))
    2255           0 :         ereport(ERROR,
    2256             :                 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    2257             :                  errmsg("current transaction is aborted, "
    2258             :                         "commands ignored until end of transaction block"),
    2259             :                  errdetail_abort()));
    2260             : 
    2261             :     /* Check for cancel signal before we start execution */
    2262       22076 :     CHECK_FOR_INTERRUPTS();
    2263             : 
    2264             :     /*
    2265             :      * Okay to run the portal.  Set the error callback so that parameters are
    2266             :      * logged.  The parameters must have been saved during the bind phase.
    2267             :      */
    2268       22076 :     params_data.portalName = portal->name;
    2269       22076 :     params_data.params = portalParams;
    2270       22076 :     params_errcxt.previous = error_context_stack;
    2271       22076 :     params_errcxt.callback = ParamsErrorCallback;
    2272       22076 :     params_errcxt.arg = &params_data;
    2273       22076 :     error_context_stack = &params_errcxt;
    2274             : 
    2275       22076 :     if (max_rows <= 0)
    2276       22076 :         max_rows = FETCH_ALL;
    2277             : 
    2278       22076 :     completed = PortalRun(portal,
    2279             :                           max_rows,
    2280             :                           true, /* always top level */
    2281             :                           receiver,
    2282             :                           receiver,
    2283             :                           &qc);
    2284             : 
    2285       21978 :     receiver->rDestroy(receiver);
    2286             : 
    2287             :     /* Done executing; remove the params error callback */
    2288       21978 :     error_context_stack = error_context_stack->previous;
    2289             : 
    2290       21978 :     if (completed)
    2291             :     {
    2292       21978 :         if (is_xact_command || (MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT))
    2293             :         {
    2294             :             /*
    2295             :              * If this was a transaction control statement, commit it.  We
    2296             :              * will start a new xact command for the next command (if any).
    2297             :              * Likewise if the statement required immediate commit.  Without
    2298             :              * this provision, we wouldn't force commit until Sync is
    2299             :              * received, which creates a hazard if the client tries to
    2300             :              * pipeline immediate-commit statements.
    2301             :              */
    2302         958 :             finish_xact_command();
    2303             : 
    2304             :             /*
    2305             :              * These commands typically don't have any parameters, and even if
    2306             :              * one did we couldn't print them now because the storage went
    2307             :              * away during finish_xact_command.  So pretend there were none.
    2308             :              */
    2309         958 :             portalParams = NULL;
    2310             :         }
    2311             :         else
    2312             :         {
    2313             :             /*
    2314             :              * We need a CommandCounterIncrement after every query, except
    2315             :              * those that start or end a transaction block.
    2316             :              */
    2317       21020 :             CommandCounterIncrement();
    2318             : 
    2319             :             /*
    2320             :              * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
    2321             :              * message without immediately committing the transaction.
    2322             :              */
    2323       21020 :             MyXactFlags |= XACT_FLAGS_PIPELINING;
    2324             : 
    2325             :             /*
    2326             :              * Disable statement timeout whenever we complete an Execute
    2327             :              * message.  The next protocol message will start a fresh timeout.
    2328             :              */
    2329       21020 :             disable_statement_timeout();
    2330             :         }
    2331             : 
    2332             :         /* Send appropriate CommandComplete to client */
    2333       21978 :         EndCommand(&qc, dest, false);
    2334             :     }
    2335             :     else
    2336             :     {
    2337             :         /* Portal run not complete, so send PortalSuspended */
    2338           0 :         if (whereToSendOutput == DestRemote)
    2339           0 :             pq_putemptymessage(PqMsg_PortalSuspended);
    2340             : 
    2341             :         /*
    2342             :          * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
    2343             :          * too.
    2344             :          */
    2345           0 :         MyXactFlags |= XACT_FLAGS_PIPELINING;
    2346             :     }
    2347             : 
    2348             :     /*
    2349             :      * Emit duration logging if appropriate.
    2350             :      */
    2351       21978 :     switch (check_log_duration(msec_str, was_logged))
    2352             :     {
    2353          16 :         case 1:
    2354          16 :             ereport(LOG,
    2355             :                     (errmsg("duration: %s ms", msec_str),
    2356             :                      errhidestmt(true)));
    2357          16 :             break;
    2358           0 :         case 2:
    2359           0 :             ereport(LOG,
    2360             :                     (errmsg("duration: %s ms  %s %s%s%s: %s",
    2361             :                             msec_str,
    2362             :                             execute_is_fetch ?
    2363             :                             _("execute fetch from") :
    2364             :                             _("execute"),
    2365             :                             prepStmtName,
    2366             :                             *portal_name ? "/" : "",
    2367             :                             *portal_name ? portal_name : "",
    2368             :                             sourceText),
    2369             :                      errhidestmt(true),
    2370             :                      errdetail_params(portalParams)));
    2371           0 :             break;
    2372             :     }
    2373             : 
    2374       21978 :     if (save_log_statement_stats)
    2375           0 :         ShowUsage("EXECUTE MESSAGE STATISTICS");
    2376             : 
    2377             :     valgrind_report_error_query(debug_query_string);
    2378             : 
    2379       21978 :     debug_query_string = NULL;
    2380             : }
    2381             : 
    2382             : /*
    2383             :  * check_log_statement
    2384             :  *      Determine whether command should be logged because of log_statement
    2385             :  *
    2386             :  * stmt_list can be either raw grammar output or a list of planned
    2387             :  * statements
    2388             :  */
    2389             : static bool
    2390      677948 : check_log_statement(List *stmt_list)
    2391             : {
    2392             :     ListCell   *stmt_item;
    2393             : 
    2394      677948 :     if (log_statement == LOGSTMT_NONE)
    2395      418418 :         return false;
    2396      259530 :     if (log_statement == LOGSTMT_ALL)
    2397      259530 :         return true;
    2398             : 
    2399             :     /* Else we have to inspect the statement(s) to see whether to log */
    2400           0 :     foreach(stmt_item, stmt_list)
    2401             :     {
    2402           0 :         Node       *stmt = (Node *) lfirst(stmt_item);
    2403             : 
    2404           0 :         if (GetCommandLogLevel(stmt) <= log_statement)
    2405           0 :             return true;
    2406             :     }
    2407             : 
    2408           0 :     return false;
    2409             : }
    2410             : 
    2411             : /*
    2412             :  * check_log_duration
    2413             :  *      Determine whether current command's duration should be logged
    2414             :  *      We also check if this statement in this transaction must be logged
    2415             :  *      (regardless of its duration).
    2416             :  *
    2417             :  * Returns:
    2418             :  *      0 if no logging is needed
    2419             :  *      1 if just the duration should be logged
    2420             :  *      2 if duration and query details should be logged
    2421             :  *
    2422             :  * If logging is needed, the duration in msec is formatted into msec_str[],
    2423             :  * which must be a 32-byte buffer.
    2424             :  *
    2425             :  * was_logged should be true if caller already logged query details (this
    2426             :  * essentially prevents 2 from being returned).
    2427             :  */
    2428             : int
    2429      670668 : check_log_duration(char *msec_str, bool was_logged)
    2430             : {
    2431      670668 :     if (log_duration || log_min_duration_sample >= 0 ||
    2432      670668 :         log_min_duration_statement >= 0 || xact_is_sampled)
    2433             :     {
    2434             :         long        secs;
    2435             :         int         usecs;
    2436             :         int         msecs;
    2437             :         bool        exceeded_duration;
    2438             :         bool        exceeded_sample_duration;
    2439         102 :         bool        in_sample = false;
    2440             : 
    2441         102 :         TimestampDifference(GetCurrentStatementStartTimestamp(),
    2442             :                             GetCurrentTimestamp(),
    2443             :                             &secs, &usecs);
    2444         102 :         msecs = usecs / 1000;
    2445             : 
    2446             :         /*
    2447             :          * This odd-looking test for log_min_duration_* being exceeded is
    2448             :          * designed to avoid integer overflow with very long durations: don't
    2449             :          * compute secs * 1000 until we've verified it will fit in int.
    2450             :          */
    2451         102 :         exceeded_duration = (log_min_duration_statement == 0 ||
    2452           0 :                              (log_min_duration_statement > 0 &&
    2453           0 :                               (secs > log_min_duration_statement / 1000 ||
    2454           0 :                                secs * 1000 + msecs >= log_min_duration_statement)));
    2455             : 
    2456         204 :         exceeded_sample_duration = (log_min_duration_sample == 0 ||
    2457         102 :                                     (log_min_duration_sample > 0 &&
    2458           0 :                                      (secs > log_min_duration_sample / 1000 ||
    2459           0 :                                       secs * 1000 + msecs >= log_min_duration_sample)));
    2460             : 
    2461             :         /*
    2462             :          * Do not log if log_statement_sample_rate = 0. Log a sample if
    2463             :          * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
    2464             :          * log_statement_sample_rate = 1.
    2465             :          */
    2466         102 :         if (exceeded_sample_duration)
    2467           0 :             in_sample = log_statement_sample_rate != 0 &&
    2468           0 :                 (log_statement_sample_rate == 1 ||
    2469           0 :                  pg_prng_double(&pg_global_prng_state) <= log_statement_sample_rate);
    2470             : 
    2471         102 :         if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
    2472             :         {
    2473         102 :             snprintf(msec_str, 32, "%ld.%03d",
    2474         102 :                      secs * 1000 + msecs, usecs % 1000);
    2475         102 :             if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
    2476         102 :                 return 2;
    2477             :             else
    2478          52 :                 return 1;
    2479             :         }
    2480             :     }
    2481             : 
    2482      670566 :     return 0;
    2483             : }
    2484             : 
    2485             : /*
    2486             :  * errdetail_execute
    2487             :  *
    2488             :  * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
    2489             :  * The argument is the raw parsetree list.
    2490             :  */
    2491             : static int
    2492      251824 : errdetail_execute(List *raw_parsetree_list)
    2493             : {
    2494             :     ListCell   *parsetree_item;
    2495             : 
    2496      492676 :     foreach(parsetree_item, raw_parsetree_list)
    2497             :     {
    2498      252188 :         RawStmt    *parsetree = lfirst_node(RawStmt, parsetree_item);
    2499             : 
    2500      252188 :         if (IsA(parsetree->stmt, ExecuteStmt))
    2501             :         {
    2502       11336 :             ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
    2503             :             PreparedStatement *pstmt;
    2504             : 
    2505       11336 :             pstmt = FetchPreparedStatement(stmt->name, false);
    2506       11336 :             if (pstmt)
    2507             :             {
    2508       11336 :                 errdetail("prepare: %s", pstmt->plansource->query_string);
    2509       11336 :                 return 0;
    2510             :             }
    2511             :         }
    2512             :     }
    2513             : 
    2514      240488 :     return 0;
    2515             : }
    2516             : 
    2517             : /*
    2518             :  * errdetail_params
    2519             :  *
    2520             :  * Add an errdetail() line showing bind-parameter data, if available.
    2521             :  * Note that this is only used for statement logging, so it is controlled
    2522             :  * by log_parameter_max_length not log_parameter_max_length_on_error.
    2523             :  */
    2524             : static int
    2525        7730 : errdetail_params(ParamListInfo params)
    2526             : {
    2527        7730 :     if (params && params->numParams > 0 && log_parameter_max_length != 0)
    2528             :     {
    2529             :         char       *str;
    2530             : 
    2531        4752 :         str = BuildParamLogString(params, NULL, log_parameter_max_length);
    2532        4752 :         if (str && str[0] != '\0')
    2533        4752 :             errdetail("Parameters: %s", str);
    2534             :     }
    2535             : 
    2536        7730 :     return 0;
    2537             : }
    2538             : 
    2539             : /*
    2540             :  * errdetail_abort
    2541             :  *
    2542             :  * Add an errdetail() line showing abort reason, if any.
    2543             :  */
    2544             : static int
    2545          94 : errdetail_abort(void)
    2546             : {
    2547          94 :     if (MyProc->recoveryConflictPending)
    2548           0 :         errdetail("Abort reason: recovery conflict");
    2549             : 
    2550          94 :     return 0;
    2551             : }
    2552             : 
    2553             : /*
    2554             :  * errdetail_recovery_conflict
    2555             :  *
    2556             :  * Add an errdetail() line showing conflict source.
    2557             :  */
    2558             : static int
    2559          24 : errdetail_recovery_conflict(ProcSignalReason reason)
    2560             : {
    2561          24 :     switch (reason)
    2562             :     {
    2563           2 :         case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
    2564           2 :             errdetail("User was holding shared buffer pin for too long.");
    2565           2 :             break;
    2566           2 :         case PROCSIG_RECOVERY_CONFLICT_LOCK:
    2567           2 :             errdetail("User was holding a relation lock for too long.");
    2568           2 :             break;
    2569           2 :         case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
    2570           2 :             errdetail("User was or might have been using tablespace that must be dropped.");
    2571           2 :             break;
    2572           2 :         case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
    2573           2 :             errdetail("User query might have needed to see row versions that must be removed.");
    2574           2 :             break;
    2575          10 :         case PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT:
    2576          10 :             errdetail("User was using a logical replication slot that must be invalidated.");
    2577          10 :             break;
    2578           2 :         case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
    2579           2 :             errdetail("User transaction caused buffer deadlock with recovery.");
    2580           2 :             break;
    2581           4 :         case PROCSIG_RECOVERY_CONFLICT_DATABASE:
    2582           4 :             errdetail("User was connected to a database that must be dropped.");
    2583           4 :             break;
    2584           0 :         default:
    2585           0 :             break;
    2586             :             /* no errdetail */
    2587             :     }
    2588             : 
    2589          24 :     return 0;
    2590             : }
    2591             : 
    2592             : /*
    2593             :  * bind_param_error_callback
    2594             :  *
    2595             :  * Error context callback used while parsing parameters in a Bind message
    2596             :  */
    2597             : static void
    2598           2 : bind_param_error_callback(void *arg)
    2599             : {
    2600           2 :     BindParamCbData *data = (BindParamCbData *) arg;
    2601             :     StringInfoData buf;
    2602             :     char       *quotedval;
    2603             : 
    2604           2 :     if (data->paramno < 0)
    2605           0 :         return;
    2606             : 
    2607             :     /* If we have a textual value, quote it, and trim if necessary */
    2608           2 :     if (data->paramval)
    2609             :     {
    2610           2 :         initStringInfo(&buf);
    2611           2 :         appendStringInfoStringQuoted(&buf, data->paramval,
    2612             :                                      log_parameter_max_length_on_error);
    2613           2 :         quotedval = buf.data;
    2614             :     }
    2615             :     else
    2616           0 :         quotedval = NULL;
    2617             : 
    2618           2 :     if (data->portalName && data->portalName[0] != '\0')
    2619             :     {
    2620           0 :         if (quotedval)
    2621           0 :             errcontext("portal \"%s\" parameter $%d = %s",
    2622           0 :                        data->portalName, data->paramno + 1, quotedval);
    2623             :         else
    2624           0 :             errcontext("portal \"%s\" parameter $%d",
    2625           0 :                        data->portalName, data->paramno + 1);
    2626             :     }
    2627             :     else
    2628             :     {
    2629           2 :         if (quotedval)
    2630           2 :             errcontext("unnamed portal parameter $%d = %s",
    2631           2 :                        data->paramno + 1, quotedval);
    2632             :         else
    2633           0 :             errcontext("unnamed portal parameter $%d",
    2634           0 :                        data->paramno + 1);
    2635             :     }
    2636             : 
    2637           2 :     if (quotedval)
    2638           2 :         pfree(quotedval);
    2639             : }
    2640             : 
    2641             : /*
    2642             :  * exec_describe_statement_message
    2643             :  *
    2644             :  * Process a "Describe" message for a prepared statement
    2645             :  */
    2646             : static void
    2647         142 : exec_describe_statement_message(const char *stmt_name)
    2648             : {
    2649             :     CachedPlanSource *psrc;
    2650             : 
    2651             :     /*
    2652             :      * Start up a transaction command. (Note that this will normally change
    2653             :      * current memory context.) Nothing happens if we are already in one.
    2654             :      */
    2655         142 :     start_xact_command();
    2656             : 
    2657             :     /* Switch back to message context */
    2658         142 :     MemoryContextSwitchTo(MessageContext);
    2659             : 
    2660             :     /* Find prepared statement */
    2661         142 :     if (stmt_name[0] != '\0')
    2662             :     {
    2663             :         PreparedStatement *pstmt;
    2664             : 
    2665          88 :         pstmt = FetchPreparedStatement(stmt_name, true);
    2666          86 :         psrc = pstmt->plansource;
    2667             :     }
    2668             :     else
    2669             :     {
    2670             :         /* special-case the unnamed statement */
    2671          54 :         psrc = unnamed_stmt_psrc;
    2672          54 :         if (!psrc)
    2673           0 :             ereport(ERROR,
    2674             :                     (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
    2675             :                      errmsg("unnamed prepared statement does not exist")));
    2676             :     }
    2677             : 
    2678             :     /* Prepared statements shouldn't have changeable result descs */
    2679             :     Assert(psrc->fixed_result);
    2680             : 
    2681             :     /*
    2682             :      * If we are in aborted transaction state, we can't run
    2683             :      * SendRowDescriptionMessage(), because that needs catalog accesses.
    2684             :      * Hence, refuse to Describe statements that return data.  (We shouldn't
    2685             :      * just refuse all Describes, since that might break the ability of some
    2686             :      * clients to issue COMMIT or ROLLBACK commands, if they use code that
    2687             :      * blindly Describes whatever it does.)  We can Describe parameters
    2688             :      * without doing anything dangerous, so we don't restrict that.
    2689             :      */
    2690         140 :     if (IsAbortedTransactionBlockState() &&
    2691           6 :         psrc->resultDesc)
    2692           0 :         ereport(ERROR,
    2693             :                 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    2694             :                  errmsg("current transaction is aborted, "
    2695             :                         "commands ignored until end of transaction block"),
    2696             :                  errdetail_abort()));
    2697             : 
    2698         140 :     if (whereToSendOutput != DestRemote)
    2699           0 :         return;                 /* can't actually do anything... */
    2700             : 
    2701             :     /*
    2702             :      * First describe the parameters...
    2703             :      */
    2704         140 :     pq_beginmessage_reuse(&row_description_buf, PqMsg_ParameterDescription);
    2705         140 :     pq_sendint16(&row_description_buf, psrc->num_params);
    2706             : 
    2707         154 :     for (int i = 0; i < psrc->num_params; i++)
    2708             :     {
    2709          14 :         Oid         ptype = psrc->param_types[i];
    2710             : 
    2711          14 :         pq_sendint32(&row_description_buf, (int) ptype);
    2712             :     }
    2713         140 :     pq_endmessage_reuse(&row_description_buf);
    2714             : 
    2715             :     /*
    2716             :      * Next send RowDescription or NoData to describe the result...
    2717             :      */
    2718         140 :     if (psrc->resultDesc)
    2719             :     {
    2720             :         List       *tlist;
    2721             : 
    2722             :         /* Get the plan's primary targetlist */
    2723         128 :         tlist = CachedPlanGetTargetList(psrc, NULL);
    2724             : 
    2725         128 :         SendRowDescriptionMessage(&row_description_buf,
    2726             :                                   psrc->resultDesc,
    2727             :                                   tlist,
    2728             :                                   NULL);
    2729             :     }
    2730             :     else
    2731          12 :         pq_putemptymessage(PqMsg_NoData);
    2732             : }
    2733             : 
    2734             : /*
    2735             :  * exec_describe_portal_message
    2736             :  *
    2737             :  * Process a "Describe" message for a portal
    2738             :  */
    2739             : static void
    2740       22080 : exec_describe_portal_message(const char *portal_name)
    2741             : {
    2742             :     Portal      portal;
    2743             : 
    2744             :     /*
    2745             :      * Start up a transaction command. (Note that this will normally change
    2746             :      * current memory context.) Nothing happens if we are already in one.
    2747             :      */
    2748       22080 :     start_xact_command();
    2749             : 
    2750             :     /* Switch back to message context */
    2751       22080 :     MemoryContextSwitchTo(MessageContext);
    2752             : 
    2753       22080 :     portal = GetPortalByName(portal_name);
    2754       22080 :     if (!PortalIsValid(portal))
    2755           2 :         ereport(ERROR,
    2756             :                 (errcode(ERRCODE_UNDEFINED_CURSOR),
    2757             :                  errmsg("portal \"%s\" does not exist", portal_name)));
    2758             : 
    2759             :     /*
    2760             :      * If we are in aborted transaction state, we can't run
    2761             :      * SendRowDescriptionMessage(), because that needs catalog accesses.
    2762             :      * Hence, refuse to Describe portals that return data.  (We shouldn't just
    2763             :      * refuse all Describes, since that might break the ability of some
    2764             :      * clients to issue COMMIT or ROLLBACK commands, if they use code that
    2765             :      * blindly Describes whatever it does.)
    2766             :      */
    2767       22078 :     if (IsAbortedTransactionBlockState() &&
    2768           2 :         portal->tupDesc)
    2769           0 :         ereport(ERROR,
    2770             :                 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
    2771             :                  errmsg("current transaction is aborted, "
    2772             :                         "commands ignored until end of transaction block"),
    2773             :                  errdetail_abort()));
    2774             : 
    2775       22078 :     if (whereToSendOutput != DestRemote)
    2776           0 :         return;                 /* can't actually do anything... */
    2777             : 
    2778       22078 :     if (portal->tupDesc)
    2779        9462 :         SendRowDescriptionMessage(&row_description_buf,
    2780             :                                   portal->tupDesc,
    2781             :                                   FetchPortalTargetList(portal),
    2782             :                                   portal->formats);
    2783             :     else
    2784       12616 :         pq_putemptymessage(PqMsg_NoData);
    2785             : }
    2786             : 
    2787             : 
    2788             : /*
    2789             :  * Convenience routines for starting/committing a single command.
    2790             :  */
    2791             : static void
    2792     1437076 : start_xact_command(void)
    2793             : {
    2794     1437076 :     if (!xact_started)
    2795             :     {
    2796      683690 :         StartTransactionCommand();
    2797             : 
    2798      683690 :         xact_started = true;
    2799             :     }
    2800      753386 :     else if (MyXactFlags & XACT_FLAGS_PIPELINING)
    2801             :     {
    2802             :         /*
    2803             :          * When the first Execute message is completed, following commands
    2804             :          * will be done in an implicit transaction block created via
    2805             :          * pipelining. The transaction state needs to be updated to an
    2806             :          * implicit block if we're not already in a transaction block (like
    2807             :          * one started by an explicit BEGIN).
    2808             :          */
    2809       31108 :         BeginImplicitTransactionBlock();
    2810             :     }
    2811             : 
    2812             :     /*
    2813             :      * Start statement timeout if necessary.  Note that this'll intentionally
    2814             :      * not reset the clock on an already started timeout, to avoid the timing
    2815             :      * overhead when start_xact_command() is invoked repeatedly, without an
    2816             :      * interceding finish_xact_command() (e.g. parse/bind/execute).  If that's
    2817             :      * not desired, the timeout has to be disabled explicitly.
    2818             :      */
    2819     1437076 :     enable_statement_timeout();
    2820             : 
    2821             :     /* Start timeout for checking if the client has gone away if necessary. */
    2822     1437076 :     if (client_connection_check_interval > 0 &&
    2823           0 :         IsUnderPostmaster &&
    2824           0 :         MyProcPort &&
    2825           0 :         !get_timeout_active(CLIENT_CONNECTION_CHECK_TIMEOUT))
    2826           0 :         enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
    2827             :                              client_connection_check_interval);
    2828     1437076 : }
    2829             : 
    2830             : static void
    2831     1253676 : finish_xact_command(void)
    2832             : {
    2833             :     /* cancel active statement timeout after each command */
    2834     1253676 :     disable_statement_timeout();
    2835             : 
    2836     1253676 :     if (xact_started)
    2837             :     {
    2838      640378 :         CommitTransactionCommand();
    2839             : 
    2840             : #ifdef MEMORY_CONTEXT_CHECKING
    2841             :         /* Check all memory contexts that weren't freed during commit */
    2842             :         /* (those that were, were checked before being deleted) */
    2843             :         MemoryContextCheck(TopMemoryContext);
    2844             : #endif
    2845             : 
    2846             : #ifdef SHOW_MEMORY_STATS
    2847             :         /* Print mem stats after each commit for leak tracking */
    2848             :         MemoryContextStats(TopMemoryContext);
    2849             : #endif
    2850             : 
    2851      639826 :         xact_started = false;
    2852             :     }
    2853     1253124 : }
    2854             : 
    2855             : 
    2856             : /*
    2857             :  * Convenience routines for checking whether a statement is one of the
    2858             :  * ones that we allow in transaction-aborted state.
    2859             :  */
    2860             : 
    2861             : /* Test a bare parsetree */
    2862             : static bool
    2863        1802 : IsTransactionExitStmt(Node *parsetree)
    2864             : {
    2865        1802 :     if (parsetree && IsA(parsetree, TransactionStmt))
    2866             :     {
    2867        1720 :         TransactionStmt *stmt = (TransactionStmt *) parsetree;
    2868             : 
    2869        1720 :         if (stmt->kind == TRANS_STMT_COMMIT ||
    2870         908 :             stmt->kind == TRANS_STMT_PREPARE ||
    2871         904 :             stmt->kind == TRANS_STMT_ROLLBACK ||
    2872         220 :             stmt->kind == TRANS_STMT_ROLLBACK_TO)
    2873        1708 :             return true;
    2874             :     }
    2875          94 :     return false;
    2876             : }
    2877             : 
    2878             : /* Test a list that contains PlannedStmt nodes */
    2879             : static bool
    2880           2 : IsTransactionExitStmtList(List *pstmts)
    2881             : {
    2882           2 :     if (list_length(pstmts) == 1)
    2883             :     {
    2884           2 :         PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
    2885             : 
    2886           4 :         if (pstmt->commandType == CMD_UTILITY &&
    2887           2 :             IsTransactionExitStmt(pstmt->utilityStmt))
    2888           2 :             return true;
    2889             :     }
    2890           0 :     return false;
    2891             : }
    2892             : 
    2893             : /* Test a list that contains PlannedStmt nodes */
    2894             : static bool
    2895       22076 : IsTransactionStmtList(List *pstmts)
    2896             : {
    2897       22076 :     if (list_length(pstmts) == 1)
    2898             :     {
    2899       22076 :         PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
    2900             : 
    2901       22076 :         if (pstmt->commandType == CMD_UTILITY &&
    2902        3758 :             IsA(pstmt->utilityStmt, TransactionStmt))
    2903         966 :             return true;
    2904             :     }
    2905       21110 :     return false;
    2906             : }
    2907             : 
    2908             : /* Release any existing unnamed prepared statement */
    2909             : static void
    2910      663778 : drop_unnamed_stmt(void)
    2911             : {
    2912             :     /* paranoia to avoid a dangling pointer in case of error */
    2913      663778 :     if (unnamed_stmt_psrc)
    2914             :     {
    2915        6404 :         CachedPlanSource *psrc = unnamed_stmt_psrc;
    2916             : 
    2917        6404 :         unnamed_stmt_psrc = NULL;
    2918        6404 :         DropCachedPlan(psrc);
    2919             :     }
    2920      663778 : }
    2921             : 
    2922             : 
    2923             : /* --------------------------------
    2924             :  *      signal handler routines used in PostgresMain()
    2925             :  * --------------------------------
    2926             :  */
    2927             : 
    2928             : /*
    2929             :  * quickdie() occurs when signaled SIGQUIT by the postmaster.
    2930             :  *
    2931             :  * Either some backend has bought the farm, or we've been told to shut down
    2932             :  * "immediately"; so we need to stop what we're doing and exit.
    2933             :  */
    2934             : void
    2935           0 : quickdie(SIGNAL_ARGS)
    2936             : {
    2937           0 :     sigaddset(&BlockSig, SIGQUIT);  /* prevent nested calls */
    2938           0 :     sigprocmask(SIG_SETMASK, &BlockSig, NULL);
    2939             : 
    2940             :     /*
    2941             :      * Prevent interrupts while exiting; though we just blocked signals that
    2942             :      * would queue new interrupts, one may have been pending.  We don't want a
    2943             :      * quickdie() downgraded to a mere query cancel.
    2944             :      */
    2945           0 :     HOLD_INTERRUPTS();
    2946             : 
    2947             :     /*
    2948             :      * If we're aborting out of client auth, don't risk trying to send
    2949             :      * anything to the client; we will likely violate the protocol, not to
    2950             :      * mention that we may have interrupted the guts of OpenSSL or some
    2951             :      * authentication library.
    2952             :      */
    2953           0 :     if (ClientAuthInProgress && whereToSendOutput == DestRemote)
    2954           0 :         whereToSendOutput = DestNone;
    2955             : 
    2956             :     /*
    2957             :      * Notify the client before exiting, to give a clue on what happened.
    2958             :      *
    2959             :      * It's dubious to call ereport() from a signal handler.  It is certainly
    2960             :      * not async-signal safe.  But it seems better to try, than to disconnect
    2961             :      * abruptly and leave the client wondering what happened.  It's remotely
    2962             :      * possible that we crash or hang while trying to send the message, but
    2963             :      * receiving a SIGQUIT is a sign that something has already gone badly
    2964             :      * wrong, so there's not much to lose.  Assuming the postmaster is still
    2965             :      * running, it will SIGKILL us soon if we get stuck for some reason.
    2966             :      *
    2967             :      * One thing we can do to make this a tad safer is to clear the error
    2968             :      * context stack, so that context callbacks are not called.  That's a lot
    2969             :      * less code that could be reached here, and the context info is unlikely
    2970             :      * to be very relevant to a SIGQUIT report anyway.
    2971             :      */
    2972           0 :     error_context_stack = NULL;
    2973             : 
    2974             :     /*
    2975             :      * When responding to a postmaster-issued signal, we send the message only
    2976             :      * to the client; sending to the server log just creates log spam, plus
    2977             :      * it's more code that we need to hope will work in a signal handler.
    2978             :      *
    2979             :      * Ideally these should be ereport(FATAL), but then we'd not get control
    2980             :      * back to force the correct type of process exit.
    2981             :      */
    2982           0 :     switch (GetQuitSignalReason())
    2983             :     {
    2984           0 :         case PMQUIT_NOT_SENT:
    2985             :             /* Hmm, SIGQUIT arrived out of the blue */
    2986           0 :             ereport(WARNING,
    2987             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    2988             :                      errmsg("terminating connection because of unexpected SIGQUIT signal")));
    2989           0 :             break;
    2990           0 :         case PMQUIT_FOR_CRASH:
    2991             :             /* A crash-and-restart cycle is in progress */
    2992           0 :             ereport(WARNING_CLIENT_ONLY,
    2993             :                     (errcode(ERRCODE_CRASH_SHUTDOWN),
    2994             :                      errmsg("terminating connection because of crash of another server process"),
    2995             :                      errdetail("The postmaster has commanded this server process to roll back"
    2996             :                                " the current transaction and exit, because another"
    2997             :                                " server process exited abnormally and possibly corrupted"
    2998             :                                " shared memory."),
    2999             :                      errhint("In a moment you should be able to reconnect to the"
    3000             :                              " database and repeat your command.")));
    3001           0 :             break;
    3002           0 :         case PMQUIT_FOR_STOP:
    3003             :             /* Immediate-mode stop */
    3004           0 :             ereport(WARNING_CLIENT_ONLY,
    3005             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    3006             :                      errmsg("terminating connection due to immediate shutdown command")));
    3007           0 :             break;
    3008             :     }
    3009             : 
    3010             :     /*
    3011             :      * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
    3012             :      * because shared memory may be corrupted, so we don't want to try to
    3013             :      * clean up our transaction.  Just nail the windows shut and get out of
    3014             :      * town.  The callbacks wouldn't be safe to run from a signal handler,
    3015             :      * anyway.
    3016             :      *
    3017             :      * Note we do _exit(2) not _exit(0).  This is to force the postmaster into
    3018             :      * a system reset cycle if someone sends a manual SIGQUIT to a random
    3019             :      * backend.  This is necessary precisely because we don't clean up our
    3020             :      * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
    3021             :      * should ensure the postmaster sees this as a crash, too, but no harm in
    3022             :      * being doubly sure.)
    3023             :      */
    3024           0 :     _exit(2);
    3025             : }
    3026             : 
    3027             : /*
    3028             :  * Shutdown signal from postmaster: abort transaction and exit
    3029             :  * at soonest convenient time
    3030             :  */
    3031             : void
    3032        2076 : die(SIGNAL_ARGS)
    3033             : {
    3034             :     /* Don't joggle the elbow of proc_exit */
    3035        2076 :     if (!proc_exit_inprogress)
    3036             :     {
    3037        1288 :         InterruptPending = true;
    3038        1288 :         ProcDiePending = true;
    3039             :     }
    3040             : 
    3041             :     /* for the cumulative stats system */
    3042        2076 :     pgStatSessionEndCause = DISCONNECT_KILLED;
    3043             : 
    3044             :     /* If we're still here, waken anything waiting on the process latch */
    3045        2076 :     SetLatch(MyLatch);
    3046             : 
    3047             :     /*
    3048             :      * If we're in single user mode, we want to quit immediately - we can't
    3049             :      * rely on latches as they wouldn't work when stdin/stdout is a file.
    3050             :      * Rather ugly, but it's unlikely to be worthwhile to invest much more
    3051             :      * effort just for the benefit of single user mode.
    3052             :      */
    3053        2076 :     if (DoingCommandRead && whereToSendOutput != DestRemote)
    3054           4 :         ProcessInterrupts();
    3055        2076 : }
    3056             : 
    3057             : /*
    3058             :  * Query-cancel signal from postmaster: abort current transaction
    3059             :  * at soonest convenient time
    3060             :  */
    3061             : void
    3062         130 : StatementCancelHandler(SIGNAL_ARGS)
    3063             : {
    3064             :     /*
    3065             :      * Don't joggle the elbow of proc_exit
    3066             :      */
    3067         130 :     if (!proc_exit_inprogress)
    3068             :     {
    3069         130 :         InterruptPending = true;
    3070         130 :         QueryCancelPending = true;
    3071             :     }
    3072             : 
    3073             :     /* If we're still here, waken anything waiting on the process latch */
    3074         130 :     SetLatch(MyLatch);
    3075         130 : }
    3076             : 
    3077             : /* signal handler for floating point exception */
    3078             : void
    3079           0 : FloatExceptionHandler(SIGNAL_ARGS)
    3080             : {
    3081             :     /* We're not returning, so no need to save errno */
    3082           0 :     ereport(ERROR,
    3083             :             (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
    3084             :              errmsg("floating-point exception"),
    3085             :              errdetail("An invalid floating-point operation was signaled. "
    3086             :                        "This probably means an out-of-range result or an "
    3087             :                        "invalid operation, such as division by zero.")));
    3088             : }
    3089             : 
    3090             : /*
    3091             :  * Tell the next CHECK_FOR_INTERRUPTS() to check for a particular type of
    3092             :  * recovery conflict.  Runs in a SIGUSR1 handler.
    3093             :  */
    3094             : void
    3095          36 : HandleRecoveryConflictInterrupt(ProcSignalReason reason)
    3096             : {
    3097          36 :     RecoveryConflictPendingReasons[reason] = true;
    3098          36 :     RecoveryConflictPending = true;
    3099          36 :     InterruptPending = true;
    3100             :     /* latch will be set by procsignal_sigusr1_handler */
    3101          36 : }
    3102             : 
    3103             : /*
    3104             :  * Check one individual conflict reason.
    3105             :  */
    3106             : static void
    3107          36 : ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
    3108             : {
    3109          36 :     switch (reason)
    3110             :     {
    3111          14 :         case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
    3112             : 
    3113             :             /*
    3114             :              * If we aren't waiting for a lock we can never deadlock.
    3115             :              */
    3116          14 :             if (GetAwaitedLock() == NULL)
    3117          12 :                 return;
    3118             : 
    3119             :             /* Intentional fall through to check wait for pin */
    3120             :             /* FALLTHROUGH */
    3121             : 
    3122             :         case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
    3123             : 
    3124             :             /*
    3125             :              * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
    3126             :              * aren't blocking the Startup process there is nothing more to
    3127             :              * do.
    3128             :              *
    3129             :              * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
    3130             :              * if we're waiting for locks and the startup process is not
    3131             :              * waiting for buffer pin (i.e., also waiting for locks), we set
    3132             :              * the flag so that ProcSleep() will check for deadlocks.
    3133             :              */
    3134           4 :             if (!HoldingBufferPinThatDelaysRecovery())
    3135             :             {
    3136           0 :                 if (reason == PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK &&
    3137           0 :                     GetStartupBufferPinWaitBufId() < 0)
    3138           0 :                     CheckDeadLockAlert();
    3139           0 :                 return;
    3140             :             }
    3141             : 
    3142           4 :             MyProc->recoveryConflictPending = true;
    3143             : 
    3144             :             /* Intentional fall through to error handling */
    3145             :             /* FALLTHROUGH */
    3146             : 
    3147          10 :         case PROCSIG_RECOVERY_CONFLICT_LOCK:
    3148             :         case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
    3149             :         case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
    3150             : 
    3151             :             /*
    3152             :              * If we aren't in a transaction any longer then ignore.
    3153             :              */
    3154          10 :             if (!IsTransactionOrTransactionBlock())
    3155           0 :                 return;
    3156             : 
    3157             :             /* FALLTHROUGH */
    3158             : 
    3159             :         case PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT:
    3160             : 
    3161             :             /*
    3162             :              * If we're not in a subtransaction then we are OK to throw an
    3163             :              * ERROR to resolve the conflict.  Otherwise drop through to the
    3164             :              * FATAL case.
    3165             :              *
    3166             :              * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
    3167             :              * always throws an ERROR (ie never promotes to FATAL), though it
    3168             :              * still has to respect QueryCancelHoldoffCount, so it shares this
    3169             :              * code path.  Logical decoding slots are only acquired while
    3170             :              * performing logical decoding.  During logical decoding no user
    3171             :              * controlled code is run.  During [sub]transaction abort, the
    3172             :              * slot is released.  Therefore user controlled code cannot
    3173             :              * intercept an error before the replication slot is released.
    3174             :              *
    3175             :              * XXX other times that we can throw just an ERROR *may* be
    3176             :              * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
    3177             :              * transactions
    3178             :              *
    3179             :              * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
    3180             :              * parent transactions and the transaction is not
    3181             :              * transaction-snapshot mode
    3182             :              *
    3183             :              * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
    3184             :              * cursors open in parent transactions
    3185             :              */
    3186          20 :             if (reason == PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT ||
    3187          10 :                 !IsSubTransaction())
    3188             :             {
    3189             :                 /*
    3190             :                  * If we already aborted then we no longer need to cancel.  We
    3191             :                  * do this here since we do not wish to ignore aborted
    3192             :                  * subtransactions, which must cause FATAL, currently.
    3193             :                  */
    3194          20 :                 if (IsAbortedTransactionBlockState())
    3195           0 :                     return;
    3196             : 
    3197             :                 /*
    3198             :                  * If a recovery conflict happens while we are waiting for
    3199             :                  * input from the client, the client is presumably just
    3200             :                  * sitting idle in a transaction, preventing recovery from
    3201             :                  * making progress.  We'll drop through to the FATAL case
    3202             :                  * below to dislodge it, in that case.
    3203             :                  */
    3204          20 :                 if (!DoingCommandRead)
    3205             :                 {
    3206             :                     /* Avoid losing sync in the FE/BE protocol. */
    3207          12 :                     if (QueryCancelHoldoffCount != 0)
    3208             :                     {
    3209             :                         /*
    3210             :                          * Re-arm and defer this interrupt until later.  See
    3211             :                          * similar code in ProcessInterrupts().
    3212             :                          */
    3213           0 :                         RecoveryConflictPendingReasons[reason] = true;
    3214           0 :                         RecoveryConflictPending = true;
    3215           0 :                         InterruptPending = true;
    3216           0 :                         return;
    3217             :                     }
    3218             : 
    3219             :                     /*
    3220             :                      * We are cleared to throw an ERROR.  Either it's the
    3221             :                      * logical slot case, or we have a top-level transaction
    3222             :                      * that we can abort and a conflict that isn't inherently
    3223             :                      * non-retryable.
    3224             :                      */
    3225          12 :                     LockErrorCleanup();
    3226          12 :                     pgstat_report_recovery_conflict(reason);
    3227          12 :                     ereport(ERROR,
    3228             :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3229             :                              errmsg("canceling statement due to conflict with recovery"),
    3230             :                              errdetail_recovery_conflict(reason)));
    3231             :                     break;
    3232             :                 }
    3233             :             }
    3234             : 
    3235             :             /* Intentional fall through to session cancel */
    3236             :             /* FALLTHROUGH */
    3237             : 
    3238             :         case PROCSIG_RECOVERY_CONFLICT_DATABASE:
    3239             : 
    3240             :             /*
    3241             :              * Retrying is not possible because the database is dropped, or we
    3242             :              * decided above that we couldn't resolve the conflict with an
    3243             :              * ERROR and fell through.  Terminate the session.
    3244             :              */
    3245          12 :             pgstat_report_recovery_conflict(reason);
    3246          12 :             ereport(FATAL,
    3247             :                     (errcode(reason == PROCSIG_RECOVERY_CONFLICT_DATABASE ?
    3248             :                              ERRCODE_DATABASE_DROPPED :
    3249             :                              ERRCODE_T_R_SERIALIZATION_FAILURE),
    3250             :                      errmsg("terminating connection due to conflict with recovery"),
    3251             :                      errdetail_recovery_conflict(reason),
    3252             :                      errhint("In a moment you should be able to reconnect to the"
    3253             :                              " database and repeat your command.")));
    3254             :             break;
    3255             : 
    3256           0 :         default:
    3257           0 :             elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
    3258             :     }
    3259             : }
    3260             : 
    3261             : /*
    3262             :  * Check each possible recovery conflict reason.
    3263             :  */
    3264             : static void
    3265          36 : ProcessRecoveryConflictInterrupts(void)
    3266             : {
    3267             :     /*
    3268             :      * We don't need to worry about joggling the elbow of proc_exit, because
    3269             :      * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
    3270             :      * us.
    3271             :      */
    3272             :     Assert(!proc_exit_inprogress);
    3273             :     Assert(InterruptHoldoffCount == 0);
    3274             :     Assert(RecoveryConflictPending);
    3275             : 
    3276          36 :     RecoveryConflictPending = false;
    3277             : 
    3278          36 :     for (ProcSignalReason reason = PROCSIG_RECOVERY_CONFLICT_FIRST;
    3279         194 :          reason <= PROCSIG_RECOVERY_CONFLICT_LAST;
    3280         158 :          reason++)
    3281             :     {
    3282         182 :         if (RecoveryConflictPendingReasons[reason])
    3283             :         {
    3284          36 :             RecoveryConflictPendingReasons[reason] = false;
    3285          36 :             ProcessRecoveryConflictInterrupt(reason);
    3286             :         }
    3287             :     }
    3288          12 : }
    3289             : 
    3290             : /*
    3291             :  * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
    3292             :  *
    3293             :  * If an interrupt condition is pending, and it's safe to service it,
    3294             :  * then clear the flag and accept the interrupt.  Called only when
    3295             :  * InterruptPending is true.
    3296             :  *
    3297             :  * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
    3298             :  * is guaranteed to clear the InterruptPending flag before returning.
    3299             :  * (This is not the same as guaranteeing that it's still clear when we
    3300             :  * return; another interrupt could have arrived.  But we promise that
    3301             :  * any pre-existing one will have been serviced.)
    3302             :  */
    3303             : void
    3304        6698 : ProcessInterrupts(void)
    3305             : {
    3306             :     /* OK to accept any interrupts now? */
    3307        6698 :     if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
    3308        1022 :         return;
    3309        5676 :     InterruptPending = false;
    3310             : 
    3311        5676 :     if (ProcDiePending)
    3312             :     {
    3313        1276 :         ProcDiePending = false;
    3314        1276 :         QueryCancelPending = false; /* ProcDie trumps QueryCancel */
    3315        1276 :         LockErrorCleanup();
    3316             :         /* As in quickdie, don't risk sending to client during auth */
    3317        1276 :         if (ClientAuthInProgress && whereToSendOutput == DestRemote)
    3318           0 :             whereToSendOutput = DestNone;
    3319        1276 :         if (ClientAuthInProgress)
    3320           0 :             ereport(FATAL,
    3321             :                     (errcode(ERRCODE_QUERY_CANCELED),
    3322             :                      errmsg("canceling authentication due to timeout")));
    3323        1276 :         else if (AmAutoVacuumWorkerProcess())
    3324           2 :             ereport(FATAL,
    3325             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    3326             :                      errmsg("terminating autovacuum process due to administrator command")));
    3327        1274 :         else if (IsLogicalWorker())
    3328         210 :             ereport(FATAL,
    3329             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    3330             :                      errmsg("terminating logical replication worker due to administrator command")));
    3331        1064 :         else if (IsLogicalLauncher())
    3332             :         {
    3333         844 :             ereport(DEBUG1,
    3334             :                     (errmsg_internal("logical replication launcher shutting down")));
    3335             : 
    3336             :             /*
    3337             :              * The logical replication launcher can be stopped at any time.
    3338             :              * Use exit status 1 so the background worker is restarted.
    3339             :              */
    3340         844 :             proc_exit(1);
    3341             :         }
    3342         220 :         else if (AmWalReceiverProcess())
    3343         164 :             ereport(FATAL,
    3344             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    3345             :                      errmsg("terminating walreceiver process due to administrator command")));
    3346          56 :         else if (AmBackgroundWorkerProcess())
    3347           2 :             ereport(FATAL,
    3348             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    3349             :                      errmsg("terminating background worker \"%s\" due to administrator command",
    3350             :                             MyBgworkerEntry->bgw_type)));
    3351          54 :         else if (AmIoWorkerProcess())
    3352             :         {
    3353           8 :             ereport(DEBUG1,
    3354             :                     (errmsg_internal("io worker shutting down due to administrator command")));
    3355             : 
    3356           8 :             proc_exit(0);
    3357             :         }
    3358             :         else
    3359          46 :             ereport(FATAL,
    3360             :                     (errcode(ERRCODE_ADMIN_SHUTDOWN),
    3361             :                      errmsg("terminating connection due to administrator command")));
    3362             :     }
    3363             : 
    3364        4400 :     if (CheckClientConnectionPending)
    3365             :     {
    3366           0 :         CheckClientConnectionPending = false;
    3367             : 
    3368             :         /*
    3369             :          * Check for lost connection and re-arm, if still configured, but not
    3370             :          * if we've arrived back at DoingCommandRead state.  We don't want to
    3371             :          * wake up idle sessions, and they already know how to detect lost
    3372             :          * connections.
    3373             :          */
    3374           0 :         if (!DoingCommandRead && client_connection_check_interval > 0)
    3375             :         {
    3376           0 :             if (!pq_check_connection())
    3377           0 :                 ClientConnectionLost = true;
    3378             :             else
    3379           0 :                 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
    3380             :                                      client_connection_check_interval);
    3381             :         }
    3382             :     }
    3383             : 
    3384        4400 :     if (ClientConnectionLost)
    3385             :     {
    3386          48 :         QueryCancelPending = false; /* lost connection trumps QueryCancel */
    3387          48 :         LockErrorCleanup();
    3388             :         /* don't send to client, we already know the connection to be dead. */
    3389          48 :         whereToSendOutput = DestNone;
    3390          48 :         ereport(FATAL,
    3391             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    3392             :                  errmsg("connection to client lost")));
    3393             :     }
    3394             : 
    3395             :     /*
    3396             :      * Don't allow query cancel interrupts while reading input from the
    3397             :      * client, because we might lose sync in the FE/BE protocol.  (Die
    3398             :      * interrupts are OK, because we won't read any further messages from the
    3399             :      * client in that case.)
    3400             :      *
    3401             :      * See similar logic in ProcessRecoveryConflictInterrupts().
    3402             :      */
    3403        4352 :     if (QueryCancelPending && QueryCancelHoldoffCount != 0)
    3404             :     {
    3405             :         /*
    3406             :          * Re-arm InterruptPending so that we process the cancel request as
    3407             :          * soon as we're done reading the message.  (XXX this is seriously
    3408             :          * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
    3409             :          * can't use that macro directly as the initial test in this function,
    3410             :          * meaning that this code also creates opportunities for other bugs to
    3411             :          * appear.)
    3412             :          */
    3413          20 :         InterruptPending = true;
    3414             :     }
    3415        4332 :     else if (QueryCancelPending)
    3416             :     {
    3417             :         bool        lock_timeout_occurred;
    3418             :         bool        stmt_timeout_occurred;
    3419             : 
    3420         110 :         QueryCancelPending = false;
    3421             : 
    3422             :         /*
    3423             :          * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
    3424             :          * need to clear both, so always fetch both.
    3425             :          */
    3426         110 :         lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
    3427         110 :         stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
    3428             : 
    3429             :         /*
    3430             :          * If both were set, we want to report whichever timeout completed
    3431             :          * earlier; this ensures consistent behavior if the machine is slow
    3432             :          * enough that the second timeout triggers before we get here.  A tie
    3433             :          * is arbitrarily broken in favor of reporting a lock timeout.
    3434             :          */
    3435         110 :         if (lock_timeout_occurred && stmt_timeout_occurred &&
    3436           0 :             get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
    3437           0 :             lock_timeout_occurred = false;  /* report stmt timeout */
    3438             : 
    3439         110 :         if (lock_timeout_occurred)
    3440             :         {
    3441           8 :             LockErrorCleanup();
    3442           8 :             ereport(ERROR,
    3443             :                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
    3444             :                      errmsg("canceling statement due to lock timeout")));
    3445             :         }
    3446         102 :         if (stmt_timeout_occurred)
    3447             :         {
    3448          12 :             LockErrorCleanup();
    3449          12 :             ereport(ERROR,
    3450             :                     (errcode(ERRCODE_QUERY_CANCELED),
    3451             :                      errmsg("canceling statement due to statement timeout")));
    3452             :         }
    3453          90 :         if (AmAutoVacuumWorkerProcess())
    3454             :         {
    3455           0 :             LockErrorCleanup();
    3456           0 :             ereport(ERROR,
    3457             :                     (errcode(ERRCODE_QUERY_CANCELED),
    3458             :                      errmsg("canceling autovacuum task")));
    3459             :         }
    3460             : 
    3461             :         /*
    3462             :          * If we are reading a command from the client, just ignore the cancel
    3463             :          * request --- sending an extra error message won't accomplish
    3464             :          * anything.  Otherwise, go ahead and throw the error.
    3465             :          */
    3466          90 :         if (!DoingCommandRead)
    3467             :         {
    3468          80 :             LockErrorCleanup();
    3469          80 :             ereport(ERROR,
    3470             :                     (errcode(ERRCODE_QUERY_CANCELED),
    3471             :                      errmsg("canceling statement due to user request")));
    3472             :         }
    3473             :     }
    3474             : 
    3475        4252 :     if (RecoveryConflictPending)
    3476          36 :         ProcessRecoveryConflictInterrupts();
    3477             : 
    3478        4228 :     if (IdleInTransactionSessionTimeoutPending)
    3479             :     {
    3480             :         /*
    3481             :          * If the GUC has been reset to zero, ignore the signal.  This is
    3482             :          * important because the GUC update itself won't disable any pending
    3483             :          * interrupt.  We need to unset the flag before the injection point,
    3484             :          * otherwise we could loop in interrupts checking.
    3485             :          */
    3486           2 :         IdleInTransactionSessionTimeoutPending = false;
    3487           2 :         if (IdleInTransactionSessionTimeout > 0)
    3488             :         {
    3489           2 :             INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
    3490           2 :             ereport(FATAL,
    3491             :                     (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
    3492             :                      errmsg("terminating connection due to idle-in-transaction timeout")));
    3493             :         }
    3494             :     }
    3495             : 
    3496        4226 :     if (TransactionTimeoutPending)
    3497             :     {
    3498             :         /* As above, ignore the signal if the GUC has been reset to zero. */
    3499           2 :         TransactionTimeoutPending = false;
    3500           2 :         if (TransactionTimeout > 0)
    3501             :         {
    3502           2 :             INJECTION_POINT("transaction-timeout", NULL);
    3503           2 :             ereport(FATAL,
    3504             :                     (errcode(ERRCODE_TRANSACTION_TIMEOUT),
    3505             :                      errmsg("terminating connection due to transaction timeout")));
    3506             :         }
    3507             :     }
    3508             : 
    3509        4224 :     if (IdleSessionTimeoutPending)
    3510             :     {
    3511             :         /* As above, ignore the signal if the GUC has been reset to zero. */
    3512           0 :         IdleSessionTimeoutPending = false;
    3513           0 :         if (IdleSessionTimeout > 0)
    3514             :         {
    3515           0 :             INJECTION_POINT("idle-session-timeout", NULL);
    3516           0 :             ereport(FATAL,
    3517             :                     (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
    3518             :                      errmsg("terminating connection due to idle-session timeout")));
    3519             :         }
    3520             :     }
    3521             : 
    3522             :     /*
    3523             :      * If there are pending stats updates and we currently are truly idle
    3524             :      * (matching the conditions in PostgresMain(), report stats now.
    3525             :      */
    3526        4224 :     if (IdleStatsUpdateTimeoutPending &&
    3527          42 :         DoingCommandRead && !IsTransactionOrTransactionBlock())
    3528             :     {
    3529           8 :         IdleStatsUpdateTimeoutPending = false;
    3530           8 :         pgstat_report_stat(true);
    3531             :     }
    3532             : 
    3533        4224 :     if (ProcSignalBarrierPending)
    3534         874 :         ProcessProcSignalBarrier();
    3535             : 
    3536        4224 :     if (ParallelMessagePending)
    3537        3104 :         ProcessParallelMessages();
    3538             : 
    3539        4212 :     if (LogMemoryContextPending)
    3540          16 :         ProcessLogMemoryContextInterrupt();
    3541             : 
    3542        4212 :     if (ParallelApplyMessagePending)
    3543          12 :         ProcessParallelApplyMessages();
    3544             : }
    3545             : 
    3546             : /*
    3547             :  * GUC check_hook for client_connection_check_interval
    3548             :  */
    3549             : bool
    3550        2254 : check_client_connection_check_interval(int *newval, void **extra, GucSource source)
    3551             : {
    3552        2254 :     if (!WaitEventSetCanReportClosed() && *newval != 0)
    3553             :     {
    3554           0 :         GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
    3555           0 :         return false;
    3556             :     }
    3557        2254 :     return true;
    3558             : }
    3559             : 
    3560             : /*
    3561             :  * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
    3562             :  *
    3563             :  * This function and check_log_stats interact to prevent their variables from
    3564             :  * being set in a disallowed combination.  This is a hack that doesn't really
    3565             :  * work right; for example it might fail while applying pg_db_role_setting
    3566             :  * values even though the final state would have been acceptable.  However,
    3567             :  * since these variables are legacy settings with little production usage,
    3568             :  * we tolerate that.
    3569             :  */
    3570             : bool
    3571        6762 : check_stage_log_stats(bool *newval, void **extra, GucSource source)
    3572             : {
    3573        6762 :     if (*newval && log_statement_stats)
    3574             :     {
    3575           0 :         GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
    3576           0 :         return false;
    3577             :     }
    3578        6762 :     return true;
    3579             : }
    3580             : 
    3581             : /*
    3582             :  * GUC check_hook for log_statement_stats
    3583             :  */
    3584             : bool
    3585        2254 : check_log_stats(bool *newval, void **extra, GucSource source)
    3586             : {
    3587        2254 :     if (*newval &&
    3588           0 :         (log_parser_stats || log_planner_stats || log_executor_stats))
    3589             :     {
    3590           0 :         GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
    3591             :                             "\"log_parser_stats\", \"log_planner_stats\", "
    3592             :                             "or \"log_executor_stats\" is true.");
    3593           0 :         return false;
    3594             :     }
    3595        2254 :     return true;
    3596             : }
    3597             : 
    3598             : /* GUC assign hook for transaction_timeout */
    3599             : void
    3600        8442 : assign_transaction_timeout(int newval, void *extra)
    3601             : {
    3602        8442 :     if (IsTransactionState())
    3603             :     {
    3604             :         /*
    3605             :          * If transaction_timeout GUC has changed within the transaction block
    3606             :          * enable or disable the timer correspondingly.
    3607             :          */
    3608         686 :         if (newval > 0 && !get_timeout_active(TRANSACTION_TIMEOUT))
    3609           2 :             enable_timeout_after(TRANSACTION_TIMEOUT, newval);
    3610         684 :         else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
    3611           0 :             disable_timeout(TRANSACTION_TIMEOUT, false);
    3612             :     }
    3613        8442 : }
    3614             : 
    3615             : /*
    3616             :  * GUC check_hook for restrict_nonsystem_relation_kind
    3617             :  */
    3618             : bool
    3619        2696 : check_restrict_nonsystem_relation_kind(char **newval, void **extra, GucSource source)
    3620             : {
    3621             :     char       *rawstring;
    3622             :     List       *elemlist;
    3623             :     ListCell   *l;
    3624        2696 :     int         flags = 0;
    3625             : 
    3626             :     /* Need a modifiable copy of string */
    3627        2696 :     rawstring = pstrdup(*newval);
    3628             : 
    3629        2696 :     if (!SplitIdentifierString(rawstring, ',', &elemlist))
    3630             :     {
    3631             :         /* syntax error in list */
    3632           0 :         GUC_check_errdetail("List syntax is invalid.");
    3633           0 :         pfree(rawstring);
    3634           0 :         list_free(elemlist);
    3635           0 :         return false;
    3636             :     }
    3637             : 
    3638        3570 :     foreach(l, elemlist)
    3639             :     {
    3640         874 :         char       *tok = (char *) lfirst(l);
    3641             : 
    3642         874 :         if (pg_strcasecmp(tok, "view") == 0)
    3643         440 :             flags |= RESTRICT_RELKIND_VIEW;
    3644         434 :         else if (pg_strcasecmp(tok, "foreign-table") == 0)
    3645         434 :             flags |= RESTRICT_RELKIND_FOREIGN_TABLE;
    3646             :         else
    3647             :         {
    3648           0 :             GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
    3649           0 :             pfree(rawstring);
    3650           0 :             list_free(elemlist);
    3651           0 :             return false;
    3652             :         }
    3653             :     }
    3654             : 
    3655        2696 :     pfree(rawstring);
    3656        2696 :     list_free(elemlist);
    3657             : 
    3658             :     /* Save the flags in *extra, for use by the assign function */
    3659        2696 :     *extra = guc_malloc(LOG, sizeof(int));
    3660        2696 :     if (!*extra)
    3661           0 :         return false;
    3662        2696 :     *((int *) *extra) = flags;
    3663             : 
    3664        2696 :     return true;
    3665             : }
    3666             : 
    3667             : /*
    3668             :  * GUC assign_hook for restrict_nonsystem_relation_kind
    3669             :  */
    3670             : void
    3671        2706 : assign_restrict_nonsystem_relation_kind(const char *newval, void *extra)
    3672             : {
    3673        2706 :     int        *flags = (int *) extra;
    3674             : 
    3675        2706 :     restrict_nonsystem_relation_kind = *flags;
    3676        2706 : }
    3677             : 
    3678             : /*
    3679             :  * set_debug_options --- apply "-d N" command line option
    3680             :  *
    3681             :  * -d is not quite the same as setting log_min_messages because it enables
    3682             :  * other output options.
    3683             :  */
    3684             : void
    3685           0 : set_debug_options(int debug_flag, GucContext context, GucSource source)
    3686             : {
    3687           0 :     if (debug_flag > 0)
    3688             :     {
    3689             :         char        debugstr[64];
    3690             : 
    3691           0 :         sprintf(debugstr, "debug%d", debug_flag);
    3692           0 :         SetConfigOption("log_min_messages", debugstr, context, source);
    3693             :     }
    3694             :     else
    3695           0 :         SetConfigOption("log_min_messages", "notice", context, source);
    3696             : 
    3697           0 :     if (debug_flag >= 1 && context == PGC_POSTMASTER)
    3698             :     {
    3699           0 :         SetConfigOption("log_connections", "all", context, source);
    3700           0 :         SetConfigOption("log_disconnections", "true", context, source);
    3701             :     }
    3702           0 :     if (debug_flag >= 2)
    3703           0 :         SetConfigOption("log_statement", "all", context, source);
    3704           0 :     if (debug_flag >= 3)
    3705             :     {
    3706           0 :         SetConfigOption("debug_print_raw_parse", "true", context, source);
    3707           0 :         SetConfigOption("debug_print_parse", "true", context, source);
    3708             :     }
    3709           0 :     if (debug_flag >= 4)
    3710           0 :         SetConfigOption("debug_print_plan", "true", context, source);
    3711           0 :     if (debug_flag >= 5)
    3712           0 :         SetConfigOption("debug_print_rewritten", "true", context, source);
    3713           0 : }
    3714             : 
    3715             : 
    3716             : bool
    3717           0 : set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
    3718             : {
    3719           0 :     const char *tmp = NULL;
    3720             : 
    3721           0 :     switch (arg[0])
    3722             :     {
    3723           0 :         case 's':               /* seqscan */
    3724           0 :             tmp = "enable_seqscan";
    3725           0 :             break;
    3726           0 :         case 'i':               /* indexscan */
    3727           0 :             tmp = "enable_indexscan";
    3728           0 :             break;
    3729           0 :         case 'o':               /* indexonlyscan */
    3730           0 :             tmp = "enable_indexonlyscan";
    3731           0 :             break;
    3732           0 :         case 'b':               /* bitmapscan */
    3733           0 :             tmp = "enable_bitmapscan";
    3734           0 :             break;
    3735           0 :         case 't':               /* tidscan */
    3736           0 :             tmp = "enable_tidscan";
    3737           0 :             break;
    3738           0 :         case 'n':               /* nestloop */
    3739           0 :             tmp = "enable_nestloop";
    3740           0 :             break;
    3741           0 :         case 'm':               /* mergejoin */
    3742           0 :             tmp = "enable_mergejoin";
    3743           0 :             break;
    3744           0 :         case 'h':               /* hashjoin */
    3745           0 :             tmp = "enable_hashjoin";
    3746           0 :             break;
    3747             :     }
    3748           0 :     if (tmp)
    3749             :     {
    3750           0 :         SetConfigOption(tmp, "false", context, source);
    3751           0 :         return true;
    3752             :     }
    3753             :     else
    3754           0 :         return false;
    3755             : }
    3756             : 
    3757             : 
    3758             : const char *
    3759           0 : get_stats_option_name(const char *arg)
    3760             : {
    3761           0 :     switch (arg[0])
    3762             :     {
    3763           0 :         case 'p':
    3764           0 :             if (optarg[1] == 'a')   /* "parser" */
    3765           0 :                 return "log_parser_stats";
    3766           0 :             else if (optarg[1] == 'l')  /* "planner" */
    3767           0 :                 return "log_planner_stats";
    3768           0 :             break;
    3769             : 
    3770           0 :         case 'e':               /* "executor" */
    3771           0 :             return "log_executor_stats";
    3772             :             break;
    3773             :     }
    3774             : 
    3775           0 :     return NULL;
    3776             : }
    3777             : 
    3778             : 
    3779             : /* ----------------------------------------------------------------
    3780             :  * process_postgres_switches
    3781             :  *     Parse command line arguments for backends
    3782             :  *
    3783             :  * This is called twice, once for the "secure" options coming from the
    3784             :  * postmaster or command line, and once for the "insecure" options coming
    3785             :  * from the client's startup packet.  The latter have the same syntax but
    3786             :  * may be restricted in what they can do.
    3787             :  *
    3788             :  * argv[0] is ignored in either case (it's assumed to be the program name).
    3789             :  *
    3790             :  * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
    3791             :  * coming from the client, or PGC_SU_BACKEND for insecure options coming from
    3792             :  * a superuser client.
    3793             :  *
    3794             :  * If a database name is present in the command line arguments, it's
    3795             :  * returned into *dbname (this is allowed only if *dbname is initially NULL).
    3796             :  * ----------------------------------------------------------------
    3797             :  */
    3798             : void
    3799        7594 : process_postgres_switches(int argc, char *argv[], GucContext ctx,
    3800             :                           const char **dbname)
    3801             : {
    3802        7594 :     bool        secure = (ctx == PGC_POSTMASTER);
    3803        7594 :     int         errs = 0;
    3804             :     GucSource   gucsource;
    3805             :     int         flag;
    3806             : 
    3807        7594 :     if (secure)
    3808             :     {
    3809         142 :         gucsource = PGC_S_ARGV; /* switches came from command line */
    3810             : 
    3811             :         /* Ignore the initial --single argument, if present */
    3812         142 :         if (argc > 1 && strcmp(argv[1], "--single") == 0)
    3813             :         {
    3814         142 :             argv++;
    3815         142 :             argc--;
    3816             :         }
    3817             :     }
    3818             :     else
    3819             :     {
    3820        7452 :         gucsource = PGC_S_CLIENT;   /* switches came from client */
    3821             :     }
    3822             : 
    3823             : #ifdef HAVE_INT_OPTERR
    3824             : 
    3825             :     /*
    3826             :      * Turn this off because it's either printed to stderr and not the log
    3827             :      * where we'd want it, or argv[0] is now "--single", which would make for
    3828             :      * a weird error message.  We print our own error message below.
    3829             :      */
    3830        7594 :     opterr = 0;
    3831             : #endif
    3832             : 
    3833             :     /*
    3834             :      * Parse command-line options.  CAUTION: keep this in sync with
    3835             :      * postmaster/postmaster.c (the option sets should not conflict) and with
    3836             :      * the common help() function in main/main.c.
    3837             :      */
    3838       18366 :     while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
    3839             :     {
    3840       10772 :         switch (flag)
    3841             :         {
    3842           0 :             case 'B':
    3843           0 :                 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
    3844           0 :                 break;
    3845             : 
    3846           0 :             case 'b':
    3847             :                 /* Undocumented flag used for binary upgrades */
    3848           0 :                 if (secure)
    3849           0 :                     IsBinaryUpgrade = true;
    3850           0 :                 break;
    3851             : 
    3852           0 :             case 'C':
    3853             :                 /* ignored for consistency with the postmaster */
    3854           0 :                 break;
    3855             : 
    3856         134 :             case '-':
    3857             : 
    3858             :                 /*
    3859             :                  * Error if the user misplaced a special must-be-first option
    3860             :                  * for dispatching to a subprogram.  parse_dispatch_option()
    3861             :                  * returns DISPATCH_POSTMASTER if it doesn't find a match, so
    3862             :                  * error for anything else.
    3863             :                  */
    3864         134 :                 if (parse_dispatch_option(optarg) != DISPATCH_POSTMASTER)
    3865           0 :                     ereport(ERROR,
    3866             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3867             :                              errmsg("--%s must be first argument", optarg)));
    3868             : 
    3869             :                 /* FALLTHROUGH */
    3870             :             case 'c':
    3871             :                 {
    3872             :                     char       *name,
    3873             :                                *value;
    3874             : 
    3875       10390 :                     ParseLongOption(optarg, &name, &value);
    3876       10390 :                     if (!value)
    3877             :                     {
    3878           0 :                         if (flag == '-')
    3879           0 :                             ereport(ERROR,
    3880             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
    3881             :                                      errmsg("--%s requires a value",
    3882             :                                             optarg)));
    3883             :                         else
    3884           0 :                             ereport(ERROR,
    3885             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
    3886             :                                      errmsg("-c %s requires a value",
    3887             :                                             optarg)));
    3888             :                     }
    3889       10390 :                     SetConfigOption(name, value, ctx, gucsource);
    3890       10390 :                     pfree(name);
    3891       10390 :                     pfree(value);
    3892       10390 :                     break;
    3893             :                 }
    3894             : 
    3895          42 :             case 'D':
    3896          42 :                 if (secure)
    3897          42 :                     userDoption = strdup(optarg);
    3898          42 :                 break;
    3899             : 
    3900           0 :             case 'd':
    3901           0 :                 set_debug_options(atoi(optarg), ctx, gucsource);
    3902           0 :                 break;
    3903             : 
    3904           0 :             case 'E':
    3905           0 :                 if (secure)
    3906           0 :                     EchoQuery = true;
    3907           0 :                 break;
    3908             : 
    3909           0 :             case 'e':
    3910           0 :                 SetConfigOption("datestyle", "euro", ctx, gucsource);
    3911           0 :                 break;
    3912             : 
    3913         140 :             case 'F':
    3914         140 :                 SetConfigOption("fsync", "false", ctx, gucsource);
    3915         140 :                 break;
    3916             : 
    3917           0 :             case 'f':
    3918           0 :                 if (!set_plan_disabling_options(optarg, ctx, gucsource))
    3919           0 :                     errs++;
    3920           0 :                 break;
    3921             : 
    3922           0 :             case 'h':
    3923           0 :                 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
    3924           0 :                 break;
    3925             : 
    3926           0 :             case 'i':
    3927           0 :                 SetConfigOption("listen_addresses", "*", ctx, gucsource);
    3928           0 :                 break;
    3929             : 
    3930         100 :             case 'j':
    3931         100 :                 if (secure)
    3932         100 :                     UseSemiNewlineNewline = true;
    3933         100 :                 break;
    3934             : 
    3935           0 :             case 'k':
    3936           0 :                 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
    3937           0 :                 break;
    3938             : 
    3939           0 :             case 'l':
    3940           0 :                 SetConfigOption("ssl", "true", ctx, gucsource);
    3941           0 :                 break;
    3942             : 
    3943           0 :             case 'N':
    3944           0 :                 SetConfigOption("max_connections", optarg, ctx, gucsource);
    3945           0 :                 break;
    3946             : 
    3947           0 :             case 'n':
    3948             :                 /* ignored for consistency with postmaster */
    3949           0 :                 break;
    3950             : 
    3951         100 :             case 'O':
    3952         100 :                 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
    3953         100 :                 break;
    3954             : 
    3955           0 :             case 'P':
    3956           0 :                 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
    3957           0 :                 break;
    3958             : 
    3959           0 :             case 'p':
    3960           0 :                 SetConfigOption("port", optarg, ctx, gucsource);
    3961           0 :                 break;
    3962             : 
    3963           0 :             case 'r':
    3964             :                 /* send output (stdout and stderr) to the given file */
    3965           0 :                 if (secure)
    3966           0 :                     strlcpy(OutputFileName, optarg, MAXPGPATH);
    3967           0 :                 break;
    3968             : 
    3969           0 :             case 'S':
    3970           0 :                 SetConfigOption("work_mem", optarg, ctx, gucsource);
    3971           0 :                 break;
    3972             : 
    3973           0 :             case 's':
    3974           0 :                 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
    3975           0 :                 break;
    3976             : 
    3977           0 :             case 'T':
    3978             :                 /* ignored for consistency with the postmaster */
    3979           0 :                 break;
    3980             : 
    3981           0 :             case 't':
    3982             :                 {
    3983           0 :                     const char *tmp = get_stats_option_name(optarg);
    3984             : 
    3985           0 :                     if (tmp)
    3986           0 :                         SetConfigOption(tmp, "true", ctx, gucsource);
    3987             :                     else
    3988           0 :                         errs++;
    3989           0 :                     break;
    3990             :                 }
    3991             : 
    3992           0 :             case 'v':
    3993             : 
    3994             :                 /*
    3995             :                  * -v is no longer used in normal operation, since
    3996             :                  * FrontendProtocol is already set before we get here. We keep
    3997             :                  * the switch only for possible use in standalone operation,
    3998             :                  * in case we ever support using normal FE/BE protocol with a
    3999             :                  * standalone backend.
    4000             :                  */
    4001           0 :                 if (secure)
    4002           0 :                     FrontendProtocol = (ProtocolVersion) atoi(optarg);
    4003           0 :                 break;
    4004             : 
    4005           0 :             case 'W':
    4006           0 :                 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
    4007           0 :                 break;
    4008             : 
    4009           0 :             default:
    4010           0 :                 errs++;
    4011           0 :                 break;
    4012             :         }
    4013             : 
    4014       10772 :         if (errs)
    4015           0 :             break;
    4016             :     }
    4017             : 
    4018             :     /*
    4019             :      * Optional database name should be there only if *dbname is NULL.
    4020             :      */
    4021        7594 :     if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
    4022         142 :         *dbname = strdup(argv[optind++]);
    4023             : 
    4024        7594 :     if (errs || argc != optind)
    4025             :     {
    4026           0 :         if (errs)
    4027           0 :             optind--;           /* complain about the previous argument */
    4028             : 
    4029             :         /* spell the error message a bit differently depending on context */
    4030           0 :         if (IsUnderPostmaster)
    4031           0 :             ereport(FATAL,
    4032             :                     errcode(ERRCODE_SYNTAX_ERROR),
    4033             :                     errmsg("invalid command-line argument for server process: %s", argv[optind]),
    4034             :                     errhint("Try \"%s --help\" for more information.", progname));
    4035             :         else
    4036           0 :             ereport(FATAL,
    4037             :                     errcode(ERRCODE_SYNTAX_ERROR),
    4038             :                     errmsg("%s: invalid command-line argument: %s",
    4039             :                            progname, argv[optind]),
    4040             :                     errhint("Try \"%s --help\" for more information.", progname));
    4041             :     }
    4042             : 
    4043             :     /*
    4044             :      * Reset getopt(3) library so that it will work correctly in subprocesses
    4045             :      * or when this function is called a second time with another array.
    4046             :      */
    4047        7594 :     optind = 1;
    4048             : #ifdef HAVE_INT_OPTRESET
    4049             :     optreset = 1;               /* some systems need this too */
    4050             : #endif
    4051        7594 : }
    4052             : 
    4053             : 
    4054             : /*
    4055             :  * PostgresSingleUserMain
    4056             :  *     Entry point for single user mode. argc/argv are the command line
    4057             :  *     arguments to be used.
    4058             :  *
    4059             :  * Performs single user specific setup then calls PostgresMain() to actually
    4060             :  * process queries. Single user mode specific setup should go here, rather
    4061             :  * than PostgresMain() or InitPostgres() when reasonably possible.
    4062             :  */
    4063             : void
    4064         142 : PostgresSingleUserMain(int argc, char *argv[],
    4065             :                        const char *username)
    4066             : {
    4067         142 :     const char *dbname = NULL;
    4068             : 
    4069             :     Assert(!IsUnderPostmaster);
    4070             : 
    4071             :     /* Initialize startup process environment. */
    4072         142 :     InitStandaloneProcess(argv[0]);
    4073             : 
    4074             :     /*
    4075             :      * Set default values for command-line options.
    4076             :      */
    4077         142 :     InitializeGUCOptions();
    4078             : 
    4079             :     /*
    4080             :      * Parse command-line options.
    4081             :      */
    4082         142 :     process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
    4083             : 
    4084             :     /* Must have gotten a database name, or have a default (the username) */
    4085         142 :     if (dbname == NULL)
    4086             :     {
    4087           0 :         dbname = username;
    4088           0 :         if (dbname == NULL)
    4089           0 :             ereport(FATAL,
    4090             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4091             :                      errmsg("%s: no database nor user name specified",
    4092             :                             progname)));
    4093             :     }
    4094             : 
    4095             :     /* Acquire configuration parameters */
    4096         142 :     if (!SelectConfigFiles(userDoption, progname))
    4097           0 :         proc_exit(1);
    4098             : 
    4099             :     /*
    4100             :      * Validate we have been given a reasonable-looking DataDir and change
    4101             :      * into it.
    4102             :      */
    4103         142 :     checkDataDir();
    4104         142 :     ChangeToDataDir();
    4105             : 
    4106             :     /*
    4107             :      * Create lockfile for data directory.
    4108             :      */
    4109         142 :     CreateDataDirLockFile(false);
    4110             : 
    4111             :     /* read control file (error checking and contains config ) */
    4112         140 :     LocalProcessControlFile(false);
    4113             : 
    4114             :     /*
    4115             :      * process any libraries that should be preloaded at postmaster start
    4116             :      */
    4117         140 :     process_shared_preload_libraries();
    4118             : 
    4119             :     /* Initialize MaxBackends */
    4120         140 :     InitializeMaxBackends();
    4121             : 
    4122             :     /*
    4123             :      * We don't need postmaster child slots in single-user mode, but
    4124             :      * initialize them anyway to avoid having special handling.
    4125             :      */
    4126         140 :     InitPostmasterChildSlots();
    4127             : 
    4128             :     /* Initialize size of fast-path lock cache. */
    4129         140 :     InitializeFastPathLocks();
    4130             : 
    4131             :     /*
    4132             :      * Give preloaded libraries a chance to request additional shared memory.
    4133             :      */
    4134         140 :     process_shmem_requests();
    4135             : 
    4136             :     /*
    4137             :      * Now that loadable modules have had their chance to request additional
    4138             :      * shared memory, determine the value of any runtime-computed GUCs that
    4139             :      * depend on the amount of shared memory required.
    4140             :      */
    4141         140 :     InitializeShmemGUCs();
    4142             : 
    4143             :     /*
    4144             :      * Now that modules have been loaded, we can process any custom resource
    4145             :      * managers specified in the wal_consistency_checking GUC.
    4146             :      */
    4147         140 :     InitializeWalConsistencyChecking();
    4148             : 
    4149             :     /*
    4150             :      * Create shared memory etc.  (Nothing's really "shared" in single-user
    4151             :      * mode, but we must have these data structures anyway.)
    4152             :      */
    4153         140 :     CreateSharedMemoryAndSemaphores();
    4154             : 
    4155             :     /*
    4156             :      * Estimate number of openable files.  This must happen after setting up
    4157             :      * semaphores, because on some platforms semaphores count as open files.
    4158             :      */
    4159         138 :     set_max_safe_fds();
    4160             : 
    4161             :     /*
    4162             :      * Remember stand-alone backend startup time,roughly at the same point
    4163             :      * during startup that postmaster does so.
    4164             :      */
    4165         138 :     PgStartTime = GetCurrentTimestamp();
    4166             : 
    4167             :     /*
    4168             :      * Create a per-backend PGPROC struct in shared memory. We must do this
    4169             :      * before we can use LWLocks.
    4170             :      */
    4171         138 :     InitProcess();
    4172             : 
    4173             :     /*
    4174             :      * Now that sufficient infrastructure has been initialized, PostgresMain()
    4175             :      * can do the rest.
    4176             :      */
    4177         138 :     PostgresMain(dbname, username);
    4178             : }
    4179             : 
    4180             : 
    4181             : /* ----------------------------------------------------------------
    4182             :  * PostgresMain
    4183             :  *     postgres main loop -- all backends, interactive or otherwise loop here
    4184             :  *
    4185             :  * dbname is the name of the database to connect to, username is the
    4186             :  * PostgreSQL user name to be used for the session.
    4187             :  *
    4188             :  * NB: Single user mode specific setup should go to PostgresSingleUserMain()
    4189             :  * if reasonably possible.
    4190             :  * ----------------------------------------------------------------
    4191             :  */
    4192             : void
    4193       26202 : PostgresMain(const char *dbname, const char *username)
    4194             : {
    4195             :     sigjmp_buf  local_sigjmp_buf;
    4196             : 
    4197             :     /* these must be volatile to ensure state is preserved across longjmp: */
    4198       26202 :     volatile bool send_ready_for_query = true;
    4199       26202 :     volatile bool idle_in_transaction_timeout_enabled = false;
    4200       26202 :     volatile bool idle_session_timeout_enabled = false;
    4201             : 
    4202             :     Assert(dbname != NULL);
    4203             :     Assert(username != NULL);
    4204             : 
    4205             :     Assert(GetProcessingMode() == InitProcessing);
    4206             : 
    4207             :     /*
    4208             :      * Set up signal handlers.  (InitPostmasterChild or InitStandaloneProcess
    4209             :      * has already set up BlockSig and made that the active signal mask.)
    4210             :      *
    4211             :      * Note that postmaster blocked all signals before forking child process,
    4212             :      * so there is no race condition whereby we might receive a signal before
    4213             :      * we have set up the handler.
    4214             :      *
    4215             :      * Also note: it's best not to use any signals that are SIG_IGNored in the
    4216             :      * postmaster.  If such a signal arrives before we are able to change the
    4217             :      * handler to non-SIG_IGN, it'll get dropped.  Instead, make a dummy
    4218             :      * handler in the postmaster to reserve the signal. (Of course, this isn't
    4219             :      * an issue for signals that are locally generated, such as SIGALRM and
    4220             :      * SIGPIPE.)
    4221             :      */
    4222       26202 :     if (am_walsender)
    4223        2312 :         WalSndSignals();
    4224             :     else
    4225             :     {
    4226       23890 :         pqsignal(SIGHUP, SignalHandlerForConfigReload);
    4227       23890 :         pqsignal(SIGINT, StatementCancelHandler);   /* cancel current query */
    4228       23890 :         pqsignal(SIGTERM, die); /* cancel current query and exit */
    4229             : 
    4230             :         /*
    4231             :          * In a postmaster child backend, replace SignalHandlerForCrashExit
    4232             :          * with quickdie, so we can tell the client we're dying.
    4233             :          *
    4234             :          * In a standalone backend, SIGQUIT can be generated from the keyboard
    4235             :          * easily, while SIGTERM cannot, so we make both signals do die()
    4236             :          * rather than quickdie().
    4237             :          */
    4238       23890 :         if (IsUnderPostmaster)
    4239       23752 :             pqsignal(SIGQUIT, quickdie);    /* hard crash time */
    4240             :         else
    4241         138 :             pqsignal(SIGQUIT, die); /* cancel current query and exit */
    4242       23890 :         InitializeTimeouts();   /* establishes SIGALRM handler */
    4243             : 
    4244             :         /*
    4245             :          * Ignore failure to write to frontend. Note: if frontend closes
    4246             :          * connection, we will notice it and exit cleanly when control next
    4247             :          * returns to outer loop.  This seems safer than forcing exit in the
    4248             :          * midst of output during who-knows-what operation...
    4249             :          */
    4250       23890 :         pqsignal(SIGPIPE, SIG_IGN);
    4251       23890 :         pqsignal(SIGUSR1, procsignal_sigusr1_handler);
    4252       23890 :         pqsignal(SIGUSR2, SIG_IGN);
    4253       23890 :         pqsignal(SIGFPE, FloatExceptionHandler);
    4254             : 
    4255             :         /*
    4256             :          * Reset some signals that are accepted by postmaster but not by
    4257             :          * backend
    4258             :          */
    4259       23890 :         pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
    4260             :                                      * platforms */
    4261             :     }
    4262             : 
    4263             :     /* Early initialization */
    4264       26202 :     BaseInit();
    4265             : 
    4266             :     /* We need to allow SIGINT, etc during the initial transaction */
    4267       26202 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
    4268             : 
    4269             :     /*
    4270             :      * Generate a random cancel key, if this is a backend serving a
    4271             :      * connection. InitPostgres() will advertise it in shared memory.
    4272             :      */
    4273             :     Assert(MyCancelKeyLength == 0);
    4274       26202 :     if (whereToSendOutput == DestRemote)
    4275             :     {
    4276             :         int         len;
    4277             : 
    4278       26064 :         len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
    4279       52128 :             ? MAX_CANCEL_KEY_LENGTH : 4;
    4280       26064 :         if (!pg_strong_random(&MyCancelKey, len))
    4281             :         {
    4282           0 :             ereport(ERROR,
    4283             :                     (errcode(ERRCODE_INTERNAL_ERROR),
    4284             :                      errmsg("could not generate random cancel key")));
    4285             :         }
    4286       26064 :         MyCancelKeyLength = len;
    4287             :     }
    4288             : 
    4289             :     /*
    4290             :      * General initialization.
    4291             :      *
    4292             :      * NOTE: if you are tempted to add code in this vicinity, consider putting
    4293             :      * it inside InitPostgres() instead.  In particular, anything that
    4294             :      * involves database access should be there, not here.
    4295             :      *
    4296             :      * Honor session_preload_libraries if not dealing with a WAL sender.
    4297             :      */
    4298       26202 :     InitPostgres(dbname, InvalidOid,    /* database to connect to */
    4299             :                  username, InvalidOid,  /* role to connect as */
    4300       26202 :                  (!am_walsender) ? INIT_PG_LOAD_SESSION_LIBS : 0,
    4301             :                  NULL);         /* no out_dbname */
    4302             : 
    4303             :     /*
    4304             :      * If the PostmasterContext is still around, recycle the space; we don't
    4305             :      * need it anymore after InitPostgres completes.
    4306             :      */
    4307       26028 :     if (PostmasterContext)
    4308             :     {
    4309       25894 :         MemoryContextDelete(PostmasterContext);
    4310       25894 :         PostmasterContext = NULL;
    4311             :     }
    4312             : 
    4313       26028 :     SetProcessingMode(NormalProcessing);
    4314             : 
    4315             :     /*
    4316             :      * Now all GUC states are fully set up.  Report them to client if
    4317             :      * appropriate.
    4318             :      */
    4319       26028 :     BeginReportingGUCOptions();
    4320             : 
    4321             :     /*
    4322             :      * Also set up handler to log session end; we have to wait till now to be
    4323             :      * sure Log_disconnections has its final value.
    4324             :      */
    4325       26028 :     if (IsUnderPostmaster && Log_disconnections)
    4326          82 :         on_proc_exit(log_disconnections, 0);
    4327             : 
    4328       26028 :     pgstat_report_connect(MyDatabaseId);
    4329             : 
    4330             :     /* Perform initialization specific to a WAL sender process. */
    4331       26028 :     if (am_walsender)
    4332        2312 :         InitWalSender();
    4333             : 
    4334             :     /*
    4335             :      * Send this backend's cancellation info to the frontend.
    4336             :      */
    4337       26028 :     if (whereToSendOutput == DestRemote)
    4338             :     {
    4339             :         StringInfoData buf;
    4340             : 
    4341             :         Assert(MyCancelKeyLength > 0);
    4342       25894 :         pq_beginmessage(&buf, PqMsg_BackendKeyData);
    4343       25894 :         pq_sendint32(&buf, (int32) MyProcPid);
    4344             : 
    4345       25894 :         pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength);
    4346       25894 :         pq_endmessage(&buf);
    4347             :         /* Need not flush since ReadyForQuery will do it. */
    4348             :     }
    4349             : 
    4350             :     /* Welcome banner for standalone case */
    4351       26028 :     if (whereToSendOutput == DestDebug)
    4352         134 :         printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
    4353             : 
    4354             :     /*
    4355             :      * Create the memory context we will use in the main loop.
    4356             :      *
    4357             :      * MessageContext is reset once per iteration of the main loop, ie, upon
    4358             :      * completion of processing of each command message from the client.
    4359             :      */
    4360       26028 :     MessageContext = AllocSetContextCreate(TopMemoryContext,
    4361             :                                            "MessageContext",
    4362             :                                            ALLOCSET_DEFAULT_SIZES);
    4363             : 
    4364             :     /*
    4365             :      * Create memory context and buffer used for RowDescription messages. As
    4366             :      * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
    4367             :      * frequently executed for ever single statement, we don't want to
    4368             :      * allocate a separate buffer every time.
    4369             :      */
    4370       26028 :     row_description_context = AllocSetContextCreate(TopMemoryContext,
    4371             :                                                     "RowDescriptionContext",
    4372             :                                                     ALLOCSET_DEFAULT_SIZES);
    4373       26028 :     MemoryContextSwitchTo(row_description_context);
    4374       26028 :     initStringInfo(&row_description_buf);
    4375       26028 :     MemoryContextSwitchTo(TopMemoryContext);
    4376             : 
    4377             :     /* Fire any defined login event triggers, if appropriate */
    4378       26028 :     EventTriggerOnLogin();
    4379             : 
    4380             :     /*
    4381             :      * POSTGRES main processing loop begins here
    4382             :      *
    4383             :      * If an exception is encountered, processing resumes here so we abort the
    4384             :      * current transaction and start a new one.
    4385             :      *
    4386             :      * You might wonder why this isn't coded as an infinite loop around a
    4387             :      * PG_TRY construct.  The reason is that this is the bottom of the
    4388             :      * exception stack, and so with PG_TRY there would be no exception handler
    4389             :      * in force at all during the CATCH part.  By leaving the outermost setjmp
    4390             :      * always active, we have at least some chance of recovering from an error
    4391             :      * during error recovery.  (If we get into an infinite loop thereby, it
    4392             :      * will soon be stopped by overflow of elog.c's internal state stack.)
    4393             :      *
    4394             :      * Note that we use sigsetjmp(..., 1), so that this function's signal mask
    4395             :      * (to wit, UnBlockSig) will be restored when longjmp'ing to here.  This
    4396             :      * is essential in case we longjmp'd out of a signal handler on a platform
    4397             :      * where that leaves the signal blocked.  It's not redundant with the
    4398             :      * unblock in AbortTransaction() because the latter is only called if we
    4399             :      * were inside a transaction.
    4400             :      */
    4401             : 
    4402       26028 :     if (sigsetjmp(local_sigjmp_buf, 1) != 0)
    4403             :     {
    4404             :         /*
    4405             :          * NOTE: if you are tempted to add more code in this if-block,
    4406             :          * consider the high probability that it should be in
    4407             :          * AbortTransaction() instead.  The only stuff done directly here
    4408             :          * should be stuff that is guaranteed to apply *only* for outer-level
    4409             :          * error recovery, such as adjusting the FE/BE protocol status.
    4410             :          */
    4411             : 
    4412             :         /* Since not using PG_TRY, must reset error stack by hand */
    4413       43950 :         error_context_stack = NULL;
    4414             : 
    4415             :         /* Prevent interrupts while cleaning up */
    4416       43950 :         HOLD_INTERRUPTS();
    4417             : 
    4418             :         /*
    4419             :          * Forget any pending QueryCancel request, since we're returning to
    4420             :          * the idle loop anyway, and cancel any active timeout requests.  (In
    4421             :          * future we might want to allow some timeout requests to survive, but
    4422             :          * at minimum it'd be necessary to do reschedule_timeouts(), in case
    4423             :          * we got here because of a query cancel interrupting the SIGALRM
    4424             :          * interrupt handler.)  Note in particular that we must clear the
    4425             :          * statement and lock timeout indicators, to prevent any future plain
    4426             :          * query cancels from being misreported as timeouts in case we're
    4427             :          * forgetting a timeout cancel.
    4428             :          */
    4429       43950 :         disable_all_timeouts(false);    /* do first to avoid race condition */
    4430       43950 :         QueryCancelPending = false;
    4431       43950 :         idle_in_transaction_timeout_enabled = false;
    4432       43950 :         idle_session_timeout_enabled = false;
    4433             : 
    4434             :         /* Not reading from the client anymore. */
    4435       43950 :         DoingCommandRead = false;
    4436             : 
    4437             :         /* Make sure libpq is in a good state */
    4438       43950 :         pq_comm_reset();
    4439             : 
    4440             :         /* Report the error to the client and/or server log */
    4441       43950 :         EmitErrorReport();
    4442             : 
    4443             :         /*
    4444             :          * If Valgrind noticed something during the erroneous query, print the
    4445             :          * query string, assuming we have one.
    4446             :          */
    4447             :         valgrind_report_error_query(debug_query_string);
    4448             : 
    4449             :         /*
    4450             :          * Make sure debug_query_string gets reset before we possibly clobber
    4451             :          * the storage it points at.
    4452             :          */
    4453       43950 :         debug_query_string = NULL;
    4454             : 
    4455             :         /*
    4456             :          * Abort the current transaction in order to recover.
    4457             :          */
    4458       43950 :         AbortCurrentTransaction();
    4459             : 
    4460       43950 :         if (am_walsender)
    4461          96 :             WalSndErrorCleanup();
    4462             : 
    4463       43950 :         PortalErrorCleanup();
    4464             : 
    4465             :         /*
    4466             :          * We can't release replication slots inside AbortTransaction() as we
    4467             :          * need to be able to start and abort transactions while having a slot
    4468             :          * acquired. But we never need to hold them across top level errors,
    4469             :          * so releasing here is fine. There also is a before_shmem_exit()
    4470             :          * callback ensuring correct cleanup on FATAL errors.
    4471             :          */
    4472       43950 :         if (MyReplicationSlot != NULL)
    4473          28 :             ReplicationSlotRelease();
    4474             : 
    4475             :         /* We also want to cleanup temporary slots on error. */
    4476       43950 :         ReplicationSlotCleanup(false);
    4477             : 
    4478       43950 :         jit_reset_after_error();
    4479             : 
    4480             :         /*
    4481             :          * Now return to normal top-level context and clear ErrorContext for
    4482             :          * next time.
    4483             :          */
    4484       43950 :         MemoryContextSwitchTo(MessageContext);
    4485       43950 :         FlushErrorState();
    4486             : 
    4487             :         /*
    4488             :          * If we were handling an extended-query-protocol message, initiate
    4489             :          * skip till next Sync.  This also causes us not to issue
    4490             :          * ReadyForQuery (until we get Sync).
    4491             :          */
    4492       43950 :         if (doing_extended_query_message)
    4493         214 :             ignore_till_sync = true;
    4494             : 
    4495             :         /* We don't have a transaction command open anymore */
    4496       43950 :         xact_started = false;
    4497             : 
    4498             :         /*
    4499             :          * If an error occurred while we were reading a message from the
    4500             :          * client, we have potentially lost track of where the previous
    4501             :          * message ends and the next one begins.  Even though we have
    4502             :          * otherwise recovered from the error, we cannot safely read any more
    4503             :          * messages from the client, so there isn't much we can do with the
    4504             :          * connection anymore.
    4505             :          */
    4506       43950 :         if (pq_is_reading_msg())
    4507           4 :             ereport(FATAL,
    4508             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    4509             :                      errmsg("terminating connection because protocol synchronization was lost")));
    4510             : 
    4511             :         /* Now we can allow interrupts again */
    4512       43946 :         RESUME_INTERRUPTS();
    4513             :     }
    4514             : 
    4515             :     /* We can now handle ereport(ERROR) */
    4516       69974 :     PG_exception_stack = &local_sigjmp_buf;
    4517             : 
    4518       69974 :     if (!ignore_till_sync)
    4519       69764 :         send_ready_for_query = true;    /* initially, or after error */
    4520             : 
    4521             :     /*
    4522             :      * Non-error queries loop here.
    4523             :      */
    4524             : 
    4525             :     for (;;)
    4526      723428 :     {
    4527             :         int         firstchar;
    4528             :         StringInfoData input_message;
    4529             : 
    4530             :         /*
    4531             :          * At top of loop, reset extended-query-message flag, so that any
    4532             :          * errors encountered in "idle" state don't provoke skip.
    4533             :          */
    4534      793402 :         doing_extended_query_message = false;
    4535             : 
    4536             :         /*
    4537             :          * For valgrind reporting purposes, the "current query" begins here.
    4538             :          */
    4539             : #ifdef USE_VALGRIND
    4540             :         old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
    4541             : #endif
    4542             : 
    4543             :         /*
    4544             :          * Release storage left over from prior query cycle, and create a new
    4545             :          * query input buffer in the cleared MessageContext.
    4546             :          */
    4547      793402 :         MemoryContextSwitchTo(MessageContext);
    4548      793402 :         MemoryContextReset(MessageContext);
    4549             : 
    4550      793402 :         initStringInfo(&input_message);
    4551             : 
    4552             :         /*
    4553             :          * Also consider releasing our catalog snapshot if any, so that it's
    4554             :          * not preventing advance of global xmin while we wait for the client.
    4555             :          */
    4556      793402 :         InvalidateCatalogSnapshotConditionally();
    4557             : 
    4558             :         /*
    4559             :          * (1) If we've reached idle state, tell the frontend we're ready for
    4560             :          * a new query.
    4561             :          *
    4562             :          * Note: this includes fflush()'ing the last of the prior output.
    4563             :          *
    4564             :          * This is also a good time to flush out collected statistics to the
    4565             :          * cumulative stats system, and to update the PS stats display.  We
    4566             :          * avoid doing those every time through the message loop because it'd
    4567             :          * slow down processing of batched messages, and because we don't want
    4568             :          * to report uncommitted updates (that confuses autovacuum).  The
    4569             :          * notification processor wants a call too, if we are not in a
    4570             :          * transaction block.
    4571             :          *
    4572             :          * Also, if an idle timeout is enabled, start the timer for that.
    4573             :          */
    4574      793402 :         if (send_ready_for_query)
    4575             :         {
    4576      713788 :             if (IsAbortedTransactionBlockState())
    4577             :             {
    4578        1840 :                 set_ps_display("idle in transaction (aborted)");
    4579        1840 :                 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
    4580             : 
    4581             :                 /* Start the idle-in-transaction timer */
    4582        1840 :                 if (IdleInTransactionSessionTimeout > 0
    4583           0 :                     && (IdleInTransactionSessionTimeout < TransactionTimeout || TransactionTimeout == 0))
    4584             :                 {
    4585           0 :                     idle_in_transaction_timeout_enabled = true;
    4586           0 :                     enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
    4587             :                                          IdleInTransactionSessionTimeout);
    4588             :                 }
    4589             :             }
    4590      711948 :             else if (IsTransactionOrTransactionBlock())
    4591             :             {
    4592      151462 :                 set_ps_display("idle in transaction");
    4593      151462 :                 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
    4594             : 
    4595             :                 /* Start the idle-in-transaction timer */
    4596      151462 :                 if (IdleInTransactionSessionTimeout > 0
    4597           2 :                     && (IdleInTransactionSessionTimeout < TransactionTimeout || TransactionTimeout == 0))
    4598             :                 {
    4599           2 :                     idle_in_transaction_timeout_enabled = true;
    4600           2 :                     enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
    4601             :                                          IdleInTransactionSessionTimeout);
    4602             :                 }
    4603             :             }
    4604             :             else
    4605             :             {
    4606             :                 long        stats_timeout;
    4607             : 
    4608             :                 /*
    4609             :                  * Process incoming notifies (including self-notifies), if
    4610             :                  * any, and send relevant messages to the client.  Doing it
    4611             :                  * here helps ensure stable behavior in tests: if any notifies
    4612             :                  * were received during the just-finished transaction, they'll
    4613             :                  * be seen by the client before ReadyForQuery is.
    4614             :                  */
    4615      560486 :                 if (notifyInterruptPending)
    4616          58 :                     ProcessNotifyInterrupt(false);
    4617             : 
    4618             :                 /*
    4619             :                  * Check if we need to report stats. If pgstat_report_stat()
    4620             :                  * decides it's too soon to flush out pending stats / lock
    4621             :                  * contention prevented reporting, it'll tell us when we
    4622             :                  * should try to report stats again (so that stats updates
    4623             :                  * aren't unduly delayed if the connection goes idle for a
    4624             :                  * long time). We only enable the timeout if we don't already
    4625             :                  * have a timeout in progress, because we don't disable the
    4626             :                  * timeout below. enable_timeout_after() needs to determine
    4627             :                  * the current timestamp, which can have a negative
    4628             :                  * performance impact. That's OK because pgstat_report_stat()
    4629             :                  * won't have us wake up sooner than a prior call.
    4630             :                  */
    4631      560486 :                 stats_timeout = pgstat_report_stat(false);
    4632      560486 :                 if (stats_timeout > 0)
    4633             :                 {
    4634      525882 :                     if (!get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT))
    4635       69858 :                         enable_timeout_after(IDLE_STATS_UPDATE_TIMEOUT,
    4636             :                                              stats_timeout);
    4637             :                 }
    4638             :                 else
    4639             :                 {
    4640             :                     /* all stats flushed, no need for the timeout */
    4641       34604 :                     if (get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT))
    4642        2422 :                         disable_timeout(IDLE_STATS_UPDATE_TIMEOUT, false);
    4643             :                 }
    4644             : 
    4645      560486 :                 set_ps_display("idle");
    4646      560486 :                 pgstat_report_activity(STATE_IDLE, NULL);
    4647             : 
    4648             :                 /* Start the idle-session timer */
    4649      560486 :                 if (IdleSessionTimeout > 0)
    4650             :                 {
    4651           0 :                     idle_session_timeout_enabled = true;
    4652           0 :                     enable_timeout_after(IDLE_SESSION_TIMEOUT,
    4653             :                                          IdleSessionTimeout);
    4654             :                 }
    4655             :             }
    4656             : 
    4657             :             /* Report any recently-changed GUC options */
    4658      713788 :             ReportChangedGUCOptions();
    4659             : 
    4660             :             /*
    4661             :              * The first time this backend is ready for query, log the
    4662             :              * durations of the different components of connection
    4663             :              * establishment and setup.
    4664             :              */
    4665      713788 :             if (conn_timing.ready_for_use == TIMESTAMP_MINUS_INFINITY &&
    4666      713436 :                 (log_connections & LOG_CONNECTION_SETUP_DURATIONS) &&
    4667         322 :                 IsExternalConnectionBackend(MyBackendType))
    4668             :             {
    4669             :                 uint64      total_duration,
    4670             :                             fork_duration,
    4671             :                             auth_duration;
    4672             : 
    4673         322 :                 conn_timing.ready_for_use = GetCurrentTimestamp();
    4674             : 
    4675             :                 total_duration =
    4676         322 :                     TimestampDifferenceMicroseconds(conn_timing.socket_create,
    4677             :                                                     conn_timing.ready_for_use);
    4678             :                 fork_duration =
    4679         322 :                     TimestampDifferenceMicroseconds(conn_timing.fork_start,
    4680             :                                                     conn_timing.fork_end);
    4681             :                 auth_duration =
    4682         322 :                     TimestampDifferenceMicroseconds(conn_timing.auth_start,
    4683             :                                                     conn_timing.auth_end);
    4684             : 
    4685         322 :                 ereport(LOG,
    4686             :                         errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
    4687             :                                (double) total_duration / NS_PER_US,
    4688             :                                (double) fork_duration / NS_PER_US,
    4689             :                                (double) auth_duration / NS_PER_US));
    4690             :             }
    4691             : 
    4692      713788 :             ReadyForQuery(whereToSendOutput);
    4693      713788 :             send_ready_for_query = false;
    4694             :         }
    4695             : 
    4696             :         /*
    4697             :          * (2) Allow asynchronous signals to be executed immediately if they
    4698             :          * come in while we are waiting for client input. (This must be
    4699             :          * conditional since we don't want, say, reads on behalf of COPY FROM
    4700             :          * STDIN doing the same thing.)
    4701             :          */
    4702      793402 :         DoingCommandRead = true;
    4703             : 
    4704             :         /*
    4705             :          * (3) read a command (loop blocks here)
    4706             :          */
    4707      793402 :         firstchar = ReadCommand(&input_message);
    4708             : 
    4709             :         /*
    4710             :          * (4) turn off the idle-in-transaction and idle-session timeouts if
    4711             :          * active.  We do this before step (5) so that any last-moment timeout
    4712             :          * is certain to be detected in step (5).
    4713             :          *
    4714             :          * At most one of these timeouts will be active, so there's no need to
    4715             :          * worry about combining the timeout.c calls into one.
    4716             :          */
    4717      793320 :         if (idle_in_transaction_timeout_enabled)
    4718             :         {
    4719           0 :             disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
    4720           0 :             idle_in_transaction_timeout_enabled = false;
    4721             :         }
    4722      793320 :         if (idle_session_timeout_enabled)
    4723             :         {
    4724           0 :             disable_timeout(IDLE_SESSION_TIMEOUT, false);
    4725           0 :             idle_session_timeout_enabled = false;
    4726             :         }
    4727             : 
    4728             :         /*
    4729             :          * (5) disable async signal conditions again.
    4730             :          *
    4731             :          * Query cancel is supposed to be a no-op when there is no query in
    4732             :          * progress, so if a query cancel arrived while we were idle, just
    4733             :          * reset QueryCancelPending. ProcessInterrupts() has that effect when
    4734             :          * it's called when DoingCommandRead is set, so check for interrupts
    4735             :          * before resetting DoingCommandRead.
    4736             :          */
    4737      793320 :         CHECK_FOR_INTERRUPTS();
    4738      793318 :         DoingCommandRead = false;
    4739             : 
    4740             :         /*
    4741             :          * (6) check for any other interesting events that happened while we
    4742             :          * slept.
    4743             :          */
    4744      793318 :         if (ConfigReloadPending)
    4745             :         {
    4746          56 :             ConfigReloadPending = false;
    4747          56 :             ProcessConfigFile(PGC_SIGHUP);
    4748             :         }
    4749             : 
    4750             :         /*
    4751             :          * (7) process the command.  But ignore it if we're skipping till
    4752             :          * Sync.
    4753             :          */
    4754      793318 :         if (ignore_till_sync && firstchar != EOF)
    4755        1772 :             continue;
    4756             : 
    4757      791546 :         switch (firstchar)
    4758             :         {
    4759      662884 :             case PqMsg_Query:
    4760             :                 {
    4761             :                     const char *query_string;
    4762             : 
    4763             :                     /* Set statement_timestamp() */
    4764      662884 :                     SetCurrentStatementStartTimestamp();
    4765             : 
    4766      662884 :                     query_string = pq_getmsgstring(&input_message);
    4767      662884 :                     pq_getmsgend(&input_message);
    4768             : 
    4769      662884 :                     if (am_walsender)
    4770             :                     {
    4771       10508 :                         if (!exec_replication_command(query_string))
    4772        4688 :                             exec_simple_query(query_string);
    4773             :                     }
    4774             :                     else
    4775      652376 :                         exec_simple_query(query_string);
    4776             : 
    4777             :                     valgrind_report_error_query(query_string);
    4778             : 
    4779      618482 :                     send_ready_for_query = true;
    4780             :                 }
    4781      618482 :                 break;
    4782             : 
    4783       11082 :             case PqMsg_Parse:
    4784             :                 {
    4785             :                     const char *stmt_name;
    4786             :                     const char *query_string;
    4787             :                     int         numParams;
    4788       11082 :                     Oid        *paramTypes = NULL;
    4789             : 
    4790       11082 :                     forbidden_in_wal_sender(firstchar);
    4791             : 
    4792             :                     /* Set statement_timestamp() */
    4793       11082 :                     SetCurrentStatementStartTimestamp();
    4794             : 
    4795       11082 :                     stmt_name = pq_getmsgstring(&input_message);
    4796       11082 :                     query_string = pq_getmsgstring(&input_message);
    4797       11082 :                     numParams = pq_getmsgint(&input_message, 2);
    4798       11082 :                     if (numParams > 0)
    4799             :                     {
    4800          92 :                         paramTypes = palloc_array(Oid, numParams);
    4801         236 :                         for (int i = 0; i < numParams; i++)
    4802         144 :                             paramTypes[i] = pq_getmsgint(&input_message, 4);
    4803             :                     }
    4804       11082 :                     pq_getmsgend(&input_message);
    4805             : 
    4806       11082 :                     exec_parse_message(query_string, stmt_name,
    4807             :                                        paramTypes, numParams);
    4808             : 
    4809             :                     valgrind_report_error_query(query_string);
    4810             :                 }
    4811       11036 :                 break;
    4812             : 
    4813       22142 :             case PqMsg_Bind:
    4814       22142 :                 forbidden_in_wal_sender(firstchar);
    4815             : 
    4816             :                 /* Set statement_timestamp() */
    4817       22142 :                 SetCurrentStatementStartTimestamp();
    4818             : 
    4819             :                 /*
    4820             :                  * this message is complex enough that it seems best to put
    4821             :                  * the field extraction out-of-line
    4822             :                  */
    4823       22142 :                 exec_bind_message(&input_message);
    4824             : 
    4825             :                 /* exec_bind_message does valgrind_report_error_query */
    4826       22076 :                 break;
    4827             : 
    4828       22076 :             case PqMsg_Execute:
    4829             :                 {
    4830             :                     const char *portal_name;
    4831             :                     int         max_rows;
    4832             : 
    4833       22076 :                     forbidden_in_wal_sender(firstchar);
    4834             : 
    4835             :                     /* Set statement_timestamp() */
    4836       22076 :                     SetCurrentStatementStartTimestamp();
    4837             : 
    4838       22076 :                     portal_name = pq_getmsgstring(&input_message);
    4839       22076 :                     max_rows = pq_getmsgint(&input_message, 4);
    4840       22076 :                     pq_getmsgend(&input_message);
    4841             : 
    4842       22076 :                     exec_execute_message(portal_name, max_rows);
    4843             : 
    4844             :                     /* exec_execute_message does valgrind_report_error_query */
    4845             :                 }
    4846       21978 :                 break;
    4847             : 
    4848        2168 :             case PqMsg_FunctionCall:
    4849        2168 :                 forbidden_in_wal_sender(firstchar);
    4850             : 
    4851             :                 /* Set statement_timestamp() */
    4852        2168 :                 SetCurrentStatementStartTimestamp();
    4853             : 
    4854             :                 /* Report query to various monitoring facilities. */
    4855        2168 :                 pgstat_report_activity(STATE_FASTPATH, NULL);
    4856        2168 :                 set_ps_display("<FASTPATH>");
    4857             : 
    4858             :                 /* start an xact for this function invocation */
    4859        2168 :                 start_xact_command();
    4860             : 
    4861             :                 /*
    4862             :                  * Note: we may at this point be inside an aborted
    4863             :                  * transaction.  We can't throw error for that until we've
    4864             :                  * finished reading the function-call message, so
    4865             :                  * HandleFunctionRequest() must check for it after doing so.
    4866             :                  * Be careful not to do anything that assumes we're inside a
    4867             :                  * valid transaction here.
    4868             :                  */
    4869             : 
    4870             :                 /* switch back to message context */
    4871        2168 :                 MemoryContextSwitchTo(MessageContext);
    4872             : 
    4873        2168 :                 HandleFunctionRequest(&input_message);
    4874             : 
    4875             :                 /* commit the function-invocation transaction */
    4876        2168 :                 finish_xact_command();
    4877             : 
    4878             :                 valgrind_report_error_query("fastpath function call");
    4879             : 
    4880        2168 :                 send_ready_for_query = true;
    4881        2168 :                 break;
    4882             : 
    4883          34 :             case PqMsg_Close:
    4884             :                 {
    4885             :                     int         close_type;
    4886             :                     const char *close_target;
    4887             : 
    4888          34 :                     forbidden_in_wal_sender(firstchar);
    4889             : 
    4890          34 :                     close_type = pq_getmsgbyte(&input_message);
    4891          34 :                     close_target = pq_getmsgstring(&input_message);
    4892          34 :                     pq_getmsgend(&input_message);
    4893             : 
    4894             :                     switch (close_type)
    4895             :                     {
    4896          30 :                         case 'S':
    4897          30 :                             if (close_target[0] != '\0')
    4898          24 :                                 DropPreparedStatement(close_target, false);
    4899             :                             else
    4900             :                             {
    4901             :                                 /* special-case the unnamed statement */
    4902           6 :                                 drop_unnamed_stmt();
    4903             :                             }
    4904          30 :                             break;
    4905           4 :                         case 'P':
    4906             :                             {
    4907             :                                 Portal      portal;
    4908             : 
    4909           4 :                                 portal = GetPortalByName(close_target);
    4910           4 :                                 if (PortalIsValid(portal))
    4911           2 :                                     PortalDrop(portal, false);
    4912             :                             }
    4913           4 :                             break;
    4914           0 :                         default:
    4915           0 :                             ereport(ERROR,
    4916             :                                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    4917             :                                      errmsg("invalid CLOSE message subtype %d",
    4918             :                                             close_type)));
    4919             :                             break;
    4920             :                     }
    4921             : 
    4922          34 :                     if (whereToSendOutput == DestRemote)
    4923          34 :                         pq_putemptymessage(PqMsg_CloseComplete);
    4924             : 
    4925             :                     valgrind_report_error_query("CLOSE message");
    4926             :                 }
    4927          34 :                 break;
    4928             : 
    4929       22222 :             case PqMsg_Describe:
    4930             :                 {
    4931             :                     int         describe_type;
    4932             :                     const char *describe_target;
    4933             : 
    4934       22222 :                     forbidden_in_wal_sender(firstchar);
    4935             : 
    4936             :                     /* Set statement_timestamp() (needed for xact) */
    4937       22222 :                     SetCurrentStatementStartTimestamp();
    4938             : 
    4939       22222 :                     describe_type = pq_getmsgbyte(&input_message);
    4940       22222 :                     describe_target = pq_getmsgstring(&input_message);
    4941       22222 :                     pq_getmsgend(&input_message);
    4942             : 
    4943             :                     switch (describe_type)
    4944             :                     {
    4945         142 :                         case 'S':
    4946         142 :                             exec_describe_statement_message(describe_target);
    4947         140 :                             break;
    4948       22080 :                         case 'P':
    4949       22080 :                             exec_describe_portal_message(describe_target);
    4950       22078 :                             break;
    4951           0 :                         default:
    4952           0 :                             ereport(ERROR,
    4953             :                                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    4954             :                                      errmsg("invalid DESCRIBE message subtype %d",
    4955             :                                             describe_type)));
    4956             :                             break;
    4957             :                     }
    4958             : 
    4959             :                     valgrind_report_error_query("DESCRIBE message");
    4960             :                 }
    4961       22218 :                 break;
    4962             : 
    4963          50 :             case PqMsg_Flush:
    4964          50 :                 pq_getmsgend(&input_message);
    4965          50 :                 if (whereToSendOutput == DestRemote)
    4966          50 :                     pq_flush();
    4967          50 :                 break;
    4968             : 
    4969       23374 :             case PqMsg_Sync:
    4970       23374 :                 pq_getmsgend(&input_message);
    4971             : 
    4972             :                 /*
    4973             :                  * If pipelining was used, we may be in an implicit
    4974             :                  * transaction block. Close it before calling
    4975             :                  * finish_xact_command.
    4976             :                  */
    4977       23374 :                 EndImplicitTransactionBlock();
    4978       23374 :                 finish_xact_command();
    4979             :                 valgrind_report_error_query("SYNC message");
    4980       23374 :                 send_ready_for_query = true;
    4981       23374 :                 break;
    4982             : 
    4983             :                 /*
    4984             :                  * PqMsg_Terminate means that the frontend is closing down the
    4985             :                  * socket. EOF means unexpected loss of frontend connection.
    4986             :                  * Either way, perform normal shutdown.
    4987             :                  */
    4988         220 :             case EOF:
    4989             : 
    4990             :                 /* for the cumulative statistics system */
    4991         220 :                 pgStatSessionEndCause = DISCONNECT_CLIENT_EOF;
    4992             : 
    4993             :                 /* FALLTHROUGH */
    4994             : 
    4995       25274 :             case PqMsg_Terminate:
    4996             : 
    4997             :                 /*
    4998             :                  * Reset whereToSendOutput to prevent ereport from attempting
    4999             :                  * to send any more messages to client.
    5000             :                  */
    5001       25274 :                 if (whereToSendOutput == DestRemote)
    5002       25062 :                     whereToSendOutput = DestNone;
    5003             : 
    5004             :                 /*
    5005             :                  * NOTE: if you are tempted to add more code here, DON'T!
    5006             :                  * Whatever you had in mind to do should be set up as an
    5007             :                  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
    5008             :                  * it will fail to be called during other backend-shutdown
    5009             :                  * scenarios.
    5010             :                  */
    5011       25274 :                 proc_exit(0);
    5012             : 
    5013         240 :             case PqMsg_CopyData:
    5014             :             case PqMsg_CopyDone:
    5015             :             case PqMsg_CopyFail:
    5016             : 
    5017             :                 /*
    5018             :                  * Accept but ignore these messages, per protocol spec; we
    5019             :                  * probably got here because a COPY failed, and the frontend
    5020             :                  * is still sending data.
    5021             :                  */
    5022         240 :                 break;
    5023             : 
    5024           0 :             default:
    5025           0 :                 ereport(FATAL,
    5026             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
    5027             :                          errmsg("invalid frontend message type %d",
    5028             :                                 firstchar)));
    5029             :         }
    5030             :     }                           /* end of input-reading loop */
    5031             : }
    5032             : 
    5033             : /*
    5034             :  * Throw an error if we're a WAL sender process.
    5035             :  *
    5036             :  * This is used to forbid anything else than simple query protocol messages
    5037             :  * in a WAL sender process.  'firstchar' specifies what kind of a forbidden
    5038             :  * message was received, and is used to construct the error message.
    5039             :  */
    5040             : static void
    5041       79724 : forbidden_in_wal_sender(char firstchar)
    5042             : {
    5043       79724 :     if (am_walsender)
    5044             :     {
    5045           0 :         if (firstchar == PqMsg_FunctionCall)
    5046           0 :             ereport(ERROR,
    5047             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    5048             :                      errmsg("fastpath function calls not supported in a replication connection")));
    5049             :         else
    5050           0 :             ereport(ERROR,
    5051             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    5052             :                      errmsg("extended query protocol not supported in a replication connection")));
    5053             :     }
    5054       79724 : }
    5055             : 
    5056             : 
    5057             : static struct rusage Save_r;
    5058             : static struct timeval Save_t;
    5059             : 
    5060             : void
    5061           0 : ResetUsage(void)
    5062             : {
    5063           0 :     getrusage(RUSAGE_SELF, &Save_r);
    5064           0 :     gettimeofday(&Save_t, NULL);
    5065           0 : }
    5066             : 
    5067             : void
    5068           0 : ShowUsage(const char *title)
    5069             : {
    5070             :     StringInfoData str;
    5071             :     struct timeval user,
    5072             :                 sys;
    5073             :     struct timeval elapse_t;
    5074             :     struct rusage r;
    5075             : 
    5076           0 :     getrusage(RUSAGE_SELF, &r);
    5077           0 :     gettimeofday(&elapse_t, NULL);
    5078           0 :     memcpy(&user, &r.ru_utime, sizeof(user));
    5079           0 :     memcpy(&sys, &r.ru_stime, sizeof(sys));
    5080           0 :     if (elapse_t.tv_usec < Save_t.tv_usec)
    5081             :     {
    5082           0 :         elapse_t.tv_sec--;
    5083           0 :         elapse_t.tv_usec += 1000000;
    5084             :     }
    5085           0 :     if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
    5086             :     {
    5087           0 :         r.ru_utime.tv_sec--;
    5088           0 :         r.ru_utime.tv_usec += 1000000;
    5089             :     }
    5090           0 :     if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
    5091             :     {
    5092           0 :         r.ru_stime.tv_sec--;
    5093           0 :         r.ru_stime.tv_usec += 1000000;
    5094             :     }
    5095             : 
    5096             :     /*
    5097             :      * The only stats we don't show here are ixrss, idrss, isrss.  It takes
    5098             :      * some work to interpret them, and most platforms don't fill them in.
    5099             :      */
    5100           0 :     initStringInfo(&str);
    5101             : 
    5102           0 :     appendStringInfoString(&str, "! system usage stats:\n");
    5103           0 :     appendStringInfo(&str,
    5104             :                      "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
    5105           0 :                      (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
    5106           0 :                      (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
    5107           0 :                      (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
    5108           0 :                      (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
    5109           0 :                      (long) (elapse_t.tv_sec - Save_t.tv_sec),
    5110           0 :                      (long) (elapse_t.tv_usec - Save_t.tv_usec));
    5111           0 :     appendStringInfo(&str,
    5112             :                      "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
    5113           0 :                      (long) user.tv_sec,
    5114           0 :                      (long) user.tv_usec,
    5115           0 :                      (long) sys.tv_sec,
    5116           0 :                      (long) sys.tv_usec);
    5117             : #ifndef WIN32
    5118             : 
    5119             :     /*
    5120             :      * The following rusage fields are not defined by POSIX, but they're
    5121             :      * present on all current Unix-like systems so we use them without any
    5122             :      * special checks.  Some of these could be provided in our Windows
    5123             :      * emulation in src/port/win32getrusage.c with more work.
    5124             :      */
    5125           0 :     appendStringInfo(&str,
    5126             :                      "!\t%ld kB max resident size\n",
    5127             : #if defined(__darwin__)
    5128             :     /* in bytes on macOS */
    5129             :                      r.ru_maxrss / 1024
    5130             : #else
    5131             :     /* in kilobytes on most other platforms */
    5132             :                      r.ru_maxrss
    5133             : #endif
    5134             :         );
    5135           0 :     appendStringInfo(&str,
    5136             :                      "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
    5137           0 :                      r.ru_inblock - Save_r.ru_inblock,
    5138             :     /* they only drink coffee at dec */
    5139           0 :                      r.ru_oublock - Save_r.ru_oublock,
    5140             :                      r.ru_inblock, r.ru_oublock);
    5141           0 :     appendStringInfo(&str,
    5142             :                      "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
    5143           0 :                      r.ru_majflt - Save_r.ru_majflt,
    5144           0 :                      r.ru_minflt - Save_r.ru_minflt,
    5145             :                      r.ru_majflt, r.ru_minflt,
    5146           0 :                      r.ru_nswap - Save_r.ru_nswap,
    5147             :                      r.ru_nswap);
    5148           0 :     appendStringInfo(&str,
    5149             :                      "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
    5150           0 :                      r.ru_nsignals - Save_r.ru_nsignals,
    5151             :                      r.ru_nsignals,
    5152           0 :                      r.ru_msgrcv - Save_r.ru_msgrcv,
    5153           0 :                      r.ru_msgsnd - Save_r.ru_msgsnd,
    5154             :                      r.ru_msgrcv, r.ru_msgsnd);
    5155           0 :     appendStringInfo(&str,
    5156             :                      "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
    5157           0 :                      r.ru_nvcsw - Save_r.ru_nvcsw,
    5158           0 :                      r.ru_nivcsw - Save_r.ru_nivcsw,
    5159             :                      r.ru_nvcsw, r.ru_nivcsw);
    5160             : #endif                          /* !WIN32 */
    5161             : 
    5162             :     /* remove trailing newline */
    5163           0 :     if (str.data[str.len - 1] == '\n')
    5164           0 :         str.data[--str.len] = '\0';
    5165             : 
    5166           0 :     ereport(LOG,
    5167             :             (errmsg_internal("%s", title),
    5168             :              errdetail_internal("%s", str.data)));
    5169             : 
    5170           0 :     pfree(str.data);
    5171           0 : }
    5172             : 
    5173             : /*
    5174             :  * on_proc_exit handler to log end of session
    5175             :  */
    5176             : static void
    5177          82 : log_disconnections(int code, Datum arg)
    5178             : {
    5179          82 :     Port       *port = MyProcPort;
    5180             :     long        secs;
    5181             :     int         usecs;
    5182             :     int         msecs;
    5183             :     int         hours,
    5184             :                 minutes,
    5185             :                 seconds;
    5186             : 
    5187          82 :     TimestampDifference(MyStartTimestamp,
    5188             :                         GetCurrentTimestamp(),
    5189             :                         &secs, &usecs);
    5190          82 :     msecs = usecs / 1000;
    5191             : 
    5192          82 :     hours = secs / SECS_PER_HOUR;
    5193          82 :     secs %= SECS_PER_HOUR;
    5194          82 :     minutes = secs / SECS_PER_MINUTE;
    5195          82 :     seconds = secs % SECS_PER_MINUTE;
    5196             : 
    5197          82 :     ereport(LOG,
    5198             :             (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
    5199             :                     "user=%s database=%s host=%s%s%s",
    5200             :                     hours, minutes, seconds, msecs,
    5201             :                     port->user_name, port->database_name, port->remote_host,
    5202             :                     port->remote_port[0] ? " port=" : "", port->remote_port)));
    5203          82 : }
    5204             : 
    5205             : /*
    5206             :  * Start statement timeout timer, if enabled.
    5207             :  *
    5208             :  * If there's already a timeout running, don't restart the timer.  That
    5209             :  * enables compromises between accuracy of timeouts and cost of starting a
    5210             :  * timeout.
    5211             :  */
    5212             : static void
    5213     1437080 : enable_statement_timeout(void)
    5214             : {
    5215             :     /* must be within an xact */
    5216             :     Assert(xact_started);
    5217             : 
    5218     1437080 :     if (StatementTimeout > 0
    5219         104 :         && (StatementTimeout < TransactionTimeout || TransactionTimeout == 0))
    5220             :     {
    5221         104 :         if (!get_timeout_active(STATEMENT_TIMEOUT))
    5222          40 :             enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
    5223             :     }
    5224             :     else
    5225             :     {
    5226     1436976 :         if (get_timeout_active(STATEMENT_TIMEOUT))
    5227           0 :             disable_timeout(STATEMENT_TIMEOUT, false);
    5228             :     }
    5229     1437080 : }
    5230             : 
    5231             : /*
    5232             :  * Disable statement timeout, if active.
    5233             :  */
    5234             : static void
    5235     1319448 : disable_statement_timeout(void)
    5236             : {
    5237     1319448 :     if (get_timeout_active(STATEMENT_TIMEOUT))
    5238          24 :         disable_timeout(STATEMENT_TIMEOUT, false);
    5239     1319448 : }

Generated by: LCOV version 1.16