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/optimizer.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 3342 of file postgres.c.

References max_stack_depth_bytes.

3343 {
3344  long newval_bytes = newval * 1024L;
3345 
3346  max_stack_depth_bytes = newval_bytes;
3347 }
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 2231 of file postgres.c.

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

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

2232 {
2234  {
2235  long secs;
2236  int usecs;
2237  int msecs;
2238  bool exceeded;
2239 
2242  &secs, &usecs);
2243  msecs = usecs / 1000;
2244 
2245  /*
2246  * This odd-looking test for log_min_duration_statement being exceeded
2247  * is designed to avoid integer overflow with very long durations:
2248  * don't compute secs * 1000 until we've verified it will fit in int.
2249  */
2250  exceeded = (log_min_duration_statement == 0 ||
2252  (secs > log_min_duration_statement / 1000 ||
2253  secs * 1000 + msecs >= log_min_duration_statement)));
2254 
2255  if (exceeded || log_duration || xact_is_sampled)
2256  {
2257  snprintf(msec_str, 32, "%ld.%03d",
2258  secs * 1000 + msecs, usecs % 1000);
2259  if ((exceeded || xact_is_sampled) && !was_logged)
2260  return 2;
2261  else
2262  return 1;
2263  }
2264  }
2265 
2266  return 0;
2267 }
int log_min_duration_statement
Definition: guc.c:512
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
bool xact_is_sampled
Definition: xact.c:268
bool log_duration
Definition: guc.c:485
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1657
#define snprintf
Definition: port.h:192
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:792

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2192 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

2193 {
2194  ListCell *stmt_item;
2195 
2196  if (log_statement == LOGSTMT_NONE)
2197  return false;
2198  if (log_statement == LOGSTMT_ALL)
2199  return true;
2200 
2201  /* Else we have to inspect the statement(s) to see whether to log */
2202  foreach(stmt_item, stmt_list)
2203  {
2204  Node *stmt = (Node *) lfirst(stmt_item);
2205 
2206  if (GetCommandLogLevel(stmt) <= log_statement)
2207  return true;
2208  }
2209 
2210  return false;
2211 }
Definition: nodes.h:525
#define lfirst(lc)
Definition: pg_list.h:190
int log_statement
Definition: postgres.c:95
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:2968

◆ check_max_stack_depth()

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

Definition at line 3325 of file postgres.c.

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

3326 {
3327  long newval_bytes = *newval * 1024L;
3328  long stack_rlimit = get_stack_depth_rlimit();
3329 
3330  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3331  {
3332  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3333  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3334  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3335  return false;
3336  }
3337  return true;
3338 }
#define GUC_check_errdetail
Definition: guc.h:409
long get_stack_depth_rlimit(void)
Definition: postgres.c:4516
#define newval
#define GUC_check_errhint
Definition: guc.h:413
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3262 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(), emit_jsp_gin_entries(), equal(), EventTriggerInvoke(), ExecEndNode(), ExecEvalAlternativeSubPlan(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode(), execute(), executeAnyItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator(), expression_tree_walker(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), 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(), outNode(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), 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(), standard_ProcessUtility(), transformExprRecurse(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute(), TS_execute_ternary(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3263 {
3264  if (stack_is_too_deep())
3265  {
3266  ereport(ERROR,
3267  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3268  errmsg("stack depth limit exceeded"),
3269  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3270  "after ensuring the platform's stack depth limit is adequate.",
3271  max_stack_depth)));
3272  }
3273 }
int errhint(const char *fmt,...)
Definition: elog.c:974
int errcode(int sqlerrcode)
Definition: elog.c:570
#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:784
bool stack_is_too_deep(void)
Definition: postgres.c:3276

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2761 of file postgres.c.

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

Referenced by PostgresMain().

2762 {
2763  int save_errno = errno;
2764 
2765  /* Don't joggle the elbow of proc_exit */
2766  if (!proc_exit_inprogress)
2767  {
2768  InterruptPending = true;
2769  ProcDiePending = true;
2770  }
2771 
2772  /* If we're still here, waken anything waiting on the process latch */
2773  SetLatch(MyLatch);
2774 
2775  /*
2776  * If we're in single user mode, we want to quit immediately - we can't
2777  * rely on latches as they wouldn't work when stdin/stdout is a file.
2778  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2779  * effort just for the benefit of single user mode.
2780  */
2783 
2784  errno = save_errno;
2785 }
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessInterrupts(void)
Definition: postgres.c:2972
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:139
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:54
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

Definition at line 4718 of file postgres.c.

References disable_timeout(), STATEMENT_TIMEOUT, and stmt_timeout_active.

Referenced by exec_execute_message(), and finish_xact_command().

4719 {
4720  if (stmt_timeout_active)
4721  {
4723 
4724  stmt_timeout_active = false;
4725  }
4726 }
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 2669 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2670 {
2671  /* paranoia to avoid a dangling pointer in case of error */
2672  if (unnamed_stmt_psrc)
2673  {
2675 
2676  unnamed_stmt_psrc = NULL;
2677  DropCachedPlan(psrc);
2678  }
2679 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:496

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

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

4698 {
4699  /* must be within an xact */
4701 
4702  if (StatementTimeout > 0)
4703  {
4704  if (!stmt_timeout_active)
4705  {
4707  stmt_timeout_active = true;
4708  }
4709  }
4710  else
4712 }
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:62
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

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

2374 {
2376  errdetail("abort reason: recovery conflict");
2377 
2378  return 0;
2379 }
PGPROC * MyProc
Definition: proc.c:68
bool recoveryConflictPending
Definition: proc.h:127
int errdetail(const char *fmt,...)
Definition: elog.c:860

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2276 of file postgres.c.

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

Referenced by exec_simple_query().

2277 {
2278  ListCell *parsetree_item;
2279 
2280  foreach(parsetree_item, raw_parsetree_list)
2281  {
2282  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2283 
2284  if (IsA(parsetree->stmt, ExecuteStmt))
2285  {
2286  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2287  PreparedStatement *pstmt;
2288 
2289  pstmt = FetchPreparedStatement(stmt->name, false);
2290  if (pstmt)
2291  {
2292  errdetail("prepare: %s", pstmt->plansource->query_string);
2293  return 0;
2294  }
2295  }
2296  }
2297 
2298  return 0;
2299 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Node * stmt
Definition: parsenodes.h:1485
int errdetail(const char *fmt,...)
Definition: elog.c:860
char * name
Definition: parsenodes.h:3401
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:485

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

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

2308 {
2309  /* We mustn't call user-defined I/O functions when in an aborted xact */
2310  if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2311  {
2312  StringInfoData param_str;
2313  MemoryContext oldcontext;
2314 
2315  /* This code doesn't support dynamic param lists */
2316  Assert(params->paramFetch == NULL);
2317 
2318  /* Make sure any trash is generated in MessageContext */
2319  oldcontext = MemoryContextSwitchTo(MessageContext);
2320 
2321  initStringInfo(&param_str);
2322 
2323  for (int paramno = 0; paramno < params->numParams; paramno++)
2324  {
2325  ParamExternData *prm = &params->params[paramno];
2326  Oid typoutput;
2327  bool typisvarlena;
2328  char *pstring;
2329  char *p;
2330 
2331  appendStringInfo(&param_str, "%s$%d = ",
2332  paramno > 0 ? ", " : "",
2333  paramno + 1);
2334 
2335  if (prm->isnull || !OidIsValid(prm->ptype))
2336  {
2337  appendStringInfoString(&param_str, "NULL");
2338  continue;
2339  }
2340 
2341  getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2342 
2343  pstring = OidOutputFunctionCall(typoutput, prm->value);
2344 
2345  appendStringInfoCharMacro(&param_str, '\'');
2346  for (p = pstring; *p; p++)
2347  {
2348  if (*p == '\'') /* double single quotes */
2349  appendStringInfoCharMacro(&param_str, *p);
2350  appendStringInfoCharMacro(&param_str, *p);
2351  }
2352  appendStringInfoCharMacro(&param_str, '\'');
2353 
2354  pfree(pstring);
2355  }
2356 
2357  errdetail("parameters: %s", param_str.data);
2358 
2359  pfree(param_str.data);
2360 
2361  MemoryContextSwitchTo(oldcontext);
2362  }
2363 
2364  return 0;
2365 }
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:2674
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
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:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:163
int errdetail(const char *fmt,...)
Definition: elog.c:860
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:1655
bool isnull
Definition: params.h:93

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

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

2388 {
2389  switch (RecoveryConflictReason)
2390  {
2392  errdetail("User was holding shared buffer pin for too long.");
2393  break;
2395  errdetail("User was holding a relation lock for too long.");
2396  break;
2398  errdetail("User was or might have been using tablespace that must be dropped.");
2399  break;
2401  errdetail("User query might have needed to see row versions that must be removed.");
2402  break;
2404  errdetail("User transaction caused buffer deadlock with recovery.");
2405  break;
2407  errdetail("User was connected to a database that must be dropped.");
2408  break;
2409  default:
2410  break;
2411  /* no errdetail */
2412  }
2413 
2414  return 0;
2415 }
int errdetail(const char *fmt,...)
Definition: elog.c:860
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:168

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1596 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, makeParamList(), StringInfoData::maxlen, MemoryContextSwitchTo(), MessageContext, CachedPlanSource::num_params, OidInputFunctionCall(), OidReceiveFunctionCall(), palloc(), PARAM_FLAG_CONST, CachedPlanSource::param_types, ParamListInfoData::params, 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, unconstify, unnamed_stmt_psrc, ParamExternData::value, and whereToSendOutput.

Referenced by PostgresMain().

1597 {
1598  const char *portal_name;
1599  const char *stmt_name;
1600  int numPFormats;
1601  int16 *pformats = NULL;
1602  int numParams;
1603  int numRFormats;
1604  int16 *rformats = NULL;
1605  CachedPlanSource *psrc;
1606  CachedPlan *cplan;
1607  Portal portal;
1608  char *query_string;
1609  char *saved_stmt_name;
1610  ParamListInfo params;
1611  MemoryContext oldContext;
1612  bool save_log_statement_stats = log_statement_stats;
1613  bool snapshot_set = false;
1614  char msec_str[32];
1615 
1616  /* Get the fixed part of the message */
1617  portal_name = pq_getmsgstring(input_message);
1618  stmt_name = pq_getmsgstring(input_message);
1619 
1620  ereport(DEBUG2,
1621  (errmsg("bind %s to %s",
1622  *portal_name ? portal_name : "<unnamed>",
1623  *stmt_name ? stmt_name : "<unnamed>")));
1624 
1625  /* Find prepared statement */
1626  if (stmt_name[0] != '\0')
1627  {
1628  PreparedStatement *pstmt;
1629 
1630  pstmt = FetchPreparedStatement(stmt_name, true);
1631  psrc = pstmt->plansource;
1632  }
1633  else
1634  {
1635  /* special-case the unnamed statement */
1636  psrc = unnamed_stmt_psrc;
1637  if (!psrc)
1638  ereport(ERROR,
1639  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1640  errmsg("unnamed prepared statement does not exist")));
1641  }
1642 
1643  /*
1644  * Report query to various monitoring facilities.
1645  */
1647 
1649 
1650  set_ps_display("BIND", false);
1651 
1652  if (save_log_statement_stats)
1653  ResetUsage();
1654 
1655  /*
1656  * Start up a transaction command so we can call functions etc. (Note that
1657  * this will normally change current memory context.) Nothing happens if
1658  * we are already in one. This also arms the statement timeout if
1659  * necessary.
1660  */
1662 
1663  /* Switch back to message context */
1665 
1666  /* Get the parameter format codes */
1667  numPFormats = pq_getmsgint(input_message, 2);
1668  if (numPFormats > 0)
1669  {
1670  pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1671  for (int i = 0; i < numPFormats; i++)
1672  pformats[i] = pq_getmsgint(input_message, 2);
1673  }
1674 
1675  /* Get the parameter value count */
1676  numParams = pq_getmsgint(input_message, 2);
1677 
1678  if (numPFormats > 1 && numPFormats != numParams)
1679  ereport(ERROR,
1680  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1681  errmsg("bind message has %d parameter formats but %d parameters",
1682  numPFormats, numParams)));
1683 
1684  if (numParams != psrc->num_params)
1685  ereport(ERROR,
1686  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1687  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1688  numParams, stmt_name, psrc->num_params)));
1689 
1690  /*
1691  * If we are in aborted transaction state, the only portals we can
1692  * actually run are those containing COMMIT or ROLLBACK commands. We
1693  * disallow binding anything else to avoid problems with infrastructure
1694  * that expects to run inside a valid transaction. We also disallow
1695  * binding any parameters, since we can't risk calling user-defined I/O
1696  * functions.
1697  */
1699  (!(psrc->raw_parse_tree &&
1701  numParams != 0))
1702  ereport(ERROR,
1703  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1704  errmsg("current transaction is aborted, "
1705  "commands ignored until end of transaction block"),
1706  errdetail_abort()));
1707 
1708  /*
1709  * Create the portal. Allow silent replacement of an existing portal only
1710  * if the unnamed portal is specified.
1711  */
1712  if (portal_name[0] == '\0')
1713  portal = CreatePortal(portal_name, true, true);
1714  else
1715  portal = CreatePortal(portal_name, false, false);
1716 
1717  /*
1718  * Prepare to copy stuff into the portal's memory context. We do all this
1719  * copying first, because it could possibly fail (out-of-memory) and we
1720  * don't want a failure to occur between GetCachedPlan and
1721  * PortalDefineQuery; that would result in leaking our plancache refcount.
1722  */
1723  oldContext = MemoryContextSwitchTo(portal->portalContext);
1724 
1725  /* Copy the plan's query string into the portal */
1726  query_string = pstrdup(psrc->query_string);
1727 
1728  /* Likewise make a copy of the statement name, unless it's unnamed */
1729  if (stmt_name[0])
1730  saved_stmt_name = pstrdup(stmt_name);
1731  else
1732  saved_stmt_name = NULL;
1733 
1734  /*
1735  * Set a snapshot if we have parameters to fetch (since the input
1736  * functions might need it) or the query isn't a utility command (and
1737  * hence could require redoing parse analysis and planning). We keep the
1738  * snapshot active till we're done, so that plancache.c doesn't have to
1739  * take new ones.
1740  */
1741  if (numParams > 0 ||
1742  (psrc->raw_parse_tree &&
1744  {
1746  snapshot_set = true;
1747  }
1748 
1749  /*
1750  * Fetch parameters, if any, and store in the portal's memory context.
1751  */
1752  if (numParams > 0)
1753  {
1754  params = makeParamList(numParams);
1755 
1756  for (int paramno = 0; paramno < numParams; paramno++)
1757  {
1758  Oid ptype = psrc->param_types[paramno];
1759  int32 plength;
1760  Datum pval;
1761  bool isNull;
1762  StringInfoData pbuf;
1763  char csave;
1764  int16 pformat;
1765 
1766  plength = pq_getmsgint(input_message, 4);
1767  isNull = (plength == -1);
1768 
1769  if (!isNull)
1770  {
1771  const char *pvalue = pq_getmsgbytes(input_message, plength);
1772 
1773  /*
1774  * Rather than copying data around, we just set up a phony
1775  * StringInfo pointing to the correct portion of the message
1776  * buffer. We assume we can scribble on the message buffer so
1777  * as to maintain the convention that StringInfos have a
1778  * trailing null. This is grotty but is a big win when
1779  * dealing with very large parameter strings.
1780  */
1781  pbuf.data = unconstify(char *, pvalue);
1782  pbuf.maxlen = plength + 1;
1783  pbuf.len = plength;
1784  pbuf.cursor = 0;
1785 
1786  csave = pbuf.data[plength];
1787  pbuf.data[plength] = '\0';
1788  }
1789  else
1790  {
1791  pbuf.data = NULL; /* keep compiler quiet */
1792  csave = 0;
1793  }
1794 
1795  if (numPFormats > 1)
1796  pformat = pformats[paramno];
1797  else if (numPFormats > 0)
1798  pformat = pformats[0];
1799  else
1800  pformat = 0; /* default = text */
1801 
1802  if (pformat == 0) /* text mode */
1803  {
1804  Oid typinput;
1805  Oid typioparam;
1806  char *pstring;
1807 
1808  getTypeInputInfo(ptype, &typinput, &typioparam);
1809 
1810  /*
1811  * We have to do encoding conversion before calling the
1812  * typinput routine.
1813  */
1814  if (isNull)
1815  pstring = NULL;
1816  else
1817  pstring = pg_client_to_server(pbuf.data, plength);
1818 
1819  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1820 
1821  /* Free result of encoding conversion, if any */
1822  if (pstring && pstring != pbuf.data)
1823  pfree(pstring);
1824  }
1825  else if (pformat == 1) /* binary mode */
1826  {
1827  Oid typreceive;
1828  Oid typioparam;
1829  StringInfo bufptr;
1830 
1831  /*
1832  * Call the parameter type's binary input converter
1833  */
1834  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1835 
1836  if (isNull)
1837  bufptr = NULL;
1838  else
1839  bufptr = &pbuf;
1840 
1841  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1842 
1843  /* Trouble if it didn't eat the whole buffer */
1844  if (!isNull && pbuf.cursor != pbuf.len)
1845  ereport(ERROR,
1846  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1847  errmsg("incorrect binary data format in bind parameter %d",
1848  paramno + 1)));
1849  }
1850  else
1851  {
1852  ereport(ERROR,
1853  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1854  errmsg("unsupported format code: %d",
1855  pformat)));
1856  pval = 0; /* keep compiler quiet */
1857  }
1858 
1859  /* Restore message buffer contents */
1860  if (!isNull)
1861  pbuf.data[plength] = csave;
1862 
1863  params->params[paramno].value = pval;
1864  params->params[paramno].isnull = isNull;
1865 
1866  /*
1867  * We mark the params as CONST. This ensures that any custom plan
1868  * makes full use of the parameter values.
1869  */
1870  params->params[paramno].pflags = PARAM_FLAG_CONST;
1871  params->params[paramno].ptype = ptype;
1872  }
1873  }
1874  else
1875  params = NULL;
1876 
1877  /* Done storing stuff in portal's context */
1878  MemoryContextSwitchTo(oldContext);
1879 
1880  /* Get the result format codes */
1881  numRFormats = pq_getmsgint(input_message, 2);
1882  if (numRFormats > 0)
1883  {
1884  rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1885  for (int i = 0; i < numRFormats; i++)
1886  rformats[i] = pq_getmsgint(input_message, 2);
1887  }
1888 
1889  pq_getmsgend(input_message);
1890 
1891  /*
1892  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1893  * will be generated in MessageContext. The plan refcount will be
1894  * assigned to the Portal, so it will be released at portal destruction.
1895  */
1896  cplan = GetCachedPlan(psrc, params, false, NULL);
1897 
1898  /*
1899  * Now we can define the portal.
1900  *
1901  * DO NOT put any code that could possibly throw an error between the
1902  * above GetCachedPlan call and here.
1903  */
1904  PortalDefineQuery(portal,
1905  saved_stmt_name,
1906  query_string,
1907  psrc->commandTag,
1908  cplan->stmt_list,
1909  cplan);
1910 
1911  /* Done with the snapshot used for parameter I/O and parsing/planning */
1912  if (snapshot_set)
1914 
1915  /*
1916  * And we're ready to start portal execution.
1917  */
1918  PortalStart(portal, params, 0, InvalidSnapshot);
1919 
1920  /*
1921  * Apply the result format requests to the portal.
1922  */
1923  PortalSetResultFormat(portal, numRFormats, rformats);
1924 
1925  /*
1926  * Send BindComplete.
1927  */
1929  pq_putemptymessage('2');
1930 
1931  /*
1932  * Emit duration logging if appropriate.
1933  */
1934  switch (check_log_duration(msec_str, false))
1935  {
1936  case 1:
1937  ereport(LOG,
1938  (errmsg("duration: %s ms", msec_str),
1939  errhidestmt(true)));
1940  break;
1941  case 2:
1942  ereport(LOG,
1943  (errmsg("duration: %s ms bind %s%s%s: %s",
1944  msec_str,
1945  *stmt_name ? stmt_name : "<unnamed>",
1946  *portal_name ? "/" : "",
1947  *portal_name ? portal_name : "",
1948  psrc->query_string),
1949  errhidestmt(true),
1950  errdetail_params(params)));
1951  break;
1952  }
1953 
1954  if (save_log_statement_stats)
1955  ShowUsage("BIND MESSAGE STATISTICS");
1956 
1957  debug_query_string = NULL;
1958 }
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:1138
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:624
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:357
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:443
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:494
const char * commandTag
Definition: plancache.h:98
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3121
CachedPlanSource * plansource
Definition: prepare.h:31
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
void ShowUsage(const char *title)
Definition: postgres.c:4559
char * pstrdup(const char *in)
Definition: mcxt.c:1186
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
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:570
int errhidestmt(bool hide_stmt)
Definition: elog.c:1055
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2373
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
ParamListInfo makeParamList(int numParams)
Definition: params.c:32
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
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:2622
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2231
void ResetUsage(void)
Definition: postgres.c:4552
void pfree(void *pointer)
Definition: mcxt.c:1056
char * pg_client_to_server(const char *s, int len)
Definition: mbutils.c:565
#define ERROR
Definition: elog.h:43
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1664
#define DEBUG2
Definition: elog.h:24
Oid * param_types
Definition: plancache.h:99
Node * stmt
Definition: parsenodes.h:1485
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2307
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2707
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2641
#define ereport(elevel, rest)
Definition: elog.h:141
const char * debug_query_string
Definition: postgres.c:87
#define unconstify(underlying_type, expr)
Definition: c.h:1163
#define InvalidSnapshot
Definition: snapshot.h:123
static void start_xact_command(void)
Definition: postgres.c:2570
uintptr_t Datum
Definition: postgres.h:367
uint16 pflags
Definition: params.h:94
const char * query_string
Definition: plancache.h:97
MemoryContext MessageContext
Definition: mcxt.c:48
struct RawStmt * raw_parse_tree
Definition: plancache.h:96
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
List * stmt_list
Definition: plancache.h:146
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:485
bool isnull
Definition: params.h:93
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1646
#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 2518 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().

