PostgreSQL Source Code  git master
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/logicallauncher.h"
#include "replication/logicalworker.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 log_disconnections (int code, Datum arg)
 
static void enable_statement_timeout (void)
 
static void disable_statement_timeout (void)
 
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, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
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 PostgresSigHupHandler (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 bool xact_started = false
 
static bool DoingCommandRead = false
 
static bool doing_extended_query_message = false
 
static bool ignore_till_sync = false
 
static bool stmt_timeout_active = 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 MemoryContext row_description_context = NULL
 
static StringInfoData row_description_buf
 
static struct rusage Save_r
 
static struct timeval Save_t
 

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3234 of file postgres.c.

References max_stack_depth_bytes.

3235 {
3236  long newval_bytes = newval * 1024L;
3237 
3238  max_stack_depth_bytes = newval_bytes;
3239 }
static long max_stack_depth_bytes
Definition: postgres.c:109
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2130 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().

2131 {
2133  {
2134  long secs;
2135  int usecs;
2136  int msecs;
2137  bool exceeded;
2138 
2141  &secs, &usecs);
2142  msecs = usecs / 1000;
2143 
2144  /*
2145  * This odd-looking test for log_min_duration_statement being exceeded
2146  * is designed to avoid integer overflow with very long durations:
2147  * don't compute secs * 1000 until we've verified it will fit in int.
2148  */
2149  exceeded = (log_min_duration_statement == 0 ||
2151  (secs > log_min_duration_statement / 1000 ||
2152  secs * 1000 + msecs >= log_min_duration_statement)));
2153 
2154  if (exceeded || log_duration)
2155  {
2156  snprintf(msec_str, 32, "%ld.%03d",
2157  secs * 1000 + msecs, usecs % 1000);
2158  if (exceeded && !was_logged)
2159  return 2;
2160  else
2161  return 1;
2162  }
2163  }
2164 
2165  return 0;
2166 }
int log_min_duration_statement
Definition: guc.c:454
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool log_duration
Definition: guc.c:432
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:710

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2093 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

2094 {
2095  ListCell *stmt_item;
2096 
2097  if (log_statement == LOGSTMT_NONE)
2098  return false;
2099  if (log_statement == LOGSTMT_ALL)
2100  return true;
2101 
2102  /* Else we have to inspect the statement(s) to see whether to log */
2103  foreach(stmt_item, stmt_list)
2104  {
2105  Node *stmt = (Node *) lfirst(stmt_item);
2106 
2107  if (GetCommandLogLevel(stmt) <= log_statement)
2108  return true;
2109  }
2110 
2111  return false;
2112 }
Definition: nodes.h:513
#define lfirst(lc)
Definition: pg_list.h:106
int log_statement
Definition: postgres.c:93
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:2931

◆ check_max_stack_depth()

bool check_max_stack_depth ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3217 of file postgres.c.

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

3218 {
3219  long newval_bytes = *newval * 1024L;
3220  long stack_rlimit = get_stack_depth_rlimit();
3221 
3222  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3223  {
3224  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3225  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3226  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3227  return false;
3228  }
3229  return true;
3230 }
#define GUC_check_errdetail
Definition: guc.h:409
long get_stack_depth_rlimit(void)
Definition: postgres.c:4406
#define newval
#define GUC_check_errhint
Definition: guc.h:413
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:31

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3154 of file postgres.c.

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

Referenced by clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), EventTriggerInvoke(), ExecEndNode(), ExecEvalAlternativeSubPlan(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode(), execute(), expand_partitioned_rtentry(), expression_tree_mutator(), expression_tree_walker(), fillQT(), find_composite_type_dependencies(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_partition_dispatch_recurse(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), gistSplit(), hash_range(), hash_range_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), parse_array(), parse_object(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), 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(), recurse_set_operations(), set_append_rel_size(), setPath(), split_array(), transformExprRecurse(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute(), TS_execute_ternary(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3155 {
3156  if (stack_is_too_deep())
3157  {
3158  ereport(ERROR,
3159  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3160  errmsg("stack depth limit exceeded"),
3161  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3162  "after ensuring the platform's stack depth limit is adequate.",
3163  max_stack_depth)));
3164  }
3165 }
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:96
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool stack_is_too_deep(void)
Definition: postgres.c:3168

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2656 of file postgres.c.

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

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

2657 {
2658  int save_errno = errno;
2659 
2660  /* Don't joggle the elbow of proc_exit */
2661  if (!proc_exit_inprogress)
2662  {
2663  InterruptPending = true;
2664  ProcDiePending = true;
2665  }
2666 
2667  /* If we're still here, waken anything waiting on the process latch */
2668  SetLatch(MyLatch);
2669 
2670  /*
2671  * If we're in single user mode, we want to quit immediately - we can't
2672  * rely on latches as they wouldn't work when stdin/stdout is a file.
2673  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2674  * effort just for the benefit of single user mode.
2675  */
2678 
2679  errno = save_errno;
2680 }
void ProcessInterrupts(void)
Definition: postgres.c:2864
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:137
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:52
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

Definition at line 4608 of file postgres.c.

References disable_timeout(), STATEMENT_TIMEOUT, and stmt_timeout_active.

Referenced by exec_execute_message(), and finish_xact_command().

4609 {
4610  if (stmt_timeout_active)
4611  {
4613 
4614  stmt_timeout_active = false;
4615  }
4616 }
static bool stmt_timeout_active
Definition: postgres.c:149
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2570 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2571 {
2572  /* paranoia to avoid a dangling pointer in case of error */
2573  if (unnamed_stmt_psrc)
2574  {
2576 
2577  unnamed_stmt_psrc = NULL;
2578  DropCachedPlan(psrc);
2579  }
2580 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:486

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

Definition at line 4587 of file postgres.c.

References Assert, disable_timeout(), enable_timeout_after(), STATEMENT_TIMEOUT, StatementTimeout, stmt_timeout_active, and xact_started.

Referenced by start_xact_command().

4588 {
4589  /* must be within an xact */
4591 
4592  if (StatementTimeout > 0)
4593  {
4594  if (!stmt_timeout_active)
4595  {
4597  stmt_timeout_active = true;
4598  }
4599  }
4600  else
4602 }
static bool stmt_timeout_active
Definition: postgres.c:149
static bool xact_started
Definition: postgres.c:130
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
#define Assert(condition)
Definition: c.h:688
int StatementTimeout
Definition: proc.c:61
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2273 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().

2274 {
2276  errdetail("abort reason: recovery conflict");
2277 
2278  return 0;
2279 }
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:124
int errdetail(const char *fmt,...)
Definition: elog.c:873

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2175 of file postgres.c.

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

Referenced by exec_simple_query().

2176 {
2177  ListCell *parsetree_item;
2178 
2179  foreach(parsetree_item, raw_parsetree_list)
2180  {
2181  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2182 
2183  if (IsA(parsetree->stmt, ExecuteStmt))
2184  {
2185  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2186  PreparedStatement *pstmt;
2187 
2188  pstmt = FetchPreparedStatement(stmt->name, false);
2189  if (pstmt)
2190  {
2191  errdetail("prepare: %s", pstmt->plansource->query_string);
2192  return 0;
2193  }
2194  }
2195  }
2196 
2197  return 0;
2198 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Node * stmt
Definition: parsenodes.h:1447
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * name
Definition: parsenodes.h:3345
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:495

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2206 of file postgres.c.

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

Referenced by exec_bind_message(), and exec_execute_message().

2207 {
2208  /* We mustn't call user-defined I/O functions when in an aborted xact */
2209  if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2210  {
2211  StringInfoData param_str;
2212  MemoryContext oldcontext;
2213  int paramno;
2214 
2215  /* This code doesn't support dynamic param lists */
2216  Assert(params->paramFetch == NULL);
2217 
2218  /* Make sure any trash is generated in MessageContext */
2219  oldcontext = MemoryContextSwitchTo(MessageContext);
2220 
2221  initStringInfo(&param_str);
2222 
2223  for (paramno = 0; paramno < params->numParams; paramno++)
2224  {
2225  ParamExternData *prm = &params->params[paramno];
2226  Oid typoutput;
2227  bool typisvarlena;
2228  char *pstring;
2229  char *p;
2230 
2231  appendStringInfo(&param_str, "%s$%d = ",
2232  paramno > 0 ? ", " : "",
2233  paramno + 1);
2234 
2235  if (prm->isnull || !OidIsValid(prm->ptype))
2236  {
2237  appendStringInfoString(&param_str, "NULL");
2238  continue;
2239  }
2240 
2241  getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2242 
2243  pstring = OidOutputFunctionCall(typoutput, prm->value);
2244 
2245  appendStringInfoCharMacro(&param_str, '\'');
2246  for (p = pstring; *p; p++)
2247  {
2248  if (*p == '\'') /* double single quotes */
2249  appendStringInfoCharMacro(&param_str, *p);
2250  appendStringInfoCharMacro(&param_str, *p);
2251  }
2252  appendStringInfoCharMacro(&param_str, '\'');
2253 
2254  pfree(pstring);
2255  }
2256 
2257  errdetail("parameters: %s", param_str.data);
2258 
2259  pfree(param_str.data);
2260 
2261  MemoryContextSwitchTo(oldcontext);
2262  }
2263 
2264  return 0;
2265 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:124
Datum value
Definition: params.h:92
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2650
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:594
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:127
ParamFetchHook paramFetch
Definition: params.h:112
void pfree(void *pointer)
Definition: mcxt.c:936
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
int errdetail(const char *fmt,...)
Definition: elog.c:873
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define Assert(condition)
Definition: c.h:688
MemoryContext MessageContext
Definition: mcxt.c:47
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1742
bool isnull
Definition: params.h:93

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

Definition at line 2287 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().

2288 {
2289  switch (RecoveryConflictReason)
2290  {
2292  errdetail("User was holding shared buffer pin for too long.");
2293  break;
2295  errdetail("User was holding a relation lock for too long.");
2296  break;
2298  errdetail("User was or might have been using tablespace that must be dropped.");
2299  break;
2301  errdetail("User query might have needed to see row versions that must be removed.");
2302  break;
2304  errdetail("User transaction caused buffer deadlock with recovery.");
2305  break;
2307  errdetail("User was connected to a database that must be dropped.");
2308  break;
2309  default:
2310  break;
2311  /* no errdetail */
2312  }
2313 
2314  return 0;
2315 }
int errdetail(const char *fmt,...)
Definition: elog.c:873
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1482 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, CachedPlanSource::num_params, ParamListInfoData::numParams, offsetof, OidInputFunctionCall(), OidReceiveFunctionCall(), palloc(), PARAM_FLAG_CONST, CachedPlanSource::param_types, ParamListInfoData::paramCompile, ParamListInfoData::paramCompileArg, ParamListInfoData::paramFetch, ParamListInfoData::paramFetchArg, ParamListInfoData::params, ParamListInfoData::parserSetup, ParamListInfoData::parserSetupArg, ParamExternData::pflags, pfree(), pg_client_to_server(), pgstat_report_activity(), PreparedStatement::plansource, PopActiveSnapshot(), PortalData::portalContext, PortalDefineQuery(), 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().

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

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

Definition at line 2419 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().

2420 {
2421  Portal portal;
2422 
2423  /*
2424  * Start up a transaction command. (Note that this will normally change
2425  * current memory context.) Nothing happens if we are already in one.
2426  */
2428 
2429  /* Switch back to message context */
2431 
2432  portal = GetPortalByName(portal_name);
2433  if (!PortalIsValid(portal))
2434  ereport(ERROR,
2435  (errcode(ERRCODE_UNDEFINED_CURSOR),
2436  errmsg("portal \"%s\" does not exist", portal_name)));
2437 
2438  /*
2439  * If we are in aborted transaction state, we can't run
2440  * SendRowDescriptionMessage(), because that needs catalog accesses.
2441  * Hence, refuse to Describe portals that return data. (We shouldn't just
2442  * refuse all Describes, since that might break the ability of some
2443  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2444  * blindly Describes whatever it does.)
2445  */
2447  portal->tupDesc)
2448  ereport(ERROR,
2449  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2450  errmsg("current transaction is aborted, "
2451  "commands ignored until end of transaction block"),
2452  errdetail_abort()));
2453 
2455  return; /* can't actually do anything... */
2456 
2457  if (portal->tupDesc)
2459  portal->tupDesc,
2460  FetchPortalTargetList(portal),
2461  portal->formats);
2462  else
2463  pq_putemptymessage('n'); /* NoData */
2464 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
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:390
static int errdetail_abort(void)
Definition: postgres.c:2273
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define PortalIsValid(p)
Definition: portal.h:199
static void start_xact_command(void)
Definition: postgres.c:2471
int16 * formats
Definition: portal.h:157
static StringInfoData row_description_buf
Definition: postgres.c:170
TupleDesc tupDesc
Definition: portal.h:155
MemoryContext MessageContext
Definition: mcxt.c:47
int errmsg(const char *fmt,...)
Definition: elog.c:797
CommandDest whereToSendOutput
Definition: postgres.c:88
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:338
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:197

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2323 of file postgres.c.

References Assert, CachedPlanGetTargetList(), DestRemote, ereport, errcode(), errdetail_abort(), errmsg(), ERROR, FetchPreparedStatement(), CachedPlanSource::fixed_result, i, IsAbortedTransactionBlockState(), MemoryContextSwitchTo(), MessageContext, CachedPlanSource::num_params, CachedPlanSource::param_types, PreparedStatement::plansource, pq_beginmessage_reuse(), pq_endmessage_reuse(), pq_putemptymessage(), pq_sendint16(), pq_sendint32(), CachedPlanSource::resultDesc, SendRowDescriptionMessage(), start_xact_command(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

2324 {
2325  CachedPlanSource *psrc;
2326  int i;
2327 
2328  /*
2329  * Start up a transaction command. (Note that this will normally change
2330  * current memory context.) Nothing happens if we are already in one.
2331  */
2333 
2334  /* Switch back to message context */
2336 
2337  /* Find prepared statement */
2338  if (stmt_name[0] != '\0')
2339  {
2340  PreparedStatement *pstmt;
2341 
2342  pstmt = FetchPreparedStatement(stmt_name, true);
2343  psrc = pstmt->plansource;
2344  }
2345  else
2346  {
2347  /* special-case the unnamed statement */
2348  psrc = unnamed_stmt_psrc;
2349  if (!psrc)
2350  ereport(ERROR,
2351  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2352  errmsg("unnamed prepared statement does not exist")));
2353  }
2354 
2355  /* Prepared statements shouldn't have changeable result descs */
2356  Assert(psrc->fixed_result);
2357 
2358  /*
2359  * If we are in aborted transaction state, we can't run
2360  * SendRowDescriptionMessage(), because that needs catalog accesses.
2361  * Hence, refuse to Describe statements that return data. (We shouldn't
2362  * just refuse all Describes, since that might break the ability of some
2363  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2364  * blindly Describes whatever it does.) We can Describe parameters
2365  * without doing anything dangerous, so we don't restrict that.
2366  */
2368  psrc->resultDesc)
2369  ereport(ERROR,
2370  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2371  errmsg("current transaction is aborted, "
2372  "commands ignored until end of transaction block"),
2373  errdetail_abort()));
2374 
2376  return; /* can't actually do anything... */
2377 
2378  /*
2379  * First describe the parameters...
2380  */
2381  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2382  * message type */
2384 
2385  for (i = 0; i < psrc->num_params; i++)
2386  {
2387  Oid ptype = psrc->param_types[i];
2388 
2389  pq_sendint32(&row_description_buf, (int) ptype);
2390  }
2392 
2393  /*
2394  * Next send RowDescription or NoData to describe the result...
2395  */
2396  if (psrc->resultDesc)
2397  {
2398  List *tlist;
2399 
2400  /* Get the plan's primary targetlist */
2401  tlist = CachedPlanGetTargetList(psrc, NULL);
2402 
2404  psrc->resultDesc,
2405  tlist,
2406  NULL);
2407  }
2408  else
2409  pq_putemptymessage('n'); /* NoData */
2410 
2411 }
CachedPlanSource * plansource
Definition: prepare.h:31
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
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:390
static int errdetail_abort(void)
Definition: postgres.c:2273
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc resultDesc
Definition: plancache.h:92
#define ERROR
Definition: elog.h:43
Oid * param_types
Definition: plancache.h:86
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1425
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:2471
static StringInfoData row_description_buf
Definition: postgres.c:170
#define Assert(condition)
Definition: c.h:688
MemoryContext MessageContext
Definition: mcxt.c:47
static void pq_sendint16(StringInfo buf, int16 i)
Definition: pqformat.h:140
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
CommandDest whereToSendOutput
Definition: postgres.c:88
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:197
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:495
Definition: pg_list.h:45
void pq_endmessage_reuse(StringInfo buf)
Definition: pqformat.c:316
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition: pqformat.c:108

