PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
postgres.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include "rusagestub.h"
#include "access/parallel.h"
#include "access/printtup.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/async.h"
#include "commands/prepare.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "nodes/print.h"
#include "optimizer/planner.h"
#include "pgstat.h"
#include "pg_trace.h"
#include "parser/analyze.h"
#include "parser/parser.h"
#include "pg_getopt.h"
#include "postmaster/autovacuum.h"
#include "postmaster/postmaster.h"
#include "replication/slot.h"
#include "replication/walsender.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/sinval.h"
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/snapmgr.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "mb/pg_wchar.h"
Include dependency graph for postgres.c:

Go to the source code of this file.

Functions

static int InteractiveBackend (StringInfo inBuf)
 
static int interactive_getc (void)
 
static int SocketBackend (StringInfo inBuf)
 
static int ReadCommand (StringInfo inBuf)
 
static void forbidden_in_wal_sender (char firstchar)
 
static Listpg_rewrite_query (Query *query)
 
static bool check_log_statement (List *stmt_list)
 
static int errdetail_execute (List *raw_parsetree_list)
 
static int errdetail_params (ParamListInfo params)
 
static int errdetail_abort (void)
 
static int errdetail_recovery_conflict (void)
 
static void start_xact_command (void)
 
static void finish_xact_command (void)
 
static bool IsTransactionExitStmt (Node *parsetree)
 
static bool IsTransactionExitStmtList (List *pstmts)
 
static bool IsTransactionStmtList (List *pstmts)
 
static void drop_unnamed_stmt (void)
 
static void SigHupHandler (SIGNAL_ARGS)
 
static void log_disconnections (int code, Datum arg)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
Listpg_parse_query (const char *query_string)
 
Listpg_analyze_and_rewrite (RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg)
 
PlannedStmtpg_plan_query (Query *querytree, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, int cursorOptions, ParamListInfo boundParams)
 
static void exec_simple_query (const char *query_string)
 
static void exec_parse_message (const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
 
static void exec_bind_message (StringInfo input_message)
 
static void exec_execute_message (const char *portal_name, long max_rows)
 
int check_log_duration (char *msec_str, bool was_logged)
 
static void exec_describe_statement_message (const char *stmt_name)
 
static void exec_describe_portal_message (const char *portal_name)
 
void quickdie (SIGNAL_ARGS)
 
void die (SIGNAL_ARGS)
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS)
 
void RecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessInterrupts (void)
 
pg_stack_base_t set_stack_base (void)
 
void restore_stack_base (pg_stack_base_t base)
 
void check_stack_depth (void)
 
bool stack_is_too_deep (void)
 
bool check_max_stack_depth (int *newval, void **extra, GucSource source)
 
void assign_max_stack_depth (int newval, void *extra)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresMain (int argc, char *argv[], const char *dbname, const char *username)
 
long get_stack_depth_rlimit (void)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 

Variables

const char * debug_query_string
 
CommandDest whereToSendOutput = DestDebug
 
bool Log_disconnections = false
 
int log_statement = LOGSTMT_NONE
 
int max_stack_depth = 100
 
int PostAuthDelay = 0
 
static long max_stack_depth_bytes = 100 * 1024L
 
char * stack_base_ptr = NULL
 
static volatile sig_atomic_t got_SIGHUP = false
 
static bool xact_started = false
 
static bool DoingCommandRead = false
 
static bool doing_extended_query_message = false
 
static bool ignore_till_sync = false
 
static CachedPlanSourceunnamed_stmt_psrc = NULL
 
static const char * userDoption = NULL
 
static bool EchoQuery = false
 
static bool UseSemiNewlineNewline = false
 
static bool RecoveryConflictPending = false
 
static bool RecoveryConflictRetryable = true
 
static ProcSignalReason RecoveryConflictReason
 
static struct rusage Save_r
 
static struct timeval Save_t
 

Function Documentation

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3177 of file postgres.c.

References max_stack_depth_bytes.

3178 {
3179  long newval_bytes = newval * 1024L;
3180 
3181  max_stack_depth_bytes = newval_bytes;
3182 }
static long max_stack_depth_bytes
Definition: postgres.c:107
#define newval
int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2099 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_statement, snprintf(), and TimestampDifference().

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

2100 {
2102  {
2103  long secs;
2104  int usecs;
2105  int msecs;
2106  bool exceeded;
2107 
2110  &secs, &usecs);
2111  msecs = usecs / 1000;
2112 
2113  /*
2114  * This odd-looking test for log_min_duration_statement being exceeded
2115  * is designed to avoid integer overflow with very long durations:
2116  * don't compute secs * 1000 until we've verified it will fit in int.
2117  */
2118  exceeded = (log_min_duration_statement == 0 ||
2120  (secs > log_min_duration_statement / 1000 ||
2121  secs * 1000 + msecs >= log_min_duration_statement)));
2122 
2123  if (exceeded || log_duration)
2124  {
2125  snprintf(msec_str, 32, "%ld.%03d",
2126  secs * 1000 + msecs, usecs % 1000);
2127  if (exceeded && !was_logged)
2128  return 2;
2129  else
2130  return 1;
2131  }
2132  }
2133 
2134  return 0;
2135 }
int log_min_duration_statement
Definition: guc.c:447
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool log_duration
Definition: guc.c:426
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1791
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:715
static bool check_log_statement ( List stmt_list)
static

Definition at line 2062 of file postgres.c.

References GetCommandLogLevel(), lfirst, log_statement, LOGSTMT_ALL, and LOGSTMT_NONE.

Referenced by exec_execute_message(), and exec_simple_query().

2063 {
2064  ListCell *stmt_item;
2065 
2066  if (log_statement == LOGSTMT_NONE)
2067  return false;
2068  if (log_statement == LOGSTMT_ALL)
2069  return true;
2070 
2071  /* Else we have to inspect the statement(s) to see whether to log */
2072  foreach(stmt_item, stmt_list)
2073  {
2074  Node *stmt = (Node *) lfirst(stmt_item);
2075 
2076  if (GetCommandLogLevel(stmt) <= log_statement)
2077  return true;
2078  }
2079 
2080  return false;
2081 }
Definition: nodes.h:503
#define lfirst(lc)
Definition: pg_list.h:106
int log_statement
Definition: postgres.c:91
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:2765
bool check_max_stack_depth ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3160 of file postgres.c.

References get_stack_depth_rlimit(), GUC_check_errdetail, GUC_check_errhint, and STACK_DEPTH_SLOP.

3161 {
3162  long newval_bytes = *newval * 1024L;
3163  long stack_rlimit = get_stack_depth_rlimit();
3164 
3165  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3166  {
3167  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3168  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3169  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3170  return false;
3171  }
3172  return true;
3173 }
#define GUC_check_errdetail
Definition: guc.h:407
long get_stack_depth_rlimit(void)
Definition: postgres.c:4341
#define newval
#define GUC_check_errhint
Definition: guc.h:411
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:30
void check_stack_depth ( void  )

Definition at line 3097 of file postgres.c.

References ereport, errcode(), errhint(), errmsg(), ERROR, max_stack_depth, and stack_is_too_deep().

