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 "executor/spi.h"
#include "jit/jit.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 3239 of file postgres.c.

References max_stack_depth_bytes.

3240 {
3241  long newval_bytes = newval * 1024L;
3242 
3243  max_stack_depth_bytes = newval_bytes;
3244 }
static long max_stack_depth_bytes
Definition: postgres.c:111
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

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

2133 {
2135  {
2136  long secs;
2137  int usecs;
2138  int msecs;
2139  bool exceeded;
2140 
2143  &secs, &usecs);
2144  msecs = usecs / 1000;
2145 
2146  /*
2147  * This odd-looking test for log_min_duration_statement being exceeded
2148  * is designed to avoid integer overflow with very long durations:
2149  * don't compute secs * 1000 until we've verified it will fit in int.
2150  */
2151  exceeded = (log_min_duration_statement == 0 ||
2153  (secs > log_min_duration_statement / 1000 ||
2154  secs * 1000 + msecs >= log_min_duration_statement)));
2155 
2156  if (exceeded || log_duration)
2157  {
2158  snprintf(msec_str, 32, "%ld.%03d",
2159  secs * 1000 + msecs, usecs % 1000);
2160  if (exceeded && !was_logged)
2161  return 2;
2162  else
2163  return 1;
2164  }
2165  }
2166 
2167  return 0;
2168 }
int log_min_duration_statement
Definition: guc.c:456
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:434
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:709

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2095 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

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

◆ check_max_stack_depth()

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

Definition at line 3222 of file postgres.c.

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

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

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3159 of file postgres.c.

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

Referenced by apply_scanjoin_target_to_paths(), 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(), find_subplans_for_params_recurse(), 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(), get_steps_using_prefix_recurse(), 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().

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

◆ die()

void die ( SIGNAL_ARGS  )

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

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

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

Definition at line 4617 of file postgres.c.

References disable_timeout(), STATEMENT_TIMEOUT, and stmt_timeout_active.

Referenced by exec_execute_message(), and finish_xact_command().

4618 {
4619  if (stmt_timeout_active)
4620  {
4622 
4623  stmt_timeout_active = false;
4624  }
4625 }
static bool stmt_timeout_active
Definition: postgres.c:151
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 2572 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2573 {
2574  /* paranoia to avoid a dangling pointer in case of error */
2575  if (unnamed_stmt_psrc)
2576  {
2578 
2579  unnamed_stmt_psrc = NULL;
2580  DropCachedPlan(psrc);
2581  }
2582 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:487

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

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

4597 {
4598  /* must be within an xact */
4600 
4601  if (StatementTimeout > 0)
4602  {
4603  if (!stmt_timeout_active)
4604  {
4606  stmt_timeout_active = true;
4607  }
4608  }
4609  else
4611 }
static bool stmt_timeout_active
Definition: postgres.c:151
static bool xact_started
Definition: postgres.c:132
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
#define Assert(condition)
Definition: c.h:699
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 2275 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().

2276 {
2278  errdetail("abort reason: recovery conflict");
2279 
2280  return 0;
2281 }
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 2177 of file postgres.c.

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

Referenced by exec_simple_query().

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

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

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

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

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

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

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

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

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

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

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

2326 {
2327  CachedPlanSource *psrc;
2328  int i;
2329 
2330  /*
2331  * Start up a transaction command. (Note that this will normally change
2332  * current memory context.) Nothing happens if we are already in one.
2333  */
2335 
2336  /* Switch back to message context */
2338 
2339  /* Find prepared statement */
2340  if (stmt_name[0] != '\0')
2341  {
2342  PreparedStatement *pstmt;
2343 
2344  pstmt = FetchPreparedStatement(stmt_name, true);
2345  psrc = pstmt->plansource;
2346  }
2347  else
2348  {
2349  /* special-case the unnamed statement */
2350  psrc = unnamed_stmt_psrc;
2351  if (!psrc)
2352  ereport(ERROR,
2353  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2354  errmsg("unnamed prepared statement does not exist")));
2355  }
2356 
2357  /* Prepared statements shouldn't have changeable result descs */
2358  Assert(psrc->fixed_result);
2359 
2360  /*
2361  * If we are in aborted transaction state, we can't run
2362  * SendRowDescriptionMessage(), because that needs catalog accesses.
2363  * Hence, refuse to Describe statements that return data. (We shouldn't
2364  * just refuse all Describes, since that might break the ability of some
2365  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2366  * blindly Describes whatever it does.) We can Describe parameters
2367  * without doing anything dangerous, so we don't restrict that.
2368  */
2370  psrc->resultDesc)
2371  ereport(ERROR,
2372  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2373  errmsg("current transaction is aborted, "
2374  "commands ignored until end of transaction block"),
2375  errdetail_abort()));
2376 
2378  return; /* can't actually do anything... */
2379 
2380  /*
2381  * First describe the parameters...
2382  */
2383  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2384  * message type */
2386 
2387  for (i = 0; i < psrc->num_params; i++)
2388  {
2389  Oid ptype = psrc->param_types[i];
2390 
2391  pq_sendint32(&row_description_buf, (int) ptype);
2392  }
2394 
2395  /*
2396  * Next send RowDescription or NoData to describe the result...
2397  */
2398  if (psrc->resultDesc)
2399  {
2400  List *tlist;
2401 
2402  /* Get the plan's primary targetlist */
2403  tlist = CachedPlanGetTargetList(psrc, NULL);
2404 
2406  psrc->resultDesc,
2407  tlist,
2408  NULL);
2409  }
2410  else
2411  pq_putemptymessage('n'); /* NoData */
2412 
2413 }
CachedPlanSource * plansource
Definition: prepare.h:31
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:370
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:2275
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:1428
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
#define ereport(elevel, rest)
Definition: elog.h:122
static void start_xact_command(void)
Definition: postgres.c:2473
static StringInfoData row_description_buf
Definition: postgres.c:172
#define Assert(condition)
Definition: c.h:699
MemoryContext MessageContext
Definition: mcxt.c:48
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:90
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 1869 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().

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

