LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 78.4 % 1582 1240
Test Date: 2026-04-07 14:16:30 Functions: 91.4 % 58 53
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1