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 3306 of file postgres.c.

References max_stack_depth_bytes.

3307 {
3308  long newval_bytes = newval * 1024L;
3309 
3310  max_stack_depth_bytes = newval_bytes;
3311 }
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 2195 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().

2196 {
2198  {
2199  long secs;
2200  int usecs;
2201  int msecs;
2202  bool exceeded;
2203 
2206  &secs, &usecs);
2207  msecs = usecs / 1000;
2208 
2209  /*
2210  * This odd-looking test for log_min_duration_statement being exceeded
2211  * is designed to avoid integer overflow with very long durations:
2212  * don't compute secs * 1000 until we've verified it will fit in int.
2213  */
2214  exceeded = (log_min_duration_statement == 0 ||
2216  (secs > log_min_duration_statement / 1000 ||
2217  secs * 1000 + msecs >= log_min_duration_statement)));
2218 
2219  if (exceeded || log_duration)
2220  {
2221  snprintf(msec_str, 32, "%ld.%03d",
2222  secs * 1000 + msecs, usecs % 1000);
2223  if (exceeded && !was_logged)
2224  return 2;
2225  else
2226  return 1;
2227  }
2228  }
2229 
2230  return 0;
2231 }
int log_min_duration_statement
Definition: guc.c:464
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:442
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:690

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2158 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

2159 {
2160  ListCell *stmt_item;
2161 
2162  if (log_statement == LOGSTMT_NONE)
2163  return false;
2164  if (log_statement == LOGSTMT_ALL)
2165  return true;
2166 
2167  /* Else we have to inspect the statement(s) to see whether to log */
2168  foreach(stmt_item, stmt_list)
2169  {
2170  Node *stmt = (Node *) lfirst(stmt_item);
2171 
2172  if (GetCommandLogLevel(stmt) <= log_statement)
2173  return true;
2174  }
2175 
2176  return false;
2177 }
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:2939

◆ check_max_stack_depth()

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

Definition at line 3289 of file postgres.c.

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

3290 {
3291  long newval_bytes = *newval * 1024L;
3292  long stack_rlimit = get_stack_depth_rlimit();
3293 
3294  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3295  {
3296  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3297  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3298  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3299  return false;
3300  }
3301  return true;
3302 }
#define GUC_check_errdetail
Definition: guc.h:410
long get_stack_depth_rlimit(void)
Definition: postgres.c:4480
#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 3226 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_matching_subplans_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().

3227 {
3228  if (stack_is_too_deep())
3229  {
3230  ereport(ERROR,
3231  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3232  errmsg("stack depth limit exceeded"),
3233  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3234  "after ensuring the platform's stack depth limit is adequate.",
3235  max_stack_depth)));
3236  }
3237 }
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:141
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:3240

◆ die()

void die ( SIGNAL_ARGS  )

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

2726 {
2727  int save_errno = errno;
2728 
2729  /* Don't joggle the elbow of proc_exit */
2730  if (!proc_exit_inprogress)
2731  {
2732  InterruptPending = true;
2733  ProcDiePending = true;
2734  }
2735 
2736  /* If we're still here, waken anything waiting on the process latch */
2737  SetLatch(MyLatch);
2738 
2739  /*
2740  * If we're in single user mode, we want to quit immediately - we can't
2741  * rely on latches as they wouldn't work when stdin/stdout is a file.
2742  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2743  * effort just for the benefit of single user mode.
2744  */
2747 
2748  errno = save_errno;
2749 }
void ProcessInterrupts(void)
Definition: postgres.c:2936
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 4682 of file postgres.c.

References disable_timeout(), STATEMENT_TIMEOUT, and stmt_timeout_active.

Referenced by exec_execute_message(), and finish_xact_command().

4683 {
4684  if (stmt_timeout_active)
4685  {
4687 
4688  stmt_timeout_active = false;
4689  }
4690 }
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 2633 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2634 {
2635  /* paranoia to avoid a dangling pointer in case of error */
2636  if (unnamed_stmt_psrc)
2637  {
2639 
2640  unnamed_stmt_psrc = NULL;
2641  DropCachedPlan(psrc);
2642  }
2643 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:489

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

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

4662 {
4663  /* must be within an xact */
4665 
4666  if (StatementTimeout > 0)
4667  {
4668  if (!stmt_timeout_active)
4669  {
4671  stmt_timeout_active = true;
4672  }
4673  }
4674  else
4676 }
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:732
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 2337 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().

2338 {
2340  errdetail("abort reason: recovery conflict");
2341 
2342  return 0;
2343 }
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:127
int errdetail(const char *fmt,...)
Definition: elog.c:873

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2240 of file postgres.c.

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

Referenced by exec_simple_query().

2241 {
2242  ListCell *parsetree_item;
2243 
2244  foreach(parsetree_item, raw_parsetree_list)
2245  {
2246  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2247 
2248  if (IsA(parsetree->stmt, ExecuteStmt))
2249  {
2250  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2251  PreparedStatement *pstmt;
2252 
2253  pstmt = FetchPreparedStatement(stmt->name, false);
2254  if (pstmt)
2255  {
2256  errdetail("prepare: %s", pstmt->plansource->query_string);
2257  return 0;
2258  }
2259  }
2260  }
2261 
2262  return 0;
2263 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Node * stmt
Definition: parsenodes.h:1451
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * name
Definition: parsenodes.h:3364
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:495

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

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

2272 {
2273  /* We mustn't call user-defined I/O functions when in an aborted xact */
2274  if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2275  {
2276  StringInfoData param_str;
2277  MemoryContext oldcontext;
2278 
2279  /* This code doesn't support dynamic param lists */
2280  Assert(params->paramFetch == NULL);
2281 
2282  /* Make sure any trash is generated in MessageContext */
2283  oldcontext = MemoryContextSwitchTo(MessageContext);
2284 
2285  initStringInfo(&param_str);
2286 
2287  for (int paramno = 0; paramno < params->numParams; paramno++)
2288  {
2289  ParamExternData *prm = &params->params[paramno];
2290  Oid typoutput;
2291  bool typisvarlena;
2292  char *pstring;
2293  char *p;
2294 
2295  appendStringInfo(&param_str, "%s$%d = ",
2296  paramno > 0 ? ", " : "",
2297  paramno + 1);
2298 
2299  if (prm->isnull || !OidIsValid(prm->ptype))
2300  {
2301  appendStringInfoString(&param_str, "NULL");
2302  continue;
2303  }
2304 
2305  getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2306 
2307  pstring = OidOutputFunctionCall(typoutput, prm->value);
2308 
2309  appendStringInfoCharMacro(&param_str, '\'');
2310  for (p = pstring; *p; p++)
2311  {
2312  if (*p == '\'') /* double single quotes */
2313  appendStringInfoCharMacro(&param_str, *p);
2314  appendStringInfoCharMacro(&param_str, *p);
2315  }
2316  appendStringInfoCharMacro(&param_str, '\'');
2317 
2318  pfree(pstring);
2319  }
2320 
2321  errdetail("parameters: %s", param_str.data);
2322 
2323  pfree(param_str.data);
2324 
2325  MemoryContextSwitchTo(oldcontext);
2326  }
2327 
2328  return 0;
2329 }
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:2676
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
#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:732
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 2351 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().

2352 {
2353  switch (RecoveryConflictReason)
2354  {
2356  errdetail("User was holding shared buffer pin for too long.");
2357  break;
2359  errdetail("User was holding a relation lock for too long.");
2360  break;
2362  errdetail("User was or might have been using tablespace that must be dropped.");
2363  break;
2365  errdetail("User query might have needed to see row versions that must be removed.");
2366  break;
2368  errdetail("User transaction caused buffer deadlock with recovery.");
2369  break;
2371  errdetail("User was connected to a database that must be dropped.");
2372  break;
2373  default:
2374  break;
2375  /* no errdetail */
2376  }
2377 
2378  return 0;
2379 }
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 1553 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().

1554 {
1555  const char *portal_name;
1556  const char *stmt_name;
1557  int numPFormats;
1558  int16 *pformats = NULL;
1559  int numParams;
1560  int numRFormats;
1561  int16 *rformats = NULL;
1562  CachedPlanSource *psrc;
1563  CachedPlan *cplan;
1564  Portal portal;
1565  char *query_string;
1566  char *saved_stmt_name;
1567  ParamListInfo params;
1568  MemoryContext oldContext;
1569  bool save_log_statement_stats = log_statement_stats;
1570  bool snapshot_set = false;
1571  char msec_str[32];
1572 
1573  /* Get the fixed part of the message */
1574  portal_name = pq_getmsgstring(input_message);
1575  stmt_name = pq_getmsgstring(input_message);
1576 
1577  ereport(DEBUG2,
1578  (errmsg("bind %s to %s",
1579  *portal_name ? portal_name : "<unnamed>",
1580  *stmt_name ? stmt_name : "<unnamed>")));
1581 
1582  /* Find prepared statement */
1583  if (stmt_name[0] != '\0')
1584  {
1585  PreparedStatement *pstmt;
1586 
1587  pstmt = FetchPreparedStatement(stmt_name, true);
1588  psrc = pstmt->plansource;
1589  }
1590  else
1591  {
1592  /* special-case the unnamed statement */
1593  psrc = unnamed_stmt_psrc;
1594  if (!psrc)
1595  ereport(ERROR,
1596  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1597  errmsg("unnamed prepared statement does not exist")));
1598  }
1599 
1600  /*
1601  * Report query to various monitoring facilities.
1602  */
1604 
1606 
1607  set_ps_display("BIND", false);
1608 
1609  if (save_log_statement_stats)
1610  ResetUsage();
1611 
1612  /*
1613  * Start up a transaction command so we can call functions etc. (Note that
1614  * this will normally change current memory context.) Nothing happens if
1615  * we are already in one. This also arms the statement timeout if
1616  * necessary.
1617  */
1619 
1620  /* Switch back to message context */
1622 
1623  /* Get the parameter format codes */
1624  numPFormats = pq_getmsgint(input_message, 2);
1625  if (numPFormats > 0)
1626  {
1627  pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1628  for (int i = 0; i < numPFormats; i++)
1629  pformats[i] = pq_getmsgint(input_message, 2);
1630  }
1631 
1632  /* Get the parameter value count */
1633  numParams = pq_getmsgint(input_message, 2);
1634 
1635  if (numPFormats > 1 && numPFormats != numParams)
1636  ereport(ERROR,
1637  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1638  errmsg("bind message has %d parameter formats but %d parameters",
1639  numPFormats, numParams)));
1640 
1641  if (numParams != psrc->num_params)
1642  ereport(ERROR,
1643  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1644  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1645  numParams, stmt_name, psrc->num_params)));
1646 
1647  /*
1648  * If we are in aborted transaction state, the only portals we can
1649  * actually run are those containing COMMIT or ROLLBACK commands. We
1650  * disallow binding anything else to avoid problems with infrastructure
1651  * that expects to run inside a valid transaction. We also disallow
1652  * binding any parameters, since we can't risk calling user-defined I/O
1653  * functions.
1654  */
1656  (!(psrc->raw_parse_tree &&
1658  numParams != 0))
1659  ereport(ERROR,
1660  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1661  errmsg("current transaction is aborted, "
1662  "commands ignored until end of transaction block"),
1663  errdetail_abort()));
1664 
1665  /*
1666  * Create the portal. Allow silent replacement of an existing portal only
1667  * if the unnamed portal is specified.
1668  */
1669  if (portal_name[0] == '\0')
1670  portal = CreatePortal(portal_name, true, true);
1671  else
1672  portal = CreatePortal(portal_name, false, false);
1673 
1674  /*
1675  * Prepare to copy stuff into the portal's memory context. We do all this
1676  * copying first, because it could possibly fail (out-of-memory) and we
1677  * don't want a failure to occur between GetCachedPlan and
1678  * PortalDefineQuery; that would result in leaking our plancache refcount.
1679  */
1680  oldContext = MemoryContextSwitchTo(portal->portalContext);
1681 
1682  /* Copy the plan's query string into the portal */
1683  query_string = pstrdup(psrc->query_string);
1684 
1685  /* Likewise make a copy of the statement name, unless it's unnamed */
1686  if (stmt_name[0])
1687  saved_stmt_name = pstrdup(stmt_name);
1688  else
1689  saved_stmt_name = NULL;
1690 
1691  /*
1692  * Set a snapshot if we have parameters to fetch (since the input
1693  * functions might need it) or the query isn't a utility command (and
1694  * hence could require redoing parse analysis and planning). We keep the
1695  * snapshot active till we're done, so that plancache.c doesn't have to
1696  * take new ones.
1697  */
1698  if (numParams > 0 ||
1699  (psrc->raw_parse_tree &&
1701  {
1703  snapshot_set = true;
1704  }
1705 
1706  /*
1707  * Fetch parameters, if any, and store in the portal's memory context.
1708  */
1709  if (numParams > 0)
1710  {
1711  params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1712  numParams * sizeof(ParamExternData));
1713  /* we have static list of params, so no hooks needed */
1714  params->paramFetch = NULL;
1715  params->paramFetchArg = NULL;
1716  params->paramCompile = NULL;
1717  params->paramCompileArg = NULL;
1718  params->parserSetup = NULL;
1719  params->parserSetupArg = NULL;
1720  params->numParams = numParams;
1721 
1722  for (int paramno = 0; paramno < numParams; paramno++)
1723  {
1724  Oid ptype = psrc->param_types[paramno];
1725  int32 plength;
1726  Datum pval;
1727  bool isNull;
1728  StringInfoData pbuf;
1729  char csave;
1730  int16 pformat;
1731 
1732  plength = pq_getmsgint(input_message, 4);
1733  isNull = (plength == -1);
1734 
1735  if (!isNull)
1736  {
1737  const char *pvalue = pq_getmsgbytes(input_message, plength);
1738 
1739  /*
1740  * Rather than copying data around, we just set up a phony
1741  * StringInfo pointing to the correct portion of the message
1742  * buffer. We assume we can scribble on the message buffer so
1743  * as to maintain the convention that StringInfos have a
1744  * trailing null. This is grotty but is a big win when
1745  * dealing with very large parameter strings.
1746  */
1747  pbuf.data = (char *) pvalue;
1748  pbuf.maxlen = plength + 1;
1749  pbuf.len = plength;
1750  pbuf.cursor = 0;
1751 
1752  csave = pbuf.data[plength];
1753  pbuf.data[plength] = '\0';
1754  }
1755  else
1756  {
1757  pbuf.data = NULL; /* keep compiler quiet */
1758  csave = 0;
1759  }
1760 
1761  if (numPFormats > 1)
1762  pformat = pformats[paramno];
1763  else if (numPFormats > 0)
1764  pformat = pformats[0];
1765  else
1766  pformat = 0; /* default = text */
1767 
1768  if (pformat == 0) /* text mode */
1769  {
1770  Oid typinput;
1771  Oid typioparam;
1772  char *pstring;
1773 
1774  getTypeInputInfo(ptype, &typinput, &typioparam);
1775 
1776  /*
1777  * We have to do encoding conversion before calling the
1778  * typinput routine.
1779  */
1780  if (isNull)
1781  pstring = NULL;
1782  else
1783  pstring = pg_client_to_server(pbuf.data, plength);
1784 
1785  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1786 
1787  /* Free result of encoding conversion, if any */
1788  if (pstring && pstring != pbuf.data)
1789  pfree(pstring);
1790  }
1791  else if (pformat == 1) /* binary mode */
1792  {
1793  Oid typreceive;
1794  Oid typioparam;
1795  StringInfo bufptr;
1796 
1797  /*
1798  * Call the parameter type's binary input converter
1799  */
1800  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1801 
1802  if (isNull)
1803  bufptr = NULL;
1804  else
1805  bufptr = &pbuf;
1806 
1807  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1808 
1809  /* Trouble if it didn't eat the whole buffer */
1810  if (!isNull && pbuf.cursor != pbuf.len)
1811  ereport(ERROR,
1812  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1813  errmsg("incorrect binary data format in bind parameter %d",
1814  paramno + 1)));
1815  }
1816  else
1817  {
1818  ereport(ERROR,
1819  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1820  errmsg("unsupported format code: %d",
1821  pformat)));
1822  pval = 0; /* keep compiler quiet */
1823  }
1824 
1825  /* Restore message buffer contents */
1826  if (!isNull)
1827  pbuf.data[plength] = csave;
1828 
1829  params->params[paramno].value = pval;
1830  params->params[paramno].isnull = isNull;
1831 
1832  /*
1833  * We mark the params as CONST. This ensures that any custom plan
1834  * makes full use of the parameter values.
1835  */
1836  params->params[paramno].pflags = PARAM_FLAG_CONST;
1837  params->params[paramno].ptype = ptype;
1838  }
1839  }
1840  else
1841  params = NULL;
1842 
1843  /* Done storing stuff in portal's context */
1844  MemoryContextSwitchTo(oldContext);
1845 
1846  /* Get the result format codes */
1847  numRFormats = pq_getmsgint(input_message, 2);
1848  if (numRFormats > 0)
1849  {
1850  rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1851  for (int i = 0; i < numRFormats; i++)
1852  rformats[i] = pq_getmsgint(input_message, 2);
1853  }
1854 
1855  pq_getmsgend(input_message);
1856 
1857  /*
1858  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1859  * will be generated in MessageContext. The plan refcount will be
1860  * assigned to the Portal, so it will be released at portal destruction.
1861  */
1862  cplan = GetCachedPlan(psrc, params, false, NULL);
1863 
1864  /*
1865  * Now we can define the portal.
1866  *
1867  * DO NOT put any code that could possibly throw an error between the
1868  * above GetCachedPlan call and here.
1869  */
1870  PortalDefineQuery(portal,
1871  saved_stmt_name,
1872  query_string,
1873  psrc->commandTag,
1874  cplan->stmt_list,
1875  cplan);
1876 
1877  /* Done with the snapshot used for parameter I/O and parsing/planning */
1878  if (snapshot_set)
1880 
1881  /*
1882  * And we're ready to start portal execution.
1883  */
1884  PortalStart(portal, params, 0, InvalidSnapshot);
1885 
1886  /*
1887  * Apply the result format requests to the portal.
1888  */
1889  PortalSetResultFormat(portal, numRFormats, rformats);
1890 
1891  /*
1892  * Send BindComplete.
1893  */
1895  pq_putemptymessage('2');
1896 
1897  /*
1898  * Emit duration logging if appropriate.
1899  */
1900  switch (check_log_duration(msec_str, false))
1901  {
1902  case 1:
1903  ereport(LOG,
1904  (errmsg("duration: %s ms", msec_str),
1905  errhidestmt(true)));
1906  break;
1907  case 2:
1908  ereport(LOG,
1909  (errmsg("duration: %s ms bind %s%s%s: %s",
1910  msec_str,
1911  *stmt_name ? stmt_name : "<unnamed>",
1912  *portal_name ? "/" : "",
1913  *portal_name ? portal_name : "",
1914  psrc->query_string),
1915  errhidestmt(true),
1916  errdetail_params(params)));
1917  break;
1918  }
1919 
1920  if (save_log_statement_stats)
1921  ShowUsage("BIND MESSAGE STATISTICS");
1922 
1923  debug_query_string = NULL;
1924 }
signed short int16
Definition: c.h:345
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:1145
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:451
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:4523
char * pstrdup(const char *in)
Definition: mcxt.c:1161
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:331
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:2337
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:346
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2586
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2195
void ResetUsage(void)
Definition: postgres.c:4516
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:1451
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:2271
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2709
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2643
#define ereport(elevel, rest)
Definition: elog.h:141
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:2534
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:655
#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 2482 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().