Referenced by BuildTupleRemapInfo(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObject(), Cover(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), EventTriggerInvoke(), ExecInitExpr(), ExecMakeFunctionResultNoSets(), ExecMakeFunctionResultSet(), execute(), expression_tree_mutator(), expression_tree_walker(), fillQT(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), get_query_def(), get_rule_expr(), get_setop_query(), gistSplit(), hash_range(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), ltree_execute(), makepol(), maketree(), MatchText(), parse_array(), parse_object(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), setPath(), split_array(), TQExamine(), TQRemap(), transformExprRecurse(), transformSetOperationTree(), TS_execute(), TS_execute_ternary(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3098 {
3099  if (stack_is_too_deep())
3100  {
3101  ereport(ERROR,
3102  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3103  errmsg("stack depth limit exceeded"),
3104  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3105  "after ensuring the platform's stack depth limit is adequate.",
3106  max_stack_depth)));
3107  }
3108 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int max_stack_depth
Definition: postgres.c:94
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool stack_is_too_deep(void)
Definition: postgres.c:3111
void die ( SIGNAL_ARGS  )

Definition at line 2618 of file postgres.c.

References DestRemote, DoingCommandRead, InterruptPending, MyLatch, proc_exit_inprogress, ProcDiePending, ProcessInterrupts(), SetLatch(), and whereToSendOutput.

Referenced by AutoVacWorkerMain(), bootstrap_signals(), ParallelWorkerMain(), PostgresMain(), and WalSndSignals().

2619 {
2620  int save_errno = errno;
2621 
2622  /* Don't joggle the elbow of proc_exit */
2623  if (!proc_exit_inprogress)
2624  {
2625  InterruptPending = true;
2626  ProcDiePending = true;
2627  }
2628 
2629  /* If we're still here, waken anything waiting on the process latch */
2630  SetLatch(MyLatch);
2631 
2632  /*
2633  * If we're in single user mode, we want to quit immediately - we can't
2634  * rely on latches as they wouldn't work when stdin/stdout is a file.
2635  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2636  * effort just for the benefit of single user mode.
2637  */
2640 
2641  errno = save_errno;
2642 }
void ProcessInterrupts(void)
Definition: postgres.c:2820
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:380
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:142
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:51
CommandDest whereToSendOutput
Definition: postgres.c:86
static void drop_unnamed_stmt ( void  )
static

Definition at line 2532 of file postgres.c.

References DropCachedPlan(), NULL, and unnamed_stmt_psrc.

Referenced by exec_parse_message(), exec_simple_query(), and PostgresMain().

2533 {
2534  /* paranoia to avoid a dangling pointer in case of error */
2535  if (unnamed_stmt_psrc)
2536  {
2538 
2540  DropCachedPlan(psrc);
2541  }
2542 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
#define NULL
Definition: c.h:226
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:485
static int errdetail_abort ( void  )
static

Definition at line 2239 of file postgres.c.

References errdetail(), MyProc, and PGPROC::recoveryConflictPending.

Referenced by exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), and exec_simple_query().

2240 {
2242  errdetail("abort reason: recovery conflict");
2243 
2244  return 0;
2245 }
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:111
int errdetail(const char *fmt,...)
Definition: elog.c:873
static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2144 of file postgres.c.

References errdetail(), FetchPreparedStatement(), IsA, lfirst, ExecuteStmt::name, and RawStmt::stmt.

Referenced by exec_simple_query().

2145 {
2146  ListCell *parsetree_item;
2147 
2148  foreach(parsetree_item, raw_parsetree_list)
2149  {
2150  RawStmt *parsetree = (RawStmt *) lfirst(parsetree_item);
2151 
2152  if (IsA(parsetree->stmt, ExecuteStmt))
2153  {
2154  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2155  PreparedStatement *pstmt;
2156 
2157  pstmt = FetchPreparedStatement(stmt->name, false);
2158  if (pstmt)
2159  {
2160  errdetail("prepare: %s", pstmt->plansource->query_string);
2161  return 0;
2162  }
2163  }
2164  }
2165 
2166  return 0;
2167 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:554
Node * stmt
Definition: parsenodes.h:1337
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define lfirst(lc)
Definition: pg_list.h:106
char * name
Definition: parsenodes.h:3176
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:494
static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2175 of file postgres.c.

References appendStringInfo(), appendStringInfoCharMacro, appendStringInfoString(), StringInfoData::data, errdetail(), getTypeOutputInfo(), initStringInfo(), IsAbortedTransactionBlockState(), ParamExternData::isnull, MemoryContextSwitchTo(), MessageContext, ParamListInfoData::numParams, OidIsValid, OidOutputFunctionCall(), ParamListInfoData::params, pfree(), ParamExternData::ptype, and ParamExternData::value.

Referenced by exec_bind_message(), and exec_execute_message().

2176 {
2177  /* We mustn't call user-defined I/O functions when in an aborted xact */
2178  if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2179  {
2180  StringInfoData param_str;
2181  MemoryContext oldcontext;
2182  int paramno;
2183 
2184  /* Make sure any trash is generated in MessageContext */
2185  oldcontext = MemoryContextSwitchTo(MessageContext);
2186 
2187  initStringInfo(&param_str);
2188 
2189  for (paramno = 0; paramno < params->numParams; paramno++)
2190  {
2191  ParamExternData *prm = &params->params[paramno];
2192  Oid typoutput;
2193  bool typisvarlena;
2194  char *pstring;
2195  char *p;
2196 
2197  appendStringInfo(&param_str, "%s$%d = ",
2198  paramno > 0 ? ", " : "",
2199  paramno + 1);
2200 
2201  if (prm->isnull || !OidIsValid(prm->ptype))
2202  {
2203  appendStringInfoString(&param_str, "NULL");
2204  continue;
2205  }
2206 
2207  getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2208 
2209  pstring = OidOutputFunctionCall(typoutput, prm->value);
2210 
2211  appendStringInfoCharMacro(&param_str, '\'');
2212  for (p = pstring; *p; p++)
2213  {
2214  if (*p == '\'') /* double single quotes */
2215  appendStringInfoCharMacro(&param_str, *p);
2216  appendStringInfoCharMacro(&param_str, *p);
2217  }
2218  appendStringInfoCharMacro(&param_str, '\'');
2219 
2220  pfree(pstring);
2221  }
2222 
2223  errdetail("parameters: %s", param_str.data);
2224 
2225  pfree(param_str.data);
2226 
2227  MemoryContextSwitchTo(oldcontext);
2228  }
2229 
2230  return 0;
2231 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
Datum value
Definition: params.h:56
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2600
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:530
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:135
void pfree(void *pointer)
Definition: mcxt.c:992
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
int errdetail(const char *fmt,...)
Definition: elog.c:873
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
MemoryContext MessageContext
Definition: mcxt.c:47
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:2006
bool isnull
Definition: params.h:57
static int errdetail_recovery_conflict ( void  )
static

Definition at line 2253 of file postgres.c.

References errdetail(), PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, and RecoveryConflictReason.

Referenced by ProcessInterrupts().

2254 {
2255  switch (RecoveryConflictReason)
2256  {
2258  errdetail("User was holding shared buffer pin for too long.");
2259  break;
2261  errdetail("User was holding a relation lock for too long.");
2262  break;
2264  errdetail("User was or might have been using tablespace that must be dropped.");
2265  break;
2267  errdetail("User query might have needed to see row versions that must be removed.");
2268  break;
2270  errdetail("User transaction caused buffer deadlock with recovery.");
2271  break;
2273  errdetail("User was connected to a database that must be dropped.");
2274  break;
2275  default:
2276  break;
2277  /* no errdetail */
2278  }
2279 
2280  return 0;
2281 }
int errdetail(const char *fmt,...)
Definition: elog.c:873
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1458 of file postgres.c.

References analyze_requires_snapshot(), check_log_duration(), CachedPlanSource::commandTag, CreatePortal(), StringInfoData::cursor, StringInfoData::data, DEBUG2, debug_query_string, DestRemote, ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), ERROR, FetchPreparedStatement(), GetCachedPlan(), GetTransactionSnapshot(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, InvalidSnapshot, IsAbortedTransactionBlockState(), ParamExternData::isnull, IsTransactionExitStmt(), StringInfoData::len, LOG, log_statement_stats, StringInfoData::maxlen, MemoryContextSwitchTo(), MessageContext, NULL, CachedPlanSource::num_params, ParamListInfoData::numParams, offsetof, OidInputFunctionCall(), OidReceiveFunctionCall(), palloc(), PARAM_FLAG_CONST, CachedPlanSource::param_types, ParamListInfoData::paramFetch, ParamListInfoData::paramFetchArg, ParamListInfoData::paramMask, ParamListInfoData::params, ParamListInfoData::parserSetup, ParamListInfoData::parserSetupArg, ParamExternData::pflags, pfree(), pg_client_to_server(), pgstat_report_activity(), PreparedStatement::plansource, PopActiveSnapshot(), PortalDefineQuery(), PortalGetHeapMemory, PortalSetResultFormat(), PortalStart(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_putemptymessage(), pstrdup(), ParamExternData::ptype, PushActiveSnapshot(), CachedPlanSource::query_string, CachedPlanSource::raw_parse_tree, ResetUsage(), set_ps_display(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, CachedPlan::stmt_list, unnamed_stmt_psrc, ParamExternData::value, and whereToSendOutput.

Referenced by PostgresMain().

1459 {
1460  const char *portal_name;
1461  const char *stmt_name;
1462  int numPFormats;
1463  int16 *pformats = NULL;
1464  int numParams;
1465  int numRFormats;
1466  int16 *rformats = NULL;
1467  CachedPlanSource *psrc;
1468  CachedPlan *cplan;
1469  Portal portal;
1470  char *query_string;
1471  char *saved_stmt_name;
1472  ParamListInfo params;
1473  MemoryContext oldContext;
1474  bool save_log_statement_stats = log_statement_stats;
1475  bool snapshot_set = false;
1476  char msec_str[32];
1477 
1478  /* Get the fixed part of the message */
1479  portal_name = pq_getmsgstring(input_message);
1480  stmt_name = pq_getmsgstring(input_message);
1481 
1482  ereport(DEBUG2,
1483  (errmsg("bind %s to %s",
1484  *portal_name ? portal_name : "<unnamed>",
1485  *stmt_name ? stmt_name : "<unnamed>")));
1486 
1487  /* Find prepared statement */
1488  if (stmt_name[0] != '\0')
1489  {
1490  PreparedStatement *pstmt;
1491 
1492  pstmt = FetchPreparedStatement(stmt_name, true);
1493  psrc = pstmt->plansource;
1494  }
1495  else
1496  {
1497  /* special-case the unnamed statement */
1498  psrc = unnamed_stmt_psrc;
1499  if (!psrc)
1500  ereport(ERROR,
1501  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1502  errmsg("unnamed prepared statement does not exist")));
1503  }
1504 
1505  /*
1506  * Report query to various monitoring facilities.
1507  */
1509 
1511 
1512  set_ps_display("BIND", false);
1513 
1514  if (save_log_statement_stats)
1515  ResetUsage();
1516 
1517  /*
1518  * Start up a transaction command so we can call functions etc. (Note that
1519  * this will normally change current memory context.) Nothing happens if
1520  * we are already in one.
1521  */
1523 
1524  /* Switch back to message context */
1526 
1527  /* Get the parameter format codes */
1528  numPFormats = pq_getmsgint(input_message, 2);
1529  if (numPFormats > 0)
1530  {
1531  int i;
1532 
1533  pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1534  for (i = 0; i < numPFormats; i++)
1535  pformats[i] = pq_getmsgint(input_message, 2);
1536  }
1537 
1538  /* Get the parameter value count */
1539  numParams = pq_getmsgint(input_message, 2);
1540 
1541  if (numPFormats > 1 && numPFormats != numParams)
1542  ereport(ERROR,
1543  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1544  errmsg("bind message has %d parameter formats but %d parameters",
1545  numPFormats, numParams)));
1546 
1547  if (numParams != psrc->num_params)
1548  ereport(ERROR,
1549  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1550  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1551  numParams, stmt_name, psrc->num_params)));
1552 
1553  /*
1554  * If we are in aborted transaction state, the only portals we can
1555  * actually run are those containing COMMIT or ROLLBACK commands. We
1556  * disallow binding anything else to avoid problems with infrastructure
1557  * that expects to run inside a valid transaction. We also disallow
1558  * binding any parameters, since we can't risk calling user-defined I/O
1559  * functions.
1560  */
1563  numParams != 0))
1564  ereport(ERROR,
1565  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1566  errmsg("current transaction is aborted, "
1567  "commands ignored until end of transaction block"),
1568  errdetail_abort()));
1569 
1570  /*
1571  * Create the portal. Allow silent replacement of an existing portal only
1572  * if the unnamed portal is specified.
1573  */
1574  if (portal_name[0] == '\0')
1575  portal = CreatePortal(portal_name, true, true);
1576  else
1577  portal = CreatePortal(portal_name, false, false);
1578 
1579  /*
1580  * Prepare to copy stuff into the portal's memory context. We do all this
1581  * copying first, because it could possibly fail (out-of-memory) and we
1582  * don't want a failure to occur between GetCachedPlan and
1583  * PortalDefineQuery; that would result in leaking our plancache refcount.
1584  */
1585  oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1586 
1587  /* Copy the plan's query string into the portal */
1588  query_string = pstrdup(psrc->query_string);
1589 
1590  /* Likewise make a copy of the statement name, unless it's unnamed */
1591  if (stmt_name[0])
1592  saved_stmt_name = pstrdup(stmt_name);
1593  else
1594  saved_stmt_name = NULL;
1595 
1596  /*
1597  * Set a snapshot if we have parameters to fetch (since the input
1598  * functions might need it) or the query isn't a utility command (and
1599  * hence could require redoing parse analysis and planning). We keep the
1600  * snapshot active till we're done, so that plancache.c doesn't have to
1601  * take new ones.
1602  */
1603  if (numParams > 0 ||
1604  (psrc->raw_parse_tree &&
1606  {
1608  snapshot_set = true;
1609  }
1610 
1611  /*
1612  * Fetch parameters, if any, and store in the portal's memory context.
1613  */
1614  if (numParams > 0)
1615  {
1616  int paramno;
1617 
1618  params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1619  numParams * sizeof(ParamExternData));
1620  /* we have static list of params, so no hooks needed */
1621  params->paramFetch = NULL;
1622  params->paramFetchArg = NULL;
1623  params->parserSetup = NULL;
1624  params->parserSetupArg = NULL;
1625  params->numParams = numParams;
1626  params->paramMask = NULL;
1627 
1628  for (paramno = 0; paramno < numParams; paramno++)
1629  {
1630  Oid ptype = psrc->param_types[paramno];
1631  int32 plength;
1632  Datum pval;
1633  bool isNull;
1634  StringInfoData pbuf;
1635  char csave;
1636  int16 pformat;
1637 
1638  plength = pq_getmsgint(input_message, 4);
1639  isNull = (plength == -1);
1640 
1641  if (!isNull)
1642  {
1643  const char *pvalue = pq_getmsgbytes(input_message, plength);
1644 
1645  /*
1646  * Rather than copying data around, we just set up a phony
1647  * StringInfo pointing to the correct portion of the message
1648  * buffer. We assume we can scribble on the message buffer so
1649  * as to maintain the convention that StringInfos have a
1650  * trailing null. This is grotty but is a big win when
1651  * dealing with very large parameter strings.
1652  */
1653  pbuf.data = (char *) pvalue;
1654  pbuf.maxlen = plength + 1;
1655  pbuf.len = plength;
1656  pbuf.cursor = 0;
1657 
1658  csave = pbuf.data[plength];
1659  pbuf.data[plength] = '\0';
1660  }
1661  else
1662  {
1663  pbuf.data = NULL; /* keep compiler quiet */
1664  csave = 0;
1665  }
1666 
1667  if (numPFormats > 1)
1668  pformat = pformats[paramno];
1669  else if (numPFormats > 0)
1670  pformat = pformats[0];
1671  else
1672  pformat = 0; /* default = text */
1673 
1674  if (pformat == 0) /* text mode */
1675  {
1676  Oid typinput;
1677  Oid typioparam;
1678  char *pstring;
1679 
1680  getTypeInputInfo(ptype, &typinput, &typioparam);
1681 
1682  /*
1683  * We have to do encoding conversion before calling the
1684  * typinput routine.
1685  */
1686  if (isNull)
1687  pstring = NULL;
1688  else
1689  pstring = pg_client_to_server(pbuf.data, plength);
1690 
1691  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1692 
1693  /* Free result of encoding conversion, if any */
1694  if (pstring && pstring != pbuf.data)
1695  pfree(pstring);
1696  }
1697  else if (pformat == 1) /* binary mode */
1698  {
1699  Oid typreceive;
1700  Oid typioparam;
1701  StringInfo bufptr;
1702 
1703  /*
1704  * Call the parameter type's binary input converter
1705  */
1706  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1707 
1708  if (isNull)
1709  bufptr = NULL;
1710  else
1711  bufptr = &pbuf;
1712 
1713  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1714 
1715  /* Trouble if it didn't eat the whole buffer */
1716  if (!isNull && pbuf.cursor != pbuf.len)
1717  ereport(ERROR,
1718  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1719  errmsg("incorrect binary data format in bind parameter %d",
1720  paramno + 1)));
1721  }
1722  else
1723  {
1724  ereport(ERROR,
1725  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1726  errmsg("unsupported format code: %d",
1727  pformat)));
1728  pval = 0; /* keep compiler quiet */
1729  }
1730 
1731  /* Restore message buffer contents */
1732  if (!isNull)
1733  pbuf.data[plength] = csave;
1734 
1735  params->params[paramno].value = pval;
1736  params->params[paramno].isnull = isNull;
1737 
1738  /*
1739  * We mark the params as CONST. This ensures that any custom plan
1740  * makes full use of the parameter values.
1741  */
1742  params->params[paramno].pflags = PARAM_FLAG_CONST;
1743  params->params[paramno].ptype = ptype;
1744  }
1745  }
1746  else
1747  params = NULL;
1748 
1749  /* Done storing stuff in portal's context */
1750  MemoryContextSwitchTo(oldContext);
1751 
1752  /* Get the result format codes */
1753  numRFormats = pq_getmsgint(input_message, 2);
1754  if (numRFormats > 0)
1755  {
1756  int i;
1757 
1758  rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1759  for (i = 0; i < numRFormats; i++)
1760  rformats[i] = pq_getmsgint(input_message, 2);
1761  }
1762 
1763  pq_getmsgend(input_message);
1764 
1765  /*
1766  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1767  * will be generated in MessageContext. The plan refcount will be
1768  * assigned to the Portal, so it will be released at portal destruction.
1769  */
1770  cplan = GetCachedPlan(psrc, params, false);
1771 
1772  /*
1773  * Now we can define the portal.
1774  *
1775  * DO NOT put any code that could possibly throw an error between the
1776  * above GetCachedPlan call and here.
1777  */
1778  PortalDefineQuery(portal,
1779  saved_stmt_name,
1780  query_string,
1781  psrc->commandTag,
1782  cplan->stmt_list,
1783  cplan);
1784 
1785  /* Done with the snapshot used for parameter I/O and parsing/planning */
1786  if (snapshot_set)
1788 
1789  /*
1790  * And we're ready to start portal execution.
1791  */
1792  PortalStart(portal, params, 0, InvalidSnapshot);
1793 
1794  /*
1795  * Apply the result format requests to the portal.
1796  */
1797  PortalSetResultFormat(portal, numRFormats, rformats);
1798 
1799  /*
1800  * Send BindComplete.
1801  */
1803  pq_putemptymessage('2');
1804 
1805  /*
1806  * Emit duration logging if appropriate.
1807  */
1808  switch (check_log_duration(msec_str, false))
1809  {
1810  case 1:
1811  ereport(LOG,
1812  (errmsg("duration: %s ms", msec_str),
1813  errhidestmt(true)));
1814  break;
1815  case 2:
1816  ereport(LOG,
1817  (errmsg("duration: %s ms bind %s%s%s: %s",
1818  msec_str,
1819  *stmt_name ? stmt_name : "<unnamed>",
1820  *portal_name ? "/" : "",
1821  *portal_name ? portal_name : "",
1822  psrc->query_string),
1823  errhidestmt(true),
1824  errdetail_params(params)));
1825  break;
1826  }
1827 
1828  if (save_log_statement_stats)
1829  ShowUsage("BIND MESSAGE STATISTICS");
1830 
1832 }
signed short int16
Definition: c.h:252
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
Datum value
Definition: params.h:56
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:176
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:618
void * parserSetupArg
Definition: params.h:73
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:343
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:437
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:279
bool log_statement_stats
Definition: guc.c:435
const char * commandTag
Definition: plancache.h:84
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2805
CachedPlanSource * plansource
Definition: prepare.h:31
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:621
void ShowUsage(const char *title)
Definition: postgres.c:4384
char * pstrdup(const char *in)
Definition: mcxt.c:1165
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
int errcode(int sqlerrcode)
Definition: elog.c:575
int errhidestmt(bool hide_stmt)
Definition: elog.c:1068
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
static int errdetail_abort(void)
Definition: postgres.c:2239
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
ParserSetupHook parserSetup
Definition: params.h:72
struct ParamListInfoData * ParamListInfo
Definition: params.h:62
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:550
signed int int32
Definition: c.h:253
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2483
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2099
void ResetUsage(void)
Definition: postgres.c:4377
void * paramFetchArg
Definition: params.h:71
ParamFetchHook paramFetch
Definition: params.h:70
void pfree(void *pointer)
Definition: mcxt.c:992
char * pg_client_to_server(const char *s, int len)
Definition: mbutils.c:556
#define ERROR
Definition: elog.h:43
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner)
Definition: plancache.c:1131
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:2015
#define DEBUG2
Definition: elog.h:24
Oid * param_types
Definition: plancache.h:85
Node * stmt
Definition: parsenodes.h:1337
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
struct Bitmapset * paramMask
Definition: params.h:75
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2175
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2633
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2567
#define ereport(elevel, rest)
Definition: elog.h:122
struct ParamExternData ParamExternData
const char * debug_query_string
Definition: postgres.c:83
#define InvalidSnapshot
Definition: snapshot.h:24
static void start_xact_command(void)
Definition: postgres.c:2433
uintptr_t Datum
Definition: postgres.h:374
#define NULL
Definition: c.h:226
uint16 pflags
Definition: params.h:58
const char * query_string
Definition: plancache.h:83
#define PortalGetHeapMemory(portal)
Definition: portal.h:203
MemoryContext MessageContext
Definition: mcxt.c:47
struct RawStmt * raw_parse_tree
Definition: plancache.h:82
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
List * stmt_list
Definition: plancache.h:132
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:677
CommandDest whereToSendOutput
Definition: postgres.c:86
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:494
bool isnull
Definition: params.h:57
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1997
#define offsetof(type, field)
Definition: c.h:547
#define PARAM_FLAG_CONST
Definition: params.h:52
static void exec_describe_portal_message ( const char *  portal_name)
static

Definition at line 2382 of file postgres.c.

References DestRemote, ereport, errcode(), errdetail_abort(), errmsg(), ERROR, FetchPortalTargetList(), PortalData::formats, GetPortalByName(), IsAbortedTransactionBlockState(), MemoryContextSwitchTo(), MessageContext, PortalIsValid, pq_putemptymessage(), SendRowDescriptionMessage(), start_xact_command(), PortalData::tupDesc, and whereToSendOutput.

Referenced by PostgresMain().

2383 {
2384  Portal portal;
2385 
2386  /*
2387  * Start up a transaction command. (Note that this will normally change
2388  * current memory context.) Nothing happens if we are already in one.
2389  */
2391 
2392  /* Switch back to message context */
2394 
2395  portal = GetPortalByName(portal_name);
2396  if (!PortalIsValid(portal))
2397  ereport(ERROR,
2398  (errcode(ERRCODE_UNDEFINED_CURSOR),
2399  errmsg("portal \"%s\" does not exist", portal_name)));
2400 
2401  /*
2402  * If we are in aborted transaction state, we can't run
2403  * SendRowDescriptionMessage(), because that needs catalog accesses.
2404  * Hence, refuse to Describe portals that return data. (We shouldn't just
2405  * refuse all Describes, since that might break the ability of some
2406  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2407  * blindly Describes whatever it does.)
2408  */
2410  portal->tupDesc)
2411  ereport(ERROR,
2412  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2413  errmsg("current transaction is aborted, "
2414  "commands ignored until end of transaction block"),
2415  errdetail_abort()));
2416 
2418  return; /* can't actually do anything... */
2419 
2420  if (portal->tupDesc)
2422  FetchPortalTargetList(portal),
2423  portal->formats);
2424  else
2425  pq_putemptymessage('n'); /* NoData */
2426 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
static int errdetail_abort(void)
Definition: postgres.c:2239
void SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:188
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define PortalIsValid(p)
Definition: portal.h:197
static void start_xact_command(void)
Definition: postgres.c:2433
int16 * formats
Definition: portal.h:155
TupleDesc tupDesc
Definition: portal.h:153
MemoryContext MessageContext
Definition: mcxt.c:47
int errmsg(const char *fmt,...)
Definition: elog.c:797
CommandDest whereToSendOutput
Definition: postgres.c:86
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:330
static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2289 of file postgres.c.

References Assert, buf, CachedPlanGetTargetList(), DestRemote, ereport, errcode(), errdetail_abort(), errmsg(), ERROR, FetchPreparedStatement(), CachedPlanSource::fixed_result, i, IsAbortedTransactionBlockState(), MemoryContextSwitchTo(), MessageContext, NULL, CachedPlanSource::num_params, CachedPlanSource::param_types, PreparedStatement::plansource, pq_beginmessage(), pq_endmessage(), pq_putemptymessage(), pq_sendint(), CachedPlanSource::resultDesc, SendRowDescriptionMessage(), start_xact_command(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

2290 {
2291  CachedPlanSource *psrc;
2293  int i;
2294 
2295  /*
2296  * Start up a transaction command. (Note that this will normally change
2297  * current memory context.) Nothing happens if we are already in one.
2298  */
2300 
2301  /* Switch back to message context */
2303 
2304  /* Find prepared statement */
2305  if (stmt_name[0] != '\0')
2306  {
2307  PreparedStatement *pstmt;
2308 
2309  pstmt = FetchPreparedStatement(stmt_name, true);
2310  psrc = pstmt->plansource;
2311  }
2312  else
2313  {
2314  /* special-case the unnamed statement */
2315  psrc = unnamed_stmt_psrc;
2316  if (!psrc)
2317  ereport(ERROR,
2318  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2319  errmsg("unnamed prepared statement does not exist")));
2320  }
2321 
2322  /* Prepared statements shouldn't have changeable result descs */
2323  Assert(psrc->fixed_result);
2324 
2325  /*
2326  * If we are in aborted transaction state, we can't run
2327  * SendRowDescriptionMessage(), because that needs catalog accesses.
2328  * Hence, refuse to Describe statements that return data. (We shouldn't
2329  * just refuse all Describes, since that might break the ability of some
2330  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2331  * blindly Describes whatever it does.) We can Describe parameters
2332  * without doing anything dangerous, so we don't restrict that.
2333  */
2335  psrc->resultDesc)
2336  ereport(ERROR,
2337  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2338  errmsg("current transaction is aborted, "
2339  "commands ignored until end of transaction block"),
2340  errdetail_abort()));
2341 
2343  return; /* can't actually do anything... */
2344 
2345  /*
2346  * First describe the parameters...
2347  */
2348  pq_beginmessage(&buf, 't'); /* parameter description message type */
2349  pq_sendint(&buf, psrc->num_params, 2);
2350 
2351  for (i = 0; i < psrc->num_params; i++)
2352  {
2353  Oid ptype = psrc->param_types[i];
2354 
2355  pq_sendint(&buf, (int) ptype, 4);
2356  }
2357  pq_endmessage(&buf);
2358 
2359  /*
2360  * Next send RowDescription or NoData to describe the result...
2361  */
2362  if (psrc->resultDesc)
2363  {
2364  List *tlist;
2365 
2366  /* Get the plan's primary targetlist */
2367  tlist = CachedPlanGetTargetList(psrc);
2368 
2369  SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2370  }
2371  else
2372  pq_putemptymessage('n'); /* NoData */
2373 
2374 }
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
static int errdetail_abort(void)
Definition: postgres.c:2239
unsigned int Oid
Definition: postgres_ext.h:31
void SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:188
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
TupleDesc resultDesc
Definition: plancache.h:91
#define ERROR
Definition: elog.h:43
Oid * param_types
Definition: plancache.h:85
static char * buf
Definition: pg_test_fsync.c:65
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
#define ereport(elevel, rest)
Definition: elog.h:122
static void start_xact_command(void)
Definition: postgres.c:2433
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
List * CachedPlanGetTargetList(CachedPlanSource *plansource)
Definition: plancache.c:1421
MemoryContext MessageContext
Definition: mcxt.c:47
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:344
int i
CommandDest whereToSendOutput
Definition: postgres.c:86
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:494
Definition: pg_list.h:45
static void exec_execute_message ( const char *  portal_name,
long  max_rows 
)
static

