Coverage Report

Created: 2026-11-09 07:20

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