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