2483 {
2484  Portal portal;
2485 
2486  /*
2487  * Start up a transaction command. (Note that this will normally change
2488  * current memory context.) Nothing happens if we are already in one.
2489  */
2491 
2492  /* Switch back to message context */
2494 
2495  portal = GetPortalByName(portal_name);
2496  if (!PortalIsValid(portal))
2497  ereport(ERROR,
2498  (errcode(ERRCODE_UNDEFINED_CURSOR),
2499  errmsg("portal \"%s\" does not exist", portal_name)));
2500 
2501  /*
2502  * If we are in aborted transaction state, we can't run
2503  * SendRowDescriptionMessage(), because that needs catalog accesses.
2504  * Hence, refuse to Describe portals that return data. (We shouldn't just
2505  * refuse all Describes, since that might break the ability of some
2506  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2507  * blindly Describes whatever it does.)
2508  */
2510  portal->tupDesc)
2511  ereport(ERROR,
2512  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2513  errmsg("current transaction is aborted, "
2514  "commands ignored until end of transaction block"),
2515  errdetail_abort()));
2516 
2518  return; /* can't actually do anything... */
2519 
2520  if (portal->tupDesc)
2522  portal->tupDesc,
2523  FetchPortalTargetList(portal),
2524  portal->formats);
2525  else
2526  pq_putemptymessage('n'); /* NoData */
2527 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
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:2337
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2534
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 2387 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().

2388 {
2389  CachedPlanSource *psrc;
2390 
2391  /*
2392  * Start up a transaction command. (Note that this will normally change
2393  * current memory context.) Nothing happens if we are already in one.
2394  */
2396 
2397  /* Switch back to message context */
2399 
2400  /* Find prepared statement */
2401  if (stmt_name[0] != '\0')
2402  {
2403  PreparedStatement *pstmt;
2404 
2405  pstmt = FetchPreparedStatement(stmt_name, true);
2406  psrc = pstmt->plansource;
2407  }
2408  else
2409  {
2410  /* special-case the unnamed statement */
2411  psrc = unnamed_stmt_psrc;
2412  if (!psrc)
2413  ereport(ERROR,
2414  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2415  errmsg("unnamed prepared statement does not exist")));
2416  }
2417 
2418  /* Prepared statements shouldn't have changeable result descs */
2419  Assert(psrc->fixed_result);
2420 
2421  /*
2422  * If we are in aborted transaction state, we can't run
2423  * SendRowDescriptionMessage(), because that needs catalog accesses.
2424  * Hence, refuse to Describe statements that return data. (We shouldn't
2425  * just refuse all Describes, since that might break the ability of some
2426  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2427  * blindly Describes whatever it does.) We can Describe parameters
2428  * without doing anything dangerous, so we don't restrict that.
2429  */
2431  psrc->resultDesc)
2432  ereport(ERROR,
2433  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2434  errmsg("current transaction is aborted, "
2435  "commands ignored until end of transaction block"),
2436  errdetail_abort()));
2437 
2439  return; /* can't actually do anything... */
2440 
2441  /*
2442  * First describe the parameters...
2443  */
2444  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2445  * message type */
2447 
2448  for (int i = 0; i < psrc->num_params; i++)
2449  {
2450  Oid ptype = psrc->param_types[i];
2451 
2452  pq_sendint32(&row_description_buf, (int) ptype);
2453  }
2455 
2456  /*
2457  * Next send RowDescription or NoData to describe the result...
2458  */
2459  if (psrc->resultDesc)
2460  {
2461  List *tlist;
2462 
2463  /* Get the plan's primary targetlist */
2464  tlist = CachedPlanGetTargetList(psrc, NULL);
2465 
2467  psrc->resultDesc,
2468  tlist,
2469  NULL);
2470  }
2471  else
2472  pq_putemptymessage('n'); /* NoData */
2473 
2474 }
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
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:2337
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc resultDesc
Definition: plancache.h:92
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define ERROR
Definition: elog.h:43
Oid * param_types
Definition: plancache.h:86
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1436
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
#define ereport(elevel, rest)
Definition: elog.h:141
static void start_xact_command(void)
Definition: postgres.c:2534
static StringInfoData row_description_buf
Definition: postgres.c:172
#define Assert(condition)
Definition: c.h:732
MemoryContext MessageContext
Definition: mcxt.c:48
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 1932 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().