2519 {
2520  Portal portal;
2521 
2522  /*
2523  * Start up a transaction command. (Note that this will normally change
2524  * current memory context.) Nothing happens if we are already in one.
2525  */
2527 
2528  /* Switch back to message context */
2530 
2531  portal = GetPortalByName(portal_name);
2532  if (!PortalIsValid(portal))
2533  ereport(ERROR,
2534  (errcode(ERRCODE_UNDEFINED_CURSOR),
2535  errmsg("portal \"%s\" does not exist", portal_name)));
2536 
2537  /*
2538  * If we are in aborted transaction state, we can't run
2539  * SendRowDescriptionMessage(), because that needs catalog accesses.
2540  * Hence, refuse to Describe portals that return data. (We shouldn't just
2541  * refuse all Describes, since that might break the ability of some
2542  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2543  * blindly Describes whatever it does.)
2544  */
2546  portal->tupDesc)
2547  ereport(ERROR,
2548  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2549  errmsg("current transaction is aborted, "
2550  "commands ignored until end of transaction block"),
2551  errdetail_abort()));
2552 
2554  return; /* can't actually do anything... */
2555 
2556  if (portal->tupDesc)
2558  portal->tupDesc,
2559  FetchPortalTargetList(portal),
2560  portal->formats);
2561  else
2562  pq_putemptymessage('n'); /* NoData */
2563 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:570
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2373
#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:2570
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:784
CommandDest whereToSendOutput
Definition: postgres.c:90
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:336
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:201

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

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

2424 {
2425  CachedPlanSource *psrc;
2426 
2427  /*
2428  * Start up a transaction command. (Note that this will normally change
2429  * current memory context.) Nothing happens if we are already in one.
2430  */
2432 
2433  /* Switch back to message context */
2435 
2436  /* Find prepared statement */
2437  if (stmt_name[0] != '\0')
2438  {
2439  PreparedStatement *pstmt;
2440 
2441  pstmt = FetchPreparedStatement(stmt_name, true);
2442  psrc = pstmt->plansource;
2443  }
2444  else
2445  {
2446  /* special-case the unnamed statement */
2447  psrc = unnamed_stmt_psrc;
2448  if (!psrc)
2449  ereport(ERROR,
2450  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2451  errmsg("unnamed prepared statement does not exist")));
2452  }
2453 
2454  /* Prepared statements shouldn't have changeable result descs */
2455  Assert(psrc->fixed_result);
2456 
2457  /*
2458  * If we are in aborted transaction state, we can't run
2459  * SendRowDescriptionMessage(), because that needs catalog accesses.
2460  * Hence, refuse to Describe statements that return data. (We shouldn't
2461  * just refuse all Describes, since that might break the ability of some
2462  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2463  * blindly Describes whatever it does.) We can Describe parameters
2464  * without doing anything dangerous, so we don't restrict that.
2465  */
2467  psrc->resultDesc)
2468  ereport(ERROR,
2469  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2470  errmsg("current transaction is aborted, "
2471  "commands ignored until end of transaction block"),
2472  errdetail_abort()));
2473 
2475  return; /* can't actually do anything... */
2476 
2477  /*
2478  * First describe the parameters...
2479  */
2480  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2481  * message type */
2483 
2484  for (int i = 0; i < psrc->num_params; i++)
2485  {
2486  Oid ptype = psrc->param_types[i];
2487 
2488  pq_sendint32(&row_description_buf, (int) ptype);
2489  }
2491 
2492  /*
2493  * Next send RowDescription or NoData to describe the result...
2494  */
2495  if (psrc->resultDesc)
2496  {
2497  List *tlist;
2498 
2499  /* Get the plan's primary targetlist */
2500  tlist = CachedPlanGetTargetList(psrc, NULL);
2501 
2503  psrc->resultDesc,
2504  tlist,
2505  NULL);
2506  }
2507  else
2508  pq_putemptymessage('n'); /* NoData */
2509 
2510 }
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:570
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2373
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc resultDesc
Definition: plancache.h:105
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define ERROR
Definition: elog.h:43
Oid * param_types
Definition: plancache.h:99
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1428
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158
#define ereport(elevel, rest)
Definition: elog.h:141
static void start_xact_command(void)
Definition: postgres.c:2570
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:784
int i
CommandDest whereToSendOutput
Definition: postgres.c:90
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:201
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:485
Definition: pg_list.h:50
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 1966 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().

