PageRenderTime 53ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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 requ…

Large files files are truncated, but you can click here to view the full file