1933 {
1934  CommandDest dest;
1935  DestReceiver *receiver;
1936  Portal portal;
1937  bool completed;
1938  char completionTag[COMPLETION_TAG_BUFSIZE];
1939  const char *sourceText;
1940  const char *prepStmtName;
1941  ParamListInfo portalParams;
1942  bool save_log_statement_stats = log_statement_stats;
1943  bool is_xact_command;
1944  bool execute_is_fetch;
1945  bool was_logged = false;
1946  char msec_str[32];
1947 
1948  /* Adjust destination to tell printtup.c what to do */
1949  dest = whereToSendOutput;
1950  if (dest == DestRemote)
1951  dest = DestRemoteExecute;
1952 
1953  portal = GetPortalByName(portal_name);
1954  if (!PortalIsValid(portal))
1955  ereport(ERROR,
1956  (errcode(ERRCODE_UNDEFINED_CURSOR),
1957  errmsg("portal \"%s\" does not exist", portal_name)));
1958 
1959  /*
1960  * If the original query was a null string, just return
1961  * EmptyQueryResponse.
1962  */
1963  if (portal->commandTag == NULL)
1964  {
1965  Assert(portal->stmts == NIL);
1966  NullCommand(dest);
1967  return;
1968  }
1969 
1970  /* Does the portal contain a transaction command? */
1971  is_xact_command = IsTransactionStmtList(portal->stmts);
1972 
1973  /*
1974  * We must copy the sourceText and prepStmtName into MessageContext in
1975  * case the portal is destroyed during finish_xact_command. Can avoid the
1976  * copy if it's not an xact command, though.
1977  */
1978  if (is_xact_command)
1979  {
1980  sourceText = pstrdup(portal->sourceText);
1981  if (portal->prepStmtName)
1982  prepStmtName = pstrdup(portal->prepStmtName);
1983  else
1984  prepStmtName = "<unnamed>";
1985 
1986  /*
1987  * An xact command shouldn't have any parameters, which is a good
1988  * thing because they wouldn't be around after finish_xact_command.
1989  */
1990  portalParams = NULL;
1991  }
1992  else
1993  {
1994  sourceText = portal->sourceText;
1995  if (portal->prepStmtName)
1996  prepStmtName = portal->prepStmtName;
1997  else
1998  prepStmtName = "<unnamed>";
1999  portalParams = portal->portalParams;
2000  }
2001 
2002  /*
2003  * Report query to various monitoring facilities.
2004  */
2005  debug_query_string = sourceText;
2006 
2008 
2009  set_ps_display(portal->commandTag, false);
2010 
2011  if (save_log_statement_stats)
2012  ResetUsage();
2013 
2014  BeginCommand(portal->commandTag, dest);
2015 
2016  /*
2017  * Create dest receiver in MessageContext (we don't want it in transaction
2018  * context, because that may get deleted if portal contains VACUUM).
2019  */
2020  receiver = CreateDestReceiver(dest);
2021  if (dest == DestRemoteExecute)
2022  SetRemoteDestReceiverParams(receiver, portal);
2023 
2024  /*
2025  * Ensure we are in a transaction command (this should normally be the
2026  * case already due to prior BIND).
2027  */
2029 
2030  /*
2031  * If we re-issue an Execute protocol request against an existing portal,
2032  * then we are only fetching more rows rather than completely re-executing
2033  * the query from the start. atStart is never reset for a v3 portal, so we
2034  * are safe to use this check.
2035  */
2036  execute_is_fetch = !portal->atStart;
2037 
2038  /* Log immediately if dictated by log_statement */
2039  if (check_log_statement(portal->stmts))
2040  {
2041  ereport(LOG,
2042  (errmsg("%s %s%s%s: %s",
2043  execute_is_fetch ?
2044  _("execute fetch from") :
2045  _("execute"),
2046  prepStmtName,
2047  *portal_name ? "/" : "",
2048  *portal_name ? portal_name : "",
2049  sourceText),
2050  errhidestmt(true),
2051  errdetail_params(portalParams)));
2052  was_logged = true;
2053  }
2054 
2055  /*
2056  * If we are in aborted transaction state, the only portals we can
2057  * actually run are those containing COMMIT or ROLLBACK commands.
2058  */
2060  !IsTransactionExitStmtList(portal->stmts))
2061  ereport(ERROR,
2062  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2063  errmsg("current transaction is aborted, "
2064  "commands ignored until end of transaction block"),
2065  errdetail_abort()));
2066 
2067  /* Check for cancel signal before we start execution */
2069 
2070  /*
2071  * Okay to run the portal.
2072  */
2073  if (max_rows <= 0)
2074  max_rows = FETCH_ALL;
2075 
2076  completed = PortalRun(portal,
2077  max_rows,
2078  true, /* always top level */
2079  !execute_is_fetch && max_rows == FETCH_ALL,
2080  receiver,
2081  receiver,
2082  completionTag);
2083 
2084  receiver->rDestroy(receiver);
2085 
2086  if (completed)
2087  {
2088  if (is_xact_command)
2089  {
2090  /*
2091  * If this was a transaction control statement, commit it. We
2092  * will start a new xact command for the next command (if any).
2093  */
2095  }
2096  else
2097  {
2098  /*
2099  * We need a CommandCounterIncrement after every query, except
2100  * those that start or end a transaction block.
2101  */
2103 
2104  /* full command has been executed, reset timeout */
2106  }
2107 
2108  /* Send appropriate CommandComplete to client */
2109  EndCommand(completionTag, dest);
2110  }
2111  else
2112  {
2113  /* Portal run not complete, so send PortalSuspended */
2115  pq_putemptymessage('s');
2116  }
2117 
2118  /*
2119  * Emit duration logging if appropriate.
2120  */
2121  switch (check_log_duration(msec_str, was_logged))
2122  {
2123  case 1:
2124  ereport(LOG,
2125  (errmsg("duration: %s ms", msec_str),
2126  errhidestmt(true)));
2127  break;
2128  case 2:
2129  ereport(LOG,
2130  (errmsg("duration: %s ms %s %s%s%s: %s",
2131  msec_str,
2132  execute_is_fetch ?
2133  _("execute fetch from") :
2134  _("execute"),
2135  prepStmtName,
2136  *portal_name ? "/" : "",
2137  *portal_name ? portal_name : "",
2138  sourceText),
2139  errhidestmt(true),
2140  errdetail_params(portalParams)));
2141  break;
2142  }
2143 
2144  if (save_log_statement_stats)
2145  ShowUsage("EXECUTE MESSAGE STATISTICS");
2146 
2147  debug_query_string = NULL;
2148 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2618
#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:2554
CommandDest
Definition: dest.h:86
bool log_statement_stats
Definition: guc.c:451
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void ShowUsage(const char *title)
Definition: postgres.c:4523
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
char * pstrdup(const char *in)
Definition: mcxt.c:1161
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:331
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:2337
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:2195
void ResetUsage(void)
Definition: postgres.c:4516
static void disable_statement_timeout(void)
Definition: postgres.c:4682
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:2271
#define ereport(elevel, rest)
Definition: elog.h:141
const char * debug_query_string
Definition: postgres.c:87
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2158
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2534
void CommandCounterIncrement(void)
Definition: xact.c:895
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:732
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2603
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:2689

◆ exec_parse_message()

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

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

1295 {
1296  MemoryContext unnamed_stmt_context = NULL;
1297  MemoryContext oldcontext;
1298  List *parsetree_list;
1299  RawStmt *raw_parse_tree;
1300  const char *commandTag;
1301  List *querytree_list;
1302  CachedPlanSource *psrc;
1303  bool is_named;
1304  bool save_log_statement_stats = log_statement_stats;
1305  char msec_str[32];
1306 
1307  /*
1308  * Report query to various monitoring facilities.
1309  */
1310  debug_query_string = query_string;
1311 
1312  pgstat_report_activity(STATE_RUNNING, query_string);
1313 
1314  set_ps_display("PARSE", false);
1315 
1316  if (save_log_statement_stats)
1317  ResetUsage();
1318 
1319  ereport(DEBUG2,
1320  (errmsg("parse %s: %s",
1321  *stmt_name ? stmt_name : "<unnamed>",
1322  query_string)));
1323 
1324  /*
1325  * Start up a transaction command so we can run parse analysis etc. (Note
1326  * that this will normally change current memory context.) Nothing happens
1327  * if we are already in one. This also arms the statement timeout if
1328  * necessary.
1329  */
1331 
1332  /*
1333  * Switch to appropriate context for constructing parsetrees.
1334  *
1335  * We have two strategies depending on whether the prepared statement is
1336  * named or not. For a named prepared statement, we do parsing in
1337  * MessageContext and copy the finished trees into the prepared
1338  * statement's plancache entry; then the reset of MessageContext releases
1339  * temporary space used by parsing and rewriting. For an unnamed prepared
1340  * statement, we assume the statement isn't going to hang around long, so
1341  * getting rid of temp space quickly is probably not worth the costs of
1342  * copying parse trees. So in this case, we create the plancache entry's
1343  * query_context here, and do all the parsing work therein.
1344  */
1345  is_named = (stmt_name[0] != '\0');
1346  if (is_named)
1347  {
1348  /* Named prepared statement --- parse in MessageContext */
1349  oldcontext = MemoryContextSwitchTo(MessageContext);
1350  }
1351  else
1352  {
1353  /* Unnamed prepared statement --- release any prior unnamed stmt */
1355  /* Create context for parsing */
1356  unnamed_stmt_context =
1358  "unnamed prepared statement",
1360  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1361  }
1362 
1363  /*
1364  * Do basic parsing of the query or queries (this should be safe even if
1365  * we are in aborted transaction state!)
1366  */
1367  parsetree_list = pg_parse_query(query_string);
1368 
1369  /*
1370  * We only allow a single user statement in a prepared statement. This is
1371  * mainly to keep the protocol simple --- otherwise we'd need to worry
1372  * about multiple result tupdescs and things like that.
1373  */
1374  if (list_length(parsetree_list) > 1)
1375  ereport(ERROR,
1376  (errcode(ERRCODE_SYNTAX_ERROR),
1377  errmsg("cannot insert multiple commands into a prepared statement")));
1378 
1379  if (parsetree_list != NIL)
1380  {
1381  Query *query;
1382  bool snapshot_set = false;
1383 
1384  raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1385 
1386  /*
1387  * Get the command name for possible use in status display.
1388  */
1389  commandTag = CreateCommandTag(raw_parse_tree->stmt);
1390 
1391  /*
1392  * If we are in an aborted transaction, reject all commands except
1393  * COMMIT/ROLLBACK. It is important that this test occur before we
1394  * try to do parse analysis, rewrite, or planning, since all those
1395  * phases try to do database accesses, which may fail in abort state.
1396  * (It might be safe to allow some additional utility commands in this
1397  * state, but not many...)
1398  */
1400  !IsTransactionExitStmt(raw_parse_tree->stmt))
1401  ereport(ERROR,
1402  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1403  errmsg("current transaction is aborted, "
1404  "commands ignored until end of transaction block"),
1405  errdetail_abort()));
1406 
1407  /*
1408  * Create the CachedPlanSource before we do parse analysis, since it
1409  * needs to see the unmodified raw parse tree.
1410  */
1411  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1412 
1413  /*
1414  * Set up a snapshot if parse analysis will need one.
1415  */
1416  if (analyze_requires_snapshot(raw_parse_tree))
1417  {
1419  snapshot_set = true;
1420  }
1421 
1422  /*
1423  * Analyze and rewrite the query. Note that the originally specified
1424  * parameter set is not required to be complete, so we have to use
1425  * parse_analyze_varparams().
1426  */
1427  if (log_parser_stats)
1428  ResetUsage();
1429 
1430  query = parse_analyze_varparams(raw_parse_tree,
1431  query_string,
1432  &paramTypes,
1433  &numParams);
1434 
1435  /*
1436  * Check all parameter types got determined.
1437  */
1438  for (int i = 0; i < numParams; i++)
1439  {
1440  Oid ptype = paramTypes[i];
1441 
1442  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1443  ereport(ERROR,
1444  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1445  errmsg("could not determine data type of parameter $%d",
1446  i + 1)));
1447  }
1448 
1449  if (log_parser_stats)
1450  ShowUsage("PARSE ANALYSIS STATISTICS");
1451 
1452  querytree_list = pg_rewrite_query(query);
1453 
1454  /* Done with the snapshot used for parsing */
1455  if (snapshot_set)
1457  }
1458  else
1459  {
1460  /* Empty input string. This is legal. */
1461  raw_parse_tree = NULL;
1462  commandTag = NULL;
1463  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1464  querytree_list = NIL;
1465  }
1466 
1467  /*
1468  * CachedPlanSource must be a direct child of MessageContext before we
1469  * reparent unnamed_stmt_context under it, else we have a disconnected
1470  * circular subgraph. Klugy, but less so than flipping contexts even more
1471  * above.
1472  */
1473  if (unnamed_stmt_context)
1475 
1476  /* Finish filling in the CachedPlanSource */
1477  CompleteCachedPlan(psrc,
1478  querytree_list,
1479  unnamed_stmt_context,
1480  paramTypes,
1481  numParams,
1482  NULL,
1483  NULL,
1484  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1485  true); /* fixed result */
1486 
1487  /* If we got a cancel signal during analysis, quit */
1489 
1490  if (is_named)
1491  {
1492  /*
1493  * Store the query as a prepared statement.
1494  */
1495  StorePreparedStatement(stmt_name, psrc, false);
1496  }
1497  else
1498  {
1499  /*
1500  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1501  */
1502  SaveCachedPlan(psrc);
1503  unnamed_stmt_psrc = psrc;
1504  }
1505 
1506  MemoryContextSwitchTo(oldcontext);
1507 
1508  /*
1509  * We do NOT close the open transaction command here; that only happens
1510  * when the client sends Sync. Instead, do CommandCounterIncrement just
1511  * in case something happened during parse/plan.
1512  */
1514 
1515  /*
1516  * Send ParseComplete.
1517  */
1519  pq_putemptymessage('1');
1520 
1521  /*
1522  * Emit duration logging if appropriate.
1523  */
1524  switch (check_log_duration(msec_str, false))
1525  {
1526  case 1:
1527  ereport(LOG,
1528  (errmsg("duration: %s ms", msec_str),
1529  errhidestmt(true)));
1530  break;
1531  case 2:
1532  ereport(LOG,
1533  (errmsg("duration: %s ms parse %s: %s",
1534  msec_str,
1535  *stmt_name ? stmt_name : "<unnamed>",
1536  query_string),
1537  errhidestmt(true)));
1538  break;
1539  }
1540 
1541  if (save_log_statement_stats)
1542  ShowUsage("PARSE MESSAGE STATISTICS");
1543 
1544  debug_query_string = NULL;
1545 }
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:448
bool log_statement_stats
Definition: guc.c:451
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void ShowUsage(const char *title)
Definition: postgres.c:4523
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:354
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:331
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:2337
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:2586
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2195
void ResetUsage(void)
Definition: postgres.c:4516
#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:1451
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:154
#define ereport(elevel, rest)
Definition: elog.h:141
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2079
#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:746
static void start_xact_command(void)
Definition: postgres.c:2534
void CommandCounterIncrement(void)
Definition: xact.c:895
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:444
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:328
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:2654
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void drop_unnamed_stmt(void)
Definition: postgres.c:2633
#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 961 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().