1967 {
1968  CommandDest dest;
1969  DestReceiver *receiver;
1970  Portal portal;
1971  bool completed;
1972  char completionTag[COMPLETION_TAG_BUFSIZE];
1973  const char *sourceText;
1974  const char *prepStmtName;
1975  ParamListInfo portalParams;
1976  bool save_log_statement_stats = log_statement_stats;
1977  bool is_xact_command;
1978  bool execute_is_fetch;
1979  bool was_logged = false;
1980  char msec_str[32];
1981 
1982  /* Adjust destination to tell printtup.c what to do */
1983  dest = whereToSendOutput;
1984  if (dest == DestRemote)
1985  dest = DestRemoteExecute;
1986 
1987  portal = GetPortalByName(portal_name);
1988  if (!PortalIsValid(portal))
1989  ereport(ERROR,
1990  (errcode(ERRCODE_UNDEFINED_CURSOR),
1991  errmsg("portal \"%s\" does not exist", portal_name)));
1992 
1993  /*
1994  * If the original query was a null string, just return
1995  * EmptyQueryResponse.
1996  */
1997  if (portal->commandTag == NULL)
1998  {
1999  Assert(portal->stmts == NIL);
2000  NullCommand(dest);
2001  return;
2002  }
2003 
2004  /* Does the portal contain a transaction command? */
2005  is_xact_command = IsTransactionStmtList(portal->stmts);
2006 
2007  /*
2008  * We must copy the sourceText and prepStmtName into MessageContext in
2009  * case the portal is destroyed during finish_xact_command. Can avoid the
2010  * copy if it's not an xact command, though.
2011  */
2012  if (is_xact_command)
2013  {
2014  sourceText = pstrdup(portal->sourceText);
2015  if (portal->prepStmtName)
2016  prepStmtName = pstrdup(portal->prepStmtName);
2017  else
2018  prepStmtName = "<unnamed>";
2019 
2020  /*
2021  * An xact command shouldn't have any parameters, which is a good
2022  * thing because they wouldn't be around after finish_xact_command.
2023  */
2024  portalParams = NULL;
2025  }
2026  else
2027  {
2028  sourceText = portal->sourceText;
2029  if (portal->prepStmtName)
2030  prepStmtName = portal->prepStmtName;
2031  else
2032  prepStmtName = "<unnamed>";
2033  portalParams = portal->portalParams;
2034  }
2035 
2036  /*
2037  * Report query to various monitoring facilities.
2038  */
2039  debug_query_string = sourceText;
2040 
2042 
2043  set_ps_display(portal->commandTag, false);
2044 
2045  if (save_log_statement_stats)
2046  ResetUsage();
2047 
2048  BeginCommand(portal->commandTag, dest);
2049 
2050  /*
2051  * Create dest receiver in MessageContext (we don't want it in transaction
2052  * context, because that may get deleted if portal contains VACUUM).
2053  */
2054  receiver = CreateDestReceiver(dest);
2055  if (dest == DestRemoteExecute)
2056  SetRemoteDestReceiverParams(receiver, portal);
2057 
2058  /*
2059  * Ensure we are in a transaction command (this should normally be the
2060  * case already due to prior BIND).
2061  */
2063 
2064  /*
2065  * If we re-issue an Execute protocol request against an existing portal,
2066  * then we are only fetching more rows rather than completely re-executing
2067  * the query from the start. atStart is never reset for a v3 portal, so we
2068  * are safe to use this check.
2069  */
2070  execute_is_fetch = !portal->atStart;
2071 
2072  /* Log immediately if dictated by log_statement */
2073  if (check_log_statement(portal->stmts))
2074  {
2075  ereport(LOG,
2076  (errmsg("%s %s%s%s: %s",
2077  execute_is_fetch ?
2078  _("execute fetch from") :
2079  _("execute"),
2080  prepStmtName,
2081  *portal_name ? "/" : "",
2082  *portal_name ? portal_name : "",
2083  sourceText),
2084  errhidestmt(true),
2085  errdetail_params(portalParams)));
2086  was_logged = true;
2087  }
2088 
2089  /*
2090  * If we are in aborted transaction state, the only portals we can
2091  * actually run are those containing COMMIT or ROLLBACK commands.
2092  */
2094  !IsTransactionExitStmtList(portal->stmts))
2095  ereport(ERROR,
2096  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2097  errmsg("current transaction is aborted, "
2098  "commands ignored until end of transaction block"),
2099  errdetail_abort()));
2100 
2101  /* Check for cancel signal before we start execution */
2103 
2104  /*
2105  * Okay to run the portal.
2106  */
2107  if (max_rows <= 0)
2108  max_rows = FETCH_ALL;
2109 
2110  completed = PortalRun(portal,
2111  max_rows,
2112  true, /* always top level */
2113  !execute_is_fetch && max_rows == FETCH_ALL,
2114  receiver,
2115  receiver,
2116  completionTag);
2117 
2118  receiver->rDestroy(receiver);
2119 
2120  if (completed)
2121  {
2122  if (is_xact_command)
2123  {
2124  /*
2125  * If this was a transaction control statement, commit it. We
2126  * will start a new xact command for the next command (if any).
2127  */
2129  }
2130  else
2131  {
2132  /*
2133  * We need a CommandCounterIncrement after every query, except
2134  * those that start or end a transaction block.
2135  */
2137 
2138  /* full command has been executed, reset timeout */
2140  }
2141 
2142  /* Send appropriate CommandComplete to client */
2143  EndCommand(completionTag, dest);
2144  }
2145  else
2146  {
2147  /* Portal run not complete, so send PortalSuspended */
2149  pq_putemptymessage('s');
2150  }
2151 
2152  /*
2153  * Emit duration logging if appropriate.
2154  */
2155  switch (check_log_duration(msec_str, was_logged))
2156  {
2157  case 1:
2158  ereport(LOG,
2159  (errmsg("duration: %s ms", msec_str),
2160  errhidestmt(true)));
2161  break;
2162  case 2:
2163  ereport(LOG,
2164  (errmsg("duration: %s ms %s %s%s%s: %s",
2165  msec_str,
2166  execute_is_fetch ?
2167  _("execute fetch from") :
2168  _("execute"),
2169  prepStmtName,
2170  *portal_name ? "/" : "",
2171  *portal_name ? portal_name : "",
2172  sourceText),
2173  errhidestmt(true),
2174  errdetail_params(portalParams)));
2175  break;
2176  }
2177 
2178  if (save_log_statement_stats)
2179  ShowUsage("EXECUTE MESSAGE STATISTICS");
2180 
2181  debug_query_string = NULL;
2182 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2654
#define NIL
Definition: pg_list.h:65
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:107
static void finish_xact_command(void)
Definition: postgres.c:2590
CommandDest
Definition: dest.h:86
bool log_statement_stats
Definition: guc.c:494
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3121
void ShowUsage(const char *title)
Definition: postgres.c:4559
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
char * pstrdup(const char *in)
Definition: mcxt.c:1186
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
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:686
int errcode(int sqlerrcode)
Definition: elog.c:570
int errhidestmt(bool hide_stmt)
Definition: elog.c:1055
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2373
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:103
#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:2231
void ResetUsage(void)
Definition: postgres.c:4552
static void disable_statement_timeout(void)
Definition: postgres.c:4718
ParamListInfo portalParams
Definition: portal.h:139
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:166
#define ERROR
Definition: elog.h:43
const char * commandTag
Definition: portal.h:135
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2307
#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:2192
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2570
void CommandCounterIncrement(void)
Definition: xact.c:1003
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:2639
bool atStart
Definition: portal.h:188
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
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:207
#define FETCH_ALL
Definition: parsenodes.h:2727

◆ exec_parse_message()

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

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

1338 {
1339  MemoryContext unnamed_stmt_context = NULL;
1340  MemoryContext oldcontext;
1341  List *parsetree_list;
1342  RawStmt *raw_parse_tree;
1343  const char *commandTag;
1344  List *querytree_list;
1345  CachedPlanSource *psrc;
1346  bool is_named;
1347  bool save_log_statement_stats = log_statement_stats;
1348  char msec_str[32];
1349 
1350  /*
1351  * Report query to various monitoring facilities.
1352  */
1353  debug_query_string = query_string;
1354 
1355  pgstat_report_activity(STATE_RUNNING, query_string);
1356 
1357  set_ps_display("PARSE", false);
1358 
1359  if (save_log_statement_stats)
1360  ResetUsage();
1361 
1362  ereport(DEBUG2,
1363  (errmsg("parse %s: %s",
1364  *stmt_name ? stmt_name : "<unnamed>",
1365  query_string)));
1366 
1367  /*
1368  * Start up a transaction command so we can run parse analysis etc. (Note
1369  * that this will normally change current memory context.) Nothing happens
1370  * if we are already in one. This also arms the statement timeout if
1371  * necessary.
1372  */
1374 
1375  /*
1376  * Switch to appropriate context for constructing parsetrees.
1377  *
1378  * We have two strategies depending on whether the prepared statement is
1379  * named or not. For a named prepared statement, we do parsing in
1380  * MessageContext and copy the finished trees into the prepared
1381  * statement's plancache entry; then the reset of MessageContext releases
1382  * temporary space used by parsing and rewriting. For an unnamed prepared
1383  * statement, we assume the statement isn't going to hang around long, so
1384  * getting rid of temp space quickly is probably not worth the costs of
1385  * copying parse trees. So in this case, we create the plancache entry's
1386  * query_context here, and do all the parsing work therein.
1387  */
1388  is_named = (stmt_name[0] != '\0');
1389  if (is_named)
1390  {
1391  /* Named prepared statement --- parse in MessageContext */
1392  oldcontext = MemoryContextSwitchTo(MessageContext);
1393  }
1394  else
1395  {
1396  /* Unnamed prepared statement --- release any prior unnamed stmt */
1398  /* Create context for parsing */
1399  unnamed_stmt_context =
1401  "unnamed prepared statement",
1403  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1404  }
1405 
1406  /*
1407  * Do basic parsing of the query or queries (this should be safe even if
1408  * we are in aborted transaction state!)
1409  */
1410  parsetree_list = pg_parse_query(query_string);
1411 
1412  /*
1413  * We only allow a single user statement in a prepared statement. This is
1414  * mainly to keep the protocol simple --- otherwise we'd need to worry
1415  * about multiple result tupdescs and things like that.
1416  */
1417  if (list_length(parsetree_list) > 1)
1418  ereport(ERROR,
1419  (errcode(ERRCODE_SYNTAX_ERROR),
1420  errmsg("cannot insert multiple commands into a prepared statement")));
1421 
1422  if (parsetree_list != NIL)
1423  {
1424  Query *query;
1425  bool snapshot_set = false;
1426 
1427  raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1428 
1429  /*
1430  * Get the command name for possible use in status display.
1431  */
1432  commandTag = CreateCommandTag(raw_parse_tree->stmt);
1433 
1434  /*
1435  * If we are in an aborted transaction, reject all commands except
1436  * COMMIT/ROLLBACK. It is important that this test occur before we
1437  * try to do parse analysis, rewrite, or planning, since all those
1438  * phases try to do database accesses, which may fail in abort state.
1439  * (It might be safe to allow some additional utility commands in this
1440  * state, but not many...)
1441  */
1443  !IsTransactionExitStmt(raw_parse_tree->stmt))
1444  ereport(ERROR,
1445  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1446  errmsg("current transaction is aborted, "
1447  "commands ignored until end of transaction block"),
1448  errdetail_abort()));
1449 
1450  /*
1451  * Create the CachedPlanSource before we do parse analysis, since it
1452  * needs to see the unmodified raw parse tree.
1453  */
1454  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1455 
1456  /*
1457  * Set up a snapshot if parse analysis will need one.
1458  */
1459  if (analyze_requires_snapshot(raw_parse_tree))
1460  {
1462  snapshot_set = true;
1463  }
1464 
1465  /*
1466  * Analyze and rewrite the query. Note that the originally specified
1467  * parameter set is not required to be complete, so we have to use
1468  * parse_analyze_varparams().
1469  */
1470  if (log_parser_stats)
1471  ResetUsage();
1472 
1473  query = parse_analyze_varparams(raw_parse_tree,
1474  query_string,
1475  &paramTypes,
1476  &numParams);
1477 
1478  /*
1479  * Check all parameter types got determined.
1480  */
1481  for (int i = 0; i < numParams; i++)
1482  {
1483  Oid ptype = paramTypes[i];
1484 
1485  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1486  ereport(ERROR,
1487  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1488  errmsg("could not determine data type of parameter $%d",
1489  i + 1)));
1490  }
1491 
1492  if (log_parser_stats)
1493  ShowUsage("PARSE ANALYSIS STATISTICS");
1494 
1495  querytree_list = pg_rewrite_query(query);
1496 
1497  /* Done with the snapshot used for parsing */
1498  if (snapshot_set)
1500  }
1501  else
1502  {
1503  /* Empty input string. This is legal. */
1504  raw_parse_tree = NULL;
1505  commandTag = NULL;
1506  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1507  querytree_list = NIL;
1508  }
1509 
1510  /*
1511  * CachedPlanSource must be a direct child of MessageContext before we
1512  * reparent unnamed_stmt_context under it, else we have a disconnected
1513  * circular subgraph. Klugy, but less so than flipping contexts even more
1514  * above.
1515  */
1516  if (unnamed_stmt_context)
1518 
1519  /* Finish filling in the CachedPlanSource */
1520  CompleteCachedPlan(psrc,
1521  querytree_list,
1522  unnamed_stmt_context,
1523  paramTypes,
1524  numParams,
1525  NULL,
1526  NULL,
1527  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1528  true); /* fixed result */
1529 
1530  /* If we got a cancel signal during analysis, quit */
1532 
1533  if (is_named)
1534  {
1535  /*
1536  * Store the query as a prepared statement.
1537  */
1538  StorePreparedStatement(stmt_name, psrc, false);
1539  }
1540  else
1541  {
1542  /*
1543  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1544  */
1545  SaveCachedPlan(psrc);
1546  unnamed_stmt_psrc = psrc;
1547  }
1548 
1549  MemoryContextSwitchTo(oldcontext);
1550 
1551  /*
1552  * We do NOT close the open transaction command here; that only happens
1553  * when the client sends Sync. Instead, do CommandCounterIncrement just
1554  * in case something happened during parse/plan.
1555  */
1557 
1558  /*
1559  * Send ParseComplete.
1560  */
1562  pq_putemptymessage('1');
1563 
1564  /*
1565  * Emit duration logging if appropriate.
1566  */
1567  switch (check_log_duration(msec_str, false))
1568  {
1569  case 1:
1570  ereport(LOG,
1571  (errmsg("duration: %s ms", msec_str),
1572  errhidestmt(true)));
1573  break;
1574  case 2:
1575  ereport(LOG,
1576  (errmsg("duration: %s ms parse %s: %s",
1577  msec_str,
1578  *stmt_name ? stmt_name : "<unnamed>",
1579  query_string),
1580  errhidestmt(true)));
1581  break;
1582  }
1583 
1584  if (save_log_statement_stats)
1585  ShowUsage("PARSE MESSAGE STATISTICS");
1586 
1587  debug_query_string = NULL;
1588 }
MemoryContext context
Definition: plancache.h:106
#define NIL
Definition: pg_list.h:65
#define AllocSetContextCreate
Definition: memutils.h:170
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:357
bool log_parser_stats
Definition: guc.c:491
bool log_statement_stats
Definition: guc.c:494
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3121
void ShowUsage(const char *title)
Definition: postgres.c:4559
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:354
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
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:570
int errhidestmt(bool hide_stmt)
Definition: elog.c:1055
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:2373
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:198
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2622
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2231
void ResetUsage(void)
Definition: postgres.c:4552
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:632
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define DEBUG2
Definition: elog.h:24
Node * stmt
Definition: parsenodes.h:1485
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
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:164
#define ereport(elevel, rest)
Definition: elog.h:141
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2104
const char * debug_query_string
Definition: postgres.c:87
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:769
static void start_xact_command(void)
Definition: postgres.c:2570
void CommandCounterIncrement(void)
Definition: xact.c:1003
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:443
#define InvalidOid
Definition: postgres_ext.h:36
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:452
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:336
static int list_length(const List *l)
Definition: pg_list.h:169
MemoryContext MessageContext
Definition: mcxt.c:48
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2692
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
static void drop_unnamed_stmt(void)
Definition: postgres.c:2669
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandDest whereToSendOutput
Definition: postgres.c:90
Definition: pg_list.h:50

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 984 of file postgres.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, 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, MemoryContextDelete(), 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().

