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