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