◆ exec_execute_message()

static void exec_execute_message ( const char *  portal_name,
long  max_rows 
)
static

Definition at line 1867 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, generate_unaccent_rules::dest, DestRemote, DestRemoteExecute, disable_statement_timeout(), EndCommand(), ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), ERROR, FETCH_ALL, finish_xact_command(), GetPortalByName(), IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), LOG, log_statement_stats, NIL, 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().

1868 {
1869  CommandDest dest;
1870  DestReceiver *receiver;
1871  Portal portal;
1872  bool completed;
1873  char completionTag[COMPLETION_TAG_BUFSIZE];
1874  const char *sourceText;
1875  const char *prepStmtName;
1876  ParamListInfo portalParams;
1877  bool save_log_statement_stats = log_statement_stats;
1878  bool is_xact_command;
1879  bool execute_is_fetch;
1880  bool was_logged = false;
1881  char msec_str[32];
1882 
1883  /* Adjust destination to tell printtup.c what to do */
1884  dest = whereToSendOutput;
1885  if (dest == DestRemote)
1886  dest = DestRemoteExecute;
1887 
1888  portal = GetPortalByName(portal_name);
1889  if (!PortalIsValid(portal))
1890  ereport(ERROR,
1891  (errcode(ERRCODE_UNDEFINED_CURSOR),
1892  errmsg("portal \"%s\" does not exist", portal_name)));
1893 
1894  /*
1895  * If the original query was a null string, just return
1896  * EmptyQueryResponse.
1897  */
1898  if (portal->commandTag == NULL)
1899  {
1900  Assert(portal->stmts == NIL);
1901  NullCommand(dest);
1902  return;
1903  }
1904 
1905  /* Does the portal contain a transaction command? */
1906  is_xact_command = IsTransactionStmtList(portal->stmts);
1907 
1908  /*
1909  * We must copy the sourceText and prepStmtName into MessageContext in
1910  * case the portal is destroyed during finish_xact_command. Can avoid the
1911  * copy if it's not an xact command, though.
1912  */
1913  if (is_xact_command)
1914  {
1915  sourceText = pstrdup(portal->sourceText);
1916  if (portal->prepStmtName)
1917  prepStmtName = pstrdup(portal->prepStmtName);
1918  else
1919  prepStmtName = "<unnamed>";
1920 
1921  /*
1922  * An xact command shouldn't have any parameters, which is a good
1923  * thing because they wouldn't be around after finish_xact_command.
1924  */
1925  portalParams = NULL;
1926  }
1927  else
1928  {
1929  sourceText = portal->sourceText;
1930  if (portal->prepStmtName)
1931  prepStmtName = portal->prepStmtName;
1932  else
1933  prepStmtName = "<unnamed>";
1934  portalParams = portal->portalParams;
1935  }
1936 
1937  /*
1938  * Report query to various monitoring facilities.
1939  */
1940  debug_query_string = sourceText;
1941 
1943 
1944  set_ps_display(portal->commandTag, false);
1945 
1946  if (save_log_statement_stats)
1947  ResetUsage();
1948 
1949  BeginCommand(portal->commandTag, dest);
1950 
1951  /*
1952  * Create dest receiver in MessageContext (we don't want it in transaction
1953  * context, because that may get deleted if portal contains VACUUM).
1954  */
1955  receiver = CreateDestReceiver(dest);
1956  if (dest == DestRemoteExecute)
1957  SetRemoteDestReceiverParams(receiver, portal);
1958 
1959  /*
1960  * Ensure we are in a transaction command (this should normally be the
1961  * case already due to prior BIND).
1962  */
1964 
1965  /*
1966  * If we re-issue an Execute protocol request against an existing portal,
1967  * then we are only fetching more rows rather than completely re-executing
1968  * the query from the start. atStart is never reset for a v3 portal, so we
1969  * are safe to use this check.
1970  */
1971  execute_is_fetch = !portal->atStart;
1972 
1973  /* Log immediately if dictated by log_statement */
1974  if (check_log_statement(portal->stmts))
1975  {
1976  ereport(LOG,
1977  (errmsg("%s %s%s%s: %s",
1978  execute_is_fetch ?
1979  _("execute fetch from") :
1980  _("execute"),
1981  prepStmtName,
1982  *portal_name ? "/" : "",
1983  *portal_name ? portal_name : "",
1984  sourceText),
1985  errhidestmt(true),
1986  errdetail_params(portalParams)));
1987  was_logged = true;
1988  }
1989 
1990  /*
1991  * If we are in aborted transaction state, the only portals we can
1992  * actually run are those containing COMMIT or ROLLBACK commands.
1993  */
1995  !IsTransactionExitStmtList(portal->stmts))
1996  ereport(ERROR,
1997  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1998  errmsg("current transaction is aborted, "
1999  "commands ignored until end of transaction block"),
2000  errdetail_abort()));
2001 
2002  /* Check for cancel signal before we start execution */
2004 
2005  /*
2006  * Okay to run the portal.
2007  */
2008  if (max_rows <= 0)
2009  max_rows = FETCH_ALL;
2010 
2011  completed = PortalRun(portal,
2012  max_rows,
2013  true, /* always top level */
2014  !execute_is_fetch && max_rows == FETCH_ALL,
2015  receiver,
2016  receiver,
2017  completionTag);
2018 
2019  receiver->rDestroy(receiver);
2020 
2021  if (completed)
2022  {
2023  if (is_xact_command)
2024  {
2025  /*
2026  * If this was a transaction control statement, commit it. We
2027  * will start a new xact command for the next command (if any).
2028  */
2030  }
2031  else
2032  {
2033  /*
2034  * We need a CommandCounterIncrement after every query, except
2035  * those that start or end a transaction block.
2036  */
2038 
2039  /* full command has been executed, reset timeout */
2041  }
2042 
2043  /* Send appropriate CommandComplete to client */
2044  EndCommand(completionTag, dest);
2045  }
2046  else
2047  {
2048  /* Portal run not complete, so send PortalSuspended */
2050  pq_putemptymessage('s');
2051  }
2052 
2053  /*
2054  * Emit duration logging if appropriate.
2055  */
2056  switch (check_log_duration(msec_str, was_logged))
2057  {
2058  case 1:
2059  ereport(LOG,
2060  (errmsg("duration: %s ms", msec_str),
2061  errhidestmt(true)));
2062  break;
2063  case 2:
2064  ereport(LOG,
2065  (errmsg("duration: %s ms %s %s%s%s: %s",
2066  msec_str,
2067  execute_is_fetch ?
2068  _("execute fetch from") :
2069  _("execute"),
2070  prepStmtName,
2071  *portal_name ? "/" : "",
2072  *portal_name ? portal_name : "",
2073  sourceText),
2074  errhidestmt(true),
2075  errdetail_params(portalParams)));
2076  break;
2077  }
2078 
2079  if (save_log_statement_stats)
2080  ShowUsage("EXECUTE MESSAGE STATISTICS");
2081 
2082  debug_query_string = NULL;
2083 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2555
#define NIL
Definition: pg_list.h:69
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:106
static void finish_xact_command(void)
Definition: postgres.c:2491
CommandDest
Definition: dest.h:86
bool log_statement_stats
Definition: guc.c:441
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void ShowUsage(const char *title)
Definition: postgres.c:4449
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
char * pstrdup(const char *in)
Definition: mcxt.c:1063
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, char *completionTag)
Definition: pquery.c:689
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:390
static int errdetail_abort(void)
Definition: postgres.c:2273
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:99
#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:2130
void ResetUsage(void)
Definition: postgres.c:4442
static void disable_statement_timeout(void)
Definition: postgres.c:4608
ParamListInfo portalParams
Definition: portal.h:139
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:157
#define ERROR
Definition: elog.h:43
const char * commandTag
Definition: portal.h:135
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2206
#define ereport(elevel, rest)
Definition: elog.h:122
const char * debug_query_string
Definition: postgres.c:85
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2093
#define PortalIsValid(p)
Definition: portal.h:199
static void start_xact_command(void)
Definition: postgres.c:2471
void CommandCounterIncrement(void)
Definition: xact.c:915
const char * sourceText
Definition: portal.h:134
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define Assert(condition)
Definition: c.h:688
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2540
bool atStart
Definition: portal.h:186
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
CommandDest whereToSendOutput
Definition: postgres.c:88
#define _(x)
Definition: elog.c:84
const char * prepStmtName
Definition: portal.h:118
void NullCommand(CommandDest dest)
Definition: dest.c:198
#define FETCH_ALL
Definition: parsenodes.h:2682

◆ exec_parse_message()

static void exec_parse_message ( const char *  query_string,
const char *  stmt_name,
Oid paramTypes,
int  numParams 
)
static

Definition at line 1219 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_node, list_length(), LOG, log_parser_stats, log_statement_stats, MemoryContextSetParent(), MemoryContextSwitchTo(), MessageContext, NIL, 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().