◆ exec_parse_message()

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

Definition at line 1221 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(), and whereToSendOutput.

Referenced by PostgresMain().

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

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

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

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

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2493 of file postgres.c.

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

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

2494 {
2495  /* cancel active statement timeout after each command */
2497 
2498  if (xact_started)
2499  {
2501 
2502 #ifdef MEMORY_CONTEXT_CHECKING
2503  /* Check all memory contexts that weren't freed during commit */
2504  /* (those that were, were checked before being deleted) */
2505  MemoryContextCheck(TopMemoryContext);
2506 #endif
2507 
2508 #ifdef SHOW_MEMORY_STATS
2509  /* Print mem stats after each commit for leak tracking */
2511 #endif
2512 
2513  xact_started = false;
2514  }
2515 }
void CommitTransactionCommand(void)
Definition: xact.c:2744
static void disable_statement_timeout(void)
Definition: postgres.c:4617
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:474
static bool xact_started
Definition: postgres.c:132
MemoryContext TopMemoryContext
Definition: mcxt.c:44

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2710 of file postgres.c.

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

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

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

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

Referenced by PostgresMain().

4394 {
4395  if (am_walsender)
4396  {
4397  if (firstchar == 'F')
4398  ereport(ERROR,
4399  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4400  errmsg("fastpath function calls not supported in a replication connection")));
4401  else
4402  ereport(ERROR,
4403  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4404  errmsg("extended query protocol not supported in a replication connection")));
4405  }
4406 }
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 4415 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3325 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

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

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 304 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

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

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 216 of file postgres.c.

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

Referenced by ReadCommand().

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

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

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

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

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2542 of file postgres.c.

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

Referenced by exec_execute_message().

2543 {
2544  if (list_length(pstmts) == 1)
2545  {
2546  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2547 
2548  if (pstmt->commandType == CMD_UTILITY &&
2550  return true;
2551  }
2552  return false;
2553 }
#define linitial_node(type, l)
Definition: pg_list.h:114
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2525
Node * utilityStmt
Definition: plannodes.h:96
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 2557 of file postgres.c.

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

Referenced by exec_execute_message().

2558 {
2559  if (list_length(pstmts) == 1)
2560  {
2561  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2562 
2563  if (pstmt->commandType == CMD_UTILITY &&
2564  IsA(pstmt->utilityStmt, TransactionStmt))
2565  return true;
2566  }
2567  return false;
2568 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define linitial_node(type, l)
Definition: pg_list.h:114
Node * utilityStmt
Definition: plannodes.h:96
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 4560 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().

4561 {
4562  Port *port = MyProcPort;
4563  long secs;
4564  int usecs;
4565  int msecs;
4566  int hours,
4567  minutes,
4568  seconds;
4569 
4572  &secs, &usecs);
4573  msecs = usecs / 1000;
4574 
4575  hours = secs / SECS_PER_HOUR;
4576  secs %= SECS_PER_HOUR;
4577  minutes = secs / SECS_PER_MINUTE;
4578  seconds = secs % SECS_PER_MINUTE;
4579 
4580  ereport(LOG,
4581  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4582  "user=%s database=%s host=%s%s%s",
4583  hours, minutes, seconds, msecs,
4584  port->user_name, port->database_name, port->remote_host,
4585  port->remote_port[0] ? " port=" : "", port->remote_port)));
4586 }
struct Port * MyProcPort
Definition: globals.c:42
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 651 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().