Definition at line 1840 of file postgres.c.

References _, Assert, PortalData::atStart, BeginCommand(), CHECK_FOR_INTERRUPTS, check_log_duration(), check_log_statement(), CommandCounterIncrement(), PortalData::commandTag, COMPLETION_TAG_BUFSIZE, CreateDestReceiver(), debug_query_string, DestRemote, DestRemoteExecute, EndCommand(), ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), ERROR, FETCH_ALL, finish_xact_command(), GetPortalByName(), IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), LOG, log_statement_stats, NIL, NULL, NullCommand(), pgstat_report_activity(), PortalIsValid, PortalData::portalParams, PortalRun(), pq_putemptymessage(), PortalData::prepStmtName, pstrdup(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display(), SetRemoteDestReceiverParams(), ShowUsage(), PortalData::sourceText, start_xact_command(), STATE_RUNNING, PortalData::stmts, and whereToSendOutput.

Referenced by PostgresMain().

1841 {
1842  CommandDest dest;
1843  DestReceiver *receiver;
1844  Portal portal;
1845  bool completed;
1846  char completionTag[COMPLETION_TAG_BUFSIZE];
1847  const char *sourceText;
1848  const char *prepStmtName;
1849  ParamListInfo portalParams;
1850  bool save_log_statement_stats = log_statement_stats;
1851  bool is_xact_command;
1852  bool execute_is_fetch;
1853  bool was_logged = false;
1854  char msec_str[32];
1855 
1856  /* Adjust destination to tell printtup.c what to do */
1857  dest = whereToSendOutput;
1858  if (dest == DestRemote)
1859  dest = DestRemoteExecute;
1860 
1861  portal = GetPortalByName(portal_name);
1862  if (!PortalIsValid(portal))
1863  ereport(ERROR,
1864  (errcode(ERRCODE_UNDEFINED_CURSOR),
1865  errmsg("portal \"%s\" does not exist", portal_name)));
1866 
1867  /*
1868  * If the original query was a null string, just return
1869  * EmptyQueryResponse.
1870  */
1871  if (portal->commandTag == NULL)
1872  {
1873  Assert(portal->stmts == NIL);
1874  NullCommand(dest);
1875  return;
1876  }
1877 
1878  /* Does the portal contain a transaction command? */
1879  is_xact_command = IsTransactionStmtList(portal->stmts);
1880 
1881  /*
1882  * We must copy the sourceText and prepStmtName into MessageContext in
1883  * case the portal is destroyed during finish_xact_command. Can avoid the
1884  * copy if it's not an xact command, though.
1885  */
1886  if (is_xact_command)
1887  {
1888  sourceText = pstrdup(portal->sourceText);
1889  if (portal->prepStmtName)
1890  prepStmtName = pstrdup(portal->prepStmtName);
1891  else
1892  prepStmtName = "<unnamed>";
1893 
1894  /*
1895  * An xact command shouldn't have any parameters, which is a good
1896  * thing because they wouldn't be around after finish_xact_command.
1897  */
1898  portalParams = NULL;
1899  }
1900  else
1901  {
1902  sourceText = portal->sourceText;
1903  if (portal->prepStmtName)
1904  prepStmtName = portal->prepStmtName;
1905  else
1906  prepStmtName = "<unnamed>";
1907  portalParams = portal->portalParams;
1908  }
1909 
1910  /*
1911  * Report query to various monitoring facilities.
1912  */
1913  debug_query_string = sourceText;
1914 
1916 
1917  set_ps_display(portal->commandTag, false);
1918 
1919  if (save_log_statement_stats)
1920  ResetUsage();
1921 
1922  BeginCommand(portal->commandTag, dest);
1923 
1924  /*
1925  * Create dest receiver in MessageContext (we don't want it in transaction
1926  * context, because that may get deleted if portal contains VACUUM).
1927  */
1928  receiver = CreateDestReceiver(dest);
1929  if (dest == DestRemoteExecute)
1930  SetRemoteDestReceiverParams(receiver, portal);
1931 
1932  /*
1933  * Ensure we are in a transaction command (this should normally be the
1934  * case already due to prior BIND).
1935  */
1937 
1938  /*
1939  * If we re-issue an Execute protocol request against an existing portal,
1940  * then we are only fetching more rows rather than completely re-executing
1941  * the query from the start. atStart is never reset for a v3 portal, so we
1942  * are safe to use this check.
1943  */
1944  execute_is_fetch = !portal->atStart;
1945 
1946  /* Log immediately if dictated by log_statement */
1947  if (check_log_statement(portal->stmts))
1948  {
1949  ereport(LOG,
1950  (errmsg("%s %s%s%s: %s",
1951  execute_is_fetch ?
1952  _("execute fetch from") :
1953  _("execute"),
1954  prepStmtName,
1955  *portal_name ? "/" : "",
1956  *portal_name ? portal_name : "",
1957  sourceText),
1958  errhidestmt(true),
1959  errdetail_params(portalParams)));
1960  was_logged = true;
1961  }
1962 
1963  /*
1964  * If we are in aborted transaction state, the only portals we can
1965  * actually run are those containing COMMIT or ROLLBACK commands.
1966  */
1968  !IsTransactionExitStmtList(portal->stmts))
1969  ereport(ERROR,
1970  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1971  errmsg("current transaction is aborted, "
1972  "commands ignored until end of transaction block"),
1973  errdetail_abort()));
1974 
1975  /* Check for cancel signal before we start execution */
1977 
1978  /*
1979  * Okay to run the portal.
1980  */
1981  if (max_rows <= 0)
1982  max_rows = FETCH_ALL;
1983 
1984  completed = PortalRun(portal,
1985  max_rows,
1986  true, /* always top level */
1987  receiver,
1988  receiver,
1989  completionTag);
1990 
1991  (*receiver->rDestroy) (receiver);
1992 
1993  if (completed)
1994  {
1995  if (is_xact_command)
1996  {
1997  /*
1998  * If this was a transaction control statement, commit it. We
1999  * will start a new xact command for the next command (if any).
2000  */
2002  }
2003  else
2004  {
2005  /*
2006  * We need a CommandCounterIncrement after every query, except
2007  * those that start or end a transaction block.
2008  */
2010  }
2011 
2012  /* Send appropriate CommandComplete to client */
2013  EndCommand(completionTag, dest);
2014  }
2015  else
2016  {
2017  /* Portal run not complete, so send PortalSuspended */
2019  pq_putemptymessage('s');
2020  }
2021 
2022  /*
2023  * Emit duration logging if appropriate.
2024  */
2025  switch (check_log_duration(msec_str, was_logged))
2026  {
2027  case 1:
2028  ereport(LOG,
2029  (errmsg("duration: %s ms", msec_str),
2030  errhidestmt(true)));
2031  break;
2032  case 2:
2033  ereport(LOG,
2034  (errmsg("duration: %s ms %s %s%s%s: %s",
2035  msec_str,
2036  execute_is_fetch ?
2037  _("execute fetch from") :
2038  _("execute"),
2039  prepStmtName,
2040  *portal_name ? "/" : "",
2041  *portal_name ? portal_name : "",
2042  sourceText),
2043  errhidestmt(true),
2044  errdetail_params(portalParams)));
2045  break;
2046  }
2047 
2048  if (save_log_statement_stats)
2049  ShowUsage("EXECUTE MESSAGE STATISTICS");
2050 
2052 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2516
#define NIL
Definition: pg_list.h:69
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:101
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:125
static void finish_xact_command(void)
Definition: postgres.c:2451
CommandDest
Definition: dest.h:86
bool log_statement_stats
Definition: guc.c:435
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2805
void ShowUsage(const char *title)
Definition: postgres.c:4384
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
char * pstrdup(const char *in)
Definition: mcxt.c:1165
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
int errcode(int sqlerrcode)
Definition: elog.c:575
int errhidestmt(bool hide_stmt)
Definition: elog.c:1068
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
static int errdetail_abort(void)
Definition: postgres.c:2239
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:93
#define LOG
Definition: elog.h:26
List * stmts
Definition: portal.h:136
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2099
void ResetUsage(void)
Definition: postgres.c:4377
ParamListInfo portalParams
Definition: portal.h:139
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:148
#define ERROR
Definition: elog.h:43
const char * commandTag
Definition: portal.h:135
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:103
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2175
#define ereport(elevel, rest)
Definition: elog.h:122
const char * debug_query_string
Definition: postgres.c:83
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2062
#define PortalIsValid(p)
Definition: portal.h:197
static void start_xact_command(void)
Definition: postgres.c:2433
void CommandCounterIncrement(void)
Definition: xact.c:920
const char * sourceText
Definition: portal.h:134
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define NULL
Definition: c.h:226
bool PortalRun(Portal portal, long count, bool isTopLevel, DestReceiver *dest, DestReceiver *altdest, char *completionTag)
Definition: pquery.c:680
#define Assert(condition)
Definition: c.h:667
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2500
bool atStart
Definition: portal.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
CommandDest whereToSendOutput
Definition: postgres.c:86
#define _(x)
Definition: elog.c:84
const char * prepStmtName
Definition: portal.h:118
void NullCommand(CommandDest dest)
Definition: dest.c:188
#define FETCH_ALL
Definition: parsenodes.h:2559
static void exec_parse_message ( const char *  query_string,
const char *  stmt_name,
Oid paramTypes,
int  numParams 
)
static

Definition at line 1196 of file postgres.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), analyze_requires_snapshot(), CHECK_FOR_INTERRUPTS, check_log_duration(), CommandCounterIncrement(), CompleteCachedPlan(), CachedPlanSource::context, CreateCachedPlan(), CreateCommandTag(), CURSOR_OPT_PARALLEL_OK, DEBUG2, debug_query_string, DestRemote, drop_unnamed_stmt(), ereport, errcode(), errdetail_abort(), errhidestmt(), errmsg(), ERROR, GetTransactionSnapshot(), i, InvalidOid, IsAbortedTransactionBlockState(), IsTransactionExitStmt(), linitial, list_length(), LOG, log_parser_stats, log_statement_stats, MemoryContextSetParent(), MemoryContextSwitchTo(), MessageContext, NIL, NULL, parse_analyze_varparams(), pg_parse_query(), pg_rewrite_query(), pgstat_report_activity(), PopActiveSnapshot(), pq_putemptymessage(), PushActiveSnapshot(), ResetUsage(), SaveCachedPlan(), set_ps_display(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, StorePreparedStatement(), UNKNOWNOID, and whereToSendOutput.

Referenced by PostgresMain().

1200 {
1201  MemoryContext unnamed_stmt_context = NULL;
1202  MemoryContext oldcontext;
1203  List *parsetree_list;
1204  RawStmt *raw_parse_tree;
1205  const char *commandTag;
1206  List *querytree_list;
1207  CachedPlanSource *psrc;
1208  bool is_named;
1209  bool save_log_statement_stats = log_statement_stats;
1210  char msec_str[32];
1211 
1212  /*
1213  * Report query to various monitoring facilities.
1214  */
1215  debug_query_string = query_string;
1216 
1217  pgstat_report_activity(STATE_RUNNING, query_string);
1218 
1219  set_ps_display("PARSE", false);
1220 
1221  if (save_log_statement_stats)
1222  ResetUsage();
1223 
1224  ereport(DEBUG2,
1225  (errmsg("parse %s: %s",
1226  *stmt_name ? stmt_name : "<unnamed>",
1227  query_string)));
1228 
1229  /*
1230  * Start up a transaction command so we can run parse analysis etc. (Note
1231  * that this will normally change current memory context.) Nothing happens
1232  * if we are already in one.
1233  */
1235 
1236  /*
1237  * Switch to appropriate context for constructing parsetrees.
1238  *
1239  * We have two strategies depending on whether the prepared statement is
1240  * named or not. For a named prepared statement, we do parsing in
1241  * MessageContext and copy the finished trees into the prepared
1242  * statement's plancache entry; then the reset of MessageContext releases
1243  * temporary space used by parsing and rewriting. For an unnamed prepared
1244  * statement, we assume the statement isn't going to hang around long, so
1245  * getting rid of temp space quickly is probably not worth the costs of
1246  * copying parse trees. So in this case, we create the plancache entry's
1247  * query_context here, and do all the parsing work therein.
1248  */
1249  is_named = (stmt_name[0] != '\0');
1250  if (is_named)
1251  {
1252  /* Named prepared statement --- parse in MessageContext */
1253  oldcontext = MemoryContextSwitchTo(MessageContext);
1254  }
1255  else
1256  {
1257  /* Unnamed prepared statement --- release any prior unnamed stmt */
1259  /* Create context for parsing */
1260  unnamed_stmt_context =
1262  "unnamed prepared statement",
1264  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1265  }
1266 
1267  /*
1268  * Do basic parsing of the query or queries (this should be safe even if
1269  * we are in aborted transaction state!)
1270  */
1271  parsetree_list = pg_parse_query(query_string);
1272 
1273  /*
1274  * We only allow a single user statement in a prepared statement. This is
1275  * mainly to keep the protocol simple --- otherwise we'd need to worry
1276  * about multiple result tupdescs and things like that.
1277  */
1278  if (list_length(parsetree_list) > 1)
1279  ereport(ERROR,
1280  (errcode(ERRCODE_SYNTAX_ERROR),
1281  errmsg("cannot insert multiple commands into a prepared statement")));
1282 
1283  if (parsetree_list != NIL)
1284  {
1285  Query *query;
1286  bool snapshot_set = false;
1287  int i;
1288 
1289  raw_parse_tree = (RawStmt *) linitial(parsetree_list);
1290 
1291  /*
1292  * Get the command name for possible use in status display.
1293  */
1294  commandTag = CreateCommandTag(raw_parse_tree->stmt);
1295 
1296  /*
1297  * If we are in an aborted transaction, reject all commands except
1298  * COMMIT/ROLLBACK. It is important that this test occur before we
1299  * try to do parse analysis, rewrite, or planning, since all those
1300  * phases try to do database accesses, which may fail in abort state.
1301  * (It might be safe to allow some additional utility commands in this
1302  * state, but not many...)
1303  */
1305  !IsTransactionExitStmt(raw_parse_tree->stmt))
1306  ereport(ERROR,
1307  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1308  errmsg("current transaction is aborted, "
1309  "commands ignored until end of transaction block"),
1310  errdetail_abort()));
1311 
1312  /*
1313  * Create the CachedPlanSource before we do parse analysis, since it
1314  * needs to see the unmodified raw parse tree.
1315  */
1316  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1317 
1318  /*
1319  * Set up a snapshot if parse analysis will need one.
1320  */
1321  if (analyze_requires_snapshot(raw_parse_tree))
1322  {
1324  snapshot_set = true;
1325  }
1326 
1327  /*
1328  * Analyze and rewrite the query. Note that the originally specified
1329  * parameter set is not required to be complete, so we have to use
1330  * parse_analyze_varparams().
1331  */
1332  if (log_parser_stats)
1333  ResetUsage();
1334 
1335  query = parse_analyze_varparams(raw_parse_tree,
1336  query_string,
1337  &paramTypes,
1338  &numParams);
1339 
1340  /*
1341  * Check all parameter types got determined.
1342  */
1343  for (i = 0; i < numParams; i++)
1344  {
1345  Oid ptype = paramTypes[i];
1346 
1347  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1348  ereport(ERROR,
1349  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1350  errmsg("could not determine data type of parameter $%d",
1351  i + 1)));
1352  }
1353 
1354  if (log_parser_stats)
1355  ShowUsage("PARSE ANALYSIS STATISTICS");
1356 
1357  querytree_list = pg_rewrite_query(query);
1358 
1359  /* Done with the snapshot used for parsing */
1360  if (snapshot_set)
1362  }
1363  else
1364  {
1365  /* Empty input string. This is legal. */
1366  raw_parse_tree = NULL;
1367  commandTag = NULL;
1368  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1369  querytree_list = NIL;
1370  }
1371 
1372  /*
1373  * CachedPlanSource must be a direct child of MessageContext before we
1374  * reparent unnamed_stmt_context under it, else we have a disconnected
1375  * circular subgraph. Klugy, but less so than flipping contexts even more
1376  * above.
1377  */
1378  if (unnamed_stmt_context)
1380 
1381  /* Finish filling in the CachedPlanSource */
1382  CompleteCachedPlan(psrc,
1383  querytree_list,
1384  unnamed_stmt_context,
1385  paramTypes,
1386  numParams,
1387  NULL,
1388  NULL,
1389  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1390  true); /* fixed result */
1391 
1392  /* If we got a cancel signal during analysis, quit */
1394 
1395  if (is_named)
1396  {
1397  /*
1398  * Store the query as a prepared statement.
1399  */
1400  StorePreparedStatement(stmt_name, psrc, false);
1401  }
1402  else
1403  {
1404  /*
1405  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1406  */
1407  SaveCachedPlan(psrc);
1408  unnamed_stmt_psrc = psrc;
1409  }
1410 
1411  MemoryContextSwitchTo(oldcontext);
1412 
1413  /*
1414  * We do NOT close the open transaction command here; that only happens
1415  * when the client sends Sync. Instead, do CommandCounterIncrement just
1416  * in case something happened during parse/plan.
1417  */
1419 
1420  /*
1421  * Send ParseComplete.
1422  */
1424  pq_putemptymessage('1');
1425 
1426  /*
1427  * Emit duration logging if appropriate.
1428  */
1429  switch (check_log_duration(msec_str, false))
1430  {
1431  case 1:
1432  ereport(LOG,
1433  (errmsg("duration: %s ms", msec_str),
1434  errhidestmt(true)));
1435  break;
1436  case 2:
1437  ereport(LOG,
1438  (errmsg("duration: %s ms parse %s: %s",
1439  msec_str,
1440  *stmt_name ? stmt_name : "<unnamed>",
1441  query_string),
1442  errhidestmt(true)));
1443  break;
1444  }
1445 
1446  if (save_log_statement_stats)
1447  ShowUsage("PARSE MESSAGE STATISTICS");
1448 
1450 }
MemoryContext context
Definition: plancache.h:92
#define NIL
Definition: pg_list.h:69
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:343
bool log_parser_stats
Definition: guc.c:432
bool log_statement_stats
Definition: guc.c:435
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2805
void ShowUsage(const char *title)
Definition: postgres.c:4384
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:317
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
int errcode(int sqlerrcode)
Definition: elog.c:575
int errhidestmt(bool hide_stmt)
Definition: elog.c:1068
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams)
Definition: analyze.c:127
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
static int errdetail_abort(void)
Definition: postgres.c:2239
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2483
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2099
void ResetUsage(void)
Definition: postgres.c:4377
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
#define DEBUG2
Definition: elog.h:24
Node * stmt
Definition: parsenodes.h:1337
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:151
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:1965
const char * debug_query_string
Definition: postgres.c:83
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:729
static void start_xact_command(void)
Definition: postgres.c:2433
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
void CommandCounterIncrement(void)
Definition: xact.c:920
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:452
#define InvalidOid
Definition: postgres_ext.h:36
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:440
#define NULL
Definition: c.h:226
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:324
static int list_length(const List *l)
Definition: pg_list.h:89
MemoryContext MessageContext
Definition: mcxt.c:47
#define UNKNOWNOID
Definition: pg_type.h:423
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2524
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void drop_unnamed_stmt(void)
Definition: postgres.c:2532
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
CommandDest whereToSendOutput
Definition: postgres.c:86
Definition: pg_list.h:45
static void exec_simple_query ( const char *  query_string)
static

