LCOV - differential code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC DUB DCB
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 77.4 % 1640 1270 1 9 360 3 43 1224 4 5
Current Date: 2026-07-25 19:08:27 +0900 Functions: 91.5 % 59 54 5 6 48
Baseline: lcov-20260725-baseline Branches: 59.3 % 1237 734 13 6 1 483 4 3 39 688
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 97.7 % 44 43 1 43
(30,360] days: 69.1 % 110 76 34 76
(360..) days: 77.5 % 1486 1151 9 326 3 1148
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 4 4 4
(360..) days: 90.7 % 54 49 5 5 44
Branch coverage date bins:
(7,30] days: 75.0 % 52 39 13 39
(30,360] days: 62.5 % 64 40 24 40
(360..) days: 58.4 % 1121 655 6 1 459 4 3 648

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

Generated by: LCOV version 2.0-1