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: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 78.0 % 1644 1282 1 2 359 10 47 1225 4 7
Current Date: 2026-11-28 16:48:44 +0900 Functions: 91.5 % 59 54 5 9 45
Baseline: lcov-20261128-baseline Branches: 60.0 % 1241 745 14 2 1 479 10 3 44 688
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 4 4 4
(7,30] days: 100.0 % 2 2 2
(30,360] days: 77.7 % 148 115 1 32 43 72
(360..) days: 77.9 % 1490 1161 2 327 10 1151
Function coverage date bins:
(30,360] days: 100.0 % 5 5 1 4
(360..) days: 90.7 % 54 49 5 8 41
Branch coverage date bins:
(1,7] days: 83.3 % 6 5 1 5
(30,360] days: 68.4 % 114 78 13 23 39 39
(360..) days: 59.1 % 1121 662 2 1 456 10 3 649

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

Generated by: LCOV version 2.0-1