985 {
987  MemoryContext oldcontext;
988  List *parsetree_list;
989  ListCell *parsetree_item;
990  bool save_log_statement_stats = log_statement_stats;
991  bool was_logged = false;
992  bool use_implicit_block;
993  char msec_str[32];
994 
995  /*
996  * Report query to various monitoring facilities.
997  */
998  debug_query_string = query_string;
999 
1000  pgstat_report_activity(STATE_RUNNING, query_string);
1001 
1002  TRACE_POSTGRESQL_QUERY_START(query_string);
1003 
1004  /*
1005  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1006  * results because ResetUsage wasn't called.
1007  */
1008  if (save_log_statement_stats)
1009  ResetUsage();
1010 
1011  /*
1012  * Start up a transaction command. All queries generated by the
1013  * query_string will be in this same command block, *unless* we find a
1014  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1015  * one of those, else bad things will happen in xact.c. (Note that this
1016  * will normally change current memory context.)
1017  */
1019 
1020  /*
1021  * Zap any pre-existing unnamed statement. (While not strictly necessary,
1022  * it seems best to define simple-Query mode as if it used the unnamed
1023  * statement and portal; this ensures we recover any storage used by prior
1024  * unnamed operations.)
1025  */
1027 
1028  /*
1029  * Switch to appropriate context for constructing parsetrees.
1030  */
1031  oldcontext = MemoryContextSwitchTo(MessageContext);
1032 
1033  /*
1034  * Do basic parsing of the query or queries (this should be safe even if
1035  * we are in aborted transaction state!)
1036  */
1037  parsetree_list = pg_parse_query(query_string);
1038 
1039  /* Log immediately if dictated by log_statement */
1040  if (check_log_statement(parsetree_list))
1041  {
1042  ereport(LOG,
1043  (errmsg("statement: %s", query_string),
1044  errhidestmt(true),
1045  errdetail_execute(parsetree_list)));
1046  was_logged = true;
1047  }
1048 
1049  /*
1050  * Switch back to transaction context to enter the loop.
1051  */
1052  MemoryContextSwitchTo(oldcontext);
1053 
1054  /*
1055  * For historical reasons, if multiple SQL statements are given in a
1056  * single "simple Query" message, we execute them as a single transaction,
1057  * unless explicit transaction control commands are included to make
1058  * portions of the list be separate transactions. To represent this
1059  * behavior properly in the transaction machinery, we use an "implicit"
1060  * transaction block.
1061  */
1062  use_implicit_block = (list_length(parsetree_list) > 1);
1063 
1064  /*
1065  * Run through the raw parsetree(s) and process each one.
1066  */
1067  foreach(parsetree_item, parsetree_list)
1068  {
1069  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1070  bool snapshot_set = false;
1071  const char *commandTag;
1072  char completionTag[COMPLETION_TAG_BUFSIZE];
1073  MemoryContext per_parsetree_context = NULL;
1074  List *querytree_list,
1075  *plantree_list;
1076  Portal portal;
1077  DestReceiver *receiver;
1078  int16 format;
1079 
1080  /*
1081  * Get the command name for use in status display (it also becomes the
1082  * default completion tag, down inside PortalRun). Set ps_status and
1083  * do any special start-of-SQL-command processing needed by the
1084  * destination.
1085  */
1086  commandTag = CreateCommandTag(parsetree->stmt);
1087 
1088  set_ps_display(commandTag, false);
1089 
1090  BeginCommand(commandTag, dest);
1091 
1092  /*
1093  * If we are in an aborted transaction, reject all commands except
1094  * COMMIT/ABORT. It is important that this test occur before we try
1095  * to do parse analysis, rewrite, or planning, since all those phases
1096  * try to do database accesses, which may fail in abort state. (It
1097  * might be safe to allow some additional utility commands in this
1098  * state, but not many...)
1099  */
1101  !IsTransactionExitStmt(parsetree->stmt))
1102  ereport(ERROR,
1103  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1104  errmsg("current transaction is aborted, "
1105  "commands ignored until end of transaction block"),
1106  errdetail_abort()));
1107 
1108  /* Make sure we are in a transaction command */
1110 
1111  /*
1112  * If using an implicit transaction block, and we're not already in a
1113  * transaction block, start an implicit block to force this statement
1114  * to be grouped together with any following ones. (We must do this
1115  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1116  * list would cause later statements to not be grouped.)
1117  */
1118  if (use_implicit_block)
1120 
1121  /* If we got a cancel signal in parsing or prior command, quit */
1123 
1124  /*
1125  * Set up a snapshot if parse analysis/planning will need one.
1126  */
1127  if (analyze_requires_snapshot(parsetree))
1128  {
1130  snapshot_set = true;
1131  }
1132 
1133  /*
1134  * OK to analyze, rewrite, and plan this query.
1135  *
1136  * Switch to appropriate context for constructing query and plan trees
1137  * (these can't be in the transaction context, as that will get reset
1138  * when the command is COMMIT/ROLLBACK). If we have multiple
1139  * parsetrees, we use a separate context for each one, so that we can
1140  * free that memory before moving on to the next one. But for the
1141  * last (or only) parsetree, just use MessageContext, which will be
1142  * reset shortly after completion anyway. In event of an error, the
1143  * per_parsetree_context will be deleted when MessageContext is reset.
1144  */
1145  if (lnext(parsetree_list, parsetree_item) != NULL)
1146  {
1147  per_parsetree_context =
1149  "per-parsetree message context",
1151  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1152  }
1153  else
1154  oldcontext = MemoryContextSwitchTo(MessageContext);
1155 
1156  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1157  NULL, 0, NULL);
1158 
1159  plantree_list = pg_plan_queries(querytree_list,
1160  CURSOR_OPT_PARALLEL_OK, NULL);
1161 
1162  /* Done with the snapshot used for parsing/planning */
1163  if (snapshot_set)
1165 
1166  /* If we got a cancel signal in analysis or planning, quit */
1168 
1169  /*
1170  * Create unnamed portal to run the query or queries in. If there
1171  * already is one, silently drop it.
1172  */
1173  portal = CreatePortal("", true, true);
1174  /* Don't display the portal in pg_cursors */
1175  portal->visible = false;
1176 
1177  /*
1178  * We don't have to copy anything into the portal, because everything
1179  * we are passing here is in MessageContext or the
1180  * per_parsetree_context, and so will outlive the portal anyway.
1181  */
1182  PortalDefineQuery(portal,
1183  NULL,
1184  query_string,
1185  commandTag,
1186  plantree_list,
1187  NULL);
1188 
1189  /*
1190  * Start the portal. No parameters here.
1191  */
1192  PortalStart(portal, NULL, 0, InvalidSnapshot);
1193 
1194  /*
1195  * Select the appropriate output format: text unless we are doing a
1196  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1197  * --- but it avoids grottiness in other places. Ah, the joys of
1198  * backward compatibility...)
1199  */
1200  format = 0; /* TEXT is default */
1201  if (IsA(parsetree->stmt, FetchStmt))
1202  {
1203  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1204 
1205  if (!stmt->ismove)
1206  {
1207  Portal fportal = GetPortalByName(stmt->portalname);
1208 
1209  if (PortalIsValid(fportal) &&
1210  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1211  format = 1; /* BINARY */
1212  }
1213  }
1214  PortalSetResultFormat(portal, 1, &format);
1215 
1216  /*
1217  * Now we can create the destination receiver object.
1218  */
1219  receiver = CreateDestReceiver(dest);
1220  if (dest == DestRemote)
1221  SetRemoteDestReceiverParams(receiver, portal);
1222 
1223  /*
1224  * Switch back to transaction context for execution.
1225  */
1226  MemoryContextSwitchTo(oldcontext);
1227 
1228  /*
1229  * Run the portal to completion, and then drop it (and the receiver).
1230  */
1231  (void) PortalRun(portal,
1232  FETCH_ALL,
1233  true, /* always top level */
1234  true,
1235  receiver,
1236  receiver,
1237  completionTag);
1238 
1239  receiver->rDestroy(receiver);
1240 
1241  PortalDrop(portal, false);
1242 
1243  if (lnext(parsetree_list, parsetree_item) == NULL)
1244  {
1245  /*
1246  * If this is the last parsetree of the query string, close down
1247  * transaction statement before reporting command-complete. This
1248  * is so that any end-of-transaction errors are reported before
1249  * the command-complete message is issued, to avoid confusing
1250  * clients who will expect either a command-complete message or an
1251  * error, not one and then the other. Also, if we're using an
1252  * implicit transaction block, we must close that out first.
1253  */
1254  if (use_implicit_block)
1257  }
1258  else if (IsA(parsetree->stmt, TransactionStmt))
1259  {
1260  /*
1261  * If this was a transaction control statement, commit it. We will
1262  * start a new xact command for the next command.
1263  */
1265  }
1266  else
1267  {
1268  /*
1269  * We need a CommandCounterIncrement after every query, except
1270  * those that start or end a transaction block.
1271  */
1273  }
1274 
1275  /*
1276  * Tell client that we're done with this query. Note we emit exactly
1277  * one EndCommand report for each raw parsetree, thus one for each SQL
1278  * command the client sent, regardless of rewriting. (But a command
1279  * aborted by error will not send an EndCommand report at all.)
1280  */
1281  EndCommand(completionTag, dest);
1282 
1283  /* Now we may drop the per-parsetree context, if one was created. */
1284  if (per_parsetree_context)
1285  MemoryContextDelete(per_parsetree_context);
1286  } /* end loop over parsetrees */
1287 
1288  /*
1289  * Close down transaction statement, if one is open. (This will only do
1290  * something if the parsetree list was empty; otherwise the last loop
1291  * iteration already did it.)
1292  */
1294 
1295  /*
1296  * If there were no parsetrees, return EmptyQueryResponse message.
1297  */
1298  if (!parsetree_list)
1299  NullCommand(dest);
1300 
1301  /*
1302  * Emit duration logging if appropriate.
1303  */
1304  switch (check_log_duration(msec_str, was_logged))
1305  {
1306  case 1:
1307  ereport(LOG,
1308  (errmsg("duration: %s ms", msec_str),
1309  errhidestmt(true)));
1310  break;
1311  case 2:
1312  ereport(LOG,
1313  (errmsg("duration: %s ms statement: %s",
1314  msec_str, query_string),
1315  errhidestmt(true),
1316  errdetail_execute(parsetree_list)));
1317  break;
1318  }
1319 
1320  if (save_log_statement_stats)
1321  ShowUsage("QUERY STATISTICS");
1322 
1323  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1324 
1325  debug_query_string = NULL;
1326 }
signed short int16
Definition: c.h:345
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:107
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:624
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:357
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:443
static void finish_xact_command(void)
Definition: postgres.c:2590
bool visible
Definition: portal.h:194
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
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:494
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3121
void ShowUsage(const char *title)
Definition: postgres.c:4559
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2683
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
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:686
int errcode(int sqlerrcode)
Definition: elog.c:570
int errhidestmt(bool hide_stmt)
Definition: elog.c:1055
static int errdetail_abort(void)
Definition: postgres.c:2373
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:103
#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:680
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2622
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2231
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2276
void ResetUsage(void)
Definition: postgres.c:4552
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:166
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:632
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Node * stmt
Definition: parsenodes.h:1485
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
void BeginImplicitTransactionBlock(void)
Definition: xact.c:3989
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
char * portalname
Definition: parsenodes.h:2734
#define ereport(elevel, rest)
Definition: elog.h:141
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2104
const char * debug_query_string
Definition: postgres.c:87
#define InvalidSnapshot
Definition: snapshot.h:123
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2192
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2570
void EndImplicitTransactionBlock(void)
Definition: xact.c:4014
bool ismove
Definition: parsenodes.h:2735
void CommandCounterIncrement(void)
Definition: xact.c:1003
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:169
MemoryContext MessageContext
Definition: mcxt.c:48
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2692
int errmsg(const char *fmt,...)
Definition: elog.c:784
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:465
static void drop_unnamed_stmt(void)
Definition: postgres.c:2669
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static char format
Definition: pg_basebackup.c:85
int cursorOptions
Definition: portal.h:144
CommandDest whereToSendOutput
Definition: postgres.c:90
Definition: pg_list.h:50
List * pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:946
void NullCommand(CommandDest dest)
Definition: dest.c:207
#define FETCH_ALL
Definition: parsenodes.h:2727

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2590 of file postgres.c.

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

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

2591 {
2592  /* cancel active statement timeout after each command */
2594 
2595  if (xact_started)
2596  {
2598 
2599 #ifdef MEMORY_CONTEXT_CHECKING
2600  /* Check all memory contexts that weren't freed during commit */
2601  /* (those that were, were checked before being deleted) */
2602  MemoryContextCheck(TopMemoryContext);
2603 #endif
2604 
2605 #ifdef SHOW_MEMORY_STATS
2606  /* Print mem stats after each commit for leak tracking */
2608 #endif
2609 
2610  xact_started = false;
2611  }
2612 }
void CommitTransactionCommand(void)
Definition: xact.c:2895
static void disable_statement_timeout(void)
Definition: postgres.c:4718
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:498
static bool xact_started
Definition: postgres.c:132
MemoryContext TopMemoryContext
Definition: mcxt.c:44

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2813 of file postgres.c.

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

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

2814 {
2815  /* We're not returning, so no need to save errno */
2816  ereport(ERROR,
2817  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2818  errmsg("floating-point exception"),
2819  errdetail("An invalid floating-point operation was signaled. "
2820  "This probably means an out-of-range result or an "
2821  "invalid operation, such as division by zero.")));
2822 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4494 of file postgres.c.

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

Referenced by PostgresMain().