Definition at line 880 of file postgres.c.

References analyze_requires_snapshot(), BeginCommand(), CHECK_FOR_INTERRUPTS, check_log_duration(), check_log_statement(), CommandCounterIncrement(), COMPLETION_TAG_BUFSIZE, CreateCommandTag(), CreateDestReceiver(), CreatePortal(), CURSOR_OPT_BINARY, CURSOR_OPT_PARALLEL_OK, PortalData::cursorOptions, debug_query_string, DestRemote, drop_unnamed_stmt(), EndCommand(), ereport, errcode(), errdetail_abort(), errdetail_execute(), errhidestmt(), errmsg(), ERROR, FETCH_ALL, finish_xact_command(), format, GetPortalByName(), GetTransactionSnapshot(), InvalidSnapshot, IsA, IsAbortedTransactionBlockState(), FetchStmt::ismove, IsTransactionExitStmt(), lfirst, list_length(), lnext, LOG, log_statement_stats, MemoryContextSwitchTo(), MessageContext, NULL, NullCommand(), pg_analyze_and_rewrite(), pg_parse_query(), pg_plan_queries(), pgstat_report_activity(), PopActiveSnapshot(), PortalDefineQuery(), PortalDrop(), PortalIsValid, FetchStmt::portalname, PortalRun(), PortalSetResultFormat(), PortalStart(), PushActiveSnapshot(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display(), SetRemoteDestReceiverParams(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, PortalData::visible, and whereToSendOutput.

Referenced by PostgresMain().

881 {
883  MemoryContext oldcontext;
884  List *parsetree_list;
885  ListCell *parsetree_item;
886  bool save_log_statement_stats = log_statement_stats;
887  bool was_logged = false;
888  bool isTopLevel;
889  char msec_str[32];
890 
891 
892  /*
893  * Report query to various monitoring facilities.
894  */
895  debug_query_string = query_string;
896 
897  pgstat_report_activity(STATE_RUNNING, query_string);
898 
899  TRACE_POSTGRESQL_QUERY_START(query_string);
900 
901  /*
902  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
903  * results because ResetUsage wasn't called.
904  */
905  if (save_log_statement_stats)
906  ResetUsage();
907 
908  /*
909  * Start up a transaction command. All queries generated by the
910  * query_string will be in this same command block, *unless* we find a
911  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
912  * one of those, else bad things will happen in xact.c. (Note that this
913  * will normally change current memory context.)
914  */
916 
917  /*
918  * Zap any pre-existing unnamed statement. (While not strictly necessary,
919  * it seems best to define simple-Query mode as if it used the unnamed
920  * statement and portal; this ensures we recover any storage used by prior
921  * unnamed operations.)
922  */
924 
925  /*
926  * Switch to appropriate context for constructing parsetrees.
927  */
929 
930  /*
931  * Do basic parsing of the query or queries (this should be safe even if
932  * we are in aborted transaction state!)
933  */
934  parsetree_list = pg_parse_query(query_string);
935 
936  /* Log immediately if dictated by log_statement */
937  if (check_log_statement(parsetree_list))
938  {
939  ereport(LOG,
940  (errmsg("statement: %s", query_string),
941  errhidestmt(true),
942  errdetail_execute(parsetree_list)));
943  was_logged = true;
944  }
945 
946  /*
947  * Switch back to transaction context to enter the loop.
948  */
949  MemoryContextSwitchTo(oldcontext);
950 
951  /*
952  * We'll tell PortalRun it's a top-level command iff there's exactly one
953  * raw parsetree. If more than one, it's effectively a transaction block
954  * and we want PreventTransactionChain to reject unsafe commands. (Note:
955  * we're assuming that query rewrite cannot add commands that are
956  * significant to PreventTransactionChain.)
957  */
958  isTopLevel = (list_length(parsetree_list) == 1);
959 
960  /*
961  * Run through the raw parsetree(s) and process each one.
962  */
963  foreach(parsetree_item, parsetree_list)
964  {
965  RawStmt *parsetree = (RawStmt *) lfirst(parsetree_item);
966  bool snapshot_set = false;
967  const char *commandTag;
968  char completionTag[COMPLETION_TAG_BUFSIZE];
969  List *querytree_list,
970  *plantree_list;
971  Portal portal;
972  DestReceiver *receiver;
973  int16 format;
974 
975  /*
976  * Get the command name for use in status display (it also becomes the
977  * default completion tag, down inside PortalRun). Set ps_status and
978  * do any special start-of-SQL-command processing needed by the
979  * destination.
980  */
981  commandTag = CreateCommandTag(parsetree->stmt);
982 
983  set_ps_display(commandTag, false);
984 
985  BeginCommand(commandTag, dest);
986 
987  /*
988  * If we are in an aborted transaction, reject all commands except
989  * COMMIT/ABORT. It is important that this test occur before we try
990  * to do parse analysis, rewrite, or planning, since all those phases
991  * try to do database accesses, which may fail in abort state. (It
992  * might be safe to allow some additional utility commands in this
993  * state, but not many...)
994  */
996  !IsTransactionExitStmt(parsetree->stmt))
997  ereport(ERROR,
998  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
999  errmsg("current transaction is aborted, "
1000  "commands ignored until end of transaction block"),
1001  errdetail_abort()));
1002 
1003  /* Make sure we are in a transaction command */
1005 
1006  /* If we got a cancel signal in parsing or prior command, quit */
1008 
1009  /*
1010  * Set up a snapshot if parse analysis/planning will need one.
1011  */
1012  if (analyze_requires_snapshot(parsetree))
1013  {
1015  snapshot_set = true;
1016  }
1017 
1018  /*
1019  * OK to analyze, rewrite, and plan this query.
1020  *
1021  * Switch to appropriate context for constructing querytrees (again,
1022  * these must outlive the execution context).
1023  */
1024  oldcontext = MemoryContextSwitchTo(MessageContext);
1025 
1026  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1027  NULL, 0);
1028 
1029  plantree_list = pg_plan_queries(querytree_list,
1031 
1032  /* Done with the snapshot used for parsing/planning */
1033  if (snapshot_set)
1035 
1036  /* If we got a cancel signal in analysis or planning, quit */
1038 
1039  /*
1040  * Create unnamed portal to run the query or queries in. If there
1041  * already is one, silently drop it.
1042  */
1043  portal = CreatePortal("", true, true);
1044  /* Don't display the portal in pg_cursors */
1045  portal->visible = false;
1046 
1047  /*
1048  * We don't have to copy anything into the portal, because everything
1049  * we are passing here is in MessageContext, which will outlive the
1050  * portal anyway.
1051  */
1052  PortalDefineQuery(portal,
1053  NULL,
1054  query_string,
1055  commandTag,
1056  plantree_list,
1057  NULL);
1058 
1059  /*
1060  * Start the portal. No parameters here.
1061  */
1062  PortalStart(portal, NULL, 0, InvalidSnapshot);
1063 
1064  /*
1065  * Select the appropriate output format: text unless we are doing a
1066  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1067  * --- but it avoids grottiness in other places. Ah, the joys of
1068  * backward compatibility...)
1069  */
1070  format = 0; /* TEXT is default */
1071  if (IsA(parsetree->stmt, FetchStmt))
1072  {
1073  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1074 
1075  if (!stmt->ismove)
1076  {
1077  Portal fportal = GetPortalByName(stmt->portalname);
1078 
1079  if (PortalIsValid(fportal) &&
1080  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1081  format = 1; /* BINARY */
1082  }
1083  }
1084  PortalSetResultFormat(portal, 1, &format);
1085 
1086  /*
1087  * Now we can create the destination receiver object.
1088  */
1089  receiver = CreateDestReceiver(dest);
1090  if (dest == DestRemote)
1091  SetRemoteDestReceiverParams(receiver, portal);
1092 
1093  /*
1094  * Switch back to transaction context for execution.
1095  */
1096  MemoryContextSwitchTo(oldcontext);
1097 
1098  /*
1099  * Run the portal to completion, and then drop it (and the receiver).
1100  */
1101  (void) PortalRun(portal,
1102  FETCH_ALL,
1103  isTopLevel,
1104  receiver,
1105  receiver,
1106  completionTag);
1107 
1108  (*receiver->rDestroy) (receiver);
1109 
1110  PortalDrop(portal, false);
1111 
1112  if (IsA(parsetree->stmt, TransactionStmt))
1113  {
1114  /*
1115  * If this was a transaction control statement, commit it. We will
1116  * start a new xact command for the next command (if any).
1117  */
1119  }
1120  else if (lnext(parsetree_item) == NULL)
1121  {
1122  /*
1123  * If this is the last parsetree of the query string, close down
1124  * transaction statement before reporting command-complete. This
1125  * is so that any end-of-transaction errors are reported before
1126  * the command-complete message is issued, to avoid confusing
1127  * clients who will expect either a command-complete message or an
1128  * error, not one and then the other. But for compatibility with
1129  * historical Postgres behavior, we do not force a transaction
1130  * boundary between queries appearing in a single query string.
1131  */
1133  }
1134  else
1135  {
1136  /*
1137  * We need a CommandCounterIncrement after every query, except
1138  * those that start or end a transaction block.
1139  */
1141  }
1142 
1143  /*
1144  * Tell client that we're done with this query. Note we emit exactly
1145  * one EndCommand report for each raw parsetree, thus one for each SQL
1146  * command the client sent, regardless of rewriting. (But a command
1147  * aborted by error will not send an EndCommand report at all.)
1148  */
1149  EndCommand(completionTag, dest);
1150  } /* end loop over parsetrees */
1151 
1152  /*
1153  * Close down transaction statement, if one is open.
1154  */
1156 
1157  /*
1158  * If there were no parsetrees, return EmptyQueryResponse message.
1159  */
1160  if (!parsetree_list)
1161  NullCommand(dest);
1162 
1163  /*
1164  * Emit duration logging if appropriate.
1165  */
1166  switch (check_log_duration(msec_str, was_logged))
1167  {
1168  case 1:
1169  ereport(LOG,
1170  (errmsg("duration: %s ms", msec_str),
1171  errhidestmt(true)));
1172  break;
1173  case 2:
1174  ereport(LOG,
1175  (errmsg("duration: %s ms statement: %s",
1176  msec_str, query_string),
1177  errhidestmt(true),
1178  errdetail_execute(parsetree_list)));
1179  break;
1180  }
1181 
1182  if (save_log_statement_stats)
1183  ShowUsage("QUERY STATISTICS");
1184 
1185  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1186 
1188 }
signed short int16
Definition: c.h:252
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:101
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:176
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:125
#define IsA(nodeptr, _type_)
Definition: nodes.h:554
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:618
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:343
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:437
static void finish_xact_command(void)
Definition: postgres.c:2451
bool visible
Definition: portal.h:190
CommandDest
Definition: dest.h:86
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:279
bool log_statement_stats
Definition: guc.c:435
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2805
void ShowUsage(const char *title)
Definition: postgres.c:4384
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2515
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
int errcode(int sqlerrcode)
Definition: elog.c:575
int errhidestmt(bool hide_stmt)
Definition: elog.c:1068
static int errdetail_abort(void)
Definition: postgres.c:2239
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:93
#define LOG
Definition: elog.h:26
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2483
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2099
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams)
Definition: postgres.c:644
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2144
void ResetUsage(void)
Definition: postgres.c:4377
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:148
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
Node * stmt
Definition: parsenodes.h:1337
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:103
char * portalname
Definition: parsenodes.h:2566
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:1965
const char * debug_query_string
Definition: postgres.c:83
#define InvalidSnapshot
Definition: snapshot.h:24
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2062
#define PortalIsValid(p)
Definition: portal.h:197
static void start_xact_command(void)
Definition: postgres.c:2433
bool ismove
Definition: parsenodes.h:2567
void CommandCounterIncrement(void)
Definition: xact.c:920
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define NULL
Definition: c.h:226
bool PortalRun(Portal portal, long count, bool isTopLevel, DestReceiver *dest, DestReceiver *altdest, char *completionTag)
Definition: pquery.c:680
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
MemoryContext MessageContext
Definition: mcxt.c:47
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2524
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:463
static void drop_unnamed_stmt(void)
Definition: postgres.c:2532
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
static char format
Definition: pg_basebackup.c:83
int cursorOptions
Definition: portal.h:143
CommandDest whereToSendOutput
Definition: postgres.c:86
Definition: pg_list.h:45
List * pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:842
void NullCommand(CommandDest dest)
Definition: dest.c:188
#define FETCH_ALL
Definition: parsenodes.h:2559
static void finish_xact_command ( void  )
static

Definition at line 2451 of file postgres.c.

References CommitTransactionCommand(), disable_timeout(), MemoryContextStats(), STATEMENT_TIMEOUT, TopMemoryContext, and xact_started.

Referenced by exec_execute_message(), exec_simple_query(), and PostgresMain().

2452 {
2453  if (xact_started)
2454  {
2455  /* Cancel any active statement timeout before committing */
2457 
2459 
2460 #ifdef MEMORY_CONTEXT_CHECKING
2461  /* Check all memory contexts that weren't freed during commit */
2462  /* (those that were, were checked before being deleted) */
2463  MemoryContextCheck(TopMemoryContext);
2464 #endif
2465 
2466 #ifdef SHOW_MEMORY_STATS
2467  /* Print mem stats after each commit for leak tracking */
2469 #endif
2470 
2471  xact_started = false;
2472  }
2473 }
void CommitTransactionCommand(void)
Definition: xact.c:2743
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:483
static bool xact_started
Definition: postgres.c:135
MemoryContext TopMemoryContext
Definition: mcxt.c:43
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2670 of file postgres.c.