1223 {
1224  MemoryContext unnamed_stmt_context = NULL;
1225  MemoryContext oldcontext;
1226  List *parsetree_list;
1227  RawStmt *raw_parse_tree;
1228  const char *commandTag;
1229  List *querytree_list;
1230  CachedPlanSource *psrc;
1231  bool is_named;
1232  bool save_log_statement_stats = log_statement_stats;
1233  char msec_str[32];
1234 
1235  /*
1236  * Report query to various monitoring facilities.
1237  */
1238  debug_query_string = query_string;
1239 
1240  pgstat_report_activity(STATE_RUNNING, query_string);
1241 
1242  set_ps_display("PARSE", false);
1243 
1244  if (save_log_statement_stats)
1245  ResetUsage();
1246 
1247  ereport(DEBUG2,
1248  (errmsg("parse %s: %s",
1249  *stmt_name ? stmt_name : "<unnamed>",
1250  query_string)));
1251 
1252  /*
1253  * Start up a transaction command so we can run parse analysis etc. (Note
1254  * that this will normally change current memory context.) Nothing happens
1255  * if we are already in one. This also arms the statement timeout if
1256  * necessary.
1257  */
1259 
1260  /*
1261  * Switch to appropriate context for constructing parsetrees.
1262  *
1263  * We have two strategies depending on whether the prepared statement is
1264  * named or not. For a named prepared statement, we do parsing in
1265  * MessageContext and copy the finished trees into the prepared
1266  * statement's plancache entry; then the reset of MessageContext releases
1267  * temporary space used by parsing and rewriting. For an unnamed prepared
1268  * statement, we assume the statement isn't going to hang around long, so
1269  * getting rid of temp space quickly is probably not worth the costs of
1270  * copying parse trees. So in this case, we create the plancache entry's
1271  * query_context here, and do all the parsing work therein.
1272  */
1273  is_named = (stmt_name[0] != '\0');
1274  if (is_named)
1275  {
1276  /* Named prepared statement --- parse in MessageContext */
1277  oldcontext = MemoryContextSwitchTo(MessageContext);
1278  }
1279  else
1280  {
1281  /* Unnamed prepared statement --- release any prior unnamed stmt */
1283  /* Create context for parsing */
1284  unnamed_stmt_context =
1286  "unnamed prepared statement",
1288  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1289  }
1290 
1291  /*
1292  * Do basic parsing of the query or queries (this should be safe even if
1293  * we are in aborted transaction state!)
1294  */
1295  parsetree_list = pg_parse_query(query_string);
1296 
1297  /*
1298  * We only allow a single user statement in a prepared statement. This is
1299  * mainly to keep the protocol simple --- otherwise we'd need to worry
1300  * about multiple result tupdescs and things like that.
1301  */
1302  if (list_length(parsetree_list) > 1)
1303  ereport(ERROR,
1304  (errcode(ERRCODE_SYNTAX_ERROR),
1305  errmsg("cannot insert multiple commands into a prepared statement")));
1306 
1307  if (parsetree_list != NIL)
1308  {
1309  Query *query;
1310  bool snapshot_set = false;
1311  int i;
1312 
1313  raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1314 
1315  /*
1316  * Get the command name for possible use in status display.
1317  */
1318  commandTag = CreateCommandTag(raw_parse_tree->stmt);
1319 
1320  /*
1321  * If we are in an aborted transaction, reject all commands except
1322  * COMMIT/ROLLBACK. It is important that this test occur before we
1323  * try to do parse analysis, rewrite, or planning, since all those
1324  * phases try to do database accesses, which may fail in abort state.
1325  * (It might be safe to allow some additional utility commands in this
1326  * state, but not many...)
1327  */
1329  !IsTransactionExitStmt(raw_parse_tree->stmt))
1330  ereport(ERROR,
1331  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1332  errmsg("current transaction is aborted, "
1333  "commands ignored until end of transaction block"),
1334  errdetail_abort()));
1335 
1336  /*
1337  * Create the CachedPlanSource before we do parse analysis, since it
1338  * needs to see the unmodified raw parse tree.
1339  */
1340  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1341 
1342  /*
1343  * Set up a snapshot if parse analysis will need one.
1344  */
1345  if (analyze_requires_snapshot(raw_parse_tree))
1346  {
1348  snapshot_set = true;
1349  }
1350 
1351  /*
1352  * Analyze and rewrite the query. Note that the originally specified
1353  * parameter set is not required to be complete, so we have to use
1354  * parse_analyze_varparams().
1355  */
1356  if (log_parser_stats)
1357  ResetUsage();
1358 
1359  query = parse_analyze_varparams(raw_parse_tree,
1360  query_string,
1361  &paramTypes,
1362  &numParams);
1363 
1364  /*
1365  * Check all parameter types got determined.
1366  */
1367  for (i = 0; i < numParams; i++)
1368  {
1369  Oid ptype = paramTypes[i];
1370 
1371  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1372  ereport(ERROR,
1373  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1374  errmsg("could not determine data type of parameter $%d",
1375  i + 1)));
1376  }
1377 
1378  if (log_parser_stats)
1379  ShowUsage("PARSE ANALYSIS STATISTICS");
1380 
1381  querytree_list = pg_rewrite_query(query);
1382 
1383  /* Done with the snapshot used for parsing */
1384  if (snapshot_set)
1386  }
1387  else
1388  {
1389  /* Empty input string. This is legal. */
1390  raw_parse_tree = NULL;
1391  commandTag = NULL;
1392  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1393  querytree_list = NIL;
1394  }
1395 
1396  /*
1397  * CachedPlanSource must be a direct child of MessageContext before we
1398  * reparent unnamed_stmt_context under it, else we have a disconnected
1399  * circular subgraph. Klugy, but less so than flipping contexts even more
1400  * above.
1401  */
1402  if (unnamed_stmt_context)
1404 
1405  /* Finish filling in the CachedPlanSource */
1406  CompleteCachedPlan(psrc,
1407  querytree_list,
1408  unnamed_stmt_context,
1409  paramTypes,
1410  numParams,
1411  NULL,
1412  NULL,
1413  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1414  true); /* fixed result */
1415 
1416  /* If we got a cancel signal during analysis, quit */
1418 
1419  if (is_named)
1420  {
1421  /*
1422  * Store the query as a prepared statement.
1423  */
1424  StorePreparedStatement(stmt_name, psrc, false);
1425  }
1426  else
1427  {
1428  /*
1429  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1430  */
1431  SaveCachedPlan(psrc);
1432  unnamed_stmt_psrc = psrc;
1433  }
1434 
1435  MemoryContextSwitchTo(oldcontext);
1436 
1437  /*
1438  * We do NOT close the open transaction command here; that only happens
1439  * when the client sends Sync. Instead, do CommandCounterIncrement just
1440  * in case something happened during parse/plan.
1441  */
1443 
1444  /*
1445  * Send ParseComplete.
1446  */
1448  pq_putemptymessage('1');
1449 
1450  /*
1451  * Emit duration logging if appropriate.
1452  */
1453  switch (check_log_duration(msec_str, false))
1454  {
1455  case 1:
1456  ereport(LOG,
1457  (errmsg("duration: %s ms", msec_str),
1458  errhidestmt(true)));
1459  break;
1460  case 2:
1461  ereport(LOG,
1462  (errmsg("duration: %s ms parse %s: %s",
1463  msec_str,
1464  *stmt_name ? stmt_name : "<unnamed>",
1465  query_string),
1466  errhidestmt(true)));
1467  break;
1468  }
1469 
1470  if (save_log_statement_stats)
1471  ShowUsage("PARSE MESSAGE STATISTICS");
1472 
1473  debug_query_string = NULL;
1474 }
MemoryContext context
Definition: plancache.h:93
#define NIL
Definition: pg_list.h:69
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:348
bool log_parser_stats
Definition: guc.c:438
bool log_statement_stats
Definition: guc.c:441
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void ShowUsage(const char *title)
Definition: postgres.c:4449
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:317
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
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:130
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2273
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:114
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2523
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2130
void ResetUsage(void)
Definition: postgres.c:4442
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:607
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define DEBUG2
Definition: elog.h:24
Node * stmt
Definition: parsenodes.h:1447
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
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:152
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2071
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
const char * debug_query_string
Definition: postgres.c:85
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:738
static void start_xact_command(void)
Definition: postgres.c:2471
void CommandCounterIncrement(void)
Definition: xact.c:915
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:453
#define InvalidOid
Definition: postgres_ext.h:36
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:441
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:325
static int list_length(const List *l)
Definition: pg_list.h:89
MemoryContext MessageContext
Definition: mcxt.c:47
#define UNKNOWNOID
Definition: pg_type.h:431
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2647
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void drop_unnamed_stmt(void)
Definition: postgres.c:2570
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
CommandDest whereToSendOutput
Definition: postgres.c:88
Definition: pg_list.h:45

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 889 of file postgres.c.

References analyze_requires_snapshot(), BeginCommand(), BeginImplicitTransactionBlock(), 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, generate_unaccent_rules::dest, DestRemote, drop_unnamed_stmt(), EndCommand(), EndImplicitTransactionBlock(), ereport, errcode(), errdetail_abort(), errdetail_execute(), errhidestmt(), errmsg(), ERROR, FETCH_ALL, finish_xact_command(), format, GetPortalByName(), GetTransactionSnapshot(), InvalidSnapshot, IsA, IsAbortedTransactionBlockState(), FetchStmt::ismove, IsTransactionExitStmt(), lfirst_node, list_length(), lnext, LOG, log_statement_stats, MemoryContextSwitchTo(), MessageContext, 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().

