LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1219 1556 78.3 %
Date: 2026-02-07 17:18:43 Functions: 52 57 91.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16