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