890 {
892  MemoryContext oldcontext;
893  List *parsetree_list;
894  ListCell *parsetree_item;
895  bool save_log_statement_stats = log_statement_stats;
896  bool was_logged = false;
897  bool use_implicit_block;
898  char msec_str[32];
899 
900  /*
901  * Report query to various monitoring facilities.
902  */
903  debug_query_string = query_string;
904 
905  pgstat_report_activity(STATE_RUNNING, query_string);
906 
907  TRACE_POSTGRESQL_QUERY_START(query_string);
908 
909  /*
910  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
911  * results because ResetUsage wasn't called.
912  */
913  if (save_log_statement_stats)
914  ResetUsage();
915 
916  /*
917  * Start up a transaction command. All queries generated by the
918  * query_string will be in this same command block, *unless* we find a
919  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
920  * one of those, else bad things will happen in xact.c. (Note that this
921  * will normally change current memory context.)
922  */
924 
925  /*
926  * Zap any pre-existing unnamed statement. (While not strictly necessary,
927  * it seems best to define simple-Query mode as if it used the unnamed
928  * statement and portal; this ensures we recover any storage used by prior
929  * unnamed operations.)
930  */
932 
933  /*
934  * Switch to appropriate context for constructing parsetrees.
935  */
937 
938  /*
939  * Do basic parsing of the query or queries (this should be safe even if
940  * we are in aborted transaction state!)
941  */
942  parsetree_list = pg_parse_query(query_string);
943 
944  /* Log immediately if dictated by log_statement */
945  if (check_log_statement(parsetree_list))
946  {
947  ereport(LOG,
948  (errmsg("statement: %s", query_string),
949  errhidestmt(true),
950  errdetail_execute(parsetree_list)));
951  was_logged = true;
952  }
953 
954  /*
955  * Switch back to transaction context to enter the loop.
956  */
957  MemoryContextSwitchTo(oldcontext);
958 
959  /*
960  * For historical reasons, if multiple SQL statements are given in a
961  * single "simple Query" message, we execute them as a single transaction,
962  * unless explicit transaction control commands are included to make
963  * portions of the list be separate transactions. To represent this
964  * behavior properly in the transaction machinery, we use an "implicit"
965  * transaction block.
966  */
967  use_implicit_block = (list_length(parsetree_list) > 1);
968 
969  /*
970  * Run through the raw parsetree(s) and process each one.
971  */
972  foreach(parsetree_item, parsetree_list)
973  {
974  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
975  bool snapshot_set = false;
976  const char *commandTag;
977  char completionTag[COMPLETION_TAG_BUFSIZE];
978  List *querytree_list,
979  *plantree_list;
980  Portal portal;
981  DestReceiver *receiver;
982  int16 format;
983 
984  /*
985  * Get the command name for use in status display (it also becomes the
986  * default completion tag, down inside PortalRun). Set ps_status and
987  * do any special start-of-SQL-command processing needed by the
988  * destination.
989  */
990  commandTag = CreateCommandTag(parsetree->stmt);
991 
992  set_ps_display(commandTag, false);
993 
994  BeginCommand(commandTag, dest);
995 
996  /*
997  * If we are in an aborted transaction, reject all commands except
998  * COMMIT/ABORT. It is important that this test occur before we try
999  * to do parse analysis, rewrite, or planning, since all those phases
1000  * try to do database accesses, which may fail in abort state. (It
1001  * might be safe to allow some additional utility commands in this
1002  * state, but not many...)
1003  */
1005  !IsTransactionExitStmt(parsetree->stmt))
1006  ereport(ERROR,
1007  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1008  errmsg("current transaction is aborted, "
1009  "commands ignored until end of transaction block"),
1010  errdetail_abort()));
1011 
1012  /* Make sure we are in a transaction command */
1014 
1015  /*
1016  * If using an implicit transaction block, and we're not already in a
1017  * transaction block, start an implicit block to force this statement
1018  * to be grouped together with any following ones. (We must do this
1019  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1020  * list would cause later statements to not be grouped.)
1021  */
1022  if (use_implicit_block)
1024 
1025  /* If we got a cancel signal in parsing or prior command, quit */
1027 
1028  /*
1029  * Set up a snapshot if parse analysis/planning will need one.
1030  */
1031  if (analyze_requires_snapshot(parsetree))
1032  {
1034  snapshot_set = true;
1035  }
1036 
1037  /*
1038  * OK to analyze, rewrite, and plan this query.
1039  *
1040  * Switch to appropriate context for constructing querytrees (again,
1041  * these must outlive the execution context).
1042  */
1043  oldcontext = MemoryContextSwitchTo(MessageContext);
1044 
1045  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1046  NULL, 0, NULL);
1047 
1048  plantree_list = pg_plan_queries(querytree_list,
1049  CURSOR_OPT_PARALLEL_OK, NULL);
1050 
1051  /* Done with the snapshot used for parsing/planning */
1052  if (snapshot_set)
1054 
1055  /* If we got a cancel signal in analysis or planning, quit */
1057 
1058  /*
1059  * Create unnamed portal to run the query or queries in. If there
1060  * already is one, silently drop it.
1061  */
1062  portal = CreatePortal("", true, true);
1063  /* Don't display the portal in pg_cursors */
1064  portal->visible = false;
1065 
1066  /*
1067  * We don't have to copy anything into the portal, because everything
1068  * we are passing here is in MessageContext, which will outlive the
1069  * portal anyway.
1070  */
1071  PortalDefineQuery(portal,
1072  NULL,
1073  query_string,
1074  commandTag,
1075  plantree_list,
1076  NULL);
1077 
1078  /*
1079  * Start the portal. No parameters here.
1080  */
1081  PortalStart(portal, NULL, 0, InvalidSnapshot);
1082 
1083  /*
1084  * Select the appropriate output format: text unless we are doing a
1085  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1086  * --- but it avoids grottiness in other places. Ah, the joys of
1087  * backward compatibility...)
1088  */
1089  format = 0; /* TEXT is default */
1090  if (IsA(parsetree->stmt, FetchStmt))
1091  {
1092  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1093 
1094  if (!stmt->ismove)
1095  {
1096  Portal fportal = GetPortalByName(stmt->portalname);
1097 
1098  if (PortalIsValid(fportal) &&
1099  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1100  format = 1; /* BINARY */
1101  }
1102  }
1103  PortalSetResultFormat(portal, 1, &format);
1104 
1105  /*
1106  * Now we can create the destination receiver object.
1107  */
1108  receiver = CreateDestReceiver(dest);
1109  if (dest == DestRemote)
1110  SetRemoteDestReceiverParams(receiver, portal);
1111 
1112  /*
1113  * Switch back to transaction context for execution.
1114  */
1115  MemoryContextSwitchTo(oldcontext);
1116 
1117  /*
1118  * Run the portal to completion, and then drop it (and the receiver).
1119  */
1120  (void) PortalRun(portal,
1121  FETCH_ALL,
1122  true, /* always top level */
1123  true,
1124  receiver,
1125  receiver,
1126  completionTag);
1127 
1128  receiver->rDestroy(receiver);
1129 
1130  PortalDrop(portal, false);
1131 
1132  if (lnext(parsetree_item) == NULL)
1133  {
1134  /*
1135  * If this is the last parsetree of the query string, close down
1136  * transaction statement before reporting command-complete. This
1137  * is so that any end-of-transaction errors are reported before
1138  * the command-complete message is issued, to avoid confusing
1139  * clients who will expect either a command-complete message or an
1140  * error, not one and then the other. Also, if we're using an
1141  * implicit transaction block, we must close that out first.
1142  */
1143  if (use_implicit_block)
1146  }
1147  else if (IsA(parsetree->stmt, TransactionStmt))
1148  {
1149  /*
1150  * If this was a transaction control statement, commit it. We will
1151  * start a new xact command for the next command.
1152  */
1154  }
1155  else
1156  {
1157  /*
1158  * We need a CommandCounterIncrement after every query, except
1159  * those that start or end a transaction block.
1160  */
1162  }
1163 
1164  /*
1165  * Tell client that we're done with this query. Note we emit exactly
1166  * one EndCommand report for each raw parsetree, thus one for each SQL
1167  * command the client sent, regardless of rewriting. (But a command
1168  * aborted by error will not send an EndCommand report at all.)
1169  */
1170  EndCommand(completionTag, dest);
1171  } /* end loop over parsetrees */
1172 
1173  /*
1174  * Close down transaction statement, if one is open. (This will only do
1175  * something if the parsetree list was empty; otherwise the last loop
1176  * iteration already did it.)
1177  */
1179 
1180  /*
1181  * If there were no parsetrees, return EmptyQueryResponse message.
1182  */
1183  if (!parsetree_list)
1184  NullCommand(dest);
1185 
1186  /*
1187  * Emit duration logging if appropriate.
1188  */
1189  switch (check_log_duration(msec_str, was_logged))
1190  {
1191  case 1:
1192  ereport(LOG,
1193  (errmsg("duration: %s ms", msec_str),
1194  errhidestmt(true)));
1195  break;
1196  case 2:
1197  ereport(LOG,
1198  (errmsg("duration: %s ms statement: %s",
1199  msec_str, query_string),
1200  errhidestmt(true),
1201  errdetail_execute(parsetree_list)));
1202  break;
1203  }
1204 
1205  if (save_log_statement_stats)
1206  ShowUsage("QUERY STATISTICS");
1207 
1208  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1209 
1210  debug_query_string = NULL;
1211 }
signed short int16
Definition: c.h:301
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:106
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:627
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:348
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:445
static void finish_xact_command(void)
Definition: postgres.c:2491
bool visible
Definition: portal.h:192
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:278
bool log_statement_stats
Definition: guc.c:441
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void ShowUsage(const char *title)
Definition: postgres.c:4449
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2638
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, char *completionTag)
Definition: pquery.c:689
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:2273
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:99
#define LOG
Definition: elog.h:26
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:649
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2523
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2130
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2175
void ResetUsage(void)
Definition: postgres.c:4442
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:157
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:607
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Node * stmt
Definition: parsenodes.h:1447
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
void BeginImplicitTransactionBlock(void)
Definition: xact.c:3780
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
char * portalname
Definition: parsenodes.h:2689
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2071
const char * debug_query_string
Definition: postgres.c:85
#define InvalidSnapshot
Definition: snapshot.h:25
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2093
#define PortalIsValid(p)
Definition: portal.h:199
static void start_xact_command(void)
Definition: postgres.c:2471
void EndImplicitTransactionBlock(void)
Definition: xact.c:3805
bool ismove
Definition: parsenodes.h:2690
void CommandCounterIncrement(void)
Definition: xact.c:915
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
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:2647
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:462
static void drop_unnamed_stmt(void)
Definition: postgres.c:2570
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
static char format
Definition: pg_basebackup.c:81
int cursorOptions
Definition: portal.h:144
CommandDest whereToSendOutput
Definition: postgres.c:88
Definition: pg_list.h:45
List * pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:851
void NullCommand(CommandDest dest)
Definition: dest.c:198
#define FETCH_ALL
Definition: parsenodes.h:2682

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2491 of file postgres.c.

References CommitTransactionCommand(), disable_statement_timeout(), MemoryContextStats(), TopMemoryContext, and xact_started.

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

2492 {
2493  /* cancel active statement timeout after each command */
2495 
2496  if (xact_started)
2497  {
2499 
2500 #ifdef MEMORY_CONTEXT_CHECKING
2501  /* Check all memory contexts that weren't freed during commit */
2502  /* (those that were, were checked before being deleted) */
2503  MemoryContextCheck(TopMemoryContext);
2504 #endif
2505 
2506 #ifdef SHOW_MEMORY_STATS
2507  /* Print mem stats after each commit for leak tracking */
2509 #endif
2510 
2511  xact_started = false;
2512  }
2513 }
void CommitTransactionCommand(void)
Definition: xact.c:2745
static void disable_statement_timeout(void)
Definition: postgres.c:4608
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:437
static bool xact_started
Definition: postgres.c:130
MemoryContext TopMemoryContext
Definition: mcxt.c:43

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2708 of file postgres.c.

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

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

2709 {
2710  /* We're not returning, so no need to save errno */
2711  ereport(ERROR,
2712  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2713  errmsg("floating-point exception"),
2714  errdetail("An invalid floating-point operation was signaled. "
2715  "This probably means an out-of-range result or an "
2716  "invalid operation, such as division by zero.")));
2717 }
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

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4384 of file postgres.c.

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

Referenced by PostgresMain().

4385 {
4386  if (am_walsender)
4387  {
4388  if (firstchar == 'F')
4389  ereport(ERROR,
4390  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4391  errmsg("fastpath function calls not supported in a replication connection")));
4392  else
4393  ereport(ERROR,
4394  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4395  errmsg("extended query protocol not supported in a replication connection")));
4396  }
4397 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool am_walsender
Definition: walsender.c:115
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4406 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4407 {
4408 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4409  static long val = 0;
4410 
4411  /* This won't change after process launch, so check just once */
4412  if (val == 0)
4413  {
4414  struct rlimit rlim;
4415 
4416  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4417  val = -1;
4418  else if (rlim.rlim_cur == RLIM_INFINITY)
4419  val = LONG_MAX;
4420  /* rlim_cur is probably of an unsigned type, so check for overflow */
4421  else if (rlim.rlim_cur >= LONG_MAX)
4422  val = LONG_MAX;
4423  else
4424  val = rlim.rlim_cur;
4425  }
4426  return val;
4427 #else /* no getrlimit */
4428 #if defined(WIN32) || defined(__CYGWIN__)
4429  /* On Windows we set the backend stack size in src/backend/Makefile */
4430  return WIN32_STACK_RLIMIT;
4431 #else /* not windows ... give up */
4432  return -1;
4433 #endif
4434 #endif
4435 }
long val
Definition: informix.c:689

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3320 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3321 {
3322  switch (arg[0])
3323  {
3324  case 'p':
3325  if (optarg[1] == 'a') /* "parser" */
3326  return "log_parser_stats";
3327  else if (optarg[1] == 'l') /* "planner" */
3328  return "log_planner_stats";
3329  break;
3330 
3331  case 'e': /* "executor" */
3332  return "log_executor_stats";
3333  break;
3334  }
3335 
3336  return NULL;
3337 }
char * optarg
Definition: getopt.c:53
void * arg

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 302 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

303 {
304  int c;
305 
306  /*
307  * This will not process catchup interrupts or notifications while
308  * reading. But those can't really be relevant for a standalone backend
309  * anyway. To properly handle SIGTERM there's a hack in die() that
310  * directly processes interrupts at this stage...
311  */
313 
314  c = getc(stdin);
315 
317 
318  return c;
319 }
char * c
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:527
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 214 of file postgres.c.

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

Referenced by ReadCommand().

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

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2523 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().