654 {
655  Query *query;
656  List *querytree_list;
657 
658  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
659 
660  /*
661  * (1) Perform parse analysis.
662  */
663  if (log_parser_stats)
664  ResetUsage();
665 
666  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
667  queryEnv);
668 
669  if (log_parser_stats)
670  ShowUsage("PARSE ANALYSIS STATISTICS");
671 
672  /*
673  * (2) Rewrite the queries, as necessary
674  */
675  querytree_list = pg_rewrite_query(query);
676 
677  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
678 
679  return querytree_list;
680 }
bool log_parser_stats
Definition: guc.c:440
void ShowUsage(const char *title)
Definition: postgres.c:4458
void ResetUsage(void)
Definition: postgres.c:4451
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:740
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:100
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 688 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().

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

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

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

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

◆ pg_plan_queries()

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

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

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

◆ pg_plan_query()

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

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

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

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

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

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

◆ PostgresMain()

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

Definition at line 3624 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, checkDataDir(), ConfigReloadPending, CreateDataDirLockFile(), 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, jit_reset_after_error(), 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(), PortalErrorCleanup(), 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, SPICleanup(), start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), stmt_timeout_active, TopMemoryContext, UnBlockSig, userDoption, username, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

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

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2729 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

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

◆ process_postgres_switches()

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

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

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

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 529 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

530 {
531  int save_errno = errno;
532 
533  if (DoingCommandRead)
534  {
535  /* Check for general interrupts that arrived while reading */
537 
538  /* Process sinval catchup interrupts that happened while reading */
541 
542  /* Process sinval catchup interrupts that happened while reading */
545  }
546  else if (ProcDiePending && blocked)
547  {
548  /*
549  * We're dying. It's safe (and sane) to handle that now.
550  */
552  }
553 
554  errno = save_errno;
555 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1731
static bool DoingCommandRead
Definition: postgres.c:139
volatile bool ProcDiePending
Definition: globals.c:32
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 567 of file postgres.c.

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

Referenced by secure_write().

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

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

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

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

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

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

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

◆ ReadCommand()

static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 509 of file postgres.c.

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

Referenced by PostgresMain().

510 {
511  int result;
512 
514  result = SocketBackend(inBuf);
515  else
516  result = InteractiveBackend(inBuf);
517  return result;
518 }
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:216
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:332
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

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

2747 {
2748  int save_errno = errno;
2749 
2750  /*
2751  * Don't joggle the elbow of proc_exit
2752  */
2753  if (!proc_exit_inprogress)
2754  {
2755  RecoveryConflictReason = reason;
2756  switch (reason)
2757  {
2759 
2760  /*
2761  * If we aren't waiting for a lock we can never deadlock.
2762  */
2763  if (!IsWaitingForLock())
2764  return;
2765 
2766  /* Intentional fall through to check wait for pin */
2767  /* FALLTHROUGH */
2768 
2770 
2771  /*
2772  * If we aren't blocking the Startup process there is nothing
2773  * more to do.
2774  */
2776  return;
2777 
2779 
2780  /* Intentional fall through to error handling */
2781  /* FALLTHROUGH */
2782 
2786 
2787  /*
2788  * If we aren't in a transaction any longer then ignore.
2789  */
2791  return;
2792 
2793  /*
2794  * If we can abort just the current subtransaction then we are
2795  * OK to throw an ERROR to resolve the conflict. Otherwise
2796  * drop through to the FATAL case.
2797  *
2798  * XXX other times that we can throw just an ERROR *may* be
2799  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2800  * parent transactions
2801  *
2802  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2803  * by parent transactions and the transaction is not
2804  * transaction-snapshot mode
2805  *
2806  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2807  * cursors open in parent transactions
2808  */
2809  if (!IsSubTransaction())
2810  {
2811  /*
2812  * If we already aborted then we no longer need to cancel.
2813  * We do this here since we do not wish to ignore aborted
2814  * subtransactions, which must cause FATAL, currently.
2815  */
2817  return;
2818 
2819  RecoveryConflictPending = true;
2820  QueryCancelPending = true;
2821  InterruptPending = true;
2822  break;
2823  }
2824 
2825  /* Intentional fall through to session cancel */
2826  /* FALLTHROUGH */
2827 
2829  RecoveryConflictPending = true;
2830  ProcDiePending = true;
2831  InterruptPending = true;
2832  break;
2833 
2834  default:
2835  elog(FATAL, "unrecognized conflict mode: %d",
2836  (int) reason);
2837  }
2838