962 {
964  MemoryContext oldcontext;
965  List *parsetree_list;
966  ListCell *parsetree_item;
967  bool save_log_statement_stats = log_statement_stats;
968  bool was_logged = false;
969  bool use_implicit_block;
970  char msec_str[32];
971 
972  /*
973  * Report query to various monitoring facilities.
974  */
975  debug_query_string = query_string;
976 
977  pgstat_report_activity(STATE_RUNNING, query_string);
978 
979  TRACE_POSTGRESQL_QUERY_START(query_string);
980 
981  /*
982  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
983  * results because ResetUsage wasn't called.
984  */
985  if (save_log_statement_stats)
986  ResetUsage();
987 
988  /*
989  * Start up a transaction command. All queries generated by the
990  * query_string will be in this same command block, *unless* we find a
991  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
992  * one of those, else bad things will happen in xact.c. (Note that this
993  * will normally change current memory context.)
994  */
996 
997  /*
998  * Zap any pre-existing unnamed statement. (While not strictly necessary,
999  * it seems best to define simple-Query mode as if it used the unnamed
1000  * statement and portal; this ensures we recover any storage used by prior
1001  * unnamed operations.)
1002  */
1004 
1005  /*
1006  * Switch to appropriate context for constructing parsetrees.
1007  */
1008  oldcontext = MemoryContextSwitchTo(MessageContext);
1009 
1010  /*
1011  * Do basic parsing of the query or queries (this should be safe even if
1012  * we are in aborted transaction state!)
1013  */
1014  parsetree_list = pg_parse_query(query_string);
1015 
1016  /* Log immediately if dictated by log_statement */
1017  if (check_log_statement(parsetree_list))
1018  {
1019  ereport(LOG,
1020  (errmsg("statement: %s", query_string),
1021  errhidestmt(true),
1022  errdetail_execute(parsetree_list)));
1023  was_logged = true;
1024  }
1025 
1026  /*
1027  * Switch back to transaction context to enter the loop.
1028  */
1029  MemoryContextSwitchTo(oldcontext);
1030 
1031  /*
1032  * For historical reasons, if multiple SQL statements are given in a
1033  * single "simple Query" message, we execute them as a single transaction,
1034  * unless explicit transaction control commands are included to make
1035  * portions of the list be separate transactions. To represent this
1036  * behavior properly in the transaction machinery, we use an "implicit"
1037  * transaction block.
1038  */
1039  use_implicit_block = (list_length(parsetree_list) > 1);
1040 
1041  /*
1042  * Run through the raw parsetree(s) and process each one.
1043  */
1044  foreach(parsetree_item, parsetree_list)
1045  {
1046  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1047  bool snapshot_set = false;
1048  const char *commandTag;
1049  char completionTag[COMPLETION_TAG_BUFSIZE];
1050  List *querytree_list,
1051  *plantree_list;
1052  Portal portal;
1053  DestReceiver *receiver;
1054  int16 format;
1055 
1056  /*
1057  * Get the command name for use in status display (it also becomes the
1058  * default completion tag, down inside PortalRun). Set ps_status and
1059  * do any special start-of-SQL-command processing needed by the
1060  * destination.
1061  */
1062  commandTag = CreateCommandTag(parsetree->stmt);
1063 
1064  set_ps_display(commandTag, false);
1065 
1066  BeginCommand(commandTag, dest);
1067 
1068  /*
1069  * If we are in an aborted transaction, reject all commands except
1070  * COMMIT/ABORT. It is important that this test occur before we try
1071  * to do parse analysis, rewrite, or planning, since all those phases
1072  * try to do database accesses, which may fail in abort state. (It
1073  * might be safe to allow some additional utility commands in this
1074  * state, but not many...)
1075  */
1077  !IsTransactionExitStmt(parsetree->stmt))
1078  ereport(ERROR,
1079  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1080  errmsg("current transaction is aborted, "
1081  "commands ignored until end of transaction block"),
1082  errdetail_abort()));
1083 
1084  /* Make sure we are in a transaction command */
1086 
1087  /*
1088  * If using an implicit transaction block, and we're not already in a
1089  * transaction block, start an implicit block to force this statement
1090  * to be grouped together with any following ones. (We must do this
1091  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1092  * list would cause later statements to not be grouped.)
1093  */
1094  if (use_implicit_block)
1096 
1097  /* If we got a cancel signal in parsing or prior command, quit */
1099 
1100  /*
1101  * Set up a snapshot if parse analysis/planning will need one.
1102  */
1103  if (analyze_requires_snapshot(parsetree))
1104  {
1106  snapshot_set = true;
1107  }
1108 
1109  /*
1110  * OK to analyze, rewrite, and plan this query.
1111  *
1112  * Switch to appropriate context for constructing querytrees (again,
1113  * these must outlive the execution context).
1114  */
1115  oldcontext = MemoryContextSwitchTo(MessageContext);
1116 
1117  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1118  NULL, 0, NULL);
1119 
1120  plantree_list = pg_plan_queries(querytree_list,
1121  CURSOR_OPT_PARALLEL_OK, NULL);
1122 
1123  /* Done with the snapshot used for parsing/planning */
1124  if (snapshot_set)
1126 
1127  /* If we got a cancel signal in analysis or planning, quit */
1129 
1130  /*
1131  * Create unnamed portal to run the query or queries in. If there
1132  * already is one, silently drop it.
1133  */
1134  portal = CreatePortal("", true, true);
1135  /* Don't display the portal in pg_cursors */
1136  portal->visible = false;
1137 
1138  /*
1139  * We don't have to copy anything into the portal, because everything
1140  * we are passing here is in MessageContext, which will outlive the
1141  * portal anyway.
1142  */
1143  PortalDefineQuery(portal,
1144  NULL,
1145  query_string,
1146  commandTag,
1147  plantree_list,
1148  NULL);
1149 
1150  /*
1151  * Start the portal. No parameters here.
1152  */
1153  PortalStart(portal, NULL, 0, InvalidSnapshot);
1154 
1155  /*
1156  * Select the appropriate output format: text unless we are doing a
1157  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1158  * --- but it avoids grottiness in other places. Ah, the joys of
1159  * backward compatibility...)
1160  */
1161  format = 0; /* TEXT is default */
1162  if (IsA(parsetree->stmt, FetchStmt))
1163  {
1164  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1165 
1166  if (!stmt->ismove)
1167  {
1168  Portal fportal = GetPortalByName(stmt->portalname);
1169 
1170  if (PortalIsValid(fportal) &&
1171  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1172  format = 1; /* BINARY */
1173  }
1174  }
1175  PortalSetResultFormat(portal, 1, &format);
1176 
1177  /*
1178  * Now we can create the destination receiver object.
1179  */
1180  receiver = CreateDestReceiver(dest);
1181  if (dest == DestRemote)
1182  SetRemoteDestReceiverParams(receiver, portal);
1183 
1184  /*
1185  * Switch back to transaction context for execution.
1186  */
1187  MemoryContextSwitchTo(oldcontext);
1188 
1189  /*
1190  * Run the portal to completion, and then drop it (and the receiver).
1191  */
1192  (void) PortalRun(portal,
1193  FETCH_ALL,
1194  true, /* always top level */
1195  true,
1196  receiver,
1197  receiver,
1198  completionTag);
1199 
1200  receiver->rDestroy(receiver);
1201 
1202  PortalDrop(portal, false);
1203 
1204  if (lnext(parsetree_item) == NULL)
1205  {
1206  /*
1207  * If this is the last parsetree of the query string, close down
1208  * transaction statement before reporting command-complete. This
1209  * is so that any end-of-transaction errors are reported before
1210  * the command-complete message is issued, to avoid confusing
1211  * clients who will expect either a command-complete message or an
1212  * error, not one and then the other. Also, if we're using an
1213  * implicit transaction block, we must close that out first.
1214  */
1215  if (use_implicit_block)
1218  }
1219  else if (IsA(parsetree->stmt, TransactionStmt))
1220  {
1221  /*
1222  * If this was a transaction control statement, commit it. We will
1223  * start a new xact command for the next command.
1224  */
1226  }
1227  else
1228  {
1229  /*
1230  * We need a CommandCounterIncrement after every query, except
1231  * those that start or end a transaction block.
1232  */
1234  }
1235 
1236  /*
1237  * Tell client that we're done with this query. Note we emit exactly
1238  * one EndCommand report for each raw parsetree, thus one for each SQL
1239  * command the client sent, regardless of rewriting. (But a command
1240  * aborted by error will not send an EndCommand report at all.)
1241  */
1242  EndCommand(completionTag, dest);
1243  } /* end loop over parsetrees */
1244 
1245  /*
1246  * Close down transaction statement, if one is open. (This will only do
1247  * something if the parsetree list was empty; otherwise the last loop
1248  * iteration already did it.)
1249  */
1251 
1252  /*
1253  * If there were no parsetrees, return EmptyQueryResponse message.
1254  */
1255  if (!parsetree_list)
1256  NullCommand(dest);
1257 
1258  /*
1259  * Emit duration logging if appropriate.
1260  */
1261  switch (check_log_duration(msec_str, was_logged))
1262  {
1263  case 1:
1264  ereport(LOG,
1265  (errmsg("duration: %s ms", msec_str),
1266  errhidestmt(true)));
1267  break;
1268  case 2:
1269  ereport(LOG,
1270  (errmsg("duration: %s ms statement: %s",
1271  msec_str, query_string),
1272  errhidestmt(true),
1273  errdetail_execute(parsetree_list)));
1274  break;
1275  }
1276 
1277  if (save_log_statement_stats)
1278  ShowUsage("QUERY STATISTICS");
1279 
1280  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1281 
1282  debug_query_string = NULL;
1283 }
signed short int16
Definition: c.h:345
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:2554
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:451
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
void ShowUsage(const char *title)
Definition: postgres.c:4523
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2645
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:331
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:2337
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:657
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2586
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2195
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2240
void ResetUsage(void)
Definition: postgres.c:4516
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:1451
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
void BeginImplicitTransactionBlock(void)
Definition: xact.c:3759
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
char * portalname
Definition: parsenodes.h:2696
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:141
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2079
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:2158
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2534
void EndImplicitTransactionBlock(void)
Definition: xact.c:3784
bool ismove
Definition: parsenodes.h:2697
void CommandCounterIncrement(void)
Definition: xact.c:895
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:2654
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:2633
#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:923
void NullCommand(CommandDest dest)
Definition: dest.c:198
#define FETCH_ALL
Definition: parsenodes.h:2689

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2554 of file postgres.c.

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

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

2555 {
2556  /* cancel active statement timeout after each command */
2558 
2559  if (xact_started)
2560  {
2562 
2563 #ifdef MEMORY_CONTEXT_CHECKING
2564  /* Check all memory contexts that weren't freed during commit */
2565  /* (those that were, were checked before being deleted) */
2566  MemoryContextCheck(TopMemoryContext);
2567 #endif
2568 
2569 #ifdef SHOW_MEMORY_STATS
2570  /* Print mem stats after each commit for leak tracking */
2572 #endif
2573 
2574  xact_started = false;
2575  }
2576 }
void CommitTransactionCommand(void)
Definition: xact.c:2725
static void disable_statement_timeout(void)
Definition: postgres.c:4682
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 2777 of file postgres.c.

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

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