References ereport, errcode(), errdetail(), errmsg(), and ERROR.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), plperl_init_interp(), PostgresMain(), and StartBackgroundWorker().

2671 {
2672  /* We're not returning, so no need to save errno */
2673  ereport(ERROR,
2674  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2675  errmsg("floating-point exception"),
2676  errdetail("An invalid floating-point operation was signaled. "
2677  "This probably means an out-of-range result or an "
2678  "invalid operation, such as division by zero.")));
2679 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4319 of file postgres.c.

References am_walsender, ereport, errcode(), errmsg(), and ERROR.

Referenced by PostgresMain().

4320 {
4321  if (am_walsender)
4322  {
4323  if (firstchar == 'F')
4324  ereport(ERROR,
4325  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4326  errmsg("fastpath function calls not supported in a replication connection")));
4327  else
4328  ereport(ERROR,
4329  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4330  errmsg("extended query protocol not supported in a replication connection")));
4331  }
4332 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool am_walsender
Definition: walsender.c:103
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
long get_stack_depth_rlimit ( void  )

Definition at line 4341 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4342 {
4343 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4344  static long val = 0;
4345 
4346  /* This won't change after process launch, so check just once */
4347  if (val == 0)
4348  {
4349  struct rlimit rlim;
4350 
4351  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4352  val = -1;
4353  else if (rlim.rlim_cur == RLIM_INFINITY)
4354  val = LONG_MAX;
4355  /* rlim_cur is probably of an unsigned type, so check for overflow */
4356  else if (rlim.rlim_cur >= LONG_MAX)
4357  val = LONG_MAX;
4358  else
4359  val = rlim.rlim_cur;
4360  }
4361  return val;
4362 #else /* no getrlimit */
4363 #if defined(WIN32) || defined(__CYGWIN__)
4364  /* On Windows we set the backend stack size in src/backend/Makefile */
4365  return WIN32_STACK_RLIMIT;
4366 #else /* not windows ... give up */
4367  return -1;
4368 #endif
4369 #endif
4370 }
long val
Definition: informix.c:689
const char* get_stats_option_name ( const char *  arg)

Definition at line 3263 of file postgres.c.

References NULL, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3264 {
3265  switch (arg[0])
3266  {
3267  case 'p':
3268  if (optarg[1] == 'a') /* "parser" */
3269  return "log_parser_stats";
3270  else if (optarg[1] == 'l') /* "planner" */
3271  return "log_planner_stats";
3272  break;
3273 
3274  case 'e': /* "executor" */
3275  return "log_executor_stats";
3276  break;
3277  }
3278 
3279  return NULL;
3280 }
#define NULL
Definition: c.h:226
char * optarg
Definition: getopt.c:53
void * arg
static int interactive_getc ( void  )
static

Definition at line 297 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

298 {
299  int c;
300 
301  /*
302  * This will not process catchup interrupts or notifications while
303  * reading. But those can't really be relevant for a standalone backend
304  * anyway. To properly handle SIGTERM there's a hack in die() that
305  * directly processes interrupts at this stage...
306  */
308 
309  c = getc(stdin);
310 
312 
313  return c;
314 }
char * c
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:522
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 209 of file postgres.c.

References appendStringInfoChar(), StringInfoData::data, EchoQuery, interactive_getc(), StringInfoData::len, resetStringInfo(), and UseSemiNewlineNewline.

Referenced by ReadCommand().

210 {
211  int c; /* character read from getc() */
212 
213  /*
214  * display a prompt and obtain input from the user
215  */
216  printf("backend> ");
217  fflush(stdout);
218 
219  resetStringInfo(inBuf);
220 
221  /*
222  * Read characters until EOF or the appropriate delimiter is seen.
223  */
224  while ((c = interactive_getc()) != EOF)
225  {
226  if (c == '\n')
227  {
229  {
230  /*
231  * In -j mode, semicolon followed by two newlines ends the
232  * command; otherwise treat newline as regular character.
233  */
234  if (inBuf->len > 1 &&
235  inBuf->data[inBuf->len - 1] == '\n' &&
236  inBuf->data[inBuf->len - 2] == ';')
237  {
238  /* might as well drop the second newline */
239  break;
240  }
241  }
242  else
243  {
244  /*
245  * In plain mode, newline ends the command unless preceded by
246  * backslash.
247  */
248  if (inBuf->len > 0 &&
249  inBuf->data[inBuf->len - 1] == '\\')
250  {
251  /* discard backslash from inBuf */
252  inBuf->data[--inBuf->len] = '\0';
253  /* discard newline too */
254  continue;
255  }
256  else
257  {
258  /* keep the newline character, but end the command */
259  appendStringInfoChar(inBuf, '\n');
260  break;
261  }
262  }
263  }
264 
265  /* Not newline, or newline treated as regular character */
266  appendStringInfoChar(inBuf, (char) c);
267  }
268 
269  /* No input before EOF signal means time to quit. */
270  if (c == EOF && inBuf->len == 0)
271  return EOF;
272 
273  /*
274  * otherwise we have a user query so process it.
275  */
276 
277  /* Add '\0' to make it look the same as message case. */
278  appendStringInfoChar(inBuf, (char) '\0');
279 
280  /*
281  * if the query echo flag was given, print the query..
282  */
283  if (EchoQuery)
284  printf("statement: %s\n", inBuf->data);
285  fflush(stdout);
286 
287  return 'Q';
288 }
static int interactive_getc(void)
Definition: postgres.c:297
char * c
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:201
static bool EchoQuery
Definition: postgres.c:160
static bool UseSemiNewlineNewline
Definition: postgres.c:161
static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2483 of file postgres.c.

References IsA, TransactionStmt::kind, TRANS_STMT_COMMIT, TRANS_STMT_PREPARE, TRANS_STMT_ROLLBACK, and TRANS_STMT_ROLLBACK_TO.

Referenced by exec_bind_message(), exec_parse_message(), exec_simple_query(), and IsTransactionExitStmtList().

