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

/src/backend/tcop/postgres.c

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