2778 {
2779  /* We're not returning, so no need to save errno */
2780  ereport(ERROR,
2781  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2782  errmsg("floating-point exception"),
2783  errdetail("An invalid floating-point operation was signaled. "
2784  "This probably means an out-of-range result or an "
2785  "invalid operation, such as division by zero.")));
2786 }
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:141
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 4458 of file postgres.c.

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

Referenced by PostgresMain().

4459 {
4460  if (am_walsender)
4461  {
4462  if (firstchar == 'F')
4463  ereport(ERROR,
4464  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4465  errmsg("fastpath function calls not supported in a replication connection")));
4466  else
4467  ereport(ERROR,
4468  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4469  errmsg("extended query protocol not supported in a replication connection")));
4470  }
4471 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool am_walsender
Definition: walsender.c:114
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4480 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4481 {
4482 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4483  static long val = 0;
4484 
4485  /* This won't change after process launch, so check just once */
4486  if (val == 0)
4487  {
4488  struct rlimit rlim;
4489 
4490  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4491  val = -1;
4492  else if (rlim.rlim_cur == RLIM_INFINITY)
4493  val = LONG_MAX;
4494  /* rlim_cur is probably of an unsigned type, so check for overflow */
4495  else if (rlim.rlim_cur >= LONG_MAX)
4496  val = LONG_MAX;
4497  else
4498  val = rlim.rlim_cur;
4499  }
4500  return val;
4501 #else /* no getrlimit */
4502 #if defined(WIN32) || defined(__CYGWIN__)
4503  /* On Windows we set the backend stack size in src/backend/Makefile */
4504  return WIN32_STACK_RLIMIT;
4505 #else /* not windows ... give up */
4506  return -1;
4507 #endif
4508 #endif
4509 }
long val
Definition: informix.c:689

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3392 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3393 {
3394  switch (arg[0])
3395  {
3396  case 'p':
3397  if (optarg[1] == 'a') /* "parser" */
3398  return "log_parser_stats";
3399  else if (optarg[1] == 'l') /* "planner" */
3400  return "log_planner_stats";
3401  break;
3402 
3403  case 'e': /* "executor" */
3404  return "log_executor_stats";
3405  break;
3406  }
3407 
3408  return NULL;
3409 }
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 2586 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().

2587 {
2588  if (parsetree && IsA(parsetree, TransactionStmt))
2589  {
2590  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2591 
2592  if (stmt->kind == TRANS_STMT_COMMIT ||
2593  stmt->kind == TRANS_STMT_PREPARE ||
2594  stmt->kind == TRANS_STMT_ROLLBACK ||
2595  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2596  return true;
2597  }
2598  return false;
2599 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
TransactionStmtKind kind
Definition: parsenodes.h:2976

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2603 of file postgres.c.

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

Referenced by exec_execute_message().

2604 {
2605  if (list_length(pstmts) == 1)
2606  {
2607  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2608 
2609  if (pstmt->commandType == CMD_UTILITY &&
2611  return true;
2612  }
2613  return false;
2614 }
#define linitial_node(type, l)
Definition: pg_list.h:114
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2586
Node * utilityStmt
Definition: plannodes.h:97
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:89

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2618 of file postgres.c.

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

Referenced by exec_execute_message().

2619 {
2620  if (list_length(pstmts) == 1)
2621  {
2622  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2623 
2624  if (pstmt->commandType == CMD_UTILITY &&
2625  IsA(pstmt->utilityStmt, TransactionStmt))
2626  return true;
2627  }
2628  return false;
2629 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define linitial_node(type, l)
Definition: pg_list.h:114
Node * utilityStmt
Definition: plannodes.h:97
CmdType commandType
Definition: plannodes.h:46
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 4625 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().

4626 {
4627  Port *port = MyProcPort;
4628  long secs;
4629  int usecs;
4630  int msecs;
4631  int hours,
4632  minutes,
4633  seconds;
4634 
4637  &secs, &usecs);
4638  msecs = usecs / 1000;
4639 
4640  hours = secs / SECS_PER_HOUR;
4641  secs %= SECS_PER_HOUR;
4642  minutes = secs / SECS_PER_MINUTE;
4643  seconds = secs % SECS_PER_MINUTE;
4644 
4645  ereport(LOG,
4646  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4647  "user=%s database=%s host=%s%s%s",
4648  hours, minutes, seconds, msecs,
4649  port->user_name, port->database_name, port->remote_host,
4650  port->remote_port[0] ? " port=" : "", port->remote_port)));
4651 }
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:141
#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 657 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().

660 {
661  Query *query;
662  List *querytree_list;
663 
664  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
665 
666  /*
667  * (1) Perform parse analysis.
668  */
669  if (log_parser_stats)
670  ResetUsage();
671 
672  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
673  queryEnv);
674 
675  if (log_parser_stats)
676  ShowUsage("PARSE ANALYSIS STATISTICS");
677 
678  /*
679  * (2) Rewrite the queries, as necessary
680  */
681  querytree_list = pg_rewrite_query(query);
682 
683  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
684 
685  return querytree_list;
686 }
bool log_parser_stats
Definition: guc.c:448
void ShowUsage(const char *title)
Definition: postgres.c:4523
void ResetUsage(void)
Definition: postgres.c:4516
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:746
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 694 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().

699 {
700  ParseState *pstate;
701  Query *query;
702  List *querytree_list;
703 
704  Assert(query_string != NULL); /* required as of 8.4 */
705 
706  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
707 
708  /*
709  * (1) Perform parse analysis.
710  */
711  if (log_parser_stats)
712  ResetUsage();
713 
714  pstate = make_parsestate(NULL);
715  pstate->p_sourcetext = query_string;
716  pstate->p_queryEnv = queryEnv;
717  (*parserSetup) (pstate, parserSetupArg);
718 
719  query = transformTopLevelStmt(pstate, parsetree);
720 
722  (*post_parse_analyze_hook) (pstate, query);
723 
724  free_parsestate(pstate);
725 
726  if (log_parser_stats)
727  ShowUsage("PARSE ANALYSIS STATISTICS");
728 
729  /*
730  * (2) Rewrite the queries, as necessary
731  */
732  querytree_list = pg_rewrite_query(query);
733 
734  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
735 
736  return querytree_list;
737 }
bool log_parser_stats
Definition: guc.c:448
QueryEnvironment * p_queryEnv
Definition: parse_node.h:197
void ShowUsage(const char *title)
Definition: postgres.c:4523
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4516
const char * p_sourcetext
Definition: parse_node.h:173
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:746
#define Assert(condition)
Definition: c.h:732
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  /*
637  * Currently, outfuncs/readfuncs support is missing for many raw parse
638  * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
639  * here.
640  */
641 
642  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
643 
644  return raw_parsetree_list;
645 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:448
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
void ShowUsage(const char *title)
Definition: postgres.c:4523
static List * new_list(NodeTag type)
Definition: list.c:63
void ResetUsage(void)
Definition: postgres.c:4516
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:226
#define copyObject(obj)
Definition: nodes.h:633
Definition: pg_list.h:45

◆ pg_plan_queries()

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

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

924 {
925  List *stmt_list = NIL;
926  ListCell *query_list;
927 
928  foreach(query_list, querytrees)
929  {
930  Query *query = lfirst_node(Query, query_list);
931  PlannedStmt *stmt;
932 
933  if (query->commandType == CMD_UTILITY)
934  {
935  /* Utility commands require no planning. */
936  stmt = makeNode(PlannedStmt);
937  stmt->commandType = CMD_UTILITY;
938  stmt->canSetTag = query->canSetTag;
939  stmt->utilityStmt = query->utilityStmt;
940  stmt->stmt_location = query->stmt_location;
941  stmt->stmt_len = query->stmt_len;
942  }
943  else
944  {
945  stmt = pg_plan_query(query, cursorOptions, boundParams);
946  }
947 
948  stmt_list = lappend(stmt_list, stmt);
949  }
950 
951  return stmt_list;
952 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:180
Node * utilityStmt
Definition: parsenodes.h:120
int stmt_len
Definition: plannodes.h:101
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:100
Node * utilityStmt
Definition: plannodes.h:97
List * lappend(List *list, void *datum)
Definition: list.c:128
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
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:181
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:838

◆ pg_plan_query()

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

Definition at line 838 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, nodeToString(), pfree(), planner(), ResetUsage(), ShowUsage(), generate_unaccent_rules::str, and WARNING.

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

839 {
840  PlannedStmt *plan;
841 
842  /* Utility commands have no plans. */
843  if (querytree->commandType == CMD_UTILITY)
844  return NULL;
845 
846  /* Planner must have a snapshot in case it calls user-defined functions. */
848 
849  TRACE_POSTGRESQL_QUERY_PLAN_START();
850 
851  if (log_planner_stats)
852  ResetUsage();
853 
854  /* call the optimizer */
855  plan = planner(querytree, cursorOptions, boundParams);
856 
857  if (log_planner_stats)
858  ShowUsage("PLANNER STATISTICS");
859 
860 #ifdef COPY_PARSE_PLAN_TREES
861  /* Optional debugging check: pass plan tree through copyObject() */
862  {
863  PlannedStmt *new_plan = copyObject(plan);
864 
865  /*
866  * equal() currently does not have routines to compare Plan nodes, so
867  * don't try to test equality here. Perhaps fix someday?
868  */
869 #ifdef NOT_USED
870  /* This checks both copyObject() and the equal() routines... */
871  if (!equal(new_plan, plan))
872  elog(WARNING, "copyObject() failed to produce an equal plan tree");
873  else
874 #endif
875  plan = new_plan;
876  }
877 #endif
878 
879 #ifdef WRITE_READ_PARSE_PLAN_TREES
880  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
881  {
882  char *str;
883  PlannedStmt *new_plan;
884 
885  str = nodeToString(plan);
886  new_plan = stringToNodeWithLocations(str);
887  pfree(str);
888 
889  /*
890  * equal() currently does not have routines to compare Plan nodes, so
891  * don't try to test equality here. Perhaps fix someday?
892  */
893 #ifdef NOT_USED
894  /* This checks both outfuncs/readfuncs and the equal() routines... */
895  if (!equal(new_plan, plan))
896  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
897  else
898 #endif
899  plan = new_plan;
900  }
901 #endif
902 
903  /*
904  * Print plan if debugging.
905  */
906  if (Debug_print_plan)
907  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
908 
909  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
910 
911  return plan;
912 }
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:4523
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:267
void ResetUsage(void)
Definition: postgres.c:4516
bool Debug_print_plan
Definition: guc.c:443
void pfree(void *pointer)
Definition: mcxt.c:1031
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:732
#define elog(elevel,...)
Definition: elog.h:226
bool Debug_pretty_print
Definition: guc.c:446
char * nodeToString(const void *obj)
Definition: outfuncs.c:4374
#define copyObject(obj)
Definition: nodes.h:633
bool log_planner_stats
Definition: guc.c:449

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

Definition at line 746 of file postgres.c.

References castNode, CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), lappend(), lfirst, list_make1, LOG, log_parser_stats, new_list(), NIL, nodeToString(), pfree(), Query::queryId, QueryRewrite(), ResetUsage(), ShowUsage(), generate_unaccent_rules::str, and WARNING.

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