4495 {
4496  if (am_walsender)
4497  {
4498  if (firstchar == 'F')
4499  ereport(ERROR,
4500  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4501  errmsg("fastpath function calls not supported in a replication connection")));
4502  else
4503  ereport(ERROR,
4504  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4505  errmsg("extended query protocol not supported in a replication connection")));
4506  }
4507 }
int errcode(int sqlerrcode)
Definition: elog.c:570
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:784

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4516 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4517 {
4518 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4519  static long val = 0;
4520 
4521  /* This won't change after process launch, so check just once */
4522  if (val == 0)
4523  {
4524  struct rlimit rlim;
4525 
4526  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4527  val = -1;
4528  else if (rlim.rlim_cur == RLIM_INFINITY)
4529  val = LONG_MAX;
4530  /* rlim_cur is probably of an unsigned type, so check for overflow */
4531  else if (rlim.rlim_cur >= LONG_MAX)
4532  val = LONG_MAX;
4533  else
4534  val = rlim.rlim_cur;
4535  }
4536  return val;
4537 #else /* no getrlimit */
4538 #if defined(WIN32) || defined(__CYGWIN__)
4539  /* On Windows we set the backend stack size in src/backend/Makefile */
4540  return WIN32_STACK_RLIMIT;
4541 #else /* not windows ... give up */
4542  return -1;
4543 #endif
4544 #endif
4545 }
long val
Definition: informix.c:684

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3428 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3429 {
3430  switch (arg[0])
3431  {
3432  case 'p':
3433  if (optarg[1] == 'a') /* "parser" */
3434  return "log_parser_stats";
3435  else if (optarg[1] == 'l') /* "planner" */
3436  return "log_planner_stats";
3437  break;
3438 
3439  case 'e': /* "executor" */
3440  return "log_executor_stats";
3441  break;
3442  }
3443 
3444  return NULL;
3445 }
char * optarg
Definition: getopt.c:52
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:530
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 216 of file postgres.c.

References appendStringInfoChar(), StringInfoData::data, EchoQuery, interactive_getc(), StringInfoData::len, printf, resetStringInfo(), generate_unaccent_rules::stdout, 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 }
#define printf(...)
Definition: port.h:198
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:175
static bool EchoQuery
Definition: postgres.c:162
static bool UseSemiNewlineNewline
Definition: postgres.c:163

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

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

2623 {
2624  if (parsetree && IsA(parsetree, TransactionStmt))
2625  {
2626  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2627 
2628  if (stmt->kind == TRANS_STMT_COMMIT ||
2629  stmt->kind == TRANS_STMT_PREPARE ||
2630  stmt->kind == TRANS_STMT_ROLLBACK ||
2631  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2632  return true;
2633  }
2634  return false;
2635 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
TransactionStmtKind kind
Definition: parsenodes.h:3023

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2639 of file postgres.c.

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

Referenced by exec_execute_message().

2640 {
2641  if (list_length(pstmts) == 1)
2642  {
2643  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2644 
2645  if (pstmt->commandType == CMD_UTILITY &&
2647  return true;
2648  }
2649  return false;
2650 }
#define linitial_node(type, l)
Definition: pg_list.h:198
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2622
Node * utilityStmt
Definition: plannodes.h:90
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:169

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2654 of file postgres.c.

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

Referenced by exec_execute_message().

2655 {
2656  if (list_length(pstmts) == 1)
2657  {
2658  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2659 
2660  if (pstmt->commandType == CMD_UTILITY &&
2661  IsA(pstmt->utilityStmt, TransactionStmt))
2662  return true;
2663  }
2664  return false;
2665 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define linitial_node(type, l)
Definition: pg_list.h:198
Node * utilityStmt
Definition: plannodes.h:90
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:169

◆ log_disconnections()

static void log_disconnections ( int  code,
Datum  arg 
)
static

Definition at line 4661 of file postgres.c.

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

Referenced by PostgresMain().

4662 {
4663  Port *port = MyProcPort;
4664  long secs;
4665  int usecs;
4666  int msecs;
4667  int hours,
4668  minutes,
4669  seconds;
4670 
4673  &secs, &usecs);
4674  msecs = usecs / 1000;
4675 
4676  hours = secs / SECS_PER_HOUR;
4677  secs %= SECS_PER_HOUR;
4678  minutes = secs / SECS_PER_MINUTE;
4679  seconds = secs % SECS_PER_MINUTE;
4680 
4681  ereport(LOG,
4682  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4683  "user=%s database=%s host=%s%s%s",
4684  hours, minutes, seconds, msecs,
4685  port->user_name, port->database_name, port->remote_host,
4686  port->remote_port[0] ? " port=" : "", port->remote_port)));
4687 }
struct Port * MyProcPort
Definition: globals.c:43
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
Definition: libpq-be.h:120
char * remote_port
Definition: libpq-be.h:132
#define LOG
Definition: elog.h:26
#define SECS_PER_MINUTE
Definition: timestamp.h:88
char * user_name
Definition: libpq-be.h:141
#define ereport(elevel, rest)
Definition: elog.h:141
#define SECS_PER_HOUR
Definition: timestamp.h:87
static int port
Definition: pg_regress.c:92
TimestampTz MyStartTimestamp
Definition: globals.c:42
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:784
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1657
char * database_name
Definition: libpq-be.h:140

◆ pg_analyze_and_rewrite()

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

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

683 {
684  Query *query;
685  List *querytree_list;
686 
687  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
688 
689  /*
690  * (1) Perform parse analysis.
691  */
692  if (log_parser_stats)
693  ResetUsage();
694 
695  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
696  queryEnv);
697 
698  if (log_parser_stats)
699  ShowUsage("PARSE ANALYSIS STATISTICS");
700 
701  /*
702  * (2) Rewrite the queries, as necessary
703  */
704  querytree_list = pg_rewrite_query(query);
705 
706  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
707 
708  return querytree_list;
709 }
bool log_parser_stats
Definition: guc.c:491
void ShowUsage(const char *title)
Definition: postgres.c:4559
void ResetUsage(void)
Definition: postgres.c:4552
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:769
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:100
Definition: pg_list.h:50

◆ 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 717 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().

722 {
723  ParseState *pstate;
724  Query *query;
725  List *querytree_list;
726 
727  Assert(query_string != NULL); /* required as of 8.4 */
728 
729  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
730 
731  /*
732  * (1) Perform parse analysis.
733  */
734  if (log_parser_stats)
735  ResetUsage();
736 
737  pstate = make_parsestate(NULL);
738  pstate->p_sourcetext = query_string;
739  pstate->p_queryEnv = queryEnv;
740  (*parserSetup) (pstate, parserSetupArg);
741 
742  query = transformTopLevelStmt(pstate, parsetree);
743 
745  (*post_parse_analyze_hook) (pstate, query);
746 
747  free_parsestate(pstate);
748 
749  if (log_parser_stats)
750  ShowUsage("PARSE ANALYSIS STATISTICS");
751 
752  /*
753  * (2) Rewrite the queries, as necessary
754  */
755  querytree_list = pg_rewrite_query(query);
756 
757  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
758 
759  return querytree_list;
760 }
bool log_parser_stats
Definition: guc.c:491
QueryEnvironment * p_queryEnv
Definition: parse_node.h:200
void ShowUsage(const char *title)
Definition: postgres.c:4559
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4552
const char * p_sourcetext
Definition: parse_node.h:176
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:769
#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:50
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 632 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().

