LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 60.6 % 1860 1128
Test Date: 2026-01-26 10:56:24 Functions: 74.1 % 58 43
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 36.8 % 1342 494

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

Generated by: LCOV version 2.3.2-1