747 {
748  List *querytree_list;
749 
750  if (Debug_print_parse)
751  elog_node_display(LOG, "parse tree", query,
753 
754  if (log_parser_stats)
755  ResetUsage();
756 
757  if (query->commandType == CMD_UTILITY)
758  {
759  /* don't rewrite utilities, just dump 'em into result list */
760  querytree_list = list_make1(query);
761  }
762  else
763  {
764  /* rewrite regular queries */
765  querytree_list = QueryRewrite(query);
766  }
767 
768  if (log_parser_stats)
769  ShowUsage("REWRITER STATISTICS");
770 
771 #ifdef COPY_PARSE_PLAN_TREES
772  /* Optional debugging check: pass querytree through copyObject() */
773  {
774  List *new_list;
775 
776  new_list = copyObject(querytree_list);
777  /* This checks both copyObject() and the equal() routines... */
778  if (!equal(new_list, querytree_list))
779  elog(WARNING, "copyObject() failed to produce equal parse tree");
780  else
781  querytree_list = new_list;
782  }
783 #endif
784 
785 #ifdef WRITE_READ_PARSE_PLAN_TREES
786  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
787  {
788  List *new_list = NIL;
789  ListCell *lc;
790 
791  /*
792  * We currently lack outfuncs/readfuncs support for most utility
793  * statement types, so only attempt to write/read non-utility queries.
794  */
795  foreach(lc, querytree_list)
796  {
797  Query *query = castNode(Query, lfirst(lc));
798 
799  if (query->commandType != CMD_UTILITY)
800  {
801  char *str = nodeToString(query);
802  Query *new_query = stringToNodeWithLocations(str);
803 
804  /*
805  * queryId is not saved in stored rules, but we must preserve
806  * it here to avoid breaking pg_stat_statements.
807  */
808  new_query->queryId = query->queryId;
809 
810  new_list = lappend(new_list, new_query);
811  pfree(str);
812  }
813  else
814  new_list = lappend(new_list, query);
815  }
816 
817  /* This checks both outfuncs/readfuncs and the equal() routines... */
818  if (!equal(new_list, querytree_list))
819  elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
820  else
821  querytree_list = new_list;
822  }
823 #endif
824 
826  elog_node_display(LOG, "rewritten parse tree", querytree_list,
828 
829  return querytree_list;
830 }
#define NIL
Definition: pg_list.h:69
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:448
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
void ShowUsage(const char *title)
Definition: postgres.c:4523
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:4516
void pfree(void *pointer)
Definition: mcxt.c:1031
bool Debug_print_parse
Definition: guc.c:444
List * lappend(List *list, void *datum)
Definition: list.c:128
uint64 queryId
Definition: parsenodes.h:116
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:112
#define lfirst(lc)
Definition: pg_list.h:106
#define elog(elevel,...)
Definition: elog.h:226
bool Debug_pretty_print
Definition: guc.c:446
char * nodeToString(const void *obj)
Definition: outfuncs.c:4374
bool Debug_print_rewritten
Definition: guc.c:445
#define copyObject(obj)
Definition: nodes.h:633
Definition: pg_list.h:45

◆ PostgresMain()

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

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

3694 {
3695  int firstchar;
3696  StringInfoData input_message;
3697  sigjmp_buf local_sigjmp_buf;
3698  volatile bool send_ready_for_query = true;
3699  bool disable_idle_in_transaction_timeout = false;
3700 
3701  /* Initialize startup process environment if necessary. */
3702  if (!IsUnderPostmaster)
3703  InitStandaloneProcess(argv[0]);
3704 
3706 
3707  /*
3708  * Set default values for command-line options.
3709  */
3710  if (!IsUnderPostmaster)
3712 
3713  /*
3714  * Parse command-line options.
3715  */
3717 
3718  /* Must have gotten a database name, or have a default (the username) */
3719  if (dbname == NULL)
3720  {
3721  dbname = username;
3722  if (dbname == NULL)
3723  ereport(FATAL,
3724  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3725  errmsg("%s: no database nor user name specified",
3726  progname)));
3727  }
3728 
3729  /* Acquire configuration parameters, unless inherited from postmaster */
3730  if (!IsUnderPostmaster)
3731  {
3733  proc_exit(1);
3734  }
3735 
3736  /*
3737  * Set up signal handlers and masks.
3738  *
3739  * Note that postmaster blocked all signals before forking child process,
3740  * so there is no race condition whereby we might receive a signal before
3741  * we have set up the handler.
3742  *
3743  * Also note: it's best not to use any signals that are SIG_IGNored in the
3744  * postmaster. If such a signal arrives before we are able to change the
3745  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3746  * handler in the postmaster to reserve the signal. (Of course, this isn't
3747  * an issue for signals that are locally generated, such as SIGALRM and
3748  * SIGPIPE.)
3749  */
3750  if (am_walsender)
3751  WalSndSignals();
3752  else
3753  {
3754  pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3755  * file */
3756  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3757  pqsignal(SIGTERM, die); /* cancel current query and exit */
3758 
3759  /*
3760  * In a standalone backend, SIGQUIT can be generated from the keyboard
3761  * easily, while SIGTERM cannot, so we make both signals do die()
3762  * rather than quickdie().
3763  */
3764  if (IsUnderPostmaster)
3765  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3766  else
3767  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3768  InitializeTimeouts(); /* establishes SIGALRM handler */
3769 
3770  /*
3771  * Ignore failure to write to frontend. Note: if frontend closes
3772  * connection, we will notice it and exit cleanly when control next
3773  * returns to outer loop. This seems safer than forcing exit in the
3774  * midst of output during who-knows-what operation...
3775  */
3780 
3781  /*
3782  * Reset some signals that are accepted by postmaster but not by
3783  * backend
3784  */
3785  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3786  * platforms */
3787  }
3788 
3789  pqinitmask();
3790 
3791  if (IsUnderPostmaster)
3792  {
3793  /* We allow SIGQUIT (quickdie) at all times */
3794  sigdelset(&BlockSig, SIGQUIT);
3795  }
3796 
3797  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3798 
3799  if (!IsUnderPostmaster)
3800  {
3801  /*
3802  * Validate we have been given a reasonable-looking DataDir (if under
3803  * postmaster, assume postmaster did this already).
3804  */
3805  checkDataDir();
3806 
3807  /* Change into DataDir (if under postmaster, was done already) */
3808  ChangeToDataDir();
3809 
3810  /*
3811  * Create lockfile for data directory.
3812  */
3813  CreateDataDirLockFile(false);
3814 
3815  /* read control file (error checking and contains config ) */
3816  LocalProcessControlFile(false);
3817 
3818  /* Initialize MaxBackends (if under postmaster, was done already) */
3820  }
3821 
3822  /* Early initialization */
3823  BaseInit();
3824 
3825  /*
3826  * Create a per-backend PGPROC struct in shared memory, except in the
3827  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3828  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3829  * had to do some stuff with LWLocks).
3830  */
3831 #ifdef EXEC_BACKEND
3832  if (!IsUnderPostmaster)
3833  InitProcess();
3834 #else
3835  InitProcess();
3836 #endif
3837 
3838  /* We need to allow SIGINT, etc during the initial transaction */
3840 
3841  /*
3842  * General initialization.
3843  *
3844  * NOTE: if you are tempted to add code in this vicinity, consider putting
3845  * it inside InitPostgres() instead. In particular, anything that
3846  * involves database access should be there, not here.
3847  */
3849 
3850  /*
3851  * If the PostmasterContext is still around, recycle the space; we don't
3852  * need it anymore after InitPostgres completes. Note this does not trash
3853  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3854  * ... else we'd need to copy the Port data first. Also, subsidiary data
3855  * such as the username isn't lost either; see ProcessStartupPacket().
3856  */
3857  if (PostmasterContext)
3858  {
3860  PostmasterContext = NULL;
3861  }
3862 
3864 
3865  /*
3866  * Now all GUC states are fully set up. Report them to client if
3867  * appropriate.
3868  */
3870 
3871  /*
3872  * Also set up handler to log session end; we have to wait till now to be
3873  * sure Log_disconnections has its final value.
3874  */
3877 
3878  /* Perform initialization specific to a WAL sender process. */
3879  if (am_walsender)
3880  InitWalSender();
3881 
3882  /*
3883  * process any libraries that should be preloaded at backend start (this
3884  * likewise can't be done until GUC settings are complete)
3885  */
3887 
3888  /*
3889  * Send this backend's cancellation info to the frontend.
3890  */
3892  {
3894 
3895  pq_beginmessage(&buf, 'K');
3896  pq_sendint32(&buf, (int32) MyProcPid);
3897  pq_sendint32(&buf, (int32) MyCancelKey);
3898  pq_endmessage(&buf);
3899  /* Need not flush since ReadyForQuery will do it. */
3900  }
3901 
3902  /* Welcome banner for standalone case */
3904  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3905 
3906  /*
3907  * Create the memory context we will use in the main loop.
3908  *
3909  * MessageContext is reset once per iteration of the main loop, ie, upon
3910  * completion of processing of each command message from the client.
3911  */
3913  "MessageContext",
3915 
3916  /*
3917  * Create memory context and buffer used for RowDescription messages. As
3918  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3919  * frequently executed for ever single statement, we don't want to
3920  * allocate a separate buffer every time.
3921  */
3923  "RowDescriptionContext",
3928 
3929  /*
3930  * Remember stand-alone backend startup time
3931  */
3932  if (!IsUnderPostmaster)
3934 
3935  /*
3936  * POSTGRES main processing loop begins here
3937  *
3938  * If an exception is encountered, processing resumes here so we abort the
3939  * current transaction and start a new one.
3940  *
3941  * You might wonder why this isn't coded as an infinite loop around a
3942  * PG_TRY construct. The reason is that this is the bottom of the
3943  * exception stack, and so with PG_TRY there would be no exception handler
3944  * in force at all during the CATCH part. By leaving the outermost setjmp
3945  * always active, we have at least some chance of recovering from an error
3946  * during error recovery. (If we get into an infinite loop thereby, it
3947  * will soon be stopped by overflow of elog.c's internal state stack.)
3948  *
3949  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3950  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3951  * is essential in case we longjmp'd out of a signal handler on a platform
3952  * where that leaves the signal blocked. It's not redundant with the
3953  * unblock in AbortTransaction() because the latter is only called if we
3954  * were inside a transaction.
3955  */
3956 
3957  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3958  {
3959  /*
3960  * NOTE: if you are tempted to add more code in this if-block,
3961  * consider the high probability that it should be in
3962  * AbortTransaction() instead. The only stuff done directly here
3963  * should be stuff that is guaranteed to apply *only* for outer-level
3964  * error recovery, such as adjusting the FE/BE protocol status.
3965  */
3966 
3967  /* Since not using PG_TRY, must reset error stack by hand */
3968  error_context_stack = NULL;
3969 
3970  /* Prevent interrupts while cleaning up */
3971  HOLD_INTERRUPTS();
3972 
3973  /*
3974  * Forget any pending QueryCancel request, since we're returning to
3975  * the idle loop anyway, and cancel any active timeout requests. (In
3976  * future we might want to allow some timeout requests to survive, but
3977  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3978  * we got here because of a query cancel interrupting the SIGALRM
3979  * interrupt handler.) Note in particular that we must clear the
3980  * statement and lock timeout indicators, to prevent any future plain
3981  * query cancels from being misreported as timeouts in case we're
3982  * forgetting a timeout cancel.
3983  */
3984  disable_all_timeouts(false);
3985  QueryCancelPending = false; /* second to avoid race condition */
3986  stmt_timeout_active = false;
3987 
3988  /* Not reading from the client anymore. */
3989  DoingCommandRead = false;
3990 
3991  /* Make sure libpq is in a good state */
3992  pq_comm_reset();
3993 
3994  /* Report the error to the client and/or server log */
3995  EmitErrorReport();
3996 
3997  /*
3998  * Make sure debug_query_string gets reset before we possibly clobber
3999  * the storage it points at.
4000  */
4001  debug_query_string = NULL;
4002 
4003  /*
4004  * Abort the current transaction in order to recover.
4005  */
4007 
4008  if (am_walsender)
4010 
4012  SPICleanup();
4013 
4014  /*
4015  * We can't release replication slots inside AbortTransaction() as we
4016  * need to be able to start and abort transactions while having a slot
4017  * acquired. But we never need to hold them across top level errors,
4018  * so releasing here is fine. There's another cleanup in ProcKill()
4019  * ensuring we'll correctly cleanup on FATAL errors as well.
4020  */
4021  if (MyReplicationSlot != NULL)
4023 
4024  /* We also want to cleanup temporary slots on error. */
4026 
4028 
4029  /*
4030  * Now return to normal top-level context and clear ErrorContext for
4031  * next time.
4032  */
4034  FlushErrorState();
4035 
4036  /*
4037  * If we were handling an extended-query-protocol message, initiate
4038  * skip till next Sync. This also causes us not to issue
4039  * ReadyForQuery (until we get Sync).
4040  */
4042  ignore_till_sync = true;
4043 
4044  /* We don't have a transaction command open anymore */
4045  xact_started = false;
4046 
4047  /*
4048  * If an error occurred while we were reading a message from the
4049  * client, we have potentially lost track of where the previous
4050  * message ends and the next one begins. Even though we have
4051  * otherwise recovered from the error, we cannot safely read any more
4052  * messages from the client, so there isn't much we can do with the
4053  * connection anymore.
4054  */
4055  if (pq_is_reading_msg())
4056  ereport(FATAL,
4057  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4058  errmsg("terminating connection because protocol synchronization was lost")));
4059 
4060  /* Now we can allow interrupts again */
4062  }
4063 
4064  /* We can now handle ereport(ERROR) */
4065  PG_exception_stack = &local_sigjmp_buf;
4066 
4067  if (!ignore_till_sync)
4068  send_ready_for_query = true; /* initially, or after error */
4069 
4070  /*
4071  * Non-error queries loop here.
4072  */
4073 
4074  for (;;)
4075  {
4076  /*
4077  * At top of loop, reset extended-query-message flag, so that any
4078  * errors encountered in "idle" state don't provoke skip.
4079  */
4081 
4082  /*
4083  * Release storage left over from prior query cycle, and create a new
4084  * query input buffer in the cleared MessageContext.
4085  */
4088 
4089  initStringInfo(&input_message);
4090 
4091  /*
4092  * Also consider releasing our catalog snapshot if any, so that it's
4093  * not preventing advance of global xmin while we wait for the client.
4094  */
4096 
4097  /*
4098  * (1) If we've reached idle state, tell the frontend we're ready for
4099  * a new query.
4100  *
4101  * Note: this includes fflush()'ing the last of the prior output.
4102  *
4103  * This is also a good time to send collected statistics to the
4104  * collector, and to update the PS stats display. We avoid doing
4105  * those every time through the message loop because it'd slow down
4106  * processing of batched messages, and because we don't want to report
4107  * uncommitted updates (that confuses autovacuum). The notification
4108  * processor wants a call too, if we are not in a transaction block.
4109  */
4110  if (send_ready_for_query)
4111  {
4113  {
4114  set_ps_display("idle in transaction (aborted)", false);
4116 
4117  /* Start the idle-in-transaction timer */
4119  {
4120  disable_idle_in_transaction_timeout = true;
4123  }
4124  }
4126  {
4127  set_ps_display("idle in transaction", false);
4129 
4130  /* Start the idle-in-transaction timer */
4132  {
4133  disable_idle_in_transaction_timeout = true;
4136  }
4137  }
4138  else
4139  {
4141  pgstat_report_stat(false);
4142 
4143  set_ps_display("idle", false);
4145  }
4146 
4148  send_ready_for_query = false;
4149  }
4150 
4151  /*
4152  * (2) Allow asynchronous signals to be executed immediately if they
4153  * come in while we are waiting for client input. (This must be
4154  * conditional since we don't want, say, reads on behalf of COPY FROM
4155  * STDIN doing the same thing.)
4156  */
4157  DoingCommandRead = true;
4158 
4159  /*
4160  * (3) read a command (loop blocks here)
4161  */
4162  firstchar = ReadCommand(&input_message);
4163 
4164  /*
4165  * (4) disable async signal conditions again.
4166  *
4167  * Query cancel is supposed to be a no-op when there is no query in
4168  * progress, so if a query cancel arrived while we were idle, just
4169  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4170  * it's called when DoingCommandRead is set, so check for interrupts
4171  * before resetting DoingCommandRead.
4172  */
4174  DoingCommandRead = false;
4175 
4176  /*
4177  * (5) turn off the idle-in-transaction timeout
4178  */
4179  if (disable_idle_in_transaction_timeout)
4180  {
4182  disable_idle_in_transaction_timeout = false;
4183  }
4184 
4185  /*
4186  * (6) check for any other interesting events that happened while we
4187  * slept.
4188  */
4189  if (ConfigReloadPending)
4190  {
4191  ConfigReloadPending = false;
4193  }
4194 
4195  /*
4196  * (7) process the command. But ignore it if we're skipping till
4197  * Sync.
4198  */
4199  if (ignore_till_sync && firstchar != EOF)
4200  continue;
4201 
4202  switch (firstchar)
4203  {
4204  case 'Q': /* simple query */
4205  {
4206  const char *query_string;
4207 
4208  /* Set statement_timestamp() */
4210 
4211  query_string = pq_getmsgstring(&input_message);
4212  pq_getmsgend(&input_message);
4213 
4214  if (am_walsender)
4215  {
4216  if (!exec_replication_command(query_string))
4217  exec_simple_query(query_string);
4218  }
4219  else
4220  exec_simple_query(query_string);
4221 
4222  send_ready_for_query = true;
4223  }
4224  break;
4225 
4226  case 'P': /* parse */
4227  {
4228  const char *stmt_name;
4229  const char *query_string;
4230  int numParams;
4231  Oid *paramTypes = NULL;
4232 
4233  forbidden_in_wal_sender(firstchar);
4234 
4235  /* Set statement_timestamp() */
4237 
4238  stmt_name = pq_getmsgstring(&input_message);
4239  query_string = pq_getmsgstring(&input_message);
4240  numParams = pq_getmsgint(&input_message, 2);
4241  if (numParams > 0)
4242  {
4243  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4244  for (int i = 0; i < numParams; i++)
4245  paramTypes[i] = pq_getmsgint(&input_message, 4);
4246  }
4247  pq_getmsgend(&input_message);
4248 
4249  exec_parse_message(query_string, stmt_name,
4250  paramTypes, numParams);
4251  }
4252  break;
4253 
4254  case 'B': /* bind */
4255  forbidden_in_wal_sender(firstchar);
4256 
4257  /* Set statement_timestamp() */
4259 
4260  /*
4261  * this message is complex enough that it seems best to put
4262  * the field extraction out-of-line
4263  */
4264  exec_bind_message(&input_message);
4265  break;
4266 
4267  case 'E': /* execute */
4268  {
4269  const char *portal_name;
4270  int max_rows;
4271 
4272  forbidden_in_wal_sender(firstchar);
4273 
4274  /* Set statement_timestamp() */
4276 
4277  portal_name = pq_getmsgstring(&input_message);
4278  max_rows = pq_getmsgint(&input_message, 4);
4279  pq_getmsgend(&input_message);
4280 
4281  exec_execute_message(portal_name, max_rows);
4282  }
4283  break;
4284 
4285  case 'F': /* fastpath function call */
4286  forbidden_in_wal_sender(firstchar);
4287 
4288  /* Set statement_timestamp() */
4290 
4291  /* Report query to various monitoring facilities. */
4293  set_ps_display("<FASTPATH>", false);
4294 
4295  /* start an xact for this function invocation */
4297 
4298  /*
4299  * Note: we may at this point be inside an aborted
4300  * transaction. We can't throw error for that until we've
4301  * finished reading the function-call message, so
4302  * HandleFunctionRequest() must check for it after doing so.
4303  * Be careful not to do anything that assumes we're inside a
4304  * valid transaction here.
4305  */
4306 
4307  /* switch back to message context */
4309 
4310  HandleFunctionRequest(&input_message);
4311 
4312  /* commit the function-invocation transaction */
4314 
4315  send_ready_for_query = true;
4316  break;
4317 
4318  case 'C': /* close */
4319  {
4320  int close_type;
4321  const char *close_target;
4322 
4323  forbidden_in_wal_sender(firstchar);
4324 
4325  close_type = pq_getmsgbyte(&input_message);
4326  close_target = pq_getmsgstring(&input_message);
4327  pq_getmsgend(&input_message);
4328 
4329  switch (close_type)
4330  {
4331  case 'S':
4332  if (close_target[0] != '\0')
4333  DropPreparedStatement(close_target, false);
4334  else
4335  {
4336  /* special-case the unnamed statement */
4338  }
4339  break;
4340  case 'P':
4341  {
4342  Portal portal;
4343 
4344  portal = GetPortalByName(close_target);
4345  if (PortalIsValid(portal))
4346  PortalDrop(portal, false);
4347  }
4348  break;
4349  default:
4350  ereport(ERROR,
4351  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4352  errmsg("invalid CLOSE message subtype %d",
4353  close_type)));
4354  break;
4355  }
4356 
4358  pq_putemptymessage('3'); /* CloseComplete */
4359  }
4360  break;
4361 
4362  case 'D': /* describe */
4363  {
4364  int describe_type;
4365  const char *describe_target;
4366 
4367  forbidden_in_wal_sender(firstchar);
4368 
4369  /* Set statement_timestamp() (needed for xact) */
4371 
4372  describe_type = pq_getmsgbyte(&input_message);
4373  describe_target = pq_getmsgstring(&input_message);
4374  pq_getmsgend(&input_message);
4375 
4376  switch (describe_type)
4377  {
4378  case 'S':
4379  exec_describe_statement_message(describe_target);
4380  break;
4381  case 'P':
4382  exec_describe_portal_message(describe_target);
4383  break;
4384  default:
4385  ereport(ERROR,
4386  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4387  errmsg("invalid DESCRIBE message subtype %d",
4388  describe_type)));
4389  break;
4390  }
4391  }
4392  break;
4393 
4394  case 'H': /* flush */
4395  pq_getmsgend(&input_message);
4397  pq_flush();
4398  break;
4399 
4400  case 'S': /* sync */
4401  pq_getmsgend(&input_message);
4403  send_ready_for_query = true;
4404  break;
4405 
4406  /*
4407  * 'X' means that the frontend is closing down the socket. EOF
4408  * means unexpected loss of frontend connection. Either way,
4409  * perform normal shutdown.
4410  */
4411  case 'X':
4412  case EOF:
4413 
4414  /*
4415  * Reset whereToSendOutput to prevent ereport from attempting
4416  * to send any more messages to client.
4417  */
4420 
4421  /*
4422  * NOTE: if you are tempted to add more code here, DON'T!
4423  * Whatever you had in mind to do should be set up as an
4424  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4425  * it will fail to be called during other backend-shutdown
4426  * scenarios.
4427  */
4428  proc_exit(0);
4429 
4430  case 'd': /* copy data */
4431  case 'c': /* copy done */
4432  case 'f': /* copy fail */
4433 
4434  /*
4435  * Accept but ignore these messages, per protocol spec; we
4436  * probably got here because a COPY failed, and the frontend
4437  * is still sending data.
4438  */
4439  break;
4440 
4441  default:
4442  ereport(FATAL,
4443  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4444  errmsg("invalid frontend message type %d",
4445  firstchar)));
4446  }
4447  } /* end of input-reading loop */
4448 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:2965
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2482
#define SIGQUIT
Definition: win32_port.h:164
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
void BeginReportingGUCOptions(void)
Definition: guc.c:5639
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:2554
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1434
#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:305
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
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:320
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:351
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPICleanup(void)
Definition: spi.c:293
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:331
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4458
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4421
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:99
#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:2756
signed int int32
Definition: c.h:346
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1932
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4625
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
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:114
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1193
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:2988
#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:1553
Definition: dest.h:89
#define SIGHUP
Definition: win32_port.h:163
void PostgresSigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2796
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4941
void ChangeToDataDir(void)
Definition: miscinit.c:213
void ReplicationSlotRelease(void)
Definition: slot.c:424
sigset_t UnBlockSig
Definition: pqsignal.c:22
void PortalErrorCleanup(void)
Definition: portalmem.c:908
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:141
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:1291
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2534
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:1612
void WalSndErrorCleanup(void)
Definition: walsender.c:296
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4967
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:713
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:2725
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2777
static void drop_unnamed_stmt(void)
Definition: postgres.c:2633
void ReplicationSlotCleanup(void)
Definition: slot.c:479
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:3432
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:2658
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void exec_simple_query(const char *query_string)
Definition: postgres.c:961
void InitializeGUCOptions(void)
Definition: guc.c:4745
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:2387

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2796 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

