LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 1145 1526 75.0 %
Date: 2025-02-22 07:14:56 Functions: 51 58 87.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14