2524 {
2525  if (parsetree && IsA(parsetree, TransactionStmt))
2526  {
2527  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2528 
2529  if (stmt->kind == TRANS_STMT_COMMIT ||
2530  stmt->kind == TRANS_STMT_PREPARE ||
2531  stmt->kind == TRANS_STMT_ROLLBACK ||
2532  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2533  return true;
2534  }
2535  return false;
2536 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
TransactionStmtKind kind
Definition: parsenodes.h:2965

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2540 of file postgres.c.

References CMD_UTILITY, PlannedStmt::commandType, IsTransactionExitStmt(), linitial_node, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

2541 {
2542  if (list_length(pstmts) == 1)
2543  {
2544  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2545 
2546  if (pstmt->commandType == CMD_UTILITY &&
2548  return true;
2549  }
2550  return false;
2551 }
#define linitial_node(type, l)
Definition: pg_list.h:114
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2523
Node * utilityStmt
Definition: plannodes.h:94
CmdType commandType
Definition: plannodes.h:45
static int list_length(const List *l)
Definition: pg_list.h:89

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2555 of file postgres.c.

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

Referenced by exec_execute_message().

2556 {
2557  if (list_length(pstmts) == 1)
2558  {
2559  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2560 
2561  if (pstmt->commandType == CMD_UTILITY &&
2562  IsA(pstmt->utilityStmt, TransactionStmt))
2563  return true;
2564  }
2565  return false;
2566 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
#define linitial_node(type, l)
Definition: pg_list.h:114
Node * utilityStmt
Definition: plannodes.h:94
CmdType commandType
Definition: plannodes.h:45
static int list_length(const List *l)
Definition: pg_list.h:89

◆ log_disconnections()

static void log_disconnections ( int  code,
Datum  arg 
)
static

Definition at line 4551 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().

4552 {
4553  Port *port = MyProcPort;
4554  long secs;
4555  int usecs;
4556  int msecs;
4557  int hours,
4558  minutes,
4559  seconds;
4560 
4563  &secs, &usecs);
4564  msecs = usecs / 1000;
4565 
4566  hours = secs / SECS_PER_HOUR;
4567  secs %= SECS_PER_HOUR;
4568  minutes = secs / SECS_PER_MINUTE;
4569  seconds = secs % SECS_PER_MINUTE;
4570 
4571  ereport(LOG,
4572  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4573  "user=%s database=%s host=%s%s%s",
4574  hours, minutes, seconds, msecs,
4575  port->user_name, port->database_name, port->remote_host,
4576  port->remote_port[0] ? " port=" : "", port->remote_port)));
4577 }
struct Port * MyProcPort
Definition: globals.c:41
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
Definition: libpq-be.h:116
char * remote_port
Definition: libpq-be.h:128
#define LOG
Definition: elog.h:26
TimestampTz SessionStartTime
Definition: libpq-be.h:151
#define SECS_PER_MINUTE
Definition: timestamp.h:88
char * user_name
Definition: libpq-be.h:137
#define ereport(elevel, rest)
Definition: elog.h:122
#define SECS_PER_HOUR
Definition: timestamp.h:87
static int port
Definition: pg_regress.c:90
char * remote_host
Definition: libpq-be.h:123
int errmsg(const char *fmt,...)
Definition: elog.c:797
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
char * database_name
Definition: libpq-be.h:136

◆ pg_analyze_and_rewrite()

List* pg_analyze_and_rewrite ( RawStmt parsetree,
const char *  query_string,
Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 649 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().

652 {
653  Query *query;
654  List *querytree_list;
655 
656  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
657 
658  /*
659  * (1) Perform parse analysis.
660  */
661  if (log_parser_stats)
662  ResetUsage();
663 
664  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
665  queryEnv);
666 
667  if (log_parser_stats)
668  ShowUsage("PARSE ANALYSIS STATISTICS");
669 
670  /*
671  * (2) Rewrite the queries, as necessary
672  */
673  querytree_list = pg_rewrite_query(query);
674 
675  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
676 
677  return querytree_list;
678 }
bool log_parser_stats
Definition: guc.c:438
void ShowUsage(const char *title)
Definition: postgres.c:4449
void ResetUsage(void)
Definition: postgres.c:4442
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:738
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:96
Definition: pg_list.h:45

◆ pg_analyze_and_rewrite_params()

List* pg_analyze_and_rewrite_params ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 686 of file postgres.c.

References Assert, free_parsestate(), log_parser_stats, make_parsestate(), ParseState::p_queryEnv, 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().

691 {
692  ParseState *pstate;
693  Query *query;
694  List *querytree_list;
695 
696  Assert(query_string != NULL); /* required as of 8.4 */
697 
698  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
699 
700  /*
701  * (1) Perform parse analysis.
702  */
703  if (log_parser_stats)
704  ResetUsage();
705 
706  pstate = make_parsestate(NULL);
707  pstate->p_sourcetext = query_string;
708  pstate->p_queryEnv = queryEnv;
709  (*parserSetup) (pstate, parserSetupArg);
710 
711  query = transformTopLevelStmt(pstate, parsetree);
712 
714  (*post_parse_analyze_hook) (pstate, query);
715 
716  free_parsestate(pstate);
717 
718  if (log_parser_stats)
719  ShowUsage("PARSE ANALYSIS STATISTICS");
720 
721  /*
722  * (2) Rewrite the queries, as necessary
723  */
724  querytree_list = pg_rewrite_query(query);
725 
726  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
727 
728  return querytree_list;
729 }
bool log_parser_stats
Definition: guc.c:438
QueryEnvironment * p_queryEnv
Definition: parse_node.h:197
void ShowUsage(const char *title)
Definition: postgres.c:4449
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4442
const char * p_sourcetext
Definition: parse_node.h:173
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:738
#define Assert(condition)
Definition: c.h:688
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:187
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:49

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 607 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().

608 {
609  List *raw_parsetree_list;
610 
611  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
612 
613  if (log_parser_stats)
614  ResetUsage();
615 
616  raw_parsetree_list = raw_parser(query_string);
617 
618  if (log_parser_stats)
619  ShowUsage("PARSER STATISTICS");
620 
621 #ifdef COPY_PARSE_PLAN_TREES
622  /* Optional debugging check: pass raw parsetrees through copyObject() */
623  {
624  List *new_list = copyObject(raw_parsetree_list);
625 
626  /* This checks both copyObject() and the equal() routines... */
627  if (!equal(new_list, raw_parsetree_list))
628  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
629  else
630  raw_parsetree_list = new_list;
631  }
632 #endif
633 
634  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
635 
636  return raw_parsetree_list;
637 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:438
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2991
void ShowUsage(const char *title)
Definition: postgres.c:4449
static List * new_list(NodeTag type)
Definition: list.c:63
void ResetUsage(void)
Definition: postgres.c:4442
#define WARNING
Definition: elog.h:40
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:626
Definition: pg_list.h:45

◆ pg_plan_queries()

List* pg_plan_queries ( List querytrees,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 851 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst_node, 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().

852 {
853  List *stmt_list = NIL;
854  ListCell *query_list;
855 
856  foreach(query_list, querytrees)
857  {
858  Query *query = lfirst_node(Query, query_list);
859  PlannedStmt *stmt;
860 
861  if (query->commandType == CMD_UTILITY)
862  {
863  /* Utility commands require no planning. */
864  stmt = makeNode(PlannedStmt);
865  stmt->commandType = CMD_UTILITY;
866  stmt->canSetTag = query->canSetTag;
867  stmt->utilityStmt = query->utilityStmt;
868  stmt->stmt_location = query->stmt_location;
869  stmt->stmt_len = query->stmt_len;
870  }
871  else
872  {
873  stmt = pg_plan_query(query, cursorOptions, boundParams);
874  }
875 
876  stmt_list = lappend(stmt_list, stmt);
877  }
878 
879  return stmt_list;
880 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:179
Node * utilityStmt
Definition: parsenodes.h:118
int stmt_len
Definition: plannodes.h:98
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:97
Node * utilityStmt
Definition: plannodes.h:94
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:110
#define makeNode(_type_)
Definition: nodes.h:561
bool canSetTag
Definition: parsenodes.h:116
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:180
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:790

◆ pg_plan_query()

PlannedStmt* pg_plan_query ( Query querytree,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 790 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, planner(), ResetUsage(), ShowUsage(), and WARNING.

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

791 {
792  PlannedStmt *plan;
793 
794  /* Utility commands have no plans. */
795  if (querytree->commandType == CMD_UTILITY)
796  return NULL;
797 
798  /* Planner must have a snapshot in case it calls user-defined functions. */
800 
801  TRACE_POSTGRESQL_QUERY_PLAN_START();
802 
803  if (log_planner_stats)
804  ResetUsage();
805 
806  /* call the optimizer */
807  plan = planner(querytree, cursorOptions, boundParams);
808 
809  if (log_planner_stats)
810  ShowUsage("PLANNER STATISTICS");
811 
812 #ifdef COPY_PARSE_PLAN_TREES
813  /* Optional debugging check: pass plan output through copyObject() */
814  {
815  PlannedStmt *new_plan = copyObject(plan);
816 
817  /*
818  * equal() currently does not have routines to compare Plan nodes, so
819  * don't try to test equality here. Perhaps fix someday?
820  */
821 #ifdef NOT_USED
822  /* This checks both copyObject() and the equal() routines... */
823  if (!equal(new_plan, plan))
824  elog(WARNING, "copyObject() failed to produce an equal plan tree");
825  else
826 #endif
827  plan = new_plan;
828  }
829 #endif
830 
831  /*
832  * Print plan if debugging.
833  */
834  if (Debug_print_plan)
835  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
836 
837  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
838 
839  return plan;
840 }
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:2991
void ShowUsage(const char *title)
Definition: postgres.c:4449
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:224
void ResetUsage(void)
Definition: postgres.c:4442
bool Debug_print_plan
Definition: guc.c:433
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:851
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:110
#define Assert(condition)
Definition: c.h:688
bool Debug_pretty_print
Definition: guc.c:436
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:626
bool log_planner_stats
Definition: guc.c:439

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

Definition at line 738 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().

739 {
740  List *querytree_list;
741 
742  if (Debug_print_parse)
743  elog_node_display(LOG, "parse tree", query,
745 
746  if (log_parser_stats)
747  ResetUsage();
748 
749  if (query->commandType == CMD_UTILITY)
750  {
751  /* don't rewrite utilities, just dump 'em into result list */
752  querytree_list = list_make1(query);
753  }
754  else
755  {
756  /* rewrite regular queries */
757  querytree_list = QueryRewrite(query);
758  }
759 
760  if (log_parser_stats)
761  ShowUsage("REWRITER STATISTICS");
762 
763 #ifdef COPY_PARSE_PLAN_TREES
764  /* Optional debugging check: pass querytree output through copyObject() */
765  {
766  List *new_list;
767 
768  new_list = copyObject(querytree_list);
769  /* This checks both copyObject() and the equal() routines... */
770  if (!equal(new_list, querytree_list))
771  elog(WARNING, "copyObject() failed to produce equal parse tree");
772  else
773  querytree_list = new_list;
774  }
775 #endif
776 
778  elog_node_display(LOG, "rewritten parse tree", querytree_list,
780 
781  return querytree_list;
782 }
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:438
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2991
void ShowUsage(const char *title)
Definition: postgres.c:4449
static List * new_list(NodeTag type)
Definition: list.c:63
#define LOG
Definition: elog.h:26
#define list_make1(x1)
Definition: pg_list.h:139
void ResetUsage(void)
Definition: postgres.c:4442
bool Debug_print_parse
Definition: guc.c:434
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:110
bool Debug_pretty_print
Definition: guc.c:436
bool Debug_print_rewritten
Definition: guc.c:435
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:626
Definition: pg_list.h:45

◆ PostgresMain()

void PostgresMain ( int  argc,
char *  argv[],
const char *  dbname,
const char *  username 
)

Definition at line 3619 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, ConfigReloadPending, 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(), 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, LocalProcessControlFile(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyProcPid, MyReplicationSlot, NormalProcessing, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_POSTMASTER, PGC_SIGHUP, PgStartTime, pgstat_report_activity(), pgstat_report_stat(), PortalDrop(), PortalIsValid, PostgresSigHupHandler(), 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_sendint32(), 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, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), stmt_timeout_active, TopMemoryContext, UnBlockSig, userDoption, username, ValidatePgVersion(), WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3622 {
3623  int firstchar;
3624  StringInfoData input_message;
3625  sigjmp_buf local_sigjmp_buf;
3626  volatile bool send_ready_for_query = true;
3627  bool disable_idle_in_transaction_timeout = false;
3628 
3629  /* Initialize startup process environment if necessary. */
3630  if (!IsUnderPostmaster)
3631  InitStandaloneProcess(argv[0]);
3632 
3634 
3635  /*
3636  * Set default values for command-line options.
3637  */
3638  if (!IsUnderPostmaster)
3640 
3641  /*
3642  * Parse command-line options.
3643  */
3645 
3646  /* Must have gotten a database name, or have a default (the username) */
3647  if (dbname == NULL)
3648  {
3649  dbname = username;
3650  if (dbname == NULL)
3651  ereport(FATAL,
3652  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3653  errmsg("%s: no database nor user name specified",
3654  progname)));
3655  }
3656 
3657  /* Acquire configuration parameters, unless inherited from postmaster */
3658  if (!IsUnderPostmaster)
3659  {
3661  proc_exit(1);
3662  }
3663 
3664  /*
3665  * Set up signal handlers and masks.
3666  *
3667  * Note that postmaster blocked all signals before forking child process,
3668  * so there is no race condition whereby we might receive a signal before
3669  * we have set up the handler.
3670  *
3671  * Also note: it's best not to use any signals that are SIG_IGNored in the
3672  * postmaster. If such a signal arrives before we are able to change the
3673  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3674  * handler in the postmaster to reserve the signal. (Of course, this isn't
3675  * an issue for signals that are locally generated, such as SIGALRM and
3676  * SIGPIPE.)
3677  */
3678  if (am_walsender)
3679  WalSndSignals();
3680  else
3681  {
3682  pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3683  * file */
3684  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3685  pqsignal(SIGTERM, die); /* cancel current query and exit */
3686 
3687  /*
3688  * In a standalone backend, SIGQUIT can be generated from the keyboard
3689  * easily, while SIGTERM cannot, so we make both signals do die()
3690  * rather than quickdie().
3691  */
3692  if (IsUnderPostmaster)
3693  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3694  else
3695  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3696  InitializeTimeouts(); /* establishes SIGALRM handler */
3697 
3698  /*
3699  * Ignore failure to write to frontend. Note: if frontend closes
3700  * connection, we will notice it and exit cleanly when control next
3701  * returns to outer loop. This seems safer than forcing exit in the
3702  * midst of output during who-knows-what operation...
3703  */
3708 
3709  /*
3710  * Reset some signals that are accepted by postmaster but not by
3711  * backend
3712  */
3713  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3714  * platforms */
3715  }
3716 
3717  pqinitmask();
3718 
3719  if (IsUnderPostmaster)
3720  {
3721  /* We allow SIGQUIT (quickdie) at all times */
3722  sigdelset(&BlockSig, SIGQUIT);
3723  }
3724 
3725  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3726 
3727  if (!IsUnderPostmaster)
3728  {
3729  /*
3730  * Validate we have been given a reasonable-looking DataDir (if under
3731  * postmaster, assume postmaster did this already).
3732  */
3733  Assert(DataDir);
3735 
3736  /* Change into DataDir (if under postmaster, was done already) */
3737  ChangeToDataDir();
3738 
3739  /*
3740  * Create lockfile for data directory.
3741  */
3742  CreateDataDirLockFile(false);
3743 
3744  /* read control file (error checking and contains config ) */
3745  LocalProcessControlFile(false);
3746 
3747  /* Initialize MaxBackends (if under postmaster, was done already) */
3749  }
3750 
3751  /* Early initialization */
3752  BaseInit();
3753 
3754  /*
3755  * Create a per-backend PGPROC struct in shared memory, except in the
3756  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3757  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3758  * had to do some stuff with LWLocks).
3759  */
3760 #ifdef EXEC_BACKEND
3761  if (!IsUnderPostmaster)
3762  InitProcess();
3763 #else
3764  InitProcess();
3765 #endif
3766 
3767  /* We need to allow SIGINT, etc during the initial transaction */
3769 
3770  /*
3771  * General initialization.
3772  *
3773  * NOTE: if you are tempted to add code in this vicinity, consider putting
3774  * it inside InitPostgres() instead. In particular, anything that
3775  * involves database access should be there, not here.
3776  */
3778 
3779  /*
3780  * If the PostmasterContext is still around, recycle the space; we don't
3781  * need it anymore after InitPostgres completes. Note this does not trash
3782  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3783  * ... else we'd need to copy the Port data first. Also, subsidiary data
3784  * such as the username isn't lost either; see ProcessStartupPacket().
3785  */
3786  if (PostmasterContext)
3787  {
3789  PostmasterContext = NULL;
3790  }
3791 
3793 
3794  /*
3795  * Now all GUC states are fully set up. Report them to client if
3796  * appropriate.
3797  */
3799 
3800  /*
3801  * Also set up handler to log session end; we have to wait till now to be
3802  * sure Log_disconnections has its final value.
3803  */
3806 
3807  /* Perform initialization specific to a WAL sender process. */
3808  if (am_walsender)
3809  InitWalSender();
3810 
3811  /*
3812  * process any libraries that should be preloaded at backend start (this
3813  * likewise can't be done until GUC settings are complete)
3814  */
3816 
3817  /*
3818  * Send this backend's cancellation info to the frontend.
3819  */
3821  {
3823 
3824  pq_beginmessage(&buf, 'K');
3825  pq_sendint32(&buf, (int32) MyProcPid);
3826  pq_sendint32(&buf, (int32) MyCancelKey);
3827  pq_endmessage(&buf);
3828  /* Need not flush since ReadyForQuery will do it. */
3829  }
3830 
3831  /* Welcome banner for standalone case */
3833  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3834 
3835  /*
3836  * Create the memory context we will use in the main loop.
3837  *
3838  * MessageContext is reset once per iteration of the main loop, ie, upon
3839  * completion of processing of each command message from the client.
3840  */
3842  "MessageContext",
3844 
3845  /*
3846  * Create memory context and buffer used for RowDescription messages. As
3847  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3848  * frequently executed for ever single statement, we don't want to
3849  * allocate a separate buffer every time.
3850  */
3852  "RowDescriptionContext",
3857 
3858  /*
3859  * Remember stand-alone backend startup time
3860  */
3861  if (!IsUnderPostmaster)
3863 
3864  /*
3865  * POSTGRES main processing loop begins here
3866  *
3867  * If an exception is encountered, processing resumes here so we abort the
3868  * current transaction and start a new one.
3869  *
3870  * You might wonder why this isn't coded as an infinite loop around a
3871  * PG_TRY construct. The reason is that this is the bottom of the
3872  * exception stack, and so with PG_TRY there would be no exception handler
3873  * in force at all during the CATCH part. By leaving the outermost setjmp
3874  * always active, we have at least some chance of recovering from an error
3875  * during error recovery. (If we get into an infinite loop thereby, it
3876  * will soon be stopped by overflow of elog.c's internal state stack.)
3877  *
3878  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3879  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3880  * is essential in case we longjmp'd out of a signal handler on a platform
3881  * where that leaves the signal blocked. It's not redundant with the
3882  * unblock in AbortTransaction() because the latter is only called if we
3883  * were inside a transaction.
3884  */
3885 
3886  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3887  {
3888  /*
3889  * NOTE: if you are tempted to add more code in this if-block,
3890  * consider the high probability that it should be in
3891  * AbortTransaction() instead. The only stuff done directly here
3892  * should be stuff that is guaranteed to apply *only* for outer-level
3893  * error recovery, such as adjusting the FE/BE protocol status.
3894  */
3895 
3896  /* Since not using PG_TRY, must reset error stack by hand */
3897  error_context_stack = NULL;
3898 
3899  /* Prevent interrupts while cleaning up */
3900  HOLD_INTERRUPTS();
3901 
3902  /*
3903  * Forget any pending QueryCancel request, since we're returning to
3904  * the idle loop anyway, and cancel any active timeout requests. (In
3905  * future we might want to allow some timeout requests to survive, but
3906  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3907  * we got here because of a query cancel interrupting the SIGALRM
3908  * interrupt handler.) Note in particular that we must clear the
3909  * statement and lock timeout indicators, to prevent any future plain
3910  * query cancels from being misreported as timeouts in case we're
3911  * forgetting a timeout cancel.
3912  */
3913  disable_all_timeouts(false);
3914  QueryCancelPending = false; /* second to avoid race condition */
3915  stmt_timeout_active = false;
3916 
3917  /* Not reading from the client anymore. */
3918  DoingCommandRead = false;
3919 
3920  /* Make sure libpq is in a good state */
3921  pq_comm_reset();
3922 
3923  /* Report the error to the client and/or server log */
3924  EmitErrorReport();
3925 
3926  /*
3927  * Make sure debug_query_string gets reset before we possibly clobber
3928  * the storage it points at.
3929  */
3930  debug_query_string = NULL;
3931 
3932  /*
3933  * Abort the current transaction in order to recover.
3934  */
3936 
3937  if (am_walsender)
3939 
3940  /*
3941  * We can't release replication slots inside AbortTransaction() as we
3942  * need to be able to start and abort transactions while having a slot
3943  * acquired. But we never need to hold them across top level errors,
3944  * so releasing here is fine. There's another cleanup in ProcKill()
3945  * ensuring we'll correctly cleanup on FATAL errors as well.
3946  */
3947  if (MyReplicationSlot != NULL)
3949 
3950  /* We also want to cleanup temporary slots on error. */
3952 
3953  /*
3954  * Now return to normal top-level context and clear ErrorContext for
3955  * next time.
3956  */
3958  FlushErrorState();
3959 
3960  /*
3961  * If we were handling an extended-query-protocol message, initiate
3962  * skip till next Sync. This also causes us not to issue
3963  * ReadyForQuery (until we get Sync).
3964  */
3966  ignore_till_sync = true;
3967 
3968  /* We don't have a transaction command open anymore */
3969  xact_started = false;
3970 
3971  /*
3972  * If an error occurred while we were reading a message from the
3973  * client, we have potentially lost track of where the previous
3974  * message ends and the next one begins. Even though we have
3975  * otherwise recovered from the error, we cannot safely read any more
3976  * messages from the client, so there isn't much we can do with the
3977  * connection anymore.
3978  */
3979  if (pq_is_reading_msg())
3980  ereport(FATAL,
3981  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3982  errmsg("terminating connection because protocol synchronization was lost")));
3983 
3984  /* Now we can allow interrupts again */
3986  }
3987 
3988  /* We can now handle ereport(ERROR) */
3989  PG_exception_stack = &local_sigjmp_buf;
3990 
3991  if (!ignore_till_sync)
3992  send_ready_for_query = true; /* initially, or after error */
3993 
3994  /*
3995  * Non-error queries loop here.
3996  */
3997 
3998  for (;;)
3999  {
4000  /*
4001  * At top of loop, reset extended-query-message flag, so that any
4002  * errors encountered in "idle" state don't provoke skip.
4003  */
4005 
4006  /*
4007  * Release storage left over from prior query cycle, and create a new
4008  * query input buffer in the cleared MessageContext.
4009  */
4012 
4013  initStringInfo(&input_message);
4014 
4015  /*
4016  * Also consider releasing our catalog snapshot if any, so that it's
4017  * not preventing advance of global xmin while we wait for the client.
4018  */
4020 
4021  /*
4022  * (1) If we've reached idle state, tell the frontend we're ready for
4023  * a new query.
4024  *
4025  * Note: this includes fflush()'ing the last of the prior output.
4026  *
4027  * This is also a good time to send collected statistics to the
4028  * collector, and to update the PS stats display. We avoid doing
4029  * those every time through the message loop because it'd slow down
4030  * processing of batched messages, and because we don't want to report
4031  * uncommitted updates (that confuses autovacuum). The notification
4032  * processor wants a call too, if we are not in a transaction block.
4033  */
4034  if (send_ready_for_query)
4035  {
4037  {
4038  set_ps_display("idle in transaction (aborted)", false);
4040 
4041  /* Start the idle-in-transaction timer */
4043  {
4044  disable_idle_in_transaction_timeout = true;
4047  }
4048  }
4050  {
4051  set_ps_display("idle in transaction", false);
4053 
4054  /* Start the idle-in-transaction timer */
4056  {
4057  disable_idle_in_transaction_timeout = true;
4060  }
4061  }
4062  else
4063  {
4065  pgstat_report_stat(false);
4066 
4067  set_ps_display("idle", false);
4069  }
4070 
4072  send_ready_for_query = false;
4073  }
4074 
4075  /*
4076  * (2) Allow asynchronous signals to be executed immediately if they
4077  * come in while we are waiting for client input. (This must be
4078  * conditional since we don't want, say, reads on behalf of COPY FROM
4079  * STDIN doing the same thing.)
4080  */
4081  DoingCommandRead = true;
4082 
4083  /*
4084  * (3) read a command (loop blocks here)
4085  */
4086  firstchar = ReadCommand(&input_message);
4087 
4088  /*
4089  * (4) disable async signal conditions again.
4090  *
4091  * Query cancel is supposed to be a no-op when there is no query in
4092  * progress, so if a query cancel arrived while we were idle, just
4093  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4094  * it's called when DoingCommandRead is set, so check for interrupts
4095  * before resetting DoingCommandRead.
4096  */
4098  DoingCommandRead = false;
4099 
4100  /*
4101  * (5) turn off the idle-in-transaction timeout
4102  */
4103  if (disable_idle_in_transaction_timeout)
4104  {
4106  disable_idle_in_transaction_timeout = false;
4107  }
4108 
4109  /*
4110  * (6) check for any other interesting events that happened while we
4111  * slept.
4112  */
4113  if (ConfigReloadPending)
4114  {
4115  ConfigReloadPending = false;
4117  }
4118 
4119  /*
4120  * (7) process the command. But ignore it if we're skipping till
4121  * Sync.
4122  */
4123  if (ignore_till_sync && firstchar != EOF)
4124  continue;
4125 
4126  switch (firstchar)
4127  {
4128  case 'Q': /* simple query */
4129  {
4130  const char *query_string;
4131 
4132  /* Set statement_timestamp() */
4134 
4135  query_string = pq_getmsgstring(&input_message);
4136  pq_getmsgend(&input_message);
4137 
4138  if (am_walsender)
4139  {
4140  if (!exec_replication_command(query_string))
4141  exec_simple_query(query_string);
4142  }
4143  else
4144  exec_simple_query(query_string);
4145 
4146  send_ready_for_query = true;
4147  }
4148  break;
4149 
4150  case 'P': /* parse */
4151  {
4152  const char *stmt_name;
4153  const char *query_string;
4154  int numParams;
4155  Oid *paramTypes = NULL;
4156 
4157  forbidden_in_wal_sender(firstchar);
4158 
4159  /* Set statement_timestamp() */
4161 
4162  stmt_name = pq_getmsgstring(&input_message);
4163  query_string = pq_getmsgstring(&input_message);
4164  numParams = pq_getmsgint(&input_message, 2);
4165  if (numParams > 0)
4166  {
4167  int i;
4168 
4169  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4170  for (i = 0; i < numParams; i++)
4171  paramTypes[i] = pq_getmsgint(&input_message, 4);
4172  }
4173  pq_getmsgend(&input_message);
4174 
4175  exec_parse_message(query_string, stmt_name,
4176  paramTypes, numParams);
4177  }
4178  break;
4179 
4180  case 'B': /* bind */
4181  forbidden_in_wal_sender(firstchar);
4182 
4183  /* Set statement_timestamp() */
4185 
4186  /*
4187  * this message is complex enough that it seems best to put
4188  * the field extraction out-of-line
4189  */
4190  exec_bind_message(&input_message);
4191  break;
4192 
4193  case 'E': /* execute */
4194  {
4195  const char *portal_name;
4196  int max_rows;
4197 
4198  forbidden_in_wal_sender(firstchar);
4199 
4200  /* Set statement_timestamp() */
4202 
4203  portal_name = pq_getmsgstring(&input_message);
4204  max_rows = pq_getmsgint(&input_message, 4);
4205  pq_getmsgend(&input_message);
4206 
4207  exec_execute_message(portal_name, max_rows);
4208  }
4209  break;
4210 
4211  case 'F': /* fastpath function call */
4212  forbidden_in_wal_sender(firstchar);
4213 
4214  /* Set statement_timestamp() */
4216 
4217  /* Report query to various monitoring facilities. */
4219  set_ps_display("<FASTPATH>", false);
4220 
4221  /* start an xact for this function invocation */
4223 
4224  /*
4225  * Note: we may at this point be inside an aborted
4226  * transaction. We can't throw error for that until we've
4227  * finished reading the function-call message, so
4228  * HandleFunctionRequest() must check for it after doing so.
4229  * Be careful not to do anything that assumes we're inside a
4230  * valid transaction here.
4231  */
4232 
4233  /* switch back to message context */
4235 
4236  HandleFunctionRequest(&input_message);
4237 
4238  /* commit the function-invocation transaction */
4240 
4241  send_ready_for_query = true;
4242  break;
4243 
4244  case 'C': /* close */
4245  {
4246  int close_type;
4247  const char *close_target;
4248 
4249  forbidden_in_wal_sender(firstchar);
4250 
4251  close_type = pq_getmsgbyte(&input_message);
4252  close_target = pq_getmsgstring(&input_message);
4253  pq_getmsgend(&input_message);
4254 
4255  switch (close_type)
4256  {
4257  case 'S':
4258  if (close_target[0] != '\0')
4259  DropPreparedStatement(close_target, false);
4260  else
4261  {
4262  /* special-case the unnamed statement */
4264  }
4265  break;
4266  case 'P':
4267  {
4268  Portal portal;
4269 
4270  portal = GetPortalByName(close_target);
4271  if (PortalIsValid(portal))
4272  PortalDrop(portal, false);
4273  }
4274  break;
4275  default:
4276  ereport(ERROR,
4277  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4278  errmsg("invalid CLOSE message subtype %d",
4279  close_type)));
4280  break;
4281  }
4282 
4284  pq_putemptymessage('3'); /* CloseComplete */
4285  }
4286  break;
4287 
4288  case 'D': /* describe */
4289  {
4290  int describe_type;
4291  const char *describe_target;
4292 
4293  forbidden_in_wal_sender(firstchar);
4294 
4295  /* Set statement_timestamp() (needed for xact) */
4297 
4298  describe_type = pq_getmsgbyte(&input_message);
4299  describe_target = pq_getmsgstring(&input_message);
4300  pq_getmsgend(&input_message);
4301 
4302  switch (describe_type)
4303  {
4304  case 'S':
4305  exec_describe_statement_message(describe_target);
4306  break;
4307  case 'P':
4308  exec_describe_portal_message(describe_target);
4309  break;
4310  default:
4311  ereport(ERROR,
4312  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4313  errmsg("invalid DESCRIBE message subtype %d",
4314  describe_type)));
4315  break;
4316  }
4317  }
4318  break;
4319 
4320  case 'H': /* flush */
4321  pq_getmsgend(&input_message);
4323  pq_flush();
4324  break;
4325 
4326  case 'S': /* sync */
4327  pq_getmsgend(&input_message);
4329  send_ready_for_query = true;
4330  break;
4331 
4332  /*
4333  * 'X' means that the frontend is closing down the socket. EOF
4334  * means unexpected loss of frontend connection. Either way,
4335  * perform normal shutdown.
4336  */
4337  case 'X':
4338  case EOF:
4339 
4340  /*
4341  * Reset whereToSendOutput to prevent ereport from attempting
4342  * to send any more messages to client.
4343  */
4346 
4347  /*
4348  * NOTE: if you are tempted to add more code here, DON'T!
4349  * Whatever you had in mind to do should be set up as an
4350  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4351  * it will fail to be called during other backend-shutdown
4352  * scenarios.
4353  */
4354  proc_exit(0);
4355 
4356  case 'd': /* copy data */
4357  case 'c': /* copy done */
4358  case 'f': /* copy fail */
4359 
4360  /*
4361  * Accept but ignore these messages, per protocol spec; we
4362  * probably got here because a COPY failed, and the frontend
4363  * is still sending data.
4364  */
4365  break;
4366 
4367  default:
4368  ereport(FATAL,
4369  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4370  errmsg("invalid frontend message type %d",
4371  firstchar)));
4372  }
4373  } /* end of input-reading loop */
4374 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:2985
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2419
#define SIGQUIT
Definition: win32_port.h:164
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
void BeginReportingGUCOptions(void)
Definition: guc.c:5408
int MyProcPid
Definition: globals.c:39
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:507
static void finish_xact_command(void)
Definition: postgres.c:2491
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1426
#define SIGUSR1
Definition: win32_port.h:177
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:299
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
#define SIGCHLD
Definition: win32_port.h:173
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:220
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1358
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
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:4384
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4466
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:374
void BaseInit(void)
Definition: postinit.c:524
#define SIGPIPE
Definition: win32_port.h:168
#define SIGUSR2
Definition: win32_port.h:178
unsigned int Oid
Definition: postgres_ext.h:31
volatile bool QueryCancelPending
Definition: globals.c:30
const char * progname
Definition: pg_standby.c:37
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:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2687
signed int int32
Definition: c.h:302
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1867
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4551
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:115
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1081
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1250
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:42
void WalSndSignals(void)
Definition: walsender.c:2952
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
void InitProcess(void)
Definition: proc.c:288
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:67
bool IsUnderPostmaster
Definition: globals.c:101
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1482
Definition: dest.h:89
#define SIGHUP
Definition: win32_port.h:163
void PostgresSigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2727
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4831
void ChangeToDataDir(void)
Definition: miscinit.c:116
void ReplicationSlotRelease(void)
Definition: slot.c:416
sigset_t UnBlockSig
Definition: pqsignal.c:22
static bool stmt_timeout_active
Definition: postgres.c:149
static bool xact_started
Definition: postgres.c:130
void InitWalSender(void)
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
volatile sig_atomic_t ConfigReloadPending
Definition: globals.c:34
#define SIG_IGN
Definition: win32_port.h:160
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
const char * debug_query_string
Definition: postgres.c:85
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1219
#define PortalIsValid(p)
Definition: portal.h:199
static void start_xact_command(void)
Definition: postgres.c:2471
static bool doing_extended_query_message
Definition: postgres.c:143
sigset_t BlockSig
Definition: pqsignal.c:22
void process_session_preload_libraries(void)
Definition: miscinit.c:1500
void WalSndErrorCleanup(void)
Definition: walsender.c:292
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4737
void EmitErrorReport(void)
Definition: elog.c:1446
static StringInfoData row_description_buf
Definition: postgres.c:170
TimestampTz PgStartTime
Definition: timestamp.c:49
static char * username
Definition: initdb.c:132
#define InvalidOid
Definition: postgres_ext.h:36
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:38
#define SIG_DFL
Definition: win32_port.h:158
#define Assert(condition)
Definition: c.h:688
void ProcessCompletedNotifies(void)
Definition: async.c:1101
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:259
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:531
static bool DoingCommandRead
Definition: postgres.c:137
void InitializeMaxBackends(void)
Definition: postinit.c:502
char * dbname
Definition: streamutil.c:42
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:733
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:565
void * palloc(Size size)
Definition: mcxt.c:835
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:462
void ReadyForQuery(CommandDest dest)
Definition: dest.c:241
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2656
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2708
static void drop_unnamed_stmt(void)
Definition: postgres.c:2570
char * DataDir
Definition: globals.c:60
void ReplicationSlotCleanup(void)
Definition: slot.c:471
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
bool Log_disconnections
Definition: postgres.c:91
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3360
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:261
CommandDest whereToSendOutput
Definition: postgres.c:88
static bool ignore_till_sync
Definition: postgres.c:144
static MemoryContext row_description_context
Definition: postgres.c:169
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2595
MemoryContext PostmasterContext
Definition: mcxt.c:45
static void exec_simple_query(const char *query_string)
Definition: postgres.c:889
void InitializeGUCOptions(void)
Definition: guc.c:4515
void pgstat_report_stat(bool force)
Definition: pgstat.c:812
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:580
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2323

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2727 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

2728 {
2729  int save_errno = errno;
2730 
2731  ConfigReloadPending = true;
2732  SetLatch(MyLatch);
2733 
2734  errno = save_errno;
2735 }
volatile sig_atomic_t ConfigReloadPending
Definition: globals.c:34
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ process_postgres_switches()

void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3360 of file postgres.c.

References EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), free, FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, 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().

3362 {
3363  bool secure = (ctx == PGC_POSTMASTER);
3364  int errs = 0;
3365  GucSource gucsource;
3366  int flag;
3367 
3368  if (secure)
3369  {
3370  gucsource = PGC_S_ARGV; /* switches came from command line */
3371 
3372  /* Ignore the initial --single argument, if present */
3373  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3374  {
3375  argv++;
3376  argc--;
3377  }
3378  }
3379  else
3380  {
3381  gucsource = PGC_S_CLIENT; /* switches came from client */
3382  }
3383 
3384 #ifdef HAVE_INT_OPTERR
3385 
3386  /*
3387  * Turn this off because it's either printed to stderr and not the log
3388  * where we'd want it, or argv[0] is now "--single", which would make for
3389  * a weird error message. We print our own error message below.
3390  */
3391  opterr = 0;
3392 #endif
3393 
3394  /*
3395  * Parse command-line options. CAUTION: keep this in sync with
3396  * postmaster/postmaster.c (the option sets should not conflict) and with
3397  * the common help() function in main/main.c.
3398  */
3399  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3400  {
3401  switch (flag)
3402  {
3403  case 'B':
3404  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3405  break;
3406 
3407  case 'b':
3408  /* Undocumented flag used for binary upgrades */
3409  if (secure)
3410  IsBinaryUpgrade = true;
3411  break;
3412 
3413  case 'C':
3414  /* ignored for consistency with the postmaster */
3415  break;
3416 
3417  case 'D':
3418  if (secure)
3419  userDoption = strdup(optarg);
3420  break;
3421 
3422  case 'd':
3423  set_debug_options(atoi(optarg), ctx, gucsource);
3424  break;
3425 
3426  case 'E':
3427  if (secure)
3428  EchoQuery = true;
3429  break;
3430 
3431  case 'e':
3432  SetConfigOption("datestyle", "euro", ctx, gucsource);
3433  break;
3434 
3435  case 'F':
3436  SetConfigOption("fsync", "false", ctx, gucsource);
3437  break;
3438 
3439  case 'f':
3440  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3441  errs++;
3442  break;
3443 
3444  case 'h':
3445  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3446  break;
3447 
3448  case 'i':
3449  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3450  break;
3451 
3452  case 'j':
3453  if (secure)
3454  UseSemiNewlineNewline = true;
3455  break;
3456 
3457  case 'k':
3458  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3459  break;
3460 
3461  case 'l':
3462  SetConfigOption("ssl", "true", ctx, gucsource);
3463  break;
3464 
3465  case 'N':
3466  SetConfigOption("max_connections", optarg, ctx, gucsource);
3467  break;
3468 
3469  case 'n':
3470  /* ignored for consistency with postmaster */
3471  break;
3472 
3473  case 'O':
3474  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3475  break;
3476 
3477  case 'o':
3478  errs++;
3479  break;
3480 
3481  case 'P':
3482  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3483  break;
3484 
3485  case 'p':
3486  SetConfigOption("port", optarg, ctx, gucsource);
3487  break;
3488 
3489  case 'r':
3490  /* send output (stdout and stderr) to the given file */
3491  if (secure)
3493  break;
3494 
3495  case 'S':
3496  SetConfigOption("work_mem", optarg, ctx, gucsource);
3497  break;
3498 
3499  case 's':
3500  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3501  break;
3502 
3503  case 'T':
3504  /* ignored for consistency with the postmaster */
3505  break;
3506 
3507  case 't':
3508  {
3509  const char *tmp = get_stats_option_name(optarg);
3510 
3511  if (tmp)
3512  SetConfigOption(tmp, "true", ctx, gucsource);
3513  else
3514  errs++;
3515  break;
3516  }
3517 
3518  case 'v':
3519 
3520  /*
3521  * -v is no longer used in normal operation, since
3522  * FrontendProtocol is already set before we get here. We keep
3523  * the switch only for possible use in standalone operation,
3524  * in case we ever support using normal FE/BE protocol with a
3525  * standalone backend.
3526  */
3527  if (secure)
3529  break;
3530 
3531  case 'W':
3532  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3533  break;
3534 
3535  case 'c':
3536  case '-':
3537  {
3538  char *name,
3539  *value;
3540 
3541  ParseLongOption(optarg, &name, &value);
3542  if (!value)
3543  {
3544  if (flag == '-')
3545  ereport(ERROR,
3546  (errcode(ERRCODE_SYNTAX_ERROR),
3547  errmsg("--%s requires a value",
3548  optarg)));
3549  else
3550  ereport(ERROR,
3551  (errcode(ERRCODE_SYNTAX_ERROR),
3552  errmsg("-c %s requires a value",
3553  optarg)));
3554  }
3555  SetConfigOption(name, value, ctx, gucsource);
3556  free(name);
3557  if (value)
3558  free(value);
3559  break;
3560  }
3561 
3562  default:
3563  errs++;
3564  break;
3565  }
3566 
3567  if (errs)
3568  break;
3569  }
3570 
3571  /*
3572  * Optional database name should be there only if *dbname is NULL.
3573  */
3574  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3575  *dbname = strdup(argv[optind++]);
3576 
3577  if (errs || argc != optind)
3578  {
3579  if (errs)
3580  optind--; /* complain about the previous argument */
3581 
3582  /* spell the error message a bit differently depending on context */
3583  if (IsUnderPostmaster)
3584  ereport(FATAL,
3585  (errcode(ERRCODE_SYNTAX_ERROR),
3586  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3587  errhint("Try \"%s --help\" for more information.", progname)));
3588  else
3589  ereport(FATAL,
3590  (errcode(ERRCODE_SYNTAX_ERROR),
3591  errmsg("%s: invalid command-line argument: %s",
3592  progname, argv[optind]),
3593  errhint("Try \"%s --help\" for more information.", progname)));
3594  }
3595 
3596  /*
3597  * Reset getopt(3) library so that it will work correctly in subprocesses
3598  * or when this function is called a second time with another array.
3599  */
3600  optind = 1;
3601 #ifdef HAVE_INT_OPTRESET
3602  optreset = 1; /* some systems need this too */
3603 #endif
3604 }
int errhint(const char *fmt,...)
Definition: elog.c:987
static struct @130 value
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9417
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3278
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3320
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3249
const char * progname
Definition: pg_standby.c:37
bool IsBinaryUpgrade
Definition: globals.c:102
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:62
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6720
bool IsUnderPostmaster
Definition: globals.c:101
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
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * dbname
Definition: streamutil.c:42
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

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 527 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

528 {
529  int save_errno = errno;
530 
531  if (DoingCommandRead)
532  {
533  /* Check for general interrupts that arrived while reading */
535 
536  /* Process sinval catchup interrupts that happened while reading */
539 
540  /* Process sinval catchup interrupts that happened while reading */
543  }
544  else if (ProcDiePending && blocked)
545  {
546  /*
547  * We're dying. It's safe (and sane) to handle that now.
548  */
550  }
551 
552  errno = save_errno;
553 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1731
static bool DoingCommandRead
Definition: postgres.c:137
volatile bool ProcDiePending
Definition: globals.c:31
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:358
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 565 of file postgres.c.

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

Referenced by secure_write().

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

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 2864 of file postgres.c.

References Assert, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, 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(), IsLogicalLauncher(), IsLogicalWorker(), LOCK_TIMEOUT, LockErrorCleanup(), ParallelMessagePending, pgstat_report_recovery_conflict(), proc_exit(), ProcDiePending, PROCSIG_RECOVERY_CONFLICT_DATABASE, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

2865 {
2866  /* OK to accept any interrupts now? */
2867  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2868  return;
2869  InterruptPending = false;
2870 
2871  if (ProcDiePending)
2872  {
2873  ProcDiePending = false;
2874  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2875  LockErrorCleanup();
2876  /* As in quickdie, don't risk sending to client during auth */
2880  ereport(FATAL,
2881  (errcode(ERRCODE_QUERY_CANCELED),
2882  errmsg("canceling authentication due to timeout")));
2883  else if (IsAutoVacuumWorkerProcess())
2884  ereport(FATAL,
2885  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2886  errmsg("terminating autovacuum process due to administrator command")));
2887  else if (IsLogicalWorker())
2888  ereport(FATAL,
2889  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2890  errmsg("terminating logical replication worker due to administrator command")));
2891  else if (IsLogicalLauncher())
2892  {
2893  ereport(DEBUG1,
2894  (errmsg("logical replication launcher shutting down")));
2895 
2896  /*
2897  * The logical replication launcher can be stopped at any time.
2898  * Use exit status 1 so the background worker is restarted.
2899  */
2900  proc_exit(1);
2901  }
2903  {
2905  ereport(FATAL,
2906  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2907  errmsg("terminating connection due to conflict with recovery"),
2909  }
2910  else if (RecoveryConflictPending)
2911  {
2912  /* Currently there is only one non-retryable recovery conflict */
2915  ereport(FATAL,
2916  (errcode(ERRCODE_DATABASE_DROPPED),
2917  errmsg("terminating connection due to conflict with recovery"),
2919  }
2920  else
2921  ereport(FATAL,
2922  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2923  errmsg("terminating connection due to administrator command")));
2924  }
2926  {
2927  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2928  LockErrorCleanup();
2929  /* don't send to client, we already know the connection to be dead. */
2931  ereport(FATAL,
2932  (errcode(ERRCODE_CONNECTION_FAILURE),
2933  errmsg("connection to client lost")));
2934  }
2935 
2936  /*
2937  * If a recovery conflict happens while we are waiting for input from the
2938  * client, the client is presumably just sitting idle in a transaction,
2939  * preventing recovery from making progress. Terminate the connection to
2940  * dislodge it.
2941  */
2943  {
2944  QueryCancelPending = false; /* this trumps QueryCancel */
2945  RecoveryConflictPending = false;
2946  LockErrorCleanup();
2948  ereport(FATAL,
2949  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2950  errmsg("terminating connection due to conflict with recovery"),
2952  errhint("In a moment you should be able to reconnect to the"
2953  " database and repeat your command.")));
2954  }
2955 
2956  /*
2957  * Don't allow query cancel interrupts while reading input from the
2958  * client, because we might lose sync in the FE/BE protocol. (Die
2959  * interrupts are OK, because we won't read any further messages from the
2960  * client in that case.)
2961  */
2963  {
2964  /*
2965  * Re-arm InterruptPending so that we process the cancel request as
2966  * soon as we're done reading the message.
2967  */
2968  InterruptPending = true;
2969  }
2970  else if (QueryCancelPending)
2971  {
2972  bool lock_timeout_occurred;
2973  bool stmt_timeout_occurred;
2974 
2975  QueryCancelPending = false;
2976 
2977  /*
2978  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2979  * need to clear both, so always fetch both.
2980  */
2981  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2982  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2983 
2984  /*
2985  * If both were set, we want to report whichever timeout completed
2986  * earlier; this ensures consistent behavior if the machine is slow
2987  * enough that the second timeout triggers before we get here. A tie
2988  * is arbitrarily broken in favor of reporting a lock timeout.
2989  */
2990  if (lock_timeout_occurred && stmt_timeout_occurred &&
2992  lock_timeout_occurred = false; /* report stmt timeout */
2993 
2994  if (lock_timeout_occurred)
2995  {
2996  LockErrorCleanup();
2997  ereport(ERROR,
2998  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2999  errmsg("canceling statement due to lock timeout")));
3000  }
3001  if (stmt_timeout_occurred)
3002  {
3003  LockErrorCleanup();
3004  ereport(ERROR,
3005  (errcode(ERRCODE_QUERY_CANCELED),
3006  errmsg("canceling statement due to statement timeout")));
3007  }
3009  {
3010  LockErrorCleanup();
3011  ereport(ERROR,
3012  (errcode(ERRCODE_QUERY_CANCELED),
3013  errmsg("canceling autovacuum task")));
3014  }
3016  {
3017  RecoveryConflictPending = false;
3018  LockErrorCleanup();
3020  ereport(ERROR,
3021  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3022  errmsg("canceling statement due to conflict with recovery"),
3024  }
3025 
3026  /*
3027  * If we are reading a command from the client, just ignore the cancel
3028  * request --- sending an extra error message won't accomplish
3029  * anything. Otherwise, go ahead and throw the error.
3030  */
3031  if (!DoingCommandRead)
3032  {
3033  LockErrorCleanup();
3034  ereport(ERROR,
3035  (errcode(ERRCODE_QUERY_CANCELED),
3036  errmsg("canceling statement due to user request")));
3037  }
3038  }
3039 
3041  {
3042  /* Has the timeout setting changed since last we looked? */
3044  ereport(FATAL,
3045  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3046  errmsg("terminating connection due to idle-in-transaction timeout")));
3047  else
3049 
3050  }
3051 
3054 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:35
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:667
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1486
volatile bool IdleInTransactionSessionTimeoutPending
Definition: globals.c:33
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:36
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
volatile bool QueryCancelPending
Definition: globals.c:30
bool IsLogicalWorker(void)
Definition: worker.c:1661
volatile bool ClientConnectionLost
Definition: globals.c:32
volatile bool ParallelMessagePending
Definition: parallel.c:106
bool ClientAuthInProgress
Definition: postmaster.c:350
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:960
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:37
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define ereport(elevel, rest)
Definition: elog.h:122
void LockErrorCleanup(void)
Definition: proc.c:686
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:2287
volatile bool InterruptPending
Definition: globals.c:29
#define Assert(condition)
Definition: c.h:688
static bool DoingCommandRead
Definition: postgres.c:137
volatile bool ProcDiePending
Definition: globals.c:31
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool IsLogicalLauncher(void)
Definition: launcher.c:1003
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2595 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().

2596 {
2597  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2598  PG_SETMASK(&BlockSig);
2599 
2600  /*
2601  * Prevent interrupts while exiting; though we just blocked signals that
2602  * would queue new interrupts, one may have been pending. We don't want a
2603  * quickdie() downgraded to a mere query cancel.
2604  */
2605  HOLD_INTERRUPTS();
2606 
2607  /*
2608  * If we're aborting out of client auth, don't risk trying to send
2609  * anything to the client; we will likely violate the protocol, not to
2610  * mention that we may have interrupted the guts of OpenSSL or some
2611  * authentication library.
2612  */
2615 
2616  /*
2617  * Ideally this should be ereport(FATAL), but then we'd not get control
2618  * back...
2619  */
2620  ereport(WARNING,
2621  (errcode(ERRCODE_CRASH_SHUTDOWN),
2622  errmsg("terminating connection because of crash of another server process"),
2623  errdetail("The postmaster has commanded this server process to roll back"
2624  " the current transaction and exit, because another"
2625  " server process exited abnormally and possibly corrupted"
2626  " shared memory."),
2627  errhint("In a moment you should be able to reconnect to the"
2628  " database and repeat your command.")));
2629 
2630  /*
2631  * We DO NOT want to run proc_exit() callbacks -- we're here because
2632  * shared memory may be corrupted, so we don't want to try to clean up our
2633  * transaction. Just nail the windows shut and get out of town. Now that
2634  * there's an atexit callback to prevent third-party code from breaking
2635  * things by calling exit() directly, we have to reset the callbacks
2636  * explicitly to make this work as intended.
2637  */
2638  on_exit_reset();
2639 
2640  /*
2641  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2642  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2643  * backend. This is necessary precisely because we don't clean up our
2644  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2645  * should ensure the postmaster sees this as a crash, too, but no harm in
2646  * being doubly sure.)
2647  */
2648  exit(2);
2649 }
#define SIGQUIT
Definition: win32_port.h:164
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:350
void on_exit_reset(void)
Definition: ipc.c:403
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:115
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ ReadCommand()

static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 507 of file postgres.c.

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

Referenced by PostgresMain().

508 {
509  int result;
510 
512  result = SocketBackend(inBuf);
513  else
514  result = InteractiveBackend(inBuf);
515  return result;
516 }
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:214
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:330
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2744 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().

2745 {
2746  int save_errno = errno;
2747 
2748  /*
2749  * Don't joggle the elbow of proc_exit
2750  */
2751  if (!proc_exit_inprogress)
2752  {
2753  RecoveryConflictReason = reason;
2754  switch (reason)
2755  {
2757 
2758  /*
2759  * If we aren't waiting for a lock we can never deadlock.
2760  */
2761  if (!IsWaitingForLock())
2762  return;
2763 
2764  /* Intentional drop through to check wait for pin */
2765 
2767 
2768  /*
2769  * If we aren't blocking the Startup process there is nothing
2770  * more to do.
2771  */
2773  return;
2774 
2776 
2777  /* Intentional drop through to error handling */
2778 
2782 
2783  /*
2784  * If we aren't in a transaction any longer then ignore.
2785  */
2787  return;
2788 
2789  /*
2790  * If we can abort just the current subtransaction then we are
2791  * OK to throw an ERROR to resolve the conflict. Otherwise
2792  * drop through to the FATAL case.
2793  *
2794  * XXX other times that we can throw just an ERROR *may* be
2795  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2796  * parent transactions
2797  *
2798  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2799  * by parent transactions and the transaction is not
2800  * transaction-snapshot mode
2801  *
2802  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2803  * cursors open in parent transactions
2804  */
2805  if (!IsSubTransaction())
2806  {
2807  /*
2808  * If we already aborted then we no longer need to cancel.
2809  * We do this here since we do not wish to ignore aborted
2810  * subtransactions, which must cause FATAL, currently.
2811  */
2813  return;
2814 
2815  RecoveryConflictPending = true;
2816  QueryCancelPending = true;
2817  InterruptPending = true;
2818  break;
2819  }
2820 
2821  /* Intentional drop through to session cancel */
2822 
2824  RecoveryConflictPending = true;
2825  ProcDiePending = true;
2826  InterruptPending = true;
2827  break;
2828 
2829  default:
2830  elog(FATAL, "unrecognized conflict mode: %d",
2831  (int) reason);
2832  }
2833 
2835 
2836  /*
2837  * All conflicts apart from database cause dynamic errors where the
2838  * command or transaction can be retried at a later point with some
2839  * potential for success. No need to reset this, since non-retryable
2840  * conflict errors are currently FATAL.
2841  */
2842  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2843  RecoveryConflictRetryable = false;
2844  }
2845 
2846  /*
2847  * Set the process latch. This function essentially emulates signal
2848  * handlers like die() and StatementCancelHandler() and it seems prudent
2849  * to behave similarly as they do.