PageRenderTime 75ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/src/backend/tcop/postgres.c

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