633 {
634  List *raw_parsetree_list;
635 
636  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
637 
638  if (log_parser_stats)
639  ResetUsage();
640 
641  raw_parsetree_list = raw_parser(query_string);
642 
643  if (log_parser_stats)
644  ShowUsage("PARSER STATISTICS");
645 
646 #ifdef COPY_PARSE_PLAN_TREES
647  /* Optional debugging check: pass raw parsetrees through copyObject() */
648  {
649  List *new_list = copyObject(raw_parsetree_list);
650 
651  /* This checks both copyObject() and the equal() routines... */
652  if (!equal(new_list, raw_parsetree_list))
653  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
654  else
655  raw_parsetree_list = new_list;
656  }
657 #endif
658 
659  /*
660  * Currently, outfuncs/readfuncs support is missing for many raw parse
661  * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
662  * here.
663  */
664 
665  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
666 
667  return raw_parsetree_list;
668 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:491
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3008
void ShowUsage(const char *title)
Definition: postgres.c:4559
void ResetUsage(void)
Definition: postgres.c:4552
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:226
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:87

◆ pg_plan_queries()

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

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

947 {
948  List *stmt_list = NIL;
949  ListCell *query_list;
950 
951  foreach(query_list, querytrees)
952  {
953  Query *query = lfirst_node(Query, query_list);
954  PlannedStmt *stmt;
955 
956  if (query->commandType == CMD_UTILITY)
957  {
958  /* Utility commands require no planning. */
959  stmt = makeNode(PlannedStmt);
960  stmt->commandType = CMD_UTILITY;
961  stmt->canSetTag = query->canSetTag;
962  stmt->utilityStmt = query->utilityStmt;
963  stmt->stmt_location = query->stmt_location;
964  stmt->stmt_len = query->stmt_len;
965  }
966  else
967  {
968  stmt = pg_plan_query(query, cursorOptions, boundParams);
969  }
970 
971  stmt_list = lappend(stmt_list, stmt);
972  }
973 
974  return stmt_list;
975 }
#define NIL
Definition: pg_list.h:65
int stmt_location
Definition: parsenodes.h:180
Node * utilityStmt
Definition: parsenodes.h:120
int stmt_len
Definition: plannodes.h:94
#define lfirst_node(type, lc)
Definition: pg_list.h:193
int stmt_location
Definition: plannodes.h:93
Node * utilityStmt
Definition: plannodes.h:90
List * lappend(List *list, void *datum)
Definition: list.c:322
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:573
bool canSetTag
Definition: parsenodes.h:118
Definition: pg_list.h:50
int stmt_len
Definition: parsenodes.h:181
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:861

◆ pg_plan_query()

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

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

862 {
863  PlannedStmt *plan;
864 
865  /* Utility commands have no plans. */
866  if (querytree->commandType == CMD_UTILITY)
867  return NULL;
868 
869  /* Planner must have a snapshot in case it calls user-defined functions. */
871 
872  TRACE_POSTGRESQL_QUERY_PLAN_START();
873 
874  if (log_planner_stats)
875  ResetUsage();
876 
877  /* call the optimizer */
878  plan = planner(querytree, cursorOptions, boundParams);
879 
880  if (log_planner_stats)
881  ShowUsage("PLANNER STATISTICS");
882 
883 #ifdef COPY_PARSE_PLAN_TREES
884  /* Optional debugging check: pass plan tree through copyObject() */
885  {
886  PlannedStmt *new_plan = copyObject(plan);
887 
888  /*
889  * equal() currently does not have routines to compare Plan nodes, so
890  * don't try to test equality here. Perhaps fix someday?
891  */
892 #ifdef NOT_USED
893  /* This checks both copyObject() and the equal() routines... */
894  if (!equal(new_plan, plan))
895  elog(WARNING, "copyObject() failed to produce an equal plan tree");
896  else
897 #endif
898  plan = new_plan;
899  }
900 #endif
901 
902 #ifdef WRITE_READ_PARSE_PLAN_TREES
903  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
904  {
905  char *str;
906  PlannedStmt *new_plan;
907 
908  str = nodeToString(plan);
909  new_plan = stringToNodeWithLocations(str);
910  pfree(str);
911 
912  /*
913  * equal() currently does not have routines to compare Plan nodes, so
914  * don't try to test equality here. Perhaps fix someday?
915  */
916 #ifdef NOT_USED
917  /* This checks both outfuncs/readfuncs and the equal() routines... */
918  if (!equal(new_plan, plan))
919  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
920  else
921 #endif
922  plan = new_plan;
923  }
924 #endif
925 
926  /*
927  * Print plan if debugging.
928  */
929  if (Debug_print_plan)
930  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
931 
932  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
933 
934  return plan;
935 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3008
void ShowUsage(const char *title)
Definition: postgres.c:4559
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:268
void ResetUsage(void)
Definition: postgres.c:4552
bool Debug_print_plan
Definition: guc.c:486
void pfree(void *pointer)
Definition: mcxt.c:1056
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:853
#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:489
char * nodeToString(const void *obj)
Definition: outfuncs.c:4316
#define copyObject(obj)
Definition: nodes.h:641
bool log_planner_stats
Definition: guc.c:492

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

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

770 {
771  List *querytree_list;
772 
773  if (Debug_print_parse)
774  elog_node_display(LOG, "parse tree", query,
776 
777  if (log_parser_stats)
778  ResetUsage();
779 
780  if (query->commandType == CMD_UTILITY)
781  {
782  /* don't rewrite utilities, just dump 'em into result list */
783  querytree_list = list_make1(query);
784  }
785  else
786  {
787  /* rewrite regular queries */
788  querytree_list = QueryRewrite(query);
789  }
790 
791  if (log_parser_stats)
792  ShowUsage("REWRITER STATISTICS");
793 
794 #ifdef COPY_PARSE_PLAN_TREES
795  /* Optional debugging check: pass querytree through copyObject() */
796  {
797  List *new_list;
798 
799  new_list = copyObject(querytree_list);
800  /* This checks both copyObject() and the equal() routines... */
801  if (!equal(new_list, querytree_list))
802  elog(WARNING, "copyObject() failed to produce equal parse tree");
803  else
804  querytree_list = new_list;
805  }
806 #endif
807 
808 #ifdef WRITE_READ_PARSE_PLAN_TREES
809  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
810  {
811  List *new_list = NIL;
812  ListCell *lc;
813 
814  /*
815  * We currently lack outfuncs/readfuncs support for most utility
816  * statement types, so only attempt to write/read non-utility queries.
817  */
818  foreach(lc, querytree_list)
819  {
820  Query *query = castNode(Query, lfirst(lc));
821 
822  if (query->commandType != CMD_UTILITY)
823  {
824  char *str = nodeToString(query);
825  Query *new_query = stringToNodeWithLocations(str);
826 
827  /*
828  * queryId is not saved in stored rules, but we must preserve
829  * it here to avoid breaking pg_stat_statements.
830  */
831  new_query->queryId = query->queryId;
832 
833  new_list = lappend(new_list, new_query);
834  pfree(str);
835  }
836  else
837  new_list = lappend(new_list, query);
838  }
839 
840  /* This checks both outfuncs/readfuncs and the equal() routines... */
841  if (!equal(new_list, querytree_list))
842  elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
843  else
844  querytree_list = new_list;
845  }
846 #endif
847 
849  elog_node_display(LOG, "rewritten parse tree", querytree_list,
851 
852  return querytree_list;
853 }
#define NIL
Definition: pg_list.h:65
List * QueryRewrite(Query *parsetree)
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool log_parser_stats
Definition: guc.c:491
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3008
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
void ShowUsage(const char *title)
Definition: postgres.c:4559
#define LOG
Definition: elog.h:26
#define list_make1(x1)
Definition: pg_list.h:227
void ResetUsage(void)
Definition: postgres.c:4552
void pfree(void *pointer)
Definition: mcxt.c:1056
bool Debug_print_parse
Definition: guc.c:487
List * lappend(List *list, void *datum)
Definition: list.c:322
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:190
#define elog(elevel,...)
Definition: elog.h:226
bool Debug_pretty_print
Definition: guc.c:489
char * nodeToString(const void *obj)
Definition: outfuncs.c:4316
bool Debug_print_rewritten
Definition: guc.c:488
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:87

◆ PostgresMain()

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

Definition at line 3727 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(), printf, 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().

3730 {
3731  int firstchar;
3732  StringInfoData input_message;
3733  sigjmp_buf local_sigjmp_buf;
3734  volatile bool send_ready_for_query = true;
3735  bool disable_idle_in_transaction_timeout = false;
3736 
3737  /* Initialize startup process environment if necessary. */
3738  if (!IsUnderPostmaster)
3739  InitStandaloneProcess(argv[0]);
3740 
3742 
3743  /*
3744  * Set default values for command-line options.
3745  */
3746  if (!IsUnderPostmaster)
3748 
3749  /*
3750  * Parse command-line options.
3751  */
3753 
3754  /* Must have gotten a database name, or have a default (the username) */
3755  if (dbname == NULL)
3756  {
3757  dbname = username;
3758  if (dbname == NULL)
3759  ereport(FATAL,
3760  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3761  errmsg("%s: no database nor user name specified",
3762  progname)));
3763  }
3764 
3765  /* Acquire configuration parameters, unless inherited from postmaster */
3766  if (!IsUnderPostmaster)
3767  {
3769  proc_exit(1);
3770  }
3771 
3772  /*
3773  * Set up signal handlers and masks.
3774  *
3775  * Note that postmaster blocked all signals before forking child process,
3776  * so there is no race condition whereby we might receive a signal before
3777  * we have set up the handler.
3778  *
3779  * Also note: it's best not to use any signals that are SIG_IGNored in the
3780  * postmaster. If such a signal arrives before we are able to change the
3781  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3782  * handler in the postmaster to reserve the signal. (Of course, this isn't
3783  * an issue for signals that are locally generated, such as SIGALRM and
3784  * SIGPIPE.)
3785  */
3786  if (am_walsender)
3787  WalSndSignals();
3788  else
3789  {
3790  pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3791  * file */
3792  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3793  pqsignal(SIGTERM, die); /* cancel current query and exit */
3794 
3795  /*
3796  * In a standalone backend, SIGQUIT can be generated from the keyboard
3797  * easily, while SIGTERM cannot, so we make both signals do die()
3798  * rather than quickdie().
3799  */
3800  if (IsUnderPostmaster)
3801  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3802  else
3803  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3804  InitializeTimeouts(); /* establishes SIGALRM handler */
3805 
3806  /*
3807  * Ignore failure to write to frontend. Note: if frontend closes
3808  * connection, we will notice it and exit cleanly when control next
3809  * returns to outer loop. This seems safer than forcing exit in the
3810  * midst of output during who-knows-what operation...
3811  */
3816 
3817  /*
3818  * Reset some signals that are accepted by postmaster but not by
3819  * backend
3820  */
3821  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3822  * platforms */
3823  }
3824 
3825  pqinitmask();
3826 
3827  if (IsUnderPostmaster)
3828  {
3829  /* We allow SIGQUIT (quickdie) at all times */
3830  sigdelset(&BlockSig, SIGQUIT);
3831  }
3832 
3833  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3834 
3835  if (!IsUnderPostmaster)
3836  {
3837  /*
3838  * Validate we have been given a reasonable-looking DataDir (if under
3839  * postmaster, assume postmaster did this already).
3840  */
3841  checkDataDir();
3842 
3843  /* Change into DataDir (if under postmaster, was done already) */
3844  ChangeToDataDir();
3845 
3846  /*
3847  * Create lockfile for data directory.
3848  */
3849  CreateDataDirLockFile(false);
3850 
3851  /* read control file (error checking and contains config ) */
3852  LocalProcessControlFile(false);
3853 
3854  /* Initialize MaxBackends (if under postmaster, was done already) */
3856  }
3857 
3858  /* Early initialization */
3859  BaseInit();
3860 
3861  /*
3862  * Create a per-backend PGPROC struct in shared memory, except in the
3863  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3864  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3865  * had to do some stuff with LWLocks).
3866  */
3867 #ifdef EXEC_BACKEND
3868  if (!IsUnderPostmaster)
3869  InitProcess();
3870 #else
3871  InitProcess();
3872 #endif
3873 
3874  /* We need to allow SIGINT, etc during the initial transaction */
3876 
3877  /*
3878  * General initialization.
3879  *
3880  * NOTE: if you are tempted to add code in this vicinity, consider putting
3881  * it inside InitPostgres() instead. In particular, anything that
3882  * involves database access should be there, not here.
3883  */
3885 
3886  /*
3887  * If the PostmasterContext is still around, recycle the space; we don't
3888  * need it anymore after InitPostgres completes. Note this does not trash
3889  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3890  * ... else we'd need to copy the Port data first. Also, subsidiary data
3891  * such as the username isn't lost either; see ProcessStartupPacket().
3892  */
3893  if (PostmasterContext)
3894  {
3896  PostmasterContext = NULL;
3897  }
3898 
3900 
3901  /*
3902  * Now all GUC states are fully set up. Report them to client if
3903  * appropriate.
3904  */
3906 
3907  /*
3908  * Also set up handler to log session end; we have to wait till now to be
3909  * sure Log_disconnections has its final value.
3910  */
3913 
3914  /* Perform initialization specific to a WAL sender process. */
3915  if (am_walsender)
3916  InitWalSender();
3917 
3918  /*
3919  * process any libraries that should be preloaded at backend start (this
3920  * likewise can't be done until GUC settings are complete)
3921  */
3923 
3924  /*
3925  * Send this backend's cancellation info to the frontend.
3926  */
3928  {
3930 
3931  pq_beginmessage(&buf, 'K');
3932  pq_sendint32(&buf, (int32) MyProcPid);
3933  pq_sendint32(&buf, (int32) MyCancelKey);
3934  pq_endmessage(&buf);
3935  /* Need not flush since ReadyForQuery will do it. */
3936  }
3937 
3938  /* Welcome banner for standalone case */
3940  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3941 
3942  /*
3943  * Create the memory context we will use in the main loop.
3944  *
3945  * MessageContext is reset once per iteration of the main loop, ie, upon
3946  * completion of processing of each command message from the client.
3947  */
3949  "MessageContext",
3951 
3952  /*
3953  * Create memory context and buffer used for RowDescription messages. As
3954  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3955  * frequently executed for ever single statement, we don't want to
3956  * allocate a separate buffer every time.
3957  */
3959  "RowDescriptionContext",
3964 
3965  /*
3966  * Remember stand-alone backend startup time
3967  */
3968  if (!IsUnderPostmaster)
3970 
3971  /*
3972  * POSTGRES main processing loop begins here
3973  *
3974  * If an exception is encountered, processing resumes here so we abort the
3975  * current transaction and start a new one.
3976  *
3977  * You might wonder why this isn't coded as an infinite loop around a
3978  * PG_TRY construct. The reason is that this is the bottom of the
3979  * exception stack, and so with PG_TRY there would be no exception handler
3980  * in force at all during the CATCH part. By leaving the outermost setjmp
3981  * always active, we have at least some chance of recovering from an error
3982  * during error recovery. (If we get into an infinite loop thereby, it
3983  * will soon be stopped by overflow of elog.c's internal state stack.)
3984  *
3985  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3986  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3987  * is essential in case we longjmp'd out of a signal handler on a platform
3988  * where that leaves the signal blocked. It's not redundant with the
3989  * unblock in AbortTransaction() because the latter is only called if we
3990  * were inside a transaction.
3991  */
3992 
3993  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3994  {
3995  /*
3996  * NOTE: if you are tempted to add more code in this if-block,
3997  * consider the high probability that it should be in
3998  * AbortTransaction() instead. The only stuff done directly here
3999  * should be stuff that is guaranteed to apply *only* for outer-level
4000  * error recovery, such as adjusting the FE/BE protocol status.
4001  */
4002 
4003  /* Since not using PG_TRY, must reset error stack by hand */
4004  error_context_stack = NULL;
4005 
4006  /* Prevent interrupts while cleaning up */
4007  HOLD_INTERRUPTS();
4008 
4009  /*
4010  * Forget any pending QueryCancel request, since we're returning to
4011  * the idle loop anyway, and cancel any active timeout requests. (In
4012  * future we might want to allow some timeout requests to survive, but
4013  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4014  * we got here because of a query cancel interrupting the SIGALRM
4015  * interrupt handler.) Note in particular that we must clear the
4016  * statement and lock timeout indicators, to prevent any future plain
4017  * query cancels from being misreported as timeouts in case we're
4018  * forgetting a timeout cancel.
4019  */
4020  disable_all_timeouts(false);
4021  QueryCancelPending = false; /* second to avoid race condition */
4022  stmt_timeout_active = false;
4023 
4024  /* Not reading from the client anymore. */
4025  DoingCommandRead = false;
4026 
4027  /* Make sure libpq is in a good state */
4028  pq_comm_reset();
4029 
4030  /* Report the error to the client and/or server log */
4031  EmitErrorReport();
4032 
4033  /*
4034  * Make sure debug_query_string gets reset before we possibly clobber
4035  * the storage it points at.
4036  */
4037  debug_query_string = NULL;
4038 
4039  /*
4040  * Abort the current transaction in order to recover.
4041  */
4043 
4044  if (am_walsender)
4046 
4048  SPICleanup();
4049 
4050  /*
4051  * We can't release replication slots inside AbortTransaction() as we
4052  * need to be able to start and abort transactions while having a slot
4053  * acquired. But we never need to hold them across top level errors,
4054  * so releasing here is fine. There's another cleanup in ProcKill()
4055  * ensuring we'll correctly cleanup on FATAL errors as well.
4056  */
4057  if (MyReplicationSlot != NULL)
4059 
4060  /* We also want to cleanup temporary slots on error. */
4062 
4064 
4065  /*
4066  * Now return to normal top-level context and clear ErrorContext for
4067  * next time.
4068  */
4070  FlushErrorState();
4071 
4072  /*
4073  * If we were handling an extended-query-protocol message, initiate
4074  * skip till next Sync. This also causes us not to issue
4075  * ReadyForQuery (until we get Sync).
4076  */
4078  ignore_till_sync = true;
4079 
4080  /* We don't have a transaction command open anymore */
4081  xact_started = false;
4082 
4083  /*
4084  * If an error occurred while we were reading a message from the
4085  * client, we have potentially lost track of where the previous
4086  * message ends and the next one begins. Even though we have
4087  * otherwise recovered from the error, we cannot safely read any more
4088  * messages from the client, so there isn't much we can do with the
4089  * connection anymore.
4090  */
4091  if (pq_is_reading_msg())
4092  ereport(FATAL,
4093  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4094  errmsg("terminating connection because protocol synchronization was lost")));
4095 
4096  /* Now we can allow interrupts again */
4098  }
4099 
4100  /* We can now handle ereport(ERROR) */
4101  PG_exception_stack = &local_sigjmp_buf;
4102 
4103  if (!ignore_till_sync)
4104  send_ready_for_query = true; /* initially, or after error */
4105 
4106  /*
4107  * Non-error queries loop here.
4108  */
4109 
4110  for (;;)
4111  {
4112  /*
4113  * At top of loop, reset extended-query-message flag, so that any
4114  * errors encountered in "idle" state don't provoke skip.
4115  */
4117 
4118  /*
4119  * Release storage left over from prior query cycle, and create a new
4120  * query input buffer in the cleared MessageContext.
4121  */
4124 
4125  initStringInfo(&input_message);
4126 
4127  /*
4128  * Also consider releasing our catalog snapshot if any, so that it's
4129  * not preventing advance of global xmin while we wait for the client.
4130  */
4132 
4133  /*
4134  * (1) If we've reached idle state, tell the frontend we're ready for
4135  * a new query.
4136  *
4137  * Note: this includes fflush()'ing the last of the prior output.
4138  *
4139  * This is also a good time to send collected statistics to the
4140  * collector, and to update the PS stats display. We avoid doing
4141  * those every time through the message loop because it'd slow down
4142  * processing of batched messages, and because we don't want to report
4143  * uncommitted updates (that confuses autovacuum). The notification
4144  * processor wants a call too, if we are not in a transaction block.
4145  */
4146  if (send_ready_for_query)
4147  {
4149  {
4150  set_ps_display("idle in transaction (aborted)", false);
4152 
4153  /* Start the idle-in-transaction timer */
4155  {
4156  disable_idle_in_transaction_timeout = true;
4159  }
4160  }
4162  {
4163  set_ps_display("idle in transaction", false);
4165 
4166  /* Start the idle-in-transaction timer */
4168  {
4169  disable_idle_in_transaction_timeout = true;
4172  }
4173  }
4174  else
4175  {
4177  pgstat_report_stat(false);
4178 
4179  set_ps_display("idle", false);
4181  }
4182 
4184  send_ready_for_query = false;
4185  }
4186 
4187  /*
4188  * (2) Allow asynchronous signals to be executed immediately if they
4189  * come in while we are waiting for client input. (This must be
4190  * conditional since we don't want, say, reads on behalf of COPY FROM
4191  * STDIN doing the same thing.)
4192  */
4193  DoingCommandRead = true;
4194 
4195  /*
4196  * (3) read a command (loop blocks here)
4197  */
4198  firstchar = ReadCommand(&input_message);
4199 
4200  /*
4201  * (4) disable async signal conditions again.
4202  *
4203  * Query cancel is supposed to be a no-op when there is no query in
4204  * progress, so if a query cancel arrived while we were idle, just
4205  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4206  * it's called when DoingCommandRead is set, so check for interrupts
4207  * before resetting DoingCommandRead.
4208  */
4210  DoingCommandRead = false;
4211 
4212  /*
4213  * (5) turn off the idle-in-transaction timeout
4214  */
4215  if (disable_idle_in_transaction_timeout)
4216  {
4218  disable_idle_in_transaction_timeout = false;
4219  }
4220 
4221  /*
4222  * (6) check for any other interesting events that happened while we
4223  * slept.
4224  */
4225  if (ConfigReloadPending)
4226  {
4227  ConfigReloadPending = false;
4229  }
4230 
4231  /*
4232  * (7) process the command. But ignore it if we're skipping till
4233  * Sync.
4234  */
4235  if (ignore_till_sync && firstchar != EOF)
4236  continue;
4237 
4238  switch (firstchar)
4239  {
4240  case 'Q': /* simple query */
4241  {
4242  const char *query_string;
4243 
4244  /* Set statement_timestamp() */
4246 
4247  query_string = pq_getmsgstring(&input_message);
4248  pq_getmsgend(&input_message);
4249 
4250  if (am_walsender)
4251  {
4252  if (!exec_replication_command(query_string))
4253  exec_simple_query(query_string);
4254  }
4255  else
4256  exec_simple_query(query_string);
4257 
4258  send_ready_for_query = true;
4259  }
4260  break;
4261 
4262  case 'P': /* parse */
4263  {
4264  const char *stmt_name;
4265  const char *query_string;
4266  int numParams;
4267  Oid *paramTypes = NULL;
4268 
4269  forbidden_in_wal_sender(firstchar);
4270 
4271  /* Set statement_timestamp() */
4273 
4274  stmt_name = pq_getmsgstring(&input_message);
4275  query_string = pq_getmsgstring(&input_message);
4276  numParams = pq_getmsgint(&input_message, 2);
4277  if (numParams > 0)
4278  {
4279  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4280  for (int i = 0; i < numParams; i++)
4281  paramTypes[i] = pq_getmsgint(&input_message, 4);
4282  }
4283  pq_getmsgend(&input_message);
4284 
4285  exec_parse_message(query_string, stmt_name,
4286  paramTypes, numParams);
4287  }
4288  break;
4289 
4290  case 'B': /* bind */
4291  forbidden_in_wal_sender(firstchar);
4292 
4293  /* Set statement_timestamp() */
4295 
4296  /*
4297  * this message is complex enough that it seems best to put
4298  * the field extraction out-of-line
4299  */
4300  exec_bind_message(&input_message);
4301  break;
4302 
4303  case 'E': /* execute */
4304  {
4305  const char *portal_name;
4306  int max_rows;
4307 
4308  forbidden_in_wal_sender(firstchar);
4309 
4310  /* Set statement_timestamp() */
4312 
4313  portal_name = pq_getmsgstring(&input_message);
4314  max_rows = pq_getmsgint(&input_message, 4);
4315  pq_getmsgend(&input_message);
4316 
4317  exec_execute_message(portal_name, max_rows);
4318  }
4319  break;
4320 
4321  case 'F': /* fastpath function call */
4322  forbidden_in_wal_sender(firstchar);
4323 
4324  /* Set statement_timestamp() */
4326 
4327  /* Report query to various monitoring facilities. */
4329  set_ps_display("<FASTPATH>", false);
4330 
4331  /* start an xact for this function invocation */
4333 
4334  /*
4335  * Note: we may at this point be inside an aborted
4336  * transaction. We can't throw error for that until we've
4337  * finished reading the function-call message, so
4338  * HandleFunctionRequest() must check for it after doing so.
4339  * Be careful not to do anything that assumes we're inside a
4340  * valid transaction here.
4341  */
4342 
4343  /* switch back to message context */
4345 
4346  HandleFunctionRequest(&input_message);
4347 
4348  /* commit the function-invocation transaction */
4350 
4351  send_ready_for_query = true;
4352  break;
4353 
4354  case 'C': /* close */
4355  {
4356  int close_type;
4357  const char *close_target;
4358 
4359  forbidden_in_wal_sender(firstchar);
4360 
4361  close_type = pq_getmsgbyte(&input_message);
4362  close_target = pq_getmsgstring(&input_message);
4363  pq_getmsgend(&input_message);
4364 
4365  switch (close_type)
4366  {
4367  case 'S':
4368  if (close_target[0] != '\0')
4369  DropPreparedStatement(close_target, false);
4370  else
4371  {
4372  /* special-case the unnamed statement */
4374  }
4375  break;
4376  case 'P':
4377  {
4378  Portal portal;
4379 
4380  portal = GetPortalByName(close_target);
4381  if (PortalIsValid(portal))
4382  PortalDrop(portal, false);
4383  }
4384  break;
4385  default:
4386  ereport(ERROR,
4387  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4388  errmsg("invalid CLOSE message subtype %d",
4389  close_type)));
4390  break;
4391  }
4392 
4394  pq_putemptymessage('3'); /* CloseComplete */
4395  }
4396  break;
4397 
4398  case 'D': /* describe */
4399  {
4400  int describe_type;
4401  const char *describe_target;
4402 
4403  forbidden_in_wal_sender(firstchar);
4404 
4405  /* Set statement_timestamp() (needed for xact) */
4407 
4408  describe_type = pq_getmsgbyte(&input_message);
4409  describe_target = pq_getmsgstring(&input_message);
4410  pq_getmsgend(&input_message);
4411 
4412  switch (describe_type)
4413  {
4414  case 'S':
4415  exec_describe_statement_message(describe_target);
4416  break;
4417  case 'P':
4418  exec_describe_portal_message(describe_target);
4419  break;
4420  default:
4421  ereport(ERROR,
4422  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4423  errmsg("invalid DESCRIBE message subtype %d",
4424  describe_type)));
4425  break;
4426  }
4427  }
4428  break;
4429 
4430  case 'H': /* flush */
4431  pq_getmsgend(&input_message);
4433  pq_flush();
4434  break;
4435 
4436  case 'S': /* sync */
4437  pq_getmsgend(&input_message);
4439  send_ready_for_query = true;
4440  break;
4441 
4442  /*
4443  * 'X' means that the frontend is closing down the socket. EOF
4444  * means unexpected loss of frontend connection. Either way,
4445  * perform normal shutdown.
4446  */
4447  case 'X':
4448  case EOF:
4449 
4450  /*
4451  * Reset whereToSendOutput to prevent ereport from attempting
4452  * to send any more messages to client.
4453  */
4456 
4457  /*
4458  * NOTE: if you are tempted to add more code here, DON'T!
4459  * Whatever you had in mind to do should be set up as an
4460  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4461  * it will fail to be called during other backend-shutdown
4462  * scenarios.
4463  */
4464  proc_exit(0);
4465 
4466  case 'd': /* copy data */
4467  case 'c': /* copy done */
4468  case 'f': /* copy fail */
4469 
4470  /*
4471  * Accept but ignore these messages, per protocol spec; we
4472  * probably got here because a COPY failed, and the frontend
4473  * is still sending data.
4474  */
4475  break;
4476 
4477  default:
4478  ereport(FATAL,
4479  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4480  errmsg("invalid frontend message type %d",
4481  firstchar)));
4482  }
4483  } /* end of input-reading loop */
4484 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:3159
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2518
#define SIGQUIT
Definition: win32_port.h:155
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void BeginReportingGUCOptions(void)
Definition: guc.c:6011
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:2590
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1431
#define SIGUSR1
Definition: win32_port.h:166
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
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:3121
#define SIGCHLD
Definition: win32_port.h:164
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:318
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:376
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPICleanup(void)
Definition: spi.c:349
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:4494
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:570
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4651
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:380
void BaseInit(void)
Definition: postinit.c:548
#define printf(...)
Definition: port.h:198
void checkDataDir(void)
Definition: miscinit.c:99
#define SIGPIPE
Definition: win32_port.h:159
#define SIGUSR2
Definition: win32_port.h:167
unsigned int Oid
Definition: postgres_ext.h:31
const char * progname
Definition: pg_standby.c:37
void FlushErrorState(void)
Definition: elog.c:1574
#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:2792
signed int int32
Definition: c.h:346
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1966
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4661
void jit_reset_after_error(void)
Definition: jit.c:131
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
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:1177
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1251
int IdleInTransactionSessionTimeout
Definition: proc.c:64
int32 MyCancelKey
Definition: globals.c:44
void WalSndSignals(void)
Definition: walsender.c:3009
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void InitProcess(void)
Definition: proc.c:305
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:68
bool IsUnderPostmaster
Definition: globals.c:109
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1596
Definition: dest.h:89
#define SIGHUP
Definition: win32_port.h:154
void PostgresSigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2832
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4922
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:151
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:1334
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2570
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:1596
void WalSndErrorCleanup(void)
Definition: walsender.c:297
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5339
void EmitErrorReport(void)
Definition: elog.c:1433
static StringInfoData row_description_buf
Definition: postgres.c:172
TimestampTz PgStartTime
Definition: timestamp.c:49
static char * username
Definition: initdb.c:133
#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:590
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
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:149
void ProcessCompletedNotifies(void)
Definition: async.c:1225
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:259
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:533
static bool DoingCommandRead
Definition: postgres.c:139
void InitializeMaxBackends(void)
Definition: postinit.c:526
char * dbname
Definition: streamutil.c:52
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:818
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:784
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:465
void ReadyForQuery(CommandDest dest)
Definition: dest.c:250
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2761
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2813
static void drop_unnamed_stmt(void)
Definition: postgres.c:2669
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:99
bool Log_disconnections
Definition: postgres.c:93
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3468
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:2694
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void exec_simple_query(const char *query_string)
Definition: postgres.c:984
void InitializeGUCOptions(void)
Definition: guc.c:5117
void pgstat_report_stat(bool force)
Definition: pgstat.c:813
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:570
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2423

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2832 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

