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