LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 77.9 % 1578 1230
Test Date: 2026-03-01 15:14:58 Functions: 91.4 % 58 53
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1