2797 {
2798  int save_errno = errno;
2799 
2800  ConfigReloadPending = true;
2801  SetLatch(MyLatch);
2802 
2803  errno = save_errno;
2804 }
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 3432 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().

3434 {
3435  bool secure = (ctx == PGC_POSTMASTER);
3436  int errs = 0;
3437  GucSource gucsource;
3438  int flag;
3439 
3440  if (secure)
3441  {
3442  gucsource = PGC_S_ARGV; /* switches came from command line */
3443 
3444  /* Ignore the initial --single argument, if present */
3445  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3446  {
3447  argv++;
3448  argc--;
3449  }
3450  }
3451  else
3452  {
3453  gucsource = PGC_S_CLIENT; /* switches came from client */
3454  }
3455 
3456 #ifdef HAVE_INT_OPTERR
3457 
3458  /*
3459  * Turn this off because it's either printed to stderr and not the log
3460  * where we'd want it, or argv[0] is now "--single", which would make for
3461  * a weird error message. We print our own error message below.
3462  */
3463  opterr = 0;
3464 #endif
3465 
3466  /*
3467  * Parse command-line options. CAUTION: keep this in sync with
3468  * postmaster/postmaster.c (the option sets should not conflict) and with
3469  * the common help() function in main/main.c.
3470  */
3471  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3472  {
3473  switch (flag)
3474  {
3475  case 'B':
3476  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3477  break;
3478 
3479  case 'b':
3480  /* Undocumented flag used for binary upgrades */
3481  if (secure)
3482  IsBinaryUpgrade = true;
3483  break;
3484 
3485  case 'C':
3486  /* ignored for consistency with the postmaster */
3487  break;
3488 
3489  case 'D':
3490  if (secure)
3491  userDoption = strdup(optarg);
3492  break;
3493 
3494  case 'd':
3495  set_debug_options(atoi(optarg), ctx, gucsource);
3496  break;
3497 
3498  case 'E':
3499  if (secure)
3500  EchoQuery = true;
3501  break;
3502 
3503  case 'e':
3504  SetConfigOption("datestyle", "euro", ctx, gucsource);
3505  break;
3506 
3507  case 'F':
3508  SetConfigOption("fsync", "false", ctx, gucsource);
3509  break;
3510 
3511  case 'f':
3512  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3513  errs++;
3514  break;
3515 
3516  case 'h':
3517  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3518  break;
3519 
3520  case 'i':
3521  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3522  break;
3523 
3524  case 'j':
3525  if (secure)
3526  UseSemiNewlineNewline = true;
3527  break;
3528 
3529  case 'k':
3530  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3531  break;
3532 
3533  case 'l':
3534  SetConfigOption("ssl", "true", ctx, gucsource);
3535  break;
3536 
3537  case 'N':
3538  SetConfigOption("max_connections", optarg, ctx, gucsource);
3539  break;
3540 
3541  case 'n':
3542  /* ignored for consistency with postmaster */
3543  break;
3544 
3545  case 'O':
3546  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3547  break;
3548 
3549  case 'o':
3550  errs++;
3551  break;
3552 
3553  case 'P':
3554  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3555  break;
3556 
3557  case 'p':
3558  SetConfigOption("port", optarg, ctx, gucsource);
3559  break;
3560 
3561  case 'r':
3562  /* send output (stdout and stderr) to the given file */
3563  if (secure)
3565  break;
3566 
3567  case 'S':
3568  SetConfigOption("work_mem", optarg, ctx, gucsource);
3569  break;
3570 
3571  case 's':
3572  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3573  break;
3574 
3575  case 'T':
3576  /* ignored for consistency with the postmaster */
3577  break;
3578 
3579  case 't':
3580  {
3581  const char *tmp = get_stats_option_name(optarg);
3582 
3583  if (tmp)
3584  SetConfigOption(tmp, "true", ctx, gucsource);
3585  else
3586  errs++;
3587  break;
3588  }
3589 
3590  case 'v':
3591 
3592  /*
3593  * -v is no longer used in normal operation, since
3594  * FrontendProtocol is already set before we get here. We keep
3595  * the switch only for possible use in standalone operation,
3596  * in case we ever support using normal FE/BE protocol with a
3597  * standalone backend.
3598  */
3599  if (secure)
3601  break;
3602 
3603  case 'W':
3604  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3605  break;
3606 
3607  case 'c':
3608  case '-':
3609  {
3610  char *name,
3611  *value;
3612 
3613  ParseLongOption(optarg, &name, &value);
3614  if (!value)
3615  {
3616  if (flag == '-')
3617  ereport(ERROR,
3618  (errcode(ERRCODE_SYNTAX_ERROR),
3619  errmsg("--%s requires a value",
3620  optarg)));
3621  else
3622  ereport(ERROR,
3623  (errcode(ERRCODE_SYNTAX_ERROR),
3624  errmsg("-c %s requires a value",
3625  optarg)));
3626  }
3627  SetConfigOption(name, value, ctx, gucsource);
3628  free(name);
3629  if (value)
3630  free(value);
3631  break;
3632  }
3633 
3634  default:
3635  errs++;
3636  break;
3637  }
3638 
3639  if (errs)
3640  break;
3641  }
3642 
3643  /*
3644  * Optional database name should be there only if *dbname is NULL.
3645  */
3646  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3647  *dbname = strdup(argv[optind++]);
3648 
3649  if (errs || argc != optind)
3650  {
3651  if (errs)
3652  optind--; /* complain about the previous argument */
3653 
3654  /* spell the error message a bit differently depending on context */
3655  if (IsUnderPostmaster)
3656  ereport(FATAL,
3657  (errcode(ERRCODE_SYNTAX_ERROR),
3658  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3659  errhint("Try \"%s --help\" for more information.", progname)));
3660  else
3661  ereport(FATAL,
3662  (errcode(ERRCODE_SYNTAX_ERROR),
3663  errmsg("%s: invalid command-line argument: %s",
3664  progname, argv[optind]),
3665  errhint("Try \"%s --help\" for more information.", progname)));
3666  }
3667 
3668  /*
3669  * Reset getopt(3) library so that it will work correctly in subprocesses
3670  * or when this function is called a second time with another array.
3671  */
3672  optind = 1;
3673 #ifdef HAVE_INT_OPTRESET
3674  optreset = 1; /* some systems need this too */
3675 #endif
3676 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9680
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3350
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3392
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3321
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:6952
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:141
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 2936 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().

2937 {
2938  /* OK to accept any interrupts now? */
2939  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2940  return;
2941  InterruptPending = false;
2942 
2943  if (ProcDiePending)
2944  {
2945  ProcDiePending = false;
2946  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2947  LockErrorCleanup();
2948  /* As in quickdie, don't risk sending to client during auth */
2952  ereport(FATAL,
2953  (errcode(ERRCODE_QUERY_CANCELED),
2954  errmsg("canceling authentication due to timeout")));
2955  else if (IsAutoVacuumWorkerProcess())
2956  ereport(FATAL,
2957  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2958  errmsg("terminating autovacuum process due to administrator command")));
2959  else if (IsLogicalWorker())
2960  ereport(FATAL,
2961  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2962  errmsg("terminating logical replication worker due to administrator command")));
2963  else if (IsLogicalLauncher())
2964  {
2965  ereport(DEBUG1,
2966  (errmsg("logical replication launcher shutting down")));
2967 
2968  /*
2969  * The logical replication launcher can be stopped at any time.
2970  * Use exit status 1 so the background worker is restarted.
2971  */
2972  proc_exit(1);
2973  }
2975  {
2977  ereport(FATAL,
2978  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2979  errmsg("terminating connection due to conflict with recovery"),
2981  }
2982  else if (RecoveryConflictPending)
2983  {
2984  /* Currently there is only one non-retryable recovery conflict */
2987  ereport(FATAL,
2988  (errcode(ERRCODE_DATABASE_DROPPED),
2989  errmsg("terminating connection due to conflict with recovery"),
2991  }
2992  else
2993  ereport(FATAL,
2994  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2995  errmsg("terminating connection due to administrator command")));
2996  }
2998  {
2999  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3000  LockErrorCleanup();
3001  /* don't send to client, we already know the connection to be dead. */
3003  ereport(FATAL,
3004  (errcode(ERRCODE_CONNECTION_FAILURE),
3005  errmsg("connection to client lost")));
3006  }
3007 
3008  /*
3009  * If a recovery conflict happens while we are waiting for input from the
3010  * client, the client is presumably just sitting idle in a transaction,
3011  * preventing recovery from making progress. Terminate the connection to
3012  * dislodge it.
3013  */
3015  {
3016  QueryCancelPending = false; /* this trumps QueryCancel */
3017  RecoveryConflictPending = false;
3018  LockErrorCleanup();
3020  ereport(FATAL,
3021  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3022  errmsg("terminating connection due to conflict with recovery"),
3024  errhint("In a moment you should be able to reconnect to the"
3025  " database and repeat your command.")));
3026  }
3027 
3028  /*
3029  * Don't allow query cancel interrupts while reading input from the
3030  * client, because we might lose sync in the FE/BE protocol. (Die
3031  * interrupts are OK, because we won't read any further messages from the
3032  * client in that case.)
3033  */
3035  {
3036  /*
3037  * Re-arm InterruptPending so that we process the cancel request as
3038  * soon as we're done reading the message.
3039  */
3040  InterruptPending = true;
3041  }
3042  else if (QueryCancelPending)
3043  {
3044  bool lock_timeout_occurred;
3045  bool stmt_timeout_occurred;
3046 
3047  QueryCancelPending = false;
3048 
3049  /*
3050  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3051  * need to clear both, so always fetch both.
3052  */
3053  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3054  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3055 
3056  /*
3057  * If both were set, we want to report whichever timeout completed
3058  * earlier; this ensures consistent behavior if the machine is slow
3059  * enough that the second timeout triggers before we get here. A tie
3060  * is arbitrarily broken in favor of reporting a lock timeout.
3061  */
3062  if (lock_timeout_occurred && stmt_timeout_occurred &&
3064  lock_timeout_occurred = false; /* report stmt timeout */
3065 
3066  if (lock_timeout_occurred)
3067  {
3068  LockErrorCleanup();
3069  ereport(ERROR,
3070  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3071  errmsg("canceling statement due to lock timeout")));
3072  }
3073  if (stmt_timeout_occurred)
3074  {
3075  LockErrorCleanup();
3076  ereport(ERROR,
3077  (errcode(ERRCODE_QUERY_CANCELED),
3078  errmsg("canceling statement due to statement timeout")));
3079  }
3081  {
3082  LockErrorCleanup();
3083  ereport(ERROR,
3084  (errcode(ERRCODE_QUERY_CANCELED),
3085  errmsg("canceling autovacuum task")));
3086  }
3088  {
3089  RecoveryConflictPending = false;
3090  LockErrorCleanup();
3092  ereport(ERROR,
3093  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3094  errmsg("canceling statement due to conflict with recovery"),
3096  }
3097 
3098  /*
3099  * If we are reading a command from the client, just ignore the cancel
3100  * request --- sending an extra error message won't accomplish
3101  * anything. Otherwise, go ahead and throw the error.
3102  */
3103  if (!DoingCommandRead)
3104  {
3105  LockErrorCleanup();
3106  ereport(ERROR,
3107  (errcode(ERRCODE_QUERY_CANCELED),
3108  errmsg("canceling statement due to user request")));
3109  }
3110  }
3111 
3113  {
3114  /* Has the timeout setting changed since last we looked? */
3116  ereport(FATAL,
3117  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3118  errmsg("terminating connection due to idle-in-transaction timeout")));
3119  else
3121 
3122  }
3123 
3126 }
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:1762
volatile bool ClientConnectionLost
Definition: globals.c:33
volatile bool ParallelMessagePending
Definition: parallel.c:107
bool ClientAuthInProgress
Definition: postmaster.c:350
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:964
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:38
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3285
#define ereport(elevel, rest)
Definition: elog.h:141
void LockErrorCleanup(void)
Definition: proc.c:688
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:2351
volatile bool InterruptPending
Definition: globals.c:30
#define Assert(condition)
Definition: c.h:732
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:1103
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2658 of file postgres.c.

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

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

2659 {
2660  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2661  PG_SETMASK(&BlockSig);
2662 
2663  /*
2664  * Prevent interrupts while exiting; though we just blocked signals that
2665  * would queue new interrupts, one may have been pending. We don't want a
2666  * quickdie() downgraded to a mere query cancel.
2667  */
2668  HOLD_INTERRUPTS();
2669 
2670  /*
2671  * If we're aborting out of client auth, don't risk trying to send
2672  * anything to the client; we will likely violate the protocol, not to
2673  * mention that we may have interrupted the guts of OpenSSL or some
2674  * authentication library.
2675  */
2678 
2679  /*
2680  * Notify the client before exiting, to give a clue on what happened.
2681  *
2682  * It's dubious to call ereport() from a signal handler. It is certainly
2683  * not async-signal safe. But it seems better to try, than to disconnect
2684  * abruptly and leave the client wondering what happened. It's remotely
2685  * possible that we crash or hang while trying to send the message, but
2686  * receiving a SIGQUIT is a sign that something has already gone badly
2687  * wrong, so there's not much to lose. Assuming the postmaster is still
2688  * running, it will SIGKILL us soon if we get stuck for some reason.
2689  *
2690  * Ideally this should be ereport(FATAL), but then we'd not get control
2691  * back...
2692  */
2693  ereport(WARNING,
2694  (errcode(ERRCODE_CRASH_SHUTDOWN),
2695  errmsg("terminating connection because of crash of another server process"),
2696  errdetail("The postmaster has commanded this server process to roll back"
2697  " the current transaction and exit, because another"
2698  " server process exited abnormally and possibly corrupted"
2699  " shared memory."),
2700  errhint("In a moment you should be able to reconnect to the"
2701  " database and repeat your command.")));
2702 
2703  /*
2704  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2705  * because shared memory may be corrupted, so we don't want to try to
2706  * clean up our transaction. Just nail the windows shut and get out of
2707  * town. The callbacks wouldn't be safe to run from a signal handler,
2708  * anyway.
2709  *
2710  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2711  * a system reset cycle if someone sends a manual SIGQUIT to a random
2712  * backend. This is necessary precisely because we don't clean up our
2713  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2714  * should ensure the postmaster sees this as a crash, too, but no harm in
2715  * being doubly sure.)
2716  */
2717  _exit(2);
2718 }
#define SIGQUIT
Definition: win32_port.h:164
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:350
Definition: dest.h:88
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:141
#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)