LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 79.3 % 1626 1289
Test Date: 2026-07-12 12:15:41 Functions: 91.5 % 59 54
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 60.8 % 1207 734

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

Generated by: LCOV version 2.0-1