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

Generated by: LCOV version 2.0-1