2484 {
2485  if (parsetree && IsA(parsetree, TransactionStmt))
2486  {
2487  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2488 
2489  if (stmt->kind == TRANS_STMT_COMMIT ||
2490  stmt->kind == TRANS_STMT_PREPARE ||
2491  stmt->kind == TRANS_STMT_ROLLBACK ||
2492  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2493  return true;
2494  }
2495  return false;
2496 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:554
TransactionStmtKind kind
Definition: parsenodes.h:2810
static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2500 of file postgres.c.

References Assert, CMD_UTILITY, PlannedStmt::commandType, IsA, IsTransactionExitStmt(), linitial, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

2501 {
2502  if (list_length(pstmts) == 1)
2503  {
2504  PlannedStmt *pstmt = (PlannedStmt *) linitial(pstmts);
2505 
2506  Assert(IsA(pstmt, PlannedStmt));
2507  if (pstmt->commandType == CMD_UTILITY &&
2509  return true;
2510  }
2511  return false;
2512 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:554
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2483
#define linitial(l)
Definition: pg_list.h:110
Node * utilityStmt
Definition: plannodes.h:80
CmdType commandType
Definition: plannodes.h:45
#define Assert(condition)
Definition: c.h:667
static int list_length(const List *l)
Definition: pg_list.h:89
static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2516 of file postgres.c.

References Assert, CMD_UTILITY, PlannedStmt::commandType, IsA, linitial, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

2517 {
2518  if (list_length(pstmts) == 1)
2519  {
2520  PlannedStmt *pstmt = (PlannedStmt *) linitial(pstmts);
2521 
2522  Assert(IsA(pstmt, PlannedStmt));
2523  if (pstmt->commandType == CMD_UTILITY &&
2524  IsA(pstmt->utilityStmt, TransactionStmt))
2525  return true;
2526  }
2527  return false;
2528 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:554
#define linitial(l)
Definition: pg_list.h:110
Node * utilityStmt
Definition: plannodes.h:80
CmdType commandType
Definition: plannodes.h:45
#define Assert(condition)
Definition: c.h:667
static int list_length(const List *l)
Definition: pg_list.h:89
static void log_disconnections ( int  code,
Datum  arg 
)
static

Definition at line 4479 of file postgres.c.

References Port::database_name, ereport, errmsg(), GetCurrentTimestamp(), LOG, MyProcPort, port, Port::remote_host, Port::remote_port, SECS_PER_HOUR, SECS_PER_MINUTE, Port::SessionStartTime, TimestampDifference(), and Port::user_name.

Referenced by PostgresMain().

4480 {
4481  Port *port = MyProcPort;
4482  long secs;
4483  int usecs;
4484  int msecs;
4485  int hours,
4486  minutes,
4487  seconds;
4488 
4491  &secs, &usecs);
4492  msecs = usecs / 1000;
4493 
4494  hours = secs / SECS_PER_HOUR;
4495  secs %= SECS_PER_HOUR;
4496  minutes = secs / SECS_PER_MINUTE;
4497  seconds = secs % SECS_PER_MINUTE;
4498 
4499  ereport(LOG,
4500  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4501  "user=%s database=%s host=%s%s%s",
4502  hours, minutes, seconds, msecs,
4503  port->user_name, port->database_name, port->remote_host,
4504  port->remote_port[0] ? " port=" : "", port->remote_port)));
4505 }
struct Port * MyProcPort
Definition: globals.c:40
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
Definition: libpq-be.h:118
char * remote_port
Definition: libpq-be.h:130
#define LOG
Definition: elog.h:26
TimestampTz SessionStartTime
Definition: libpq-be.h:153
#define SECS_PER_MINUTE
Definition: timestamp.h:100
char * user_name
Definition: libpq-be.h:139
#define ereport(elevel, rest)
Definition: elog.h:122
#define SECS_PER_HOUR
Definition: timestamp.h:99
static int port
Definition: pg_regress.c:87
char * remote_host
Definition: libpq-be.h:125
int errmsg(const char *fmt,...)
Definition: elog.c:797
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1791
char * database_name
Definition: libpq-be.h:138
List* pg_analyze_and_rewrite ( RawStmt parsetree,
const char *  query_string,
Oid paramTypes,
int  numParams 
)

Definition at line 644 of file postgres.c.

References log_parser_stats, parse_analyze(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopy(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

646 {
647  Query *query;
648  List *querytree_list;
649 
650  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
651 
652  /*
653  * (1) Perform parse analysis.
654  */
655  if (log_parser_stats)
656  ResetUsage();
657 
658  query = parse_analyze(parsetree, query_string, paramTypes, numParams);
659 
660  if (log_parser_stats)
661  ShowUsage("PARSE ANALYSIS STATISTICS");
662 
663  /*
664  * (2) Rewrite the queries, as necessary
665  */
666  querytree_list = pg_rewrite_query(query);
667 
668  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
669 
670  return querytree_list;
671 }
bool log_parser_stats
Definition: guc.c:432
void ShowUsage(const char *title)
Definition: postgres.c:4384
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams)
Definition: analyze.c:96
void ResetUsage(void)
Definition: postgres.c:4377
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:729
Definition: pg_list.h:45
List* pg_analyze_and_rewrite_params ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg 
)

Definition at line 679 of file postgres.c.

References Assert, free_parsestate(), log_parser_stats, make_parsestate(), NULL, ParseState::p_sourcetext, pg_rewrite_query(), post_parse_analyze_hook, ResetUsage(), ShowUsage(), and transformTopLevelStmt().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

683 {
684  ParseState *pstate;
685  Query *query;
686  List *querytree_list;
687 
688  Assert(query_string != NULL); /* required as of 8.4 */
689 
690  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
691 
692  /*
693  * (1) Perform parse analysis.
694  */
695  if (log_parser_stats)
696  ResetUsage();
697 
698  pstate = make_parsestate(NULL);
699  pstate->p_sourcetext = query_string;
700  (*parserSetup) (pstate, parserSetupArg);
701 
702  query = transformTopLevelStmt(pstate, parsetree);
703 
705  (*post_parse_analyze_hook) (pstate, query);
706 
707  free_parsestate(pstate);
708 
709  if (log_parser_stats)
710  ShowUsage("PARSE ANALYSIS STATISTICS");
711 
712  /*
713  * (2) Rewrite the queries, as necessary
714  */
715  querytree_list = pg_rewrite_query(query);
716 
717  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
718 
719  return querytree_list;
720 }
bool log_parser_stats
Definition: guc.c:432
void ShowUsage(const char *title)
Definition: postgres.c:4384
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4377
const char * p_sourcetext
Definition: parse_node.h:164
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:729
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:182
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:74
Definition: pg_list.h:45
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:49
List* pg_parse_query ( const char *  query_string)

Definition at line 602 of file postgres.c.

References copyObject(), elog, equal(), log_parser_stats, new_list(), raw_parser(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by _SPI_prepare_oneshot_plan(), _SPI_prepare_plan(), exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

603 {
604  List *raw_parsetree_list;
605 
606  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
607 
608  if (log_parser_stats)
609  ResetUsage();
610 
611  raw_parsetree_list = raw_parser(query_string);
612 
613  if (log_parser_stats)
614  ShowUsage("PARSER STATISTICS");
615 
616 #ifdef COPY_PARSE_PLAN_TREES
617  /* Optional debugging check: pass raw parsetrees through copyObject() */
618  {
619  List *new_list = (List *) copyObject(raw_parsetree_list);
620 
621  /* This checks both copyObject() and the equal() routines... */
622  if (!equal(new_list, raw_parsetree_list))
623  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
624  else
625  raw_parsetree_list = new_list;
626  }
627 #endif
628 
629  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
630 
631  return raw_parsetree_list;
632 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:432
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2810
void ShowUsage(const char *title)
Definition: postgres.c:4384
static List * new_list(NodeTag type)
Definition: list.c:63
void * copyObject(const void *from)
Definition: copyfuncs.c:4410
void ResetUsage(void)
Definition: postgres.c:4377
#define WARNING
Definition: elog.h:40
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List* pg_plan_queries ( List querytrees,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 842 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst, makeNode, NIL, pg_plan_query(), PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

843 {
844  List *stmt_list = NIL;
845  ListCell *query_list;
846 
847  foreach(query_list, querytrees)
848  {
849  Query *query = (Query *) lfirst(query_list);
850  PlannedStmt *stmt;
851 
852  if (query->commandType == CMD_UTILITY)
853  {
854  /* Utility commands require no planning. */
855  stmt = makeNode(PlannedStmt);
856  stmt->commandType = CMD_UTILITY;
857  stmt->canSetTag = query->canSetTag;
858  stmt->utilityStmt = query->utilityStmt;
859  stmt->stmt_location = query->stmt_location;
860  stmt->stmt_len = query->stmt_len;
861  }
862  else
863  {
864  stmt = pg_plan_query(query, cursorOptions, boundParams);
865  }
866 
867  stmt_list = lappend(stmt_list, stmt);
868  }
869 
870  return stmt_list;
871 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:171
Node * utilityStmt
Definition: parsenodes.h:111
int stmt_len
Definition: plannodes.h:84
int stmt_location
Definition: plannodes.h:83
Node * utilityStmt
Definition: plannodes.h:80
List * lappend(List *list, void *datum)
Definition: list.c:128
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
CmdType commandType
Definition: parsenodes.h:103
#define makeNode(_type_)
Definition: nodes.h:551
#define lfirst(lc)
Definition: pg_list.h:106
bool canSetTag
Definition: parsenodes.h:109
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:172
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:781
PlannedStmt* pg_plan_query ( Query querytree,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 781 of file postgres.c.

References ActiveSnapshotSet(), Assert, CMD_UTILITY, Query::commandType, copyObject(), Debug_pretty_print, Debug_print_plan, elog, elog_node_display(), equal(), LOG, log_planner_stats, NULL, planner(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by BeginCopy(), ExecCreateTableAs(), ExplainOneQuery(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), and refresh_matview_datafill().

782 {
783  PlannedStmt *plan;
784 
785  /* Utility commands have no plans. */
786  if (querytree->commandType == CMD_UTILITY)
787  return NULL;
788 
789  /* Planner must have a snapshot in case it calls user-defined functions. */
791 
792  TRACE_POSTGRESQL_QUERY_PLAN_START();
793 
794  if (log_planner_stats)
795  ResetUsage();
796 
797  /* call the optimizer */
798  plan = planner(querytree, cursorOptions, boundParams);
799 
800  if (log_planner_stats)
801  ShowUsage("PLANNER STATISTICS");
802 
803 #ifdef COPY_PARSE_PLAN_TREES
804  /* Optional debugging check: pass plan output through copyObject() */
805  {
806  PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
807 
808  /*
809  * equal() currently does not have routines to compare Plan nodes, so
810  * don't try to test equality here. Perhaps fix someday?
811  */
812 #ifdef NOT_USED
813  /* This checks both copyObject() and the equal() routines... */
814  if (!equal(new_plan, plan))
815  elog(WARNING, "copyObject() failed to produce an equal plan tree");
816  else
817 #endif
818  plan = new_plan;
819  }
820 #endif
821 
822  /*
823  * Print plan if debugging.
824  */
825  if (Debug_print_plan)
826  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
827 
828  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
829 
830  return plan;
831 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:71
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2810
void ShowUsage(const char *title)
Definition: postgres.c:4384
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:174
void * copyObject(const void *from)
Definition: copyfuncs.c:4410
void ResetUsage(void)
Definition: postgres.c:4377
bool Debug_print_plan
Definition: guc.c:427
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:846
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:103
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
bool Debug_pretty_print
Definition: guc.c:430
#define elog
Definition: elog.h:219
bool log_planner_stats
Definition: guc.c:433
static List * pg_rewrite_query ( Query query)
static

Definition at line 729 of file postgres.c.

References CMD_UTILITY, Query::commandType, copyObject(), Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), list_make1, LOG, log_parser_stats, new_list(), QueryRewrite(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by exec_parse_message(), pg_analyze_and_rewrite(), and pg_analyze_and_rewrite_params().

730 {
731  List *querytree_list;
732 
733  if (Debug_print_parse)
734  elog_node_display(LOG, "parse tree", query,
736 
737  if (log_parser_stats)
738  ResetUsage();
739 
740  if (query->commandType == CMD_UTILITY)
741  {
742  /* don't rewrite utilities, just dump 'em into result list */
743  querytree_list = list_make1(query);
744  }
745  else
746  {
747  /* rewrite regular queries */
748  querytree_list = QueryRewrite(query);
749  }
750 
751  if (log_parser_stats)
752  ShowUsage("REWRITER STATISTICS");
753 
754 #ifdef COPY_PARSE_PLAN_TREES
755  /* Optional debugging check: pass querytree output through copyObject() */
756  {
757  List *new_list;
758 
759  new_list = (List *) copyObject(querytree_list);
760  /* This checks both copyObject() and the equal() routines... */
761  if (!equal(new_list, querytree_list))
762  elog(WARNING, "copyObject() failed to produce equal parse tree");
763  else
764  querytree_list = new_list;
765  }
766 #endif
767 
769  elog_node_display(LOG, "rewritten parse tree", querytree_list,
771 
772  return querytree_list;
773 }
List * QueryRewrite(Query *parsetree)
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:71
bool log_parser_stats
Definition: guc.c:432
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2810
void ShowUsage(const char *title)
Definition: postgres.c:4384
static List * new_list(NodeTag type)
Definition: list.c:63
#define LOG
Definition: elog.h:26
void * copyObject(const void *from)
Definition: copyfuncs.c:4410
#define list_make1(x1)
Definition: pg_list.h:133
void ResetUsage(void)
Definition: postgres.c:4377
bool Debug_print_parse
Definition: guc.c:428
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:103
bool Debug_pretty_print
Definition: guc.c:430
bool Debug_print_rewritten
Definition: guc.c:429
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
void PostgresMain ( int  argc,
char *  argv[],
const char *  dbname,
const char *  username 
)

Definition at line 3562 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, CreateDataDirLockFile(), DataDir, debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), ereport, errcode(), errmsg(), ERROR, error_context_stack, exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), FATAL, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), GetCurrentTimestamp(), GetPortalByName(), got_SIGHUP, HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, ignore_till_sync, InitializeGUCOptions(), InitializeMaxBackends(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InitStandaloneProcess(), initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyProcPid, MyReplicationSlot, NormalProcessing, NULL, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_POSTMASTER, PGC_SIGHUP, PgStartTime, pgstat_report_activity(), pgstat_report_stat(), PortalDrop(), PortalIsValid, PostmasterContext, pq_beginmessage(), pq_comm_reset, pq_endmessage(), pq_flush, pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_is_reading_msg(), pq_putemptymessage(), pq_sendint(), pqinitmask(), pqsignal(), proc_exit(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), procsignal_sigusr1_handler(), progname, QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), RESUME_INTERRUPTS, SelectConfigFiles(), set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SigHupHandler(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, UnBlockSig, userDoption, username, ValidatePgVersion(), WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3565 {
3566  int firstchar;
3567  StringInfoData input_message;
3568  sigjmp_buf local_sigjmp_buf;
3569  volatile bool send_ready_for_query = true;
3570  bool disable_idle_in_transaction_timeout = false;
3571 
3572  /* Initialize startup process environment if necessary. */
3573  if (!IsUnderPostmaster)
3574  InitStandaloneProcess(argv[0]);
3575 
3577 
3578  /*
3579  * Set default values for command-line options.
3580  */
3581  if (!IsUnderPostmaster)
3583 
3584  /*
3585  * Parse command-line options.
3586  */
3588 
3589  /* Must have gotten a database name, or have a default (the username) */
3590  if (dbname == NULL)
3591  {
3592  dbname = username;
3593  if (dbname == NULL)
3594  ereport(FATAL,
3595  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3596  errmsg("%s: no database nor user name specified",
3597  progname)));
3598  }
3599 
3600  /* Acquire configuration parameters, unless inherited from postmaster */
3601  if (!IsUnderPostmaster)
3602  {
3604  proc_exit(1);
3605  }
3606 
3607  /*
3608  * Set up signal handlers and masks.
3609  *
3610  * Note that postmaster blocked all signals before forking child process,
3611  * so there is no race condition whereby we might receive a signal before
3612  * we have set up the handler.
3613  *
3614  * Also note: it's best not to use any signals that are SIG_IGNored in the
3615  * postmaster. If such a signal arrives before we are able to change the
3616  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3617  * handler in the postmaster to reserve the signal. (Of course, this isn't
3618  * an issue for signals that are locally generated, such as SIGALRM and
3619  * SIGPIPE.)
3620  */
3621  if (am_walsender)
3622  WalSndSignals();
3623  else
3624  {
3625  pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3626  * file */
3627  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3628  pqsignal(SIGTERM, die); /* cancel current query and exit */
3629 
3630  /*
3631  * In a standalone backend, SIGQUIT can be generated from the keyboard
3632  * easily, while SIGTERM cannot, so we make both signals do die()
3633  * rather than quickdie().
3634  */
3635  if (IsUnderPostmaster)
3636  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3637  else
3638  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3639  InitializeTimeouts(); /* establishes SIGALRM handler */
3640 
3641  /*
3642  * Ignore failure to write to frontend. Note: if frontend closes
3643  * connection, we will notice it and exit cleanly when control next
3644  * returns to outer loop. This seems safer than forcing exit in the
3645  * midst of output during who-knows-what operation...
3646  */
3651 
3652  /*
3653  * Reset some signals that are accepted by postmaster but not by
3654  * backend
3655  */
3656  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3657  * platforms */
3658  }
3659 
3660  pqinitmask();
3661 
3662  if (IsUnderPostmaster)
3663  {
3664  /* We allow SIGQUIT (quickdie) at all times */
3665  sigdelset(&BlockSig, SIGQUIT);
3666  }
3667 
3668  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3669 
3670  if (!IsUnderPostmaster)
3671  {
3672  /*
3673  * Validate we have been given a reasonable-looking DataDir (if under
3674  * postmaster, assume postmaster did this already).
3675  */
3676  Assert(DataDir);
3678 
3679  /* Change into DataDir (if under postmaster, was done already) */
3680  ChangeToDataDir();
3681 
3682  /*
3683  * Create lockfile for data directory.
3684  */
3685  CreateDataDirLockFile(false);
3686 
3687  /* Initialize MaxBackends (if under postmaster, was done already) */
3689  }
3690 
3691  /* Early initialization */
3692  BaseInit();
3693 
3694  /*
3695  * Create a per-backend PGPROC struct in shared memory, except in the
3696  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3697  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3698  * had to do some stuff with LWLocks).
3699  */
3700 #ifdef EXEC_BACKEND
3701  if (!IsUnderPostmaster)
3702  InitProcess();
3703 #else
3704  InitProcess();
3705 #endif
3706 
3707  /* We need to allow SIGINT, etc during the initial transaction */
3709 
3710  /*
3711  * General initialization.
3712  *
3713  * NOTE: if you are tempted to add code in this vicinity, consider putting
3714  * it inside InitPostgres() instead. In particular, anything that
3715  * involves database access should be there, not here.
3716  */
3718 
3719  /*
3720  * If the PostmasterContext is still around, recycle the space; we don't
3721  * need it anymore after InitPostgres completes. Note this does not trash
3722  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3723  * ... else we'd need to copy the Port data first. Also, subsidiary data
3724  * such as the username isn't lost either; see ProcessStartupPacket().
3725  */
3726  if (PostmasterContext)
3727  {
3730  }
3731 
3733 
3734  /*
3735  * Now all GUC states are fully set up. Report them to client if
3736  * appropriate.
3737  */
3739 
3740  /*
3741  * Also set up handler to log session end; we have to wait till now to be
3742  * sure Log_disconnections has its final value.
3743  */
3746 
3747  /* Perform initialization specific to a WAL sender process. */
3748  if (am_walsender)
3749  InitWalSender();
3750 
3751  /*
3752  * process any libraries that should be preloaded at backend start (this
3753  * likewise can't be done until GUC settings are complete)
3754  */
3756 
3757  /*
3758  * Send this backend's cancellation info to the frontend.
3759  */
3761  {
3763 
3764  pq_beginmessage(&buf, 'K');
3765  pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3766  pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3767  pq_endmessage(&buf);
3768  /* Need not flush since ReadyForQuery will do it. */
3769  }
3770 
3771  /* Welcome banner for standalone case */
3773  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3774 
3775  /*
3776  * Create the memory context we will use in the main loop.
3777  *
3778  * MessageContext is reset once per iteration of the main loop, ie, upon
3779  * completion of processing of each command message from the client.
3780  */
3782  "MessageContext",
3784 
3785  /*
3786  * Remember stand-alone backend startup time
3787  */
3788  if (!IsUnderPostmaster)
3790 
3791  /*
3792  * POSTGRES main processing loop begins here
3793  *
3794  * If an exception is encountered, processing resumes here so we abort the
3795  * current transaction and start a new one.
3796  *
3797  * You might wonder why this isn't coded as an infinite loop around a
3798  * PG_TRY construct. The reason is that this is the bottom of the
3799  * exception stack, and so with PG_TRY there would be no exception handler
3800  * in force at all during the CATCH part. By leaving the outermost setjmp
3801  * always active, we have at least some chance of recovering from an error
3802  * during error recovery. (If we get into an infinite loop thereby, it
3803  * will soon be stopped by overflow of elog.c's internal state stack.)
3804  *
3805  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3806  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3807  * is essential in case we longjmp'd out of a signal handler on a platform
3808  * where that leaves the signal blocked. It's not redundant with the
3809  * unblock in AbortTransaction() because the latter is only called if we
3810  * were inside a transaction.
3811  */
3812 
3813  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3814  {
3815  /*
3816  * NOTE: if you are tempted to add more code in this if-block,
3817  * consider the high probability that it should be in
3818  * AbortTransaction() instead. The only stuff done directly here
3819  * should be stuff that is guaranteed to apply *only* for outer-level
3820  * error recovery, such as adjusting the FE/BE protocol status.
3821  */
3822 
3823  /* Since not using PG_TRY, must reset error stack by hand */
3825 
3826  /* Prevent interrupts while cleaning up */
3827  HOLD_INTERRUPTS();
3828 
3829  /*
3830  * Forget any pending QueryCancel request, since we're returning to
3831  * the idle loop anyway, and cancel any active timeout requests. (In
3832  * future we might want to allow some timeout requests to survive, but
3833  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3834  * we got here because of a query cancel interrupting the SIGALRM
3835  * interrupt handler.) Note in particular that we must clear the
3836  * statement and lock timeout indicators, to prevent any future plain
3837  * query cancels from being misreported as timeouts in case we're
3838  * forgetting a timeout cancel.
3839  */
3840  disable_all_timeouts(false);
3841  QueryCancelPending = false; /* second to avoid race condition */
3842 
3843  /* Not reading from the client anymore. */
3844  DoingCommandRead = false;
3845 
3846  /* Make sure libpq is in a good state */
3847  pq_comm_reset();
3848 
3849  /* Report the error to the client and/or server log */
3850  EmitErrorReport();
3851 
3852  /*
3853  * Make sure debug_query_string gets reset before we possibly clobber
3854  * the storage it points at.
3855  */
3857 
3858  /*
3859  * Abort the current transaction in order to recover.
3860  */
3862 
3863  if (am_walsender)
3865 
3866  /*
3867  * We can't release replication slots inside AbortTransaction() as we
3868  * need to be able to start and abort transactions while having a slot
3869  * acquired. But we never need to hold them across top level errors,
3870  * so releasing here is fine. There's another cleanup in ProcKill()
3871  * ensuring we'll correctly cleanup on FATAL errors as well.
3872  */
3873  if (MyReplicationSlot != NULL)
3875 
3876  /* We also want to cleanup temporary slots on error. */
3878 
3879  /*
3880  * Now return to normal top-level context and clear ErrorContext for
3881  * next time.
3882  */
3884  FlushErrorState();
3885 
3886  /*
3887  * If we were handling an extended-query-protocol message, initiate
3888  * skip till next Sync. This also causes us not to issue
3889  * ReadyForQuery (until we get Sync).
3890  */
3892  ignore_till_sync = true;
3893 
3894  /* We don't have a transaction command open anymore */
3895  xact_started = false;
3896 
3897  /*
3898  * If an error occurred while we were reading a message from the
3899  * client, we have potentially lost track of where the previous
3900  * message ends and the next one begins. Even though we have
3901  * otherwise recovered from the error, we cannot safely read any more
3902  * messages from the client, so there isn't much we can do with the
3903  * connection anymore.
3904  */
3905  if (pq_is_reading_msg())
3906  ereport(FATAL,
3907  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3908  errmsg("terminating connection because protocol synchronization was lost")));
3909 
3910  /* Now we can allow interrupts again */
3912  }
3913 
3914  /* We can now handle ereport(ERROR) */
3915  PG_exception_stack = &local_sigjmp_buf;
3916 
3917  if (!ignore_till_sync)
3918  send_ready_for_query = true; /* initially, or after error */
3919 
3920  /*
3921  * Non-error queries loop here.
3922  */
3923 
3924  for (;;)
3925  {
3926  /*
3927  * At top of loop, reset extended-query-message flag, so that any
3928  * errors encountered in "idle" state don't provoke skip.
3929  */
3931 
3932  /*
3933  * Release storage left over from prior query cycle, and create a new
3934  * query input buffer in the cleared MessageContext.
3935  */
3938 
3939  initStringInfo(&input_message);
3940 
3941  /*
3942  * Also consider releasing our catalog snapshot if any, so that it's
3943  * not preventing advance of global xmin while we wait for the client.
3944  */
3946 
3947  /*
3948  * (1) If we've reached idle state, tell the frontend we're ready for
3949  * a new query.
3950  *
3951  * Note: this includes fflush()'ing the last of the prior output.
3952  *
3953  * This is also a good time to send collected statistics to the
3954  * collector, and to update the PS stats display. We avoid doing
3955  * those every time through the message loop because it'd slow down
3956  * processing of batched messages, and because we don't want to report
3957  * uncommitted updates (that confuses autovacuum). The notification
3958  * processor wants a call too, if we are not in a transaction block.
3959  */
3960  if (send_ready_for_query)
3961  {
3963  {
3964  set_ps_display("idle in transaction (aborted)", false);
3966 
3967  /* Start the idle-in-transaction timer */
3969  {
3970  disable_idle_in_transaction_timeout = true;
3973  }
3974  }
3976  {
3977  set_ps_display("idle in transaction", false);
3979 
3980  /* Start the idle-in-transaction timer */
3982  {
3983  disable_idle_in_transaction_timeout = true;
3986  }
3987  }
3988  else
3989  {
3991  pgstat_report_stat(false);
3992 
3993  set_ps_display("idle", false);
3995  }
3996 
3998  send_ready_for_query = false;
3999  }
4000 
4001  /*
4002  * (2) Allow asynchronous signals to be executed immediately if they
4003  * come in while we are waiting for client input. (This must be
4004  * conditional since we don't want, say, reads on behalf of COPY FROM
4005  * STDIN doing the same thing.)
4006  */
4007  DoingCommandRead = true;
4008 
4009  /*
4010  * (3) read a command (loop blocks here)
4011  */
4012  firstchar = ReadCommand(&input_message);
4013 
4014  /*
4015  * (4) disable async signal conditions again.
4016  *
4017  * Query cancel is supposed to be a no-op when there is no query in
4018  * progress, so if a query cancel arrived while we were idle, just
4019  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4020  * it's called when DoingCommandRead is set, so check for interrupts
4021  * before resetting DoingCommandRead.
4022  */
4024  DoingCommandRead = false;
4025 
4026  /*
4027  * (5) turn off the idle-in-transaction timeout
4028  */
4029  if (disable_idle_in_transaction_timeout)
4030  {
4032  disable_idle_in_transaction_timeout = false;
4033  }
4034 
4035  /*
4036  * (6) check for any other interesting events that happened while we
4037  * slept.
4038  */
4039  if (got_SIGHUP)
4040  {
4041  got_SIGHUP = false;
4043  }
4044 
4045  /*
4046  * (7) process the command. But ignore it if we're skipping till
4047  * Sync.
4048  */
4049  if (ignore_till_sync && firstchar != EOF)
4050  continue;
4051 
4052  switch (firstchar)
4053  {
4054  case 'Q': /* simple query */
4055  {
4056  const char *query_string;
4057 
4058  /* Set statement_timestamp() */
4060 
4061  query_string = pq_getmsgstring(&input_message);
4062  pq_getmsgend(&input_message);
4063 
4064  if (am_walsender)
4065  exec_replication_command(query_string);
4066  else
4067  exec_simple_query(query_string);
4068 
4069  send_ready_for_query = true;
4070  }
4071  break;
4072 
4073  case 'P': /* parse */
4074  {
4075  const char *stmt_name;
4076  const char *query_string;
4077  int numParams;
4078  Oid *paramTypes = NULL;
4079 
4080  forbidden_in_wal_sender(firstchar);
4081 
4082  /* Set statement_timestamp() */
4084 
4085  stmt_name = pq_getmsgstring(&input_message);
4086  query_string = pq_getmsgstring(&input_message);
4087  numParams = pq_getmsgint(&input_message, 2);
4088  if (numParams > 0)
4089  {
4090  int i;
4091 
4092  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4093  for (i = 0; i < numParams; i++)
4094  paramTypes[i] = pq_getmsgint(&input_message, 4);
4095  }
4096  pq_getmsgend(&input_message);
4097 
4098  exec_parse_message(query_string, stmt_name,
4099  paramTypes, numParams);
4100  }
4101  break;
4102 
4103  case 'B': /* bind */
4104  forbidden_in_wal_sender(firstchar);
4105 
4106  /* Set statement_timestamp() */
4108 
4109  /*
4110  * this message is complex enough that it seems best to put
4111  * the field extraction out-of-line
4112  */
4113  exec_bind_message(&input_message);
4114  break;
4115 
4116  case 'E': /* execute */
4117  {
4118  const char *portal_name;
4119  int max_rows;
4120 
4121  forbidden_in_wal_sender(firstchar);
4122 
4123  /* Set statement_timestamp() */
4125 
4126  portal_name = pq_getmsgstring(&input_message);
4127  max_rows = pq_getmsgint(&input_message, 4);
4128  pq_getmsgend(&input_message);
4129 
4130  exec_execute_message(portal_name, max_rows);
4131  }
4132  break;
4133 
4134  case 'F': /* fastpath function call */
4135  forbidden_in_wal_sender(firstchar);
4136 
4137  /* Set statement_timestamp() */
4139 
4140  /* Report query to various monitoring facilities. */
4142  set_ps_display("<FASTPATH>", false);
4143 
4144  /* start an xact for this function invocation */
4146 
4147  /*
4148  * Note: we may at this point be inside an aborted
4149  * transaction. We can't throw error for that until we've
4150  * finished reading the function-call message, so
4151  * HandleFunctionRequest() must check for it after doing so.
4152  * Be careful not to do anything that assumes we're inside a
4153  * valid transaction here.
4154  */
4155 
4156  /* switch back to message context */
4158 
4159  if (HandleFunctionRequest(&input_message) == EOF)
4160  {
4161  /* lost frontend connection during F message input */
4162 
4163  /*
4164  * Reset whereToSendOutput to prevent ereport from
4165  * attempting to send any more messages to client.
4166  */
4169 
4170  proc_exit(0);
4171  }
4172 
4173  /* commit the function-invocation transaction */
4175 
4176  send_ready_for_query = true;
4177  break;
4178 
4179  case 'C': /* close */
4180  {
4181  int close_type;
4182  const char *close_target;
4183 
4184  forbidden_in_wal_sender(firstchar);
4185 
4186  close_type = pq_getmsgbyte(&input_message);
4187  close_target = pq_getmsgstring(&input_message);
4188  pq_getmsgend(&input_message);
4189 
4190  switch (close_type)
4191  {
4192  case 'S':
4193  if (close_target[0] != '\0')
4194  DropPreparedStatement(close_target, false);
4195  else
4196  {
4197  /* special-case the unnamed statement */
4199  }
4200  break;
4201  case 'P':
4202  {
4203  Portal portal;
4204 
4205  portal = GetPortalByName(close_target);
4206  if (PortalIsValid(portal))
4207  PortalDrop(portal, false);
4208  }
4209  break;
4210  default:
4211  ereport(ERROR,
4212  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4213  errmsg("invalid CLOSE message subtype %d",
4214  close_type)));
4215  break;
4216  }
4217 
4219  pq_putemptymessage('3'); /* CloseComplete */
4220  }
4221  break;
4222 
4223  case 'D': /* describe */
4224  {
4225  int describe_type;
4226  const char *describe_target;
4227 
4228  forbidden_in_wal_sender(firstchar);
4229 
4230  /* Set statement_timestamp() (needed for xact) */
4232 
4233  describe_type = pq_getmsgbyte(&input_message);
4234  describe_target = pq_getmsgstring(&input_message);
4235  pq_getmsgend(&input_message);
4236 
4237  switch (describe_type)
4238  {
4239  case 'S':
4240  exec_describe_statement_message(describe_target);
4241  break;
4242  case 'P':
4243  exec_describe_portal_message(describe_target);
4244  break;
4245  default:
4246  ereport(ERROR,
4247  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4248  errmsg("invalid DESCRIBE message subtype %d",
4249  describe_type)));
4250  break;
4251  }
4252  }
4253  break;
4254 
4255  case 'H': /* flush */
4256  pq_getmsgend(&input_message);
4258  pq_flush();
4259  break;
4260 
4261  case 'S': /* sync */
4262  pq_getmsgend(&input_message);
4264  send_ready_for_query = true;
4265  break;
4266 
4267  /*
4268  * 'X' means that the frontend is closing down the socket. EOF
4269  * means unexpected loss of frontend connection. Either way,
4270  * perform normal shutdown.
4271  */
4272  case 'X':
4273  case EOF:
4274 
4275  /*
4276  * Reset whereToSendOutput to prevent ereport from attempting
4277  * to send any more messages to client.
4278  */
4281 
4282  /*
4283  * NOTE: if you are tempted to add more code here, DON'T!
4284  * Whatever you had in mind to do should be set up as an
4285  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4286  * it will fail to be called during other backend-shutdown
4287  * scenarios.
4288  */
4289  proc_exit(0);
4290 
4291  case 'd': /* copy data */
4292  case 'c': /* copy done */
4293  case 'f': /* copy fail */
4294 
4295  /*
4296  * Accept but ignore these messages, per protocol spec; we
4297  * probably got here because a COPY failed, and the frontend
4298  * is still sending data.
4299  */
4300  break;
4301 
4302  default:
4303  ereport(FATAL,
4304  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4305  errmsg("invalid frontend message type %d",
4306  firstchar)));
4307  }
4308  } /* end of input-reading loop */
4309 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:2982
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2382
#define SIGUSR1
Definition: win32.h:211
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void BeginReportingGUCOptions(void)
Definition: guc.c:5279
int MyProcPid
Definition: globals.c:38
#define pq_flush()
Definition: libpq.h:40
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:502
static void finish_xact_command(void)
Definition: postgres.c:2451
void ProcessConfigFile(GucContext context)
static volatile sig_atomic_t got_SIGHUP
Definition: postgres.c:129
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2805
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:621
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:218
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1332
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4319
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4318
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
#define SetProcessingMode(mode)
Definition: miscadmin.h:371
void ReplicationSlotCleanup()
Definition: slot.c:412
void BaseInit(void)
Definition: postinit.c:517
unsigned int Oid
Definition: postgres_ext.h:31
volatile bool QueryCancelPending
Definition: globals.c:30
const char * progname
Definition: pg_standby.c:37
#define SIGQUIT
Definition: win32.h:197
void FlushErrorState(void)
Definition: elog.c:1587
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2649
signed int int32
Definition: c.h:253
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1840
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4479
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:103
#define SIG_IGN
Definition: win32.h:193
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1072
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1197
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:41
void WalSndSignals(void)
Definition: walsender.c:2629
#define FATAL
Definition: elog.h:52
static void SigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2683
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
void InitProcess(void)
Definition: proc.c:287
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:65
bool IsUnderPostmaster
Definition: globals.c:100
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1458
Definition: dest.h:89
void ChangeToDataDir(void)
Definition: miscinit.c:114
void ReplicationSlotRelease(void)
Definition: slot.c:374
sigset_t UnBlockSig
Definition: pqsignal.c:22
static bool xact_started
Definition: postgres.c:135
void InitWalSender(void)
#define ereport(elevel, rest)
Definition: elog.h:122
void exec_replication_command(const char *cmd_string)
Definition: walsender.c:1297
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
const char * debug_query_string
Definition: postgres.c:83
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:88
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1196
#define PortalIsValid(p)
Definition: portal.h:197
static void start_xact_command(void)
Definition: postgres.c:2433
static bool doing_extended_query_message
Definition: postgres.c:148
sigset_t BlockSig
Definition: pqsignal.c:22
void process_session_preload_libraries(void)
Definition: miscinit.c:1477
void WalSndErrorCleanup(void)
Definition: walsender.c:254
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4608
void EmitErrorReport(void)
Definition: elog.c:1446
TimestampTz PgStartTime
Definition: timestamp.c:48
#define SIGPIPE
Definition: win32.h:201
#define SIGHUP
Definition: win32.h:196
static char * username
Definition: initdb.c:129
#define InvalidOid
Definition: postgres_ext.h:36
#define SIG_DFL
Definition: win32.h:191
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:432
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
ReplicationSlot * MyReplicationSlot
Definition: slot.c:95
#define pq_comm_reset()
Definition: libpq.h:39
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
void ProcessCompletedNotifies(void)
Definition: async.c:1096
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:527
static bool DoingCommandRead
Definition: postgres.c:142
void InitializeMaxBackends(void)
Definition: postinit.c:495
char * dbname
Definition: streamutil.c:41
MemoryContext MessageContext
Definition: mcxt.c:47
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
static const char * userDoption
Definition: postgres.c:159
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:738
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:558
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:463
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
void ReadyForQuery(CommandDest dest)
Definition: dest.c:230
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:344
void die(SIGNAL_ARGS)
Definition: postgres.c:2618
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2670
static void drop_unnamed_stmt(void)
Definition: postgres.c:2532
char * DataDir
Definition: globals.c:59
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
bool Log_disconnections
Definition: postgres.c:89
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3303
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:677
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:260
CommandDest whereToSendOutput
Definition: postgres.c:86
#define SIGCHLD
Definition: win32.h:206
static bool ignore_till_sync
Definition: postgres.c:149
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2557
MemoryContext PostmasterContext
Definition: mcxt.c:45
#define SIGUSR2
Definition: win32.h:212
static void exec_simple_query(const char *query_string)
Definition: postgres.c:880
int HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:270
void InitializeGUCOptions(void)
Definition: guc.c:4386
void pgstat_report_stat(bool force)
Definition: pgstat.c:747
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:579
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2289
void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3303 of file postgres.c.

References EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), free, FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, NULL, optarg, opterr, optind, OutputFileName, ParseLongOption(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresMain(), and process_startup_options().

3305 {
3306  bool secure = (ctx == PGC_POSTMASTER);
3307  int errs = 0;
3308  GucSource gucsource;
3309  int flag;
3310 
3311  if (secure)
3312  {
3313  gucsource = PGC_S_ARGV; /* switches came from command line */
3314 
3315  /* Ignore the initial --single argument, if present */
3316  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3317  {
3318  argv++;
3319  argc--;
3320  }
3321  }
3322  else
3323  {
3324  gucsource = PGC_S_CLIENT; /* switches came from client */
3325  }
3326 
3327 #ifdef HAVE_INT_OPTERR
3328 
3329  /*
3330  * Turn this off because it's either printed to stderr and not the log
3331  * where we'd want it, or argv[0] is now "--single", which would make for
3332  * a weird error message. We print our own error message below.
3333  */
3334  opterr = 0;
3335 #endif
3336 
3337  /*
3338  * Parse command-line options. CAUTION: keep this in sync with
3339  * postmaster/postmaster.c (the option sets should not conflict) and with
3340  * the common help() function in main/main.c.
3341  */
3342  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3343  {
3344  switch (flag)
3345  {
3346  case 'B':
3347  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3348  break;
3349 
3350  case 'b':
3351  /* Undocumented flag used for binary upgrades */
3352  if (secure)
3353  IsBinaryUpgrade = true;
3354  break;
3355 
3356  case 'C':
3357  /* ignored for consistency with the postmaster */
3358  break;
3359 
3360  case 'D':
3361  if (secure)
3362  userDoption = strdup(optarg);
3363  break;
3364 
3365  case 'd':
3366  set_debug_options(atoi(optarg), ctx, gucsource);
3367  break;
3368 
3369  case 'E':
3370  if (secure)
3371  EchoQuery = true;
3372  break;
3373 
3374  case 'e':
3375  SetConfigOption("datestyle", "euro", ctx, gucsource);
3376  break;
3377 
3378  case 'F':
3379  SetConfigOption("fsync", "false", ctx, gucsource);
3380  break;
3381 
3382  case 'f':
3383  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3384  errs++;
3385  break;
3386 
3387  case 'h':
3388  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3389  break;
3390 
3391  case 'i':
3392  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3393  break;
3394 
3395  case 'j':
3396  if (secure)
3397  UseSemiNewlineNewline = true;
3398  break;
3399 
3400  case 'k':
3401  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3402  break;
3403 
3404  case 'l':
3405  SetConfigOption("ssl", "true", ctx, gucsource);
3406  break;
3407 
3408  case 'N':
3409  SetConfigOption("max_connections", optarg, ctx, gucsource);
3410  break;
3411 
3412  case 'n':
3413  /* ignored for consistency with postmaster */
3414  break;
3415 
3416  case 'O':
3417  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3418  break;
3419 
3420  case 'o':
3421  errs++;
3422  break;
3423 
3424  case 'P':
3425  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3426  break;
3427 
3428  case 'p':
3429  SetConfigOption("port", optarg, ctx, gucsource);
3430  break;
3431 
3432  case 'r':
3433  /* send output (stdout and stderr) to the given file */
3434  if (secure)
3436  break;
3437 
3438  case 'S':
3439  SetConfigOption("work_mem", optarg, ctx, gucsource);
3440  break;
3441 
3442  case 's':
3443  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3444  break;
3445 
3446  case 'T':
3447  /* ignored for consistency with the postmaster */
3448  break;
3449 
3450  case 't':
3451  {
3452  const char *tmp = get_stats_option_name(optarg);
3453 
3454  if (tmp)
3455  SetConfigOption(tmp, "true", ctx, gucsource);
3456  else
3457  errs++;
3458  break;
3459  }
3460 
3461  case 'v':
3462 
3463  /*
3464  * -v is no longer used in normal operation, since
3465  * FrontendProtocol is already set before we get here. We keep
3466  * the switch only for possible use in standalone operation,
3467  * in case we ever support using normal FE/BE protocol with a
3468  * standalone backend.
3469  */
3470  if (secure)
3472  break;
3473 
3474  case 'W':
3475  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3476  break;
3477 
3478  case 'c':
3479  case '-':
3480  {
3481  char *name,
3482  *value;
3483 
3484  ParseLongOption(optarg, &name, &value);
3485  if (!value)
3486  {
3487  if (flag == '-')
3488  ereport(ERROR,
3489  (errcode(ERRCODE_SYNTAX_ERROR),
3490  errmsg("--%s requires a value",
3491  optarg)));
3492  else
3493  ereport(ERROR,
3494  (errcode(ERRCODE_SYNTAX_ERROR),
3495  errmsg("-c %s requires a value",
3496  optarg)));
3497  }
3498  SetConfigOption(name, value, ctx, gucsource);
3499  free(name);
3500  if (value)
3501  free(value);
3502  break;
3503  }
3504 
3505  default:
3506  errs++;
3507  break;
3508  }
3509 
3510  if (errs)
3511  break;
3512  }
3513 
3514  /*
3515  * Optional database name should be there only if *dbname is NULL.
3516  */
3517  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3518  *dbname = strdup(argv[optind++]);
3519 
3520  if (errs || argc != optind)
3521  {
3522  if (errs)
3523  optind--; /* complain about the previous argument */
3524 
3525  /* spell the error message a bit differently depending on context */
3526  if (IsUnderPostmaster)
3527  ereport(FATAL,
3528  (errcode(ERRCODE_SYNTAX_ERROR),
3529  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3530  errhint("Try \"%s --help\" for more information.", progname)));
3531  else
3532  ereport(FATAL,
3533  (errcode(ERRCODE_SYNTAX_ERROR),
3534  errmsg("%s: invalid command-line argument: %s",
3535  progname, argv[optind]),
3536  errhint("Try \"%s --help\" for more information.", progname)));
3537  }
3538 
3539  /*
3540  * Reset getopt(3) library so that it will work correctly in subprocesses
3541  * or when this function is called a second time with another array.
3542  */
3543  optind = 1;
3544 #ifdef HAVE_INT_OPTRESET
3545  optreset = 1; /* some systems need this too */
3546 #endif
3547 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9290
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3221
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3263
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3192
const char * progname
Definition: pg_standby.c:37
bool IsBinaryUpgrade
Definition: globals.c:101
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
GucSource
Definition: guc.h:105
int optind
Definition: getopt.c:51
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
char OutputFileName[MAXPGPATH]
Definition: globals.c:61
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6591
bool IsUnderPostmaster
Definition: globals.c:100
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:50
#define ereport(elevel, rest)
Definition: elog.h:122
uint32 ProtocolVersion
Definition: pqcomm.h:113
static struct @73 value
#define free(a)
Definition: header.h:60
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define NULL
Definition: c.h:226
char * dbname
Definition: streamutil.c:41
const char * name
Definition: encode.c:521
static bool EchoQuery
Definition: postgres.c:160
static const char * userDoption
Definition: postgres.c:159
static bool UseSemiNewlineNewline
Definition: postgres.c:161
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * optarg
Definition: getopt.c:53
ProtocolVersion FrontendProtocol
Definition: globals.c:27
void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 522 of file postgres.c.

References catchupInterruptPending, CHECK_FOR_INTERRUPTS, DoingCommandRead, notifyInterruptPending, ProcDiePending, ProcessCatchupInterrupt(), and ProcessNotifyInterrupt().

Referenced by interactive_getc(), and secure_read().

523 {
524  int save_errno = errno;
525 
526  if (DoingCommandRead)
527  {
528  /* Check for general interrupts that arrived while reading */
530 
531  /* Process sinval catchup interrupts that happened while reading */
534 
535  /* Process sinval catchup interrupts that happened while reading */
538  }
539  else if (ProcDiePending && blocked)
540  {
541  /*
542  * We're dying. It's safe (and sane) to handle that now.
543  */
545  }
546 
547  errno = save_errno;
548 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1726
static bool DoingCommandRead
Definition: postgres.c:142
volatile bool ProcDiePending
Definition: globals.c:31
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:356
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 560 of file postgres.c.

References CHECK_FOR_INTERRUPTS, DestNone, DestRemote, ProcDiePending, and whereToSendOutput.

Referenced by secure_write().

561 {
562  int save_errno = errno;
563 
564  /*
565  * We only want to process the interrupt here if socket writes are
566  * blocking to increase the chance to get an error message to the client.
567  * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
568  * we're blocked we'll never get out of that situation if the client has
569  * died.
570  */
571  if (ProcDiePending && blocked)
572  {
573  /*
574  * We're dying. It's safe (and sane) to handle that now. But we don't
575  * want to send the client the error message as that a) would possibly
576  * block again b) would possibly lead to sending an error message to
577  * the client, while we already started to send something else.
578  */
581 
583  }
584 
585  errno = save_errno;
586 }
Definition: dest.h:88
volatile bool ProcDiePending
Definition: globals.c:31
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
CommandDest whereToSendOutput
Definition: postgres.c:86
void ProcessInterrupts ( void  )

Definition at line 2820 of file postgres.c.

References Assert, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DestNone, DestRemote, DoingCommandRead, ereport, errcode(), errdetail_recovery_conflict(), errhint(), errmsg(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), LOCK_TIMEOUT, LockErrorCleanup(), ParallelMessagePending, pgstat_report_recovery_conflict(), ProcDiePending, PROCSIG_RECOVERY_CONFLICT_DATABASE, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

2821 {
2822  /* OK to accept any interrupts now? */
2823  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2824  return;
2825  InterruptPending = false;
2826 
2827  if (ProcDiePending)
2828  {
2829  ProcDiePending = false;
2830  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2831  LockErrorCleanup();
2832  /* As in quickdie, don't risk sending to client during auth */
2836  ereport(FATAL,
2837  (errcode(ERRCODE_QUERY_CANCELED),
2838  errmsg("canceling authentication due to timeout")));
2839  else if (IsAutoVacuumWorkerProcess())
2840  ereport(FATAL,
2841  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2842  errmsg("terminating autovacuum process due to administrator command")));
2844  {
2846  ereport(FATAL,
2847  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2848  errmsg("terminating connection due to conflict with recovery"),
2850  }
2851  else if (RecoveryConflictPending)
2852  {
2853  /* Currently there is only one non-retryable recovery conflict */
2856  ereport(FATAL,
2857  (errcode(ERRCODE_DATABASE_DROPPED),
2858  errmsg("terminating connection due to conflict with recovery"),
2860  }
2861  else
2862  ereport(FATAL,
2863  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2864  errmsg("terminating connection due to administrator command")));
2865  }
2867  {
2868  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2869  LockErrorCleanup();
2870  /* don't send to client, we already know the connection to be dead. */
2872  ereport(FATAL,
2873  (errcode(ERRCODE_CONNECTION_FAILURE),
2874  errmsg("connection to client lost")));
2875  }
2876 
2877  /*
2878  * If a recovery conflict happens while we are waiting for input from the
2879  * client, the client is presumably just sitting idle in a transaction,
2880  * preventing recovery from making progress. Terminate the connection to
2881  * dislodge it.
2882  */
2884  {
2885  QueryCancelPending = false; /* this trumps QueryCancel */
2886  RecoveryConflictPending = false;
2887  LockErrorCleanup();
2889  ereport(FATAL,
2890  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2891  errmsg("terminating connection due to conflict with recovery"),
2893  errhint("In a moment you should be able to reconnect to the"
2894  " database and repeat your command.")));
2895  }
2896 
2897  if (QueryCancelPending)
2898  {
2899  bool lock_timeout_occurred;
2900  bool stmt_timeout_occurred;
2901 
2902  /*
2903  * Don't allow query cancel interrupts while reading input from the
2904  * client, because we might lose sync in the FE/BE protocol. (Die
2905  * interrupts are OK, because we won't read any further messages from
2906  * the client in that case.)
2907  */
2908  if (QueryCancelHoldoffCount != 0)
2909  {
2910  /*
2911  * Re-arm InterruptPending so that we process the cancel request
2912  * as soon as we're done reading the message.
2913  */
2914  InterruptPending = true;
2915  return;
2916  }
2917 
2918  QueryCancelPending = false;
2919 
2920  /*
2921  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2922  * need to clear both, so always fetch both.
2923  */
2924  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2925  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2926 
2927  /*
2928  * If both were set, we want to report whichever timeout completed
2929  * earlier; this ensures consistent behavior if the machine is slow
2930  * enough that the second timeout triggers before we get here. A tie
2931  * is arbitrarily broken in favor of reporting a lock timeout.
2932  */
2933  if (lock_timeout_occurred && stmt_timeout_occurred &&
2935  lock_timeout_occurred = false; /* report stmt timeout */
2936 
2937  if (lock_timeout_occurred)
2938  {
2939  LockErrorCleanup();
2940  ereport(ERROR,
2941  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2942  errmsg("canceling statement due to lock timeout")));
2943  }
2944  if (stmt_timeout_occurred)
2945  {
2946  LockErrorCleanup();
2947  ereport(ERROR,
2948  (errcode(ERRCODE_QUERY_CANCELED),
2949  errmsg("canceling statement due to statement timeout")));
2950  }
2952  {
2953  LockErrorCleanup();
2954  ereport(ERROR,
2955  (errcode(ERRCODE_QUERY_CANCELED),
2956  errmsg("canceling autovacuum task")));
2957  }
2959  {
2960  RecoveryConflictPending = false;
2961  LockErrorCleanup();
2963  ereport(ERROR,
2964  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2965  errmsg("canceling statement due to conflict with recovery"),
2967  }
2968 
2969  /*
2970  * If we are reading a command from the client, just ignore the cancel
2971  * request --- sending an extra error message won't accomplish
2972  * anything. Otherwise, go ahead and throw the error.
2973  */
2974  if (!DoingCommandRead)
2975  {
2976  LockErrorCleanup();
2977  ereport(ERROR,
2978  (errcode(ERRCODE_QUERY_CANCELED),
2979  errmsg("canceling statement due to user request")));
2980  }
2981  }
2982 
2984  {
2985  /* Has the timeout setting changed since last we looked? */
2987  ereport(FATAL,
2988  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
2989  errmsg("terminating connection due to idle-in-transaction timeout")));
2990  else
2992 
2993  }
2994 
2997 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:34
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:667
int errhint(const char *fmt,...)
Definition: elog.c:987
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1410
volatile bool IdleInTransactionSessionTimeoutPending
Definition: globals.c:33
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:35
int errcode(int sqlerrcode)
Definition: elog.c:575
volatile bool QueryCancelPending
Definition: globals.c:30
volatile bool ClientConnectionLost
Definition: globals.c:32
volatile bool ParallelMessagePending
Definition: parallel.c:99
bool ClientAuthInProgress
Definition: postmaster.c:346
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:705
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:36
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2967
#define ereport(elevel, rest)
Definition: elog.h:122
void LockErrorCleanup(void)
Definition: proc.c:675
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static bool RecoveryConflictPending
Definition: postgres.c:164
static bool RecoveryConflictRetryable
Definition: postgres.c:165
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:633
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2253
volatile bool InterruptPending
Definition: globals.c:29
#define Assert(condition)
Definition: c.h:667
static bool DoingCommandRead
Definition: postgres.c:142
volatile bool ProcDiePending
Definition: globals.c:31
int errmsg(const char *fmt,...)
Definition: elog.c:797
CommandDest whereToSendOutput
Definition: postgres.c:86
void quickdie ( SIGNAL_ARGS  )

Definition at line 2557 of file postgres.c.

References BlockSig, ClientAuthInProgress, DestNone, DestRemote, ereport, errcode(), errdetail(), errhint(), errmsg(), HOLD_INTERRUPTS, on_exit_reset(), PG_SETMASK, SIGQUIT, WARNING, and whereToSendOutput.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), and WalSndSignals().

2558 {
2559  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2560  PG_SETMASK(&BlockSig);
2561 
2562  /*
2563  * Prevent interrupts while exiting; though we just blocked signals that
2564  * would queue new interrupts, one may have been pending. We don't want a
2565  * quickdie() downgraded to a mere query cancel.
2566  */
2567  HOLD_INTERRUPTS();
2568 
2569  /*
2570  * If we're aborting out of client auth, don't risk trying to send
2571  * anything to the client; we will likely violate the protocol, not to
2572  * mention that we may have interrupted the guts of OpenSSL or some
2573  * authentication library.
2574  */
2577 
2578  /*
2579  * Ideally this should be ereport(FATAL), but then we'd not get control
2580  * back...
2581  */
2582  ereport(WARNING,
2583  (errcode(ERRCODE_CRASH_SHUTDOWN),
2584  errmsg("terminating connection because of crash of another server process"),
2585  errdetail("The postmaster has commanded this server process to roll back"
2586  " the current transaction and exit, because another"
2587  " server process exited abnormally and possibly corrupted"
2588  " shared memory."),
2589  errhint("In a moment you should be able to reconnect to the"
2590  " database and repeat your command.")));
2591 
2592  /*
2593  * We DO NOT want to run proc_exit() callbacks -- we're here because
2594  * shared memory may be corrupted, so we don't want to try to clean up our
2595  * transaction. Just nail the windows shut and get out of town. Now that
2596  * there's an atexit callback to prevent third-party code from breaking
2597  * things by calling exit() directly, we have to reset the callbacks
2598  * explicitly to make this work as intended.
2599  */
2600  on_exit_reset();
2601 
2602  /*
2603  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2604  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2605  * backend. This is necessary precisely because we don't clean up our
2606  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2607  * should ensure the postmaster sees this as a crash, too, but no harm in
2608  * being doubly sure.)
2609  */
2610  exit(2);
2611 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SIGQUIT
Definition: win32.h:197
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:346
void on_exit_reset(void)
Definition: ipc.c:396
Definition: dest.h:88
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
CommandDest whereToSendOutput
Definition: postgres.c:86
static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 502 of file postgres.c.

References DestRemote, InteractiveBackend(), SocketBackend(), and whereToSendOutput.

Referenced by PostgresMain().

503 {
504  int result;
505 
507  result = SocketBackend(inBuf);
508  else
509  result = InteractiveBackend(inBuf);
510  return result;
511 }
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:209
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:325
CommandDest whereToSendOutput
Definition: postgres.c:86
void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2700 of file postgres.c.

References Assert, elog, FATAL, HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), IsWaitingForLock(), MyLatch, MyProc, proc_exit_inprogress, ProcDiePending, PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelPending, PGPROC::recoveryConflictPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

2701 {
2702  int save_errno = errno;
2703 
2704  /*
2705  * Don't joggle the elbow of proc_exit
2706  */
2707  if (!proc_exit_inprogress)
2708  {
2709  RecoveryConflictReason = reason;
2710  switch (reason)
2711  {
2713 
2714  /*
2715  * If we aren't waiting for a lock we can never deadlock.
2716  */
2717  if (!IsWaitingForLock())
2718  return;
2719 
2720  /* Intentional drop through to check wait for pin */
2721 
2723 
2724  /*
2725  * If we aren't blocking the Startup process there is nothing
2726  * more to do.
2727  */
2729  return;
2730 
2732 
2733  /* Intentional drop through to error handling */
2734 
2738 
2739  /*
2740  * If we aren't in a transaction any longer then ignore.
2741  */
2743  return;
2744 
2745  /*
2746  * If we can abort just the current subtransaction then we are
2747  * OK to throw an ERROR to resolve the conflict. Otherwise
2748  * drop through to the FATAL case.
2749  *
2750  * XXX other times that we can throw just an ERROR *may* be
2751  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2752  * parent transactions
2753  *
2754  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2755  * by parent transactions and the transaction is not
2756  * transaction-snapshot mode
2757  *
2758  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2759  * cursors open in parent transactions
2760  */
2761  if (!IsSubTransaction())
2762  {
2763  /*
2764  * If we already aborted then we no longer need to cancel.
2765  * We do this here since we do not wish to ignore aborted
2766  * subtransactions, which must cause FATAL, currently.
2767  */
2769  return;
2770 
2771  RecoveryConflictPending = true;
2772  QueryCancelPending = true;
2773  InterruptPending = true;
2774  break;
2775  }
2776 
2777  /* Intentional drop through to session cancel */
2778 
2780  RecoveryConflictPending = true;
2781  ProcDiePending = true;
2782  InterruptPending = true;
2783  break;
2784 
2785  default:
2786  elog(FATAL, "unrecognized conflict mode: %d",
2787  (int) reason);
2788  }
2789 
2791 
2792  /*
2793  * All conflicts apart from database cause dynamic errors where the
2794  * command or transaction can be retried at a later point with some
2795  * potential for success. No need to reset this, since non-retryable
2796  * conflict errors are currently FATAL.
2797  */
2798  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2799  RecoveryConflictRetryable = false;
2800  }
2801 
2802  /*
2803  * Set the process latch. This function essentially emulates signal
2804  * handlers like die() and StatementCancelHandler() and it seems prudent
2805  * to behave similarly as they do.
2806  */
2807  SetLatch(MyLatch);
2808 
2809  errno = save_errno;
2810 }
bool IsWaitingForLock(void)
Definition: proc.c:658
PGPROC * MyProc
Definition: proc.c:67
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:368
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4318
volatile bool QueryCancelPending
Definition: globals.c:30
#define FATAL
Definition: elog.h:52
bool recoveryConflictPending
Definition: proc.h:111
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static bool RecoveryConflictPending
Definition: postgres.c:164
static bool RecoveryConflictRetryable
Definition: postgres.c:165
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:380
#define Assert(condition)
Definition: c.h:667
bool proc_exit_inprogress
Definition: ipc.c:40
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3675
bool IsSubTransaction(void)
Definition: xact.c:4372
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:51
#define elog
Definition: elog.h:219
void ResetUsage ( void  )

Definition at line 4377 of file postgres.c.

References getrusage(), gettimeofday(), NULL, RUSAGE_SELF, Save_r, and Save_t.

Referenced by _bt_leafbuild(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4378 {
4381 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4373
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4374
#define RUSAGE_SELF
Definition: rusagestub.h:23
#define NULL
Definition: c.h:226
void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3075 of file postgres.c.

References stack_base_ptr.

3076 {
3077 #if defined(__ia64__) || defined(__ia64)
3078  stack_base_ptr = base.stack_base_ptr;
3079  register_stack_base_ptr = base.register_stack_base_ptr;
3080 #else
3081  stack_base_ptr = base;
3082 #endif
3083 }
char * stack_base_ptr
Definition: postgres.c:115
void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3192 of file postgres.c.

References PGC_POSTMASTER, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3193 {
3194  if (debug_flag > 0)
3195  {
3196  char debugstr[64];
3197 
3198  sprintf(debugstr, "debug%d", debug_flag);
3199  SetConfigOption("log_min_messages", debugstr, context, source);
3200  }
3201  else
3202  SetConfigOption("log_min_messages", "notice", context, source);
3203 
3204  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3205  {
3206  SetConfigOption("log_connections", "true", context, source);
3207  SetConfigOption("log_disconnections", "true", context, source);
3208  }
3209  if (debug_flag >= 2)
3210  SetConfigOption("log_statement", "all", context, source);
3211  if (debug_flag >= 3)
3212  SetConfigOption("debug_print_parse", "true", context, source);
3213  if (debug_flag >= 4)
3214  SetConfigOption("debug_print_plan", "true", context, source);
3215  if (debug_flag >= 5)
3216  SetConfigOption("debug_print_rewritten", "true", context, source);
3217 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6591
bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3221 of file postgres.c.

References NULL, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3222 {
3223  const char *tmp = NULL;
3224 
3225  switch (arg[0])
3226  {
3227  case 's': /* seqscan */
3228  tmp = "enable_seqscan";
3229  break;
3230  case 'i': /* indexscan */
3231  tmp = "enable_indexscan";
3232  break;
3233  case 'o': /* indexonlyscan */
3234  tmp = "enable_indexonlyscan";
3235  break;
3236  case 'b': /* bitmapscan */
3237  tmp = "enable_bitmapscan";
3238  break;
3239  case 't': /* tidscan */
3240  tmp = "enable_tidscan";
3241  break;