2833 {
2834  int save_errno = errno;
2835 
2836  ConfigReloadPending = true;
2837  SetLatch(MyLatch);
2838 
2839  errno = save_errno;
2840 }
void SetLatch(Latch *latch)
Definition: latch.c:436
volatile sig_atomic_t ConfigReloadPending
Definition: globals.c:35
struct Latch * MyLatch
Definition: globals.c:54

◆ process_postgres_switches()

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

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

3470 {
3471  bool secure = (ctx == PGC_POSTMASTER);
3472  int errs = 0;
3473  GucSource gucsource;
3474  int flag;
3475 
3476  if (secure)
3477  {
3478  gucsource = PGC_S_ARGV; /* switches came from command line */
3479 
3480  /* Ignore the initial --single argument, if present */
3481  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3482  {
3483  argv++;
3484  argc--;
3485  }
3486  }
3487  else
3488  {
3489  gucsource = PGC_S_CLIENT; /* switches came from client */
3490  }
3491 
3492 #ifdef HAVE_INT_OPTERR
3493 
3494  /*
3495  * Turn this off because it's either printed to stderr and not the log
3496  * where we'd want it, or argv[0] is now "--single", which would make for
3497  * a weird error message. We print our own error message below.
3498  */
3499  opterr = 0;
3500 #endif
3501 
3502  /*
3503  * Parse command-line options. CAUTION: keep this in sync with
3504  * postmaster/postmaster.c (the option sets should not conflict) and with
3505  * the common help() function in main/main.c.
3506  */
3507  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3508  {
3509  switch (flag)
3510  {
3511  case 'B':
3512  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3513  break;
3514 
3515  case 'b':
3516  /* Undocumented flag used for binary upgrades */
3517  if (secure)
3518  IsBinaryUpgrade = true;
3519  break;
3520 
3521  case 'C':
3522  /* ignored for consistency with the postmaster */
3523  break;
3524 
3525  case 'D':
3526  if (secure)
3527  userDoption = strdup(optarg);
3528  break;
3529 
3530  case 'd':
3531  set_debug_options(atoi(optarg), ctx, gucsource);
3532  break;
3533 
3534  case 'E':
3535  if (secure)
3536  EchoQuery = true;
3537  break;
3538 
3539  case 'e':
3540  SetConfigOption("datestyle", "euro", ctx, gucsource);
3541  break;
3542 
3543  case 'F':
3544  SetConfigOption("fsync", "false", ctx, gucsource);
3545  break;
3546 
3547  case 'f':
3548  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3549  errs++;
3550  break;
3551 
3552  case 'h':
3553  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3554  break;
3555 
3556  case 'i':
3557  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3558  break;
3559 
3560  case 'j':
3561  if (secure)
3562  UseSemiNewlineNewline = true;
3563  break;
3564 
3565  case 'k':
3566  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3567  break;
3568 
3569  case 'l':
3570  SetConfigOption("ssl", "true", ctx, gucsource);
3571  break;
3572 
3573  case 'N':
3574  SetConfigOption("max_connections", optarg, ctx, gucsource);
3575  break;
3576 
3577  case 'n':
3578  /* ignored for consistency with postmaster */
3579  break;
3580 
3581  case 'O':
3582  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3583  break;
3584 
3585  case 'o':
3586  errs++;
3587  break;
3588 
3589  case 'P':
3590  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3591  break;
3592 
3593  case 'p':
3594  SetConfigOption("port", optarg, ctx, gucsource);
3595  break;
3596 
3597  case 'r':
3598  /* send output (stdout and stderr) to the given file */
3599  if (secure)
3601  break;
3602 
3603  case 'S':
3604  SetConfigOption("work_mem", optarg, ctx, gucsource);
3605  break;
3606 
3607  case 's':
3608  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3609  break;
3610 
3611  case 'T':
3612  /* ignored for consistency with the postmaster */
3613  break;
3614 
3615  case 't':
3616  {
3617  const char *tmp = get_stats_option_name(optarg);
3618 
3619  if (tmp)
3620  SetConfigOption(tmp, "true", ctx, gucsource);
3621  else
3622  errs++;
3623  break;
3624  }
3625 
3626  case 'v':
3627 
3628  /*
3629  * -v is no longer used in normal operation, since
3630  * FrontendProtocol is already set before we get here. We keep
3631  * the switch only for possible use in standalone operation,
3632  * in case we ever support using normal FE/BE protocol with a
3633  * standalone backend.
3634  */
3635  if (secure)
3637  break;
3638 
3639  case 'W':
3640  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3641  break;
3642 
3643  case 'c':
3644  case '-':
3645  {
3646  char *name,
3647  *value;
3648 
3649  ParseLongOption(optarg, &name, &value);
3650  if (!value)
3651  {
3652  if (flag == '-')
3653  ereport(ERROR,
3654  (errcode(ERRCODE_SYNTAX_ERROR),
3655  errmsg("--%s requires a value",
3656  optarg)));
3657  else
3658  ereport(ERROR,
3659  (errcode(ERRCODE_SYNTAX_ERROR),
3660  errmsg("-c %s requires a value",
3661  optarg)));
3662  }
3663  SetConfigOption(name, value, ctx, gucsource);
3664  free(name);
3665  if (value)
3666  free(value);
3667  break;
3668  }
3669 
3670  default:
3671  errs++;
3672  break;
3673  }
3674 
3675  if (errs)
3676  break;
3677  }
3678 
3679  /*
3680  * Optional database name should be there only if *dbname is NULL.
3681  */
3682  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3683  *dbname = strdup(argv[optind++]);
3684 
3685  if (errs || argc != optind)
3686  {
3687  if (errs)
3688  optind--; /* complain about the previous argument */
3689 
3690  /* spell the error message a bit differently depending on context */
3691  if (IsUnderPostmaster)
3692  ereport(FATAL,
3693  (errcode(ERRCODE_SYNTAX_ERROR),
3694  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3695  errhint("Try \"%s --help\" for more information.", progname)));
3696  else
3697  ereport(FATAL,
3698  (errcode(ERRCODE_SYNTAX_ERROR),
3699  errmsg("%s: invalid command-line argument: %s",
3700  progname, argv[optind]),
3701  errhint("Try \"%s --help\" for more information.", progname)));
3702  }
3703 
3704  /*
3705  * Reset getopt(3) library so that it will work correctly in subprocesses
3706  * or when this function is called a second time with another array.
3707  */
3708  optind = 1;
3709 #ifdef HAVE_INT_OPTRESET
3710  optreset = 1; /* some systems need this too */
3711 #endif
3712 }
int errhint(const char *fmt,...)
Definition: elog.c:974
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:10307
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3386
static struct @145 value
int errcode(int sqlerrcode)
Definition: elog.c:570
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3428
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3357
const char * progname
Definition: pg_standby.c:37
bool IsBinaryUpgrade
Definition: globals.c:110
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
GucSource
Definition: guc.h:105
int optind
Definition: getopt.c:50
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
char OutputFileName[MAXPGPATH]
Definition: globals.c:70
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7487
bool IsUnderPostmaster
Definition: globals.c:109
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:49
#define ereport(elevel, rest)
Definition: elog.h:141
uint32 ProtocolVersion
Definition: pqcomm.h:113
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * dbname
Definition: streamutil.c:52
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:784
char * optarg
Definition: getopt.c:52
ProtocolVersion FrontendProtocol
Definition: globals.c:28

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 530 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

531 {
532  int save_errno = errno;
533 
534  if (DoingCommandRead)
535  {
536  /* Check for general interrupts that arrived before/while reading */
538 
539  /* Process sinval catchup interrupts, if any */
542 
543  /* Process notify interrupts, if any */
546  }
547  else if (ProcDiePending)
548  {
549  /*
550  * We're dying. If there is no data available to read, then it's safe
551  * (and sane) to handle that now. If we haven't tried to read yet,
552  * make sure the process latch is set, so that if there is no data
553  * then we'll come back here and die. If we're done reading, also
554  * make sure the process latch is set, as we might've undesirably
555  * cleared it while reading.
556  */
557  if (blocked)
559  else
560  SetLatch(MyLatch);
561  }
562 
563  errno = save_errno;
564 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessNotifyInterrupt(void)
Definition: async.c:1893
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
static bool DoingCommandRead
Definition: postgres.c:139
struct Latch * MyLatch
Definition: globals.c:54
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:415
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 576 of file postgres.c.

References CHECK_FOR_INTERRUPTS, CritSectionCount, DestNone, DestRemote, InterruptHoldoffCount, MyLatch, ProcDiePending, SetLatch(), and whereToSendOutput.

Referenced by secure_write().

577 {
578  int save_errno = errno;
579 
580  if (ProcDiePending)
581  {
582  /*
583  * We're dying. If it's not possible to write, then we should handle
584  * that immediately, else a stuck client could indefinitely delay our
585  * response to the signal. If we haven't tried to write yet, make
586  * sure the process latch is set, so that if the write would block
587  * then we'll come back here and die. If we're done writing, also
588  * make sure the process latch is set, as we might've undesirably
589  * cleared it while writing.
590  */
591  if (blocked)
592  {
593  /*
594  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
595  * do anything.
596  */
597  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
598  {
599  /*
600  * We don't want to send the client the error message, as a)
601  * that would possibly block again, and b) it would likely
602  * lead to loss of protocol sync because we may have already
603  * sent a partial protocol message.
604  */
607 
609  }
610  }
611  else
612  SetLatch(MyLatch);
613  }
614 
615  errno = save_errno;
616 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:36
void SetLatch(Latch *latch)
Definition: latch.c:436
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:38
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

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

2973 {
2974  /* OK to accept any interrupts now? */
2975  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2976  return;
2977  InterruptPending = false;
2978 
2979  if (ProcDiePending)
2980  {
2981  ProcDiePending = false;
2982  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2983  LockErrorCleanup();
2984  /* As in quickdie, don't risk sending to client during auth */
2988  ereport(FATAL,
2989  (errcode(ERRCODE_QUERY_CANCELED),
2990  errmsg("canceling authentication due to timeout")));
2991  else if (IsAutoVacuumWorkerProcess())
2992  ereport(FATAL,
2993  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2994  errmsg("terminating autovacuum process due to administrator command")));
2995  else if (IsLogicalWorker())
2996  ereport(FATAL,
2997  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2998  errmsg("terminating logical replication worker due to administrator command")));
2999  else if (IsLogicalLauncher())
3000  {
3001  ereport(DEBUG1,
3002  (errmsg("logical replication launcher shutting down")));
3003 
3004  /*
3005  * The logical replication launcher can be stopped at any time.
3006  * Use exit status 1 so the background worker is restarted.
3007  */
3008  proc_exit(1);
3009  }
3011  {
3013  ereport(FATAL,
3014  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3015  errmsg("terminating connection due to conflict with recovery"),
3017  }
3018  else if (RecoveryConflictPending)
3019  {
3020  /* Currently there is only one non-retryable recovery conflict */
3023  ereport(FATAL,
3024  (errcode(ERRCODE_DATABASE_DROPPED),
3025  errmsg("terminating connection due to conflict with recovery"),
3027  }
3028  else
3029  ereport(FATAL,
3030  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3031  errmsg("terminating connection due to administrator command")));
3032  }
3034  {
3035  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3036  LockErrorCleanup();
3037  /* don't send to client, we already know the connection to be dead. */
3039  ereport(FATAL,
3040  (errcode(ERRCODE_CONNECTION_FAILURE),
3041  errmsg("connection to client lost")));
3042  }
3043 
3044  /*
3045  * If a recovery conflict happens while we are waiting for input from the
3046  * client, the client is presumably just sitting idle in a transaction,
3047  * preventing recovery from making progress. Terminate the connection to
3048  * dislodge it.
3049  */
3051  {
3052  QueryCancelPending = false; /* this trumps QueryCancel */
3053  RecoveryConflictPending = false;
3054  LockErrorCleanup();
3056  ereport(FATAL,
3057  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3058  errmsg("terminating connection due to conflict with recovery"),
3060  errhint("In a moment you should be able to reconnect to the"
3061  " database and repeat your command.")));
3062  }
3063 
3064  /*
3065  * Don't allow query cancel interrupts while reading input from the
3066  * client, because we might lose sync in the FE/BE protocol. (Die
3067  * interrupts are OK, because we won't read any further messages from the
3068  * client in that case.)
3069  */
3071  {
3072  /*
3073  * Re-arm InterruptPending so that we process the cancel request as
3074  * soon as we're done reading the message.
3075  */
3076  InterruptPending = true;
3077  }
3078  else if (QueryCancelPending)
3079  {
3080  bool lock_timeout_occurred;
3081  bool stmt_timeout_occurred;
3082 
3083  QueryCancelPending = false;
3084 
3085  /*
3086  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3087  * need to clear both, so always fetch both.
3088  */
3089  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3090  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3091 
3092  /*
3093  * If both were set, we want to report whichever timeout completed
3094  * earlier; this ensures consistent behavior if the machine is slow
3095  * enough that the second timeout triggers before we get here. A tie
3096  * is arbitrarily broken in favor of reporting a lock timeout.
3097  */
3098  if (lock_timeout_occurred && stmt_timeout_occurred &&
3100  lock_timeout_occurred = false; /* report stmt timeout */
3101 
3102  if (lock_timeout_occurred)
3103  {
3104  LockErrorCleanup();
3105  ereport(ERROR,
3106  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3107  errmsg("canceling statement due to lock timeout")));
3108  }
3109  if (stmt_timeout_occurred)
3110  {
3111  LockErrorCleanup();
3112  ereport(ERROR,
3113  (errcode(ERRCODE_QUERY_CANCELED),
3114  errmsg("canceling statement due to statement timeout")));
3115  }
3117  {
3118  LockErrorCleanup();
3119  ereport(ERROR,
3120  (errcode(ERRCODE_QUERY_CANCELED),
3121  errmsg("canceling autovacuum task")));
3122  }
3124  {
3125  RecoveryConflictPending = false;
3126  LockErrorCleanup();
3128  ereport(ERROR,
3129  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3130  errmsg("canceling statement due to conflict with recovery"),
3132  }
3133 
3134  /*
3135  * If we are reading a command from the client, just ignore the cancel
3136  * request --- sending an extra error message won't accomplish
3137  * anything. Otherwise, go ahead and throw the error.
3138  */
3139  if (!DoingCommandRead)
3140  {
3141  LockErrorCleanup();
3142  ereport(ERROR,
3143  (errcode(ERRCODE_QUERY_CANCELED),
3144  errmsg("canceling statement due to user request")));
3145  }
3146  }
3147 
3149  {
3150  /* Has the timeout setting changed since last we looked? */
3152  ereport(FATAL,
3153  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3154  errmsg("terminating connection due to idle-in-transaction timeout")));
3155  else
3157 
3158  }
3159 
3162 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:36
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:667
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:974
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1491
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:37
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:570
bool IsLogicalWorker(void)
Definition: worker.c:1743
volatile bool ParallelMessagePending
Definition: parallel.c:113
bool ClientAuthInProgress
Definition: postmaster.c:352
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:64
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:969
Definition: dest.h:88
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:33
volatile uint32 CritSectionCount
Definition: globals.c:38
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:34
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3278
#define ereport(elevel, rest)
Definition: elog.h:141
void LockErrorCleanup(void)
Definition: proc.c:712
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:2387
#define Assert(condition)
Definition: c.h:732
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
static bool DoingCommandRead
Definition: postgres.c:139
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
int errmsg(const char *fmt,...)
Definition: elog.c:784
bool IsLogicalLauncher(void)
Definition: launcher.c:1088
CommandDest whereToSendOutput
Definition: postgres.c:90

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

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

2695 {
2696  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2697  PG_SETMASK(&BlockSig);
2698 
2699  /*
2700  * Prevent interrupts while exiting; though we just blocked signals that
2701  * would queue new interrupts, one may have been pending. We don't want a
2702  * quickdie() downgraded to a mere query cancel.
2703  */
2704  HOLD_INTERRUPTS();
2705 
2706  /*
2707  * If we're aborting out of client auth, don't risk trying to send
2708  * anything to the client; we will likely violate the protocol, not to
2709  * mention that we may have interrupted the guts of OpenSSL or some
2710  * authentication library.
2711  */
2714 
2715  /*
2716  * Notify the client before exiting, to give a clue on what happened.
2717  *
2718  * It's dubious to call ereport() from a signal handler. It is certainly
2719  * not async-signal safe. But it seems better to try, than to disconnect
2720  * abruptly and leave the client wondering what happened. It's remotely
2721  * possible that we crash or hang while trying to send the message, but
2722  * receiving a SIGQUIT is a sign that something has already gone badly
2723  * wrong, so there's not much to lose. Assuming the postmaster is still
2724  * running, it will SIGKILL us soon if we get stuck for some reason.
2725  *
2726  * Ideally this should be ereport(FATAL), but then we'd not get control
2727  * back...
2728  */
2729  ereport(WARNING,
2730  (errcode(ERRCODE_CRASH_SHUTDOWN),
2731  errmsg("terminating connection because of crash of another server process"),
2732  errdetail("The postmaster has commanded this server process to roll back"
2733  " the current transaction and exit, because another"
2734  " server process exited abnormally and possibly corrupted"
2735  " shared memory."),
2736  errhint("In a moment you should be able to reconnect to the"
2737  " database and repeat your command.")));
2738 
2739  /*
2740  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2741  * because shared memory may be corrupted, so we don't want to try to
2742  * clean up our transaction. Just nail the windows shut and get out of
2743  * town. The callbacks wouldn't be safe to run from a signal handler,
2744  * anyway.
2745  *
2746  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2747  * a system reset cycle if someone sends a manual SIGQUIT to a random
2748  * backend. This is necessary precisely because we don't clean up our
2749  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2750  * should ensure the postmaster sees this as a crash, too, but no harm in
2751  * being doubly sure.)
2752  */
2753  _exit(2);
2754 }
#define SIGQUIT
Definition: win32_port.h:155
int errhint(const char *fmt,...)
Definition: elog.c:974
int errcode(int sqlerrcode)
Definition: elog.c:570
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:352
Definition: dest.h:88
int errdetail(const char *fmt,...)
Definition: elog.c:860