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