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 "mb/pg_wchar.h"
#include "mb/stringinfo_mb.h"
#include "miscadmin.h"
#include "nodes/print.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parser.h"
#include "pg_getopt.h"
#include "pg_trace.h"
#include "pgstat.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 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 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 3382 of file postgres.c.

References max_stack_depth_bytes.

3383 {
3384  long newval_bytes = newval * 1024L;
3385 
3386  max_stack_depth_bytes = newval_bytes;
3387 }
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 2299 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, MAX_RANDOM_VALUE, random(), snprintf, TimestampDifference(), and xact_is_sampled.

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

2300 {
2301  if (log_duration || log_min_duration_sample >= 0 ||
2303  {
2304  long secs;
2305  int usecs;
2306  int msecs;
2307  bool exceeded_duration;
2308  bool exceeded_sample_duration;
2309  bool in_sample = false;
2310 
2313  &secs, &usecs);
2314  msecs = usecs / 1000;
2315 
2316  /*
2317  * This odd-looking test for log_min_duration_* being exceeded is
2318  * designed to avoid integer overflow with very long durations: don't
2319  * compute secs * 1000 until we've verified it will fit in int.
2320  */
2321  exceeded_duration = (log_min_duration_statement == 0 ||
2323  (secs > log_min_duration_statement / 1000 ||
2324  secs * 1000 + msecs >= log_min_duration_statement)));
2325 
2326  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2327  (log_min_duration_sample > 0 &&
2328  (secs > log_min_duration_sample / 1000 ||
2329  secs * 1000 + msecs >= log_min_duration_sample)));
2330 
2331  /*
2332  * Do not log if log_statement_sample_rate = 0. Log a sample if
2333  * log_statement_sample_rate <= 1 and avoid unecessary random() call
2334  * if log_statement_sample_rate = 1.
2335  */
2336  if (exceeded_sample_duration)
2337  in_sample = log_statement_sample_rate != 0 &&
2338  (log_statement_sample_rate == 1 ||
2340 
2341  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2342  {
2343  snprintf(msec_str, 32, "%ld.%03d",
2344  secs * 1000 + msecs, usecs % 1000);
2345  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2346  return 2;
2347  else
2348  return 1;
2349  }
2350  }
2351 
2352  return 0;
2353 }
int log_min_duration_statement
Definition: guc.c:517
double log_statement_sample_rate
Definition: guc.c:519
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
long random(void)
Definition: random.c:22
int log_min_duration_sample
Definition: guc.c:516
#define MAX_RANDOM_VALUE
bool xact_is_sampled
Definition: xact.c:267
bool log_duration
Definition: guc.c:488
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:791

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2260 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

2261 {
2262  ListCell *stmt_item;
2263 
2264  if (log_statement == LOGSTMT_NONE)
2265  return false;
2266  if (log_statement == LOGSTMT_ALL)
2267  return true;
2268 
2269  /* Else we have to inspect the statement(s) to see whether to log */
2270  foreach(stmt_item, stmt_list)
2271  {
2272  Node *stmt = (Node *) lfirst(stmt_item);
2273 
2274  if (GetCommandLogLevel(stmt) <= log_statement)
2275  return true;
2276  }
2277 
2278  return false;
2279 }
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:2964

◆ check_max_stack_depth()

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

Definition at line 3365 of file postgres.c.

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

3366 {
3367  long newval_bytes = *newval * 1024L;
3368  long stack_rlimit = get_stack_depth_rlimit();
3369 
3370  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3371  {
3372  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3373  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3374  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3375  return false;
3376  }
3377  return true;
3378 }
#define GUC_check_errdetail
Definition: guc.h:414
long get_stack_depth_rlimit(void)
Definition: postgres.c:4566
#define newval
#define GUC_check_errhint
Definition: guc.h:418
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3302 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(), relation_is_updatable(), resolve_special_varno(), 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().

3303 {
3304  if (stack_is_too_deep())
3305  {
3306  ereport(ERROR,
3307  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3308  errmsg("stack depth limit exceeded"),
3309  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3310  "after ensuring the platform's stack depth limit is adequate.",
3311  max_stack_depth)));
3312  }
3313 }
int errhint(const char *fmt,...)
Definition: elog.c:1069
int errcode(int sqlerrcode)
Definition: elog.c:608
#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:822
bool stack_is_too_deep(void)
Definition: postgres.c:3316

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2801 of file postgres.c.

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

Referenced by PostgresMain().

2802 {
2803  int save_errno = errno;
2804 
2805  /* Don't joggle the elbow of proc_exit */
2806  if (!proc_exit_inprogress)
2807  {
2808  InterruptPending = true;
2809  ProcDiePending = true;
2810  }
2811 
2812  /* If we're still here, waken anything waiting on the process latch */
2813  SetLatch(MyLatch);
2814 
2815  /*
2816  * If we're in single user mode, we want to quit immediately - we can't
2817  * rely on latches as they wouldn't work when stdin/stdout is a file.
2818  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2819  * effort just for the benefit of single user mode.
2820  */
2823 
2824  errno = save_errno;
2825 }
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessInterrupts(void)
Definition: postgres.c:3012
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 4768 of file postgres.c.

References disable_timeout(), get_timeout_active(), and STATEMENT_TIMEOUT.

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

4769 {
4772 }
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:532
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:635

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2709 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2710 {
2711  /* paranoia to avoid a dangling pointer in case of error */
2712  if (unnamed_stmt_psrc)
2713  {
2715 
2716  unnamed_stmt_psrc = NULL;
2717  DropCachedPlan(psrc);
2718  }
2719 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:153
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:496

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

Definition at line 4747 of file postgres.c.

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

Referenced by start_xact_command().

4748 {
4749  /* must be within an xact */
4751 
4752  if (StatementTimeout > 0)
4753  {
4756  }
4757  else
4758  {
4761  }
4762 }
static bool xact_started
Definition: postgres.c:132
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:435
#define Assert(condition)
Definition: c.h:739
int StatementTimeout
Definition: proc.c:61
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:532
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:635

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

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

2414 {
2416  errdetail("abort reason: recovery conflict");
2417 
2418  return 0;
2419 }
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:127
int errdetail(const char *fmt,...)
Definition: elog.c:955

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2362 of file postgres.c.

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

Referenced by exec_simple_query().

2363 {
2364  ListCell *parsetree_item;
2365 
2366  foreach(parsetree_item, raw_parsetree_list)
2367  {
2368  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2369 
2370  if (IsA(parsetree->stmt, ExecuteStmt))
2371  {
2372  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2373  PreparedStatement *pstmt;
2374 
2375  pstmt = FetchPreparedStatement(stmt->name, false);
2376  if (pstmt)
2377  {
2378  errdetail("prepare: %s", pstmt->plansource->query_string);
2379  return 0;
2380  }
2381  }
2382  }
2383 
2384  return 0;
2385 }
#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:955
char * name
Definition: parsenodes.h:3402
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:486

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2393 of file postgres.c.

References BuildParamLogString(), errdetail(), ParamListInfoData::numParams, and generate_unaccent_rules::str.

Referenced by exec_bind_message(), and exec_execute_message().

2394 {
2395  if (params && params->numParams > 0)
2396  {
2397  char *str;
2398 
2399  str = BuildParamLogString(params, NULL, 0);
2400  if (str && str[0] != '\0')
2401  errdetail("parameters: %s", str);
2402  }
2403 
2404  return 0;
2405 }
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:277
int errdetail(const char *fmt,...)
Definition: elog.c:955

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

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

2428 {
2429  switch (RecoveryConflictReason)
2430  {
2432  errdetail("User was holding shared buffer pin for too long.");
2433  break;
2435  errdetail("User was holding a relation lock for too long.");
2436  break;
2438  errdetail("User was or might have been using tablespace that must be dropped.");
2439  break;
2441  errdetail("User query might have needed to see row versions that must be removed.");
2442  break;
2444  errdetail("User transaction caused buffer deadlock with recovery.");
2445  break;
2447  errdetail("User was connected to a database that must be dropped.");
2448  break;
2449  default:
2450  break;
2451  /* no errdetail */
2452  }
2453 
2454  return 0;
2455 }
int errdetail(const char *fmt,...)
Definition: elog.c:955
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:163

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1598 of file postgres.c.

References analyze_requires_snapshot(), ErrorContextCallback::arg, BuildParamLogString(), ErrorContextCallback::callback, check_log_duration(), CachedPlanSource::commandTag, CreatePortal(), StringInfoData::cursor, StringInfoData::data, DEBUG2, debug_query_string, DestRemote, ereport, errcode(), errdetail_abort(), errdetail_params(), errhidestmt(), errmsg(), ERROR, error_context_stack, FetchPreparedStatement(), GetCachedPlan(), GetTransactionSnapshot(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, InvalidSnapshot, IsAbortedTransactionBlockState(), ParamExternData::isnull, IsTransactionExitStmt(), StringInfoData::len, LOG, log_parameters_on_error, log_statement_stats, makeParamList(), MAX_MULTIBYTE_CHAR_LEN, StringInfoData::maxlen, MemoryContextSwitchTo(), MessageContext, PortalData::name, CachedPlanSource::num_params, OidInputFunctionCall(), OidReceiveFunctionCall(), palloc(), palloc0(), PARAM_FLAG_CONST, CachedPlanSource::param_types, ParamListInfoData::params, ParamsErrorCbData::params, ParamsErrorCallback(), ParamListInfoData::paramValuesStr, ParamExternData::pflags, pfree(), pg_client_to_server(), pgstat_report_activity(), PreparedStatement::plansource, pnstrdup(), PopActiveSnapshot(), PortalData::portalContext, PortalDefineQuery(), ParamsErrorCbData::portalName, PortalSetResultFormat(), PortalStart(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_putemptymessage(), ErrorContextCallback::previous, 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().

1599 {
1600  const char *portal_name;
1601  const char *stmt_name;
1602  int numPFormats;
1603  int16 *pformats = NULL;
1604  int numParams;
1605  int numRFormats;
1606  int16 *rformats = NULL;
1607  CachedPlanSource *psrc;
1608  CachedPlan *cplan;
1609  Portal portal;
1610  char *query_string;
1611  char *saved_stmt_name;
1612  ParamListInfo params;
1613  MemoryContext oldContext;
1614  bool save_log_statement_stats = log_statement_stats;
1615  bool snapshot_set = false;
1616  char msec_str[32];
1617  ParamsErrorCbData params_data;
1618  ErrorContextCallback params_errcxt;
1619 
1620  /* Get the fixed part of the message */
1621  portal_name = pq_getmsgstring(input_message);
1622  stmt_name = pq_getmsgstring(input_message);
1623 
1624  ereport(DEBUG2,
1625  (errmsg("bind %s to %s",
1626  *portal_name ? portal_name : "<unnamed>",
1627  *stmt_name ? stmt_name : "<unnamed>")));
1628 
1629  /* Find prepared statement */
1630  if (stmt_name[0] != '\0')
1631  {
1632  PreparedStatement *pstmt;
1633 
1634  pstmt = FetchPreparedStatement(stmt_name, true);
1635  psrc = pstmt->plansource;
1636  }
1637  else
1638  {
1639  /* special-case the unnamed statement */
1640  psrc = unnamed_stmt_psrc;
1641  if (!psrc)
1642  ereport(ERROR,
1643  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1644  errmsg("unnamed prepared statement does not exist")));
1645  }
1646 
1647  /*
1648  * Report query to various monitoring facilities.
1649  */
1651 
1653 
1654  set_ps_display("BIND", false);
1655 
1656  if (save_log_statement_stats)
1657  ResetUsage();
1658 
1659  /*
1660  * Start up a transaction command so we can call functions etc. (Note that
1661  * this will normally change current memory context.) Nothing happens if
1662  * we are already in one. This also arms the statement timeout if
1663  * necessary.
1664  */
1666 
1667  /* Switch back to message context */
1669 
1670  /* Get the parameter format codes */
1671  numPFormats = pq_getmsgint(input_message, 2);
1672  if (numPFormats > 0)
1673  {
1674  pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1675  for (int i = 0; i < numPFormats; i++)
1676  pformats[i] = pq_getmsgint(input_message, 2);
1677  }
1678 
1679  /* Get the parameter value count */
1680  numParams = pq_getmsgint(input_message, 2);
1681 
1682  if (numPFormats > 1 && numPFormats != numParams)
1683  ereport(ERROR,
1684  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1685  errmsg("bind message has %d parameter formats but %d parameters",
1686  numPFormats, numParams)));
1687 
1688  if (numParams != psrc->num_params)
1689  ereport(ERROR,
1690  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1691  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1692  numParams, stmt_name, psrc->num_params)));
1693 
1694  /*
1695  * If we are in aborted transaction state, the only portals we can
1696  * actually run are those containing COMMIT or ROLLBACK commands. We
1697  * disallow binding anything else to avoid problems with infrastructure
1698  * that expects to run inside a valid transaction. We also disallow
1699  * binding any parameters, since we can't risk calling user-defined I/O
1700  * functions.
1701  */
1703  (!(psrc->raw_parse_tree &&
1705  numParams != 0))
1706  ereport(ERROR,
1707  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1708  errmsg("current transaction is aborted, "
1709  "commands ignored until end of transaction block"),
1710  errdetail_abort()));
1711 
1712  /*
1713  * Create the portal. Allow silent replacement of an existing portal only
1714  * if the unnamed portal is specified.
1715  */
1716  if (portal_name[0] == '\0')
1717  portal = CreatePortal(portal_name, true, true);
1718  else
1719  portal = CreatePortal(portal_name, false, false);
1720 
1721  /*
1722  * Prepare to copy stuff into the portal's memory context. We do all this
1723  * copying first, because it could possibly fail (out-of-memory) and we
1724  * don't want a failure to occur between GetCachedPlan and
1725  * PortalDefineQuery; that would result in leaking our plancache refcount.
1726  */
1727  oldContext = MemoryContextSwitchTo(portal->portalContext);
1728 
1729  /* Copy the plan's query string into the portal */
1730  query_string = pstrdup(psrc->query_string);
1731 
1732  /* Likewise make a copy of the statement name, unless it's unnamed */
1733  if (stmt_name[0])
1734  saved_stmt_name = pstrdup(stmt_name);
1735  else
1736  saved_stmt_name = NULL;
1737 
1738  /*
1739  * Set a snapshot if we have parameters to fetch (since the input
1740  * functions might need it) or the query isn't a utility command (and
1741  * hence could require redoing parse analysis and planning). We keep the
1742  * snapshot active till we're done, so that plancache.c doesn't have to
1743  * take new ones.
1744  */
1745  if (numParams > 0 ||
1746  (psrc->raw_parse_tree &&
1748  {
1750  snapshot_set = true;
1751  }
1752 
1753  /*
1754  * Fetch parameters, if any, and store in the portal's memory context.
1755  */
1756  if (numParams > 0)
1757  {
1758  char **knownTextValues = NULL; /* allocate on first use */
1759 
1760  params = makeParamList(numParams);
1761 
1762  for (int paramno = 0; paramno < numParams; paramno++)
1763  {
1764  Oid ptype = psrc->param_types[paramno];
1765  int32 plength;
1766  Datum pval;
1767  bool isNull;
1768  StringInfoData pbuf;
1769  char csave;
1770  int16 pformat;
1771 
1772  plength = pq_getmsgint(input_message, 4);
1773  isNull = (plength == -1);
1774 
1775  if (!isNull)
1776  {
1777  const char *pvalue = pq_getmsgbytes(input_message, plength);
1778 
1779  /*
1780  * Rather than copying data around, we just set up a phony
1781  * StringInfo pointing to the correct portion of the message
1782  * buffer. We assume we can scribble on the message buffer so
1783  * as to maintain the convention that StringInfos have a
1784  * trailing null. This is grotty but is a big win when
1785  * dealing with very large parameter strings.
1786  */
1787  pbuf.data = unconstify(char *, pvalue);
1788  pbuf.maxlen = plength + 1;
1789  pbuf.len = plength;
1790  pbuf.cursor = 0;
1791 
1792  csave = pbuf.data[plength];
1793  pbuf.data[plength] = '\0';
1794  }
1795  else
1796  {
1797  pbuf.data = NULL; /* keep compiler quiet */
1798  csave = 0;
1799  }
1800 
1801  if (numPFormats > 1)
1802  pformat = pformats[paramno];
1803  else if (numPFormats > 0)
1804  pformat = pformats[0];
1805  else
1806  pformat = 0; /* default = text */
1807 
1808  if (pformat == 0) /* text mode */
1809  {
1810  Oid typinput;
1811  Oid typioparam;
1812  char *pstring;
1813 
1814  getTypeInputInfo(ptype, &typinput, &typioparam);
1815 
1816  /*
1817  * We have to do encoding conversion before calling the
1818  * typinput routine.
1819  */
1820  if (isNull)
1821  pstring = NULL;
1822  else
1823  pstring = pg_client_to_server(pbuf.data, plength);
1824 
1825  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1826 
1827  /*
1828  * Free result of encoding conversion, if any, and save a copy
1829  * for later when logging parameters.
1830  */
1831  if (pstring)
1832  {
1834  {
1835  MemoryContext oldcxt;
1836 
1838  if (knownTextValues == NULL)
1839  knownTextValues =
1840  palloc0(numParams * sizeof(char *));
1841  /*
1842  * Note: must copy at least two more full characters
1843  * than BuildParamLogString wants to see; otherwise it
1844  * might fail to include the ellipsis.
1845  */
1846  knownTextValues[paramno] =
1847  pnstrdup(pstring, 64 + 2 * MAX_MULTIBYTE_CHAR_LEN);
1848  MemoryContextSwitchTo(oldcxt);
1849  }
1850  if (pstring != pbuf.data)
1851  pfree(pstring);
1852  }
1853  }
1854  else if (pformat == 1) /* binary mode */
1855  {
1856  Oid typreceive;
1857  Oid typioparam;
1858  StringInfo bufptr;
1859 
1860  /*
1861  * Call the parameter type's binary input converter
1862  */
1863  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1864 
1865  if (isNull)
1866  bufptr = NULL;
1867  else
1868  bufptr = &pbuf;
1869 
1870  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1871 
1872  /* Trouble if it didn't eat the whole buffer */
1873  if (!isNull && pbuf.cursor != pbuf.len)
1874  ereport(ERROR,
1875  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1876  errmsg("incorrect binary data format in bind parameter %d",
1877  paramno + 1)));
1878  }
1879  else
1880  {
1881  ereport(ERROR,
1882  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1883  errmsg("unsupported format code: %d",
1884  pformat)));
1885  pval = 0; /* keep compiler quiet */
1886  }
1887 
1888  /* Restore message buffer contents */
1889  if (!isNull)
1890  pbuf.data[plength] = csave;
1891 
1892  params->params[paramno].value = pval;
1893  params->params[paramno].isnull = isNull;
1894 
1895  /*
1896  * We mark the params as CONST. This ensures that any custom plan
1897  * makes full use of the parameter values.
1898  */
1899  params->params[paramno].pflags = PARAM_FLAG_CONST;
1900  params->params[paramno].ptype = ptype;
1901  }
1902 
1903  /*
1904  * Once all parameters have been received, prepare for printing them in
1905  * errors, if configured to do so. (This is saved in the portal, so
1906  * that they'll appear when the query is executed later.)
1907  */
1909  params->paramValuesStr =
1910  BuildParamLogString(params, knownTextValues, 64);
1911  }
1912  else
1913  params = NULL;
1914 
1915  /* Done storing stuff in portal's context */
1916  MemoryContextSwitchTo(oldContext);
1917 
1918  /* Set the error callback so that parameters are logged, as needed */
1919  params_data.portalName = portal->name;
1920  params_data.params = params;
1921  params_errcxt.previous = error_context_stack;
1922  params_errcxt.callback = ParamsErrorCallback;
1923  params_errcxt.arg = (void *) &params_data;
1924  error_context_stack = &params_errcxt;
1925 
1926  /* Get the result format codes */
1927  numRFormats = pq_getmsgint(input_message, 2);
1928  if (numRFormats > 0)
1929  {
1930  rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1931  for (int i = 0; i < numRFormats; i++)
1932  rformats[i] = pq_getmsgint(input_message, 2);
1933  }
1934 
1935  pq_getmsgend(input_message);
1936 
1937  /*
1938  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1939  * will be generated in MessageContext. The plan refcount will be
1940  * assigned to the Portal, so it will be released at portal destruction.
1941  */
1942  cplan = GetCachedPlan(psrc, params, false, NULL);
1943 
1944  /*
1945  * Now we can define the portal.
1946  *
1947  * DO NOT put any code that could possibly throw an error between the
1948  * above GetCachedPlan call and here.
1949  */
1950  PortalDefineQuery(portal,
1951  saved_stmt_name,
1952  query_string,
1953  psrc->commandTag,
1954  cplan->stmt_list,
1955  cplan);
1956 
1957  /* Done with the snapshot used for parameter I/O and parsing/planning */
1958  if (snapshot_set)
1960 
1961  /*
1962  * And we're ready to start portal execution.
1963  */
1964  PortalStart(portal, params, 0, InvalidSnapshot);
1965 
1966  /*
1967  * Apply the result format requests to the portal.
1968  */
1969  PortalSetResultFormat(portal, numRFormats, rformats);
1970 
1971  /*
1972  * Done binding; remove the parameters error callback. Entries emitted
1973  * later determine independently whether to log the parameters or not.
1974  */
1976 
1977  /*
1978  * Send BindComplete.
1979  */
1981  pq_putemptymessage('2');
1982 
1983  /*
1984  * Emit duration logging if appropriate.
1985  */
1986  switch (check_log_duration(msec_str, false))
1987  {
1988  case 1:
1989  ereport(LOG,
1990  (errmsg("duration: %s ms", msec_str),
1991  errhidestmt(true)));
1992  break;
1993  case 2:
1994  ereport(LOG,
1995  (errmsg("duration: %s ms bind %s%s%s: %s",
1996  msec_str,
1997  *stmt_name ? stmt_name : "<unnamed>",
1998  *portal_name ? "/" : "",
1999  *portal_name ? portal_name : "",
2000  psrc->query_string),
2001  errhidestmt(true),
2002  errdetail_params(params)));
2003  break;
2004  }
2005 
2006  if (save_log_statement_stats)
2007  ShowUsage("BIND MESSAGE STATISTICS");
2008 
2009  debug_query_string = NULL;
2010 }
signed short int16
Definition: c.h:346
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
Datum value
Definition: params.h:92
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1197
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
ParamListInfo params
Definition: params.h:157
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:498
const char * commandTag
Definition: plancache.h:98
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3119
CachedPlanSource * plansource
Definition: prepare.h:31
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
void ShowUsage(const char *title)
Definition: postgres.c:4609
char * pstrdup(const char *in)
Definition: mcxt.c:1186
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:375
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:608
int errhidestmt(bool hide_stmt)
Definition: elog.c:1150
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2413
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:35
void(* callback)(void *arg)
Definition: elog.h:256
struct ErrorContextCallback * previous
Definition: elog.h:255
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:347
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2662
ErrorContextCallback * error_context_stack
Definition: elog.c:91
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2299
void ResetUsage(void)
Definition: postgres.c:4602
void pfree(void *pointer)
Definition: mcxt.c:1056
const char * name
Definition: portal.h:117
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
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:277
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:153
char * paramValuesStr
Definition: params.h:118
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2393
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
#define MAX_MULTIBYTE_CHAR_LEN
Definition: pg_wchar.h:30
const char * debug_query_string
Definition: postgres.c:87
#define unconstify(underlying_type, expr)
Definition: c.h:1194
#define InvalidSnapshot
Definition: snapshot.h:123
static void start_xact_command(void)
Definition: postgres.c:2610
void * palloc0(Size size)
Definition: mcxt.c:980
uintptr_t Datum
Definition: postgres.h:367
bool log_parameters_on_error
Definition: guc.c:489
const char * portalName
Definition: params.h:156
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:822
int i
void ParamsErrorCallback(void *arg)
Definition: params.c:348
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:486
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 2558 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().

2559 {
2560  Portal portal;
2561 
2562  /*
2563  * Start up a transaction command. (Note that this will normally change
2564  * current memory context.) Nothing happens if we are already in one.
2565  */
2567 
2568  /* Switch back to message context */
2570 
2571  portal = GetPortalByName(portal_name);
2572  if (!PortalIsValid(portal))
2573  ereport(ERROR,
2574  (errcode(ERRCODE_UNDEFINED_CURSOR),
2575  errmsg("portal \"%s\" does not exist", portal_name)));
2576 
2577  /*
2578  * If we are in aborted transaction state, we can't run
2579  * SendRowDescriptionMessage(), because that needs catalog accesses.
2580  * Hence, refuse to Describe portals that return data. (We shouldn't just
2581  * refuse all Describes, since that might break the ability of some
2582  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2583  * blindly Describes whatever it does.)
2584  */
2586  portal->tupDesc)
2587  ereport(ERROR,
2588  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2589  errmsg("current transaction is aborted, "
2590  "commands ignored until end of transaction block"),
2591  errdetail_abort()));
2592 
2594  return; /* can't actually do anything... */
2595 
2596  if (portal->tupDesc)
2598  portal->tupDesc,
2599  FetchPortalTargetList(portal),
2600  portal->formats);
2601  else
2602  pq_putemptymessage('n'); /* NoData */
2603 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:375
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:608
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2413
#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:2610
int16 * formats
Definition: portal.h:159
static StringInfoData row_description_buf
Definition: postgres.c:167
TupleDesc tupDesc
Definition: portal.h:157
MemoryContext MessageContext
Definition: mcxt.c:48
int errmsg(const char *fmt,...)
Definition: elog.c:822
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 2463 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().

2464 {
2465  CachedPlanSource *psrc;
2466 
2467  /*
2468  * Start up a transaction command. (Note that this will normally change
2469  * current memory context.) Nothing happens if we are already in one.
2470  */
2472 
2473  /* Switch back to message context */
2475 
2476  /* Find prepared statement */
2477  if (stmt_name[0] != '\0')
2478  {
2479  PreparedStatement *pstmt;
2480 
2481  pstmt = FetchPreparedStatement(stmt_name, true);
2482  psrc = pstmt->plansource;
2483  }
2484  else
2485  {
2486  /* special-case the unnamed statement */
2487  psrc = unnamed_stmt_psrc;
2488  if (!psrc)
2489  ereport(ERROR,
2490  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2491  errmsg("unnamed prepared statement does not exist")));
2492  }
2493 
2494  /* Prepared statements shouldn't have changeable result descs */
2495  Assert(psrc->fixed_result);
2496 
2497  /*
2498  * If we are in aborted transaction state, we can't run
2499  * SendRowDescriptionMessage(), because that needs catalog accesses.
2500  * Hence, refuse to Describe statements that return data. (We shouldn't
2501  * just refuse all Describes, since that might break the ability of some
2502  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2503  * blindly Describes whatever it does.) We can Describe parameters
2504  * without doing anything dangerous, so we don't restrict that.
2505  */
2507  psrc->resultDesc)
2508  ereport(ERROR,
2509  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2510  errmsg("current transaction is aborted, "
2511  "commands ignored until end of transaction block"),
2512  errdetail_abort()));
2513 
2515  return; /* can't actually do anything... */
2516 
2517  /*
2518  * First describe the parameters...
2519  */
2520  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2521  * message type */
2523 
2524  for (int i = 0; i < psrc->num_params; i++)
2525  {
2526  Oid ptype = psrc->param_types[i];
2527 
2528  pq_sendint32(&row_description_buf, (int) ptype);
2529  }
2531 
2532  /*
2533  * Next send RowDescription or NoData to describe the result...
2534  */
2535  if (psrc->resultDesc)
2536  {
2537  List *tlist;
2538 
2539  /* Get the plan's primary targetlist */
2540  tlist = CachedPlanGetTargetList(psrc, NULL);
2541 
2543  psrc->resultDesc,
2544  tlist,
2545  NULL);
2546  }
2547  else
2548  pq_putemptymessage('n'); /* NoData */
2549 
2550 }
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:375
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:608
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2413
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:153
#define ereport(elevel, rest)
Definition: elog.h:141
static void start_xact_command(void)
Definition: postgres.c:2610
static StringInfoData row_description_buf
Definition: postgres.c:167
#define Assert(condition)
Definition: c.h:739
MemoryContext MessageContext
Definition: mcxt.c:48
int errmsg(const char *fmt,...)
Definition: elog.c:822
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:486
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 2018 of file postgres.c.

References _, ErrorContextCallback::arg, Assert, PortalData::atStart, BeginCommand(), ErrorContextCallback::callback, 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, error_context_stack, FETCH_ALL, finish_xact_command(), GetPortalByName(), IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), LOG, log_statement_stats, PortalData::name, NIL, NullCommand(), ParamsErrorCbData::params, ParamsErrorCallback(), pgstat_report_activity(), PortalIsValid, ParamsErrorCbData::portalName, PortalData::portalParams, PortalRun(), pq_putemptymessage(), PortalData::prepStmtName, ErrorContextCallback::previous, pstrdup(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display(), SetRemoteDestReceiverParams(), ShowUsage(), PortalData::sourceText, start_xact_command(), STATE_RUNNING, PortalData::stmts, and whereToSendOutput.

Referenced by PostgresMain().

2019 {
2020  CommandDest dest;
2021  DestReceiver *receiver;
2022  Portal portal;
2023  bool completed;
2024  char completionTag[COMPLETION_TAG_BUFSIZE];
2025  const char *sourceText;
2026  const char *prepStmtName;
2027  ParamListInfo portalParams;
2028  bool save_log_statement_stats = log_statement_stats;
2029  bool is_xact_command;
2030  bool execute_is_fetch;
2031  bool was_logged = false;
2032  char msec_str[32];
2033  ParamsErrorCbData params_data;
2034  ErrorContextCallback params_errcxt;
2035 
2036  /* Adjust destination to tell printtup.c what to do */
2037  dest = whereToSendOutput;
2038  if (dest == DestRemote)
2039  dest = DestRemoteExecute;
2040 
2041  portal = GetPortalByName(portal_name);
2042  if (!PortalIsValid(portal))
2043  ereport(ERROR,
2044  (errcode(ERRCODE_UNDEFINED_CURSOR),
2045  errmsg("portal \"%s\" does not exist", portal_name)));
2046 
2047  /*
2048  * If the original query was a null string, just return
2049  * EmptyQueryResponse.
2050  */
2051  if (portal->commandTag == NULL)
2052  {
2053  Assert(portal->stmts == NIL);
2054  NullCommand(dest);
2055  return;
2056  }
2057 
2058  /* Does the portal contain a transaction command? */
2059  is_xact_command = IsTransactionStmtList(portal->stmts);
2060 
2061  /*
2062  * We must copy the sourceText and prepStmtName into MessageContext in
2063  * case the portal is destroyed during finish_xact_command. Can avoid the
2064  * copy if it's not an xact command, though.
2065  */
2066  if (is_xact_command)
2067  {
2068  sourceText = pstrdup(portal->sourceText);
2069  if (portal->prepStmtName)
2070  prepStmtName = pstrdup(portal->prepStmtName);
2071  else
2072  prepStmtName = "<unnamed>";
2073 
2074  /*
2075  * An xact command shouldn't have any parameters, which is a good
2076  * thing because they wouldn't be around after finish_xact_command.
2077  */
2078  portalParams = NULL;
2079  }
2080  else
2081  {
2082  sourceText = portal->sourceText;
2083  if (portal->prepStmtName)
2084  prepStmtName = portal->prepStmtName;
2085  else
2086  prepStmtName = "<unnamed>";
2087  portalParams = portal->portalParams;
2088  }
2089 
2090  /*
2091  * Report query to various monitoring facilities.
2092  */
2093  debug_query_string = sourceText;
2094 
2096 
2097  set_ps_display(portal->commandTag, false);
2098 
2099  if (save_log_statement_stats)
2100  ResetUsage();
2101 
2102  BeginCommand(portal->commandTag, dest);
2103 
2104  /*
2105  * Create dest receiver in MessageContext (we don't want it in transaction
2106  * context, because that may get deleted if portal contains VACUUM).
2107  */
2108  receiver = CreateDestReceiver(dest);
2109  if (dest == DestRemoteExecute)
2110  SetRemoteDestReceiverParams(receiver, portal);
2111 
2112  /*
2113  * Ensure we are in a transaction command (this should normally be the
2114  * case already due to prior BIND).
2115  */
2117 
2118  /*
2119  * If we re-issue an Execute protocol request against an existing portal,
2120  * then we are only fetching more rows rather than completely re-executing
2121  * the query from the start. atStart is never reset for a v3 portal, so we
2122  * are safe to use this check.
2123  */
2124  execute_is_fetch = !portal->atStart;
2125 
2126  /* Log immediately if dictated by log_statement */
2127  if (check_log_statement(portal->stmts))
2128  {
2129  ereport(LOG,
2130  (errmsg("%s %s%s%s: %s",
2131  execute_is_fetch ?
2132  _("execute fetch from") :
2133  _("execute"),
2134  prepStmtName,
2135  *portal_name ? "/" : "",
2136  *portal_name ? portal_name : "",
2137  sourceText),
2138  errhidestmt(true),
2139  errdetail_params(portalParams)));
2140  was_logged = true;
2141  }
2142 
2143  /*
2144  * If we are in aborted transaction state, the only portals we can
2145  * actually run are those containing COMMIT or ROLLBACK commands.
2146  */
2148  !IsTransactionExitStmtList(portal->stmts))
2149  ereport(ERROR,
2150  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2151  errmsg("current transaction is aborted, "
2152  "commands ignored until end of transaction block"),
2153  errdetail_abort()));
2154 
2155  /* Check for cancel signal before we start execution */
2157 
2158  /*
2159  * Okay to run the portal. Set the error callback so that parameters are
2160  * logged. The parameters must have been saved during the bind phase.
2161  */
2162  params_data.portalName = portal->name;
2163  params_data.params = portalParams;
2164  params_errcxt.previous = error_context_stack;
2165  params_errcxt.callback = ParamsErrorCallback;
2166  params_errcxt.arg = (void *) &params_data;
2167  error_context_stack = &params_errcxt;
2168 
2169  if (max_rows <= 0)
2170  max_rows = FETCH_ALL;
2171 
2172  completed = PortalRun(portal,
2173  max_rows,
2174  true, /* always top level */
2175  !execute_is_fetch && max_rows == FETCH_ALL,
2176  receiver,
2177  receiver,
2178  completionTag);
2179 
2180  receiver->rDestroy(receiver);
2181 
2182  /* Done executing; remove the params error callback */
2184 
2185  if (completed)
2186  {
2187  if (is_xact_command)
2188  {
2189  /*
2190  * If this was a transaction control statement, commit it. We
2191  * will start a new xact command for the next command (if any).
2192  */
2194  }
2195  else
2196  {
2197  /*
2198  * We need a CommandCounterIncrement after every query, except
2199  * those that start or end a transaction block.
2200  */
2202 
2203  /*
2204  * Disable statement timeout whenever we complete an Execute
2205  * message. The next protocol message will start a fresh timeout.
2206  */
2208  }
2209 
2210  /* Send appropriate CommandComplete to client */
2211  EndCommand(completionTag, dest);
2212  }
2213  else
2214  {
2215  /* Portal run not complete, so send PortalSuspended */
2217  pq_putemptymessage('s');
2218  }
2219 
2220  /*
2221  * Emit duration logging if appropriate.
2222  */
2223  switch (check_log_duration(msec_str, was_logged))
2224  {
2225  case 1:
2226  ereport(LOG,
2227  (errmsg("duration: %s ms", msec_str),
2228  errhidestmt(true)));
2229  break;
2230  case 2:
2231  ereport(LOG,
2232  (errmsg("duration: %s ms %s %s%s%s: %s",
2233  msec_str,
2234  execute_is_fetch ?
2235  _("execute fetch from") :
2236  _("execute"),
2237  prepStmtName,
2238  *portal_name ? "/" : "",
2239  *portal_name ? portal_name : "",
2240  sourceText),
2241  errhidestmt(true),
2242  errdetail_params(portalParams)));
2243  break;
2244  }
2245 
2246  if (save_log_statement_stats)
2247  ShowUsage("EXECUTE MESSAGE STATISTICS");
2248 
2249  debug_query_string = NULL;
2250 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2694
#define NIL
Definition: pg_list.h:65
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:107
ParamListInfo params
Definition: params.h:157
static void finish_xact_command(void)
Definition: postgres.c:2630
CommandDest
Definition: dest.h:86
bool log_statement_stats
Definition: guc.c:498
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3119
void ShowUsage(const char *title)
Definition: postgres.c:4609
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
char * pstrdup(const char *in)
Definition: mcxt.c:1186
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:375
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:608
int errhidestmt(bool hide_stmt)
Definition: elog.c:1150
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2413
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:103
#define LOG
Definition: elog.h:26
List * stmts
Definition: portal.h:136
void(* callback)(void *arg)
Definition: elog.h:256
struct ErrorContextCallback * previous
Definition: elog.h:255
ErrorContextCallback * error_context_stack
Definition: elog.c:91
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2299
void ResetUsage(void)
Definition: postgres.c:4602
static void disable_statement_timeout(void)
Definition: postgres.c:4768
ParamListInfo portalParams
Definition: portal.h:139
const char * name
Definition: portal.h:117
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:2393
#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:2260
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2610
void CommandCounterIncrement(void)
Definition: xact.c:1005
const char * sourceText
Definition: portal.h:134
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
const char * portalName
Definition: params.h:156
#define Assert(condition)
Definition: c.h:739
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2679
bool atStart
Definition: portal.h:188
int errmsg(const char *fmt,...)
Definition: elog.c:822
void ParamsErrorCallback(void *arg)
Definition: params.c:348
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandDest whereToSendOutput
Definition: postgres.c:90
#define _(x)
Definition: elog.c:87
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 1336 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().

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

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

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

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

2631 {
2632  /* cancel active statement timeout after each command */
2634 
2635  if (xact_started)
2636  {
2638 
2639 #ifdef MEMORY_CONTEXT_CHECKING
2640  /* Check all memory contexts that weren't freed during commit */
2641  /* (those that were, were checked before being deleted) */
2642  MemoryContextCheck(TopMemoryContext);
2643 #endif
2644 
2645 #ifdef SHOW_MEMORY_STATS
2646  /* Print mem stats after each commit for leak tracking */
2648 #endif
2649 
2650  xact_started = false;
2651  }
2652 }
void CommitTransactionCommand(void)
Definition: xact.c:2898
static void disable_statement_timeout(void)
Definition: postgres.c:4768
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 2853 of file postgres.c.

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

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

2854 {
2855  /* We're not returning, so no need to save errno */
2856  ereport(ERROR,
2857  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2858  errmsg("floating-point exception"),
2859  errdetail("An invalid floating-point operation was signaled. "
2860  "This probably means an out-of-range result or an "
2861  "invalid operation, such as division by zero.")));
2862 }
int errcode(int sqlerrcode)
Definition: elog.c:608
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4544 of file postgres.c.

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

Referenced by PostgresMain().

4545 {
4546  if (am_walsender)
4547  {
4548  if (firstchar == 'F')
4549  ereport(ERROR,
4550  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4551  errmsg("fastpath function calls not supported in a replication connection")));
4552  else
4553  ereport(ERROR,
4554  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4555  errmsg("extended query protocol not supported in a replication connection")));
4556  }
4557 }
int errcode(int sqlerrcode)
Definition: elog.c:608
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:822

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4566 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4567 {
4568 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4569  static long val = 0;
4570 
4571  /* This won't change after process launch, so check just once */
4572  if (val == 0)
4573  {
4574  struct rlimit rlim;
4575 
4576  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4577  val = -1;
4578  else if (rlim.rlim_cur == RLIM_INFINITY)
4579  val = LONG_MAX;
4580  /* rlim_cur is probably of an unsigned type, so check for overflow */
4581  else if (rlim.rlim_cur >= LONG_MAX)
4582  val = LONG_MAX;
4583  else
4584  val = rlim.rlim_cur;
4585  }
4586  return val;
4587 #else /* no getrlimit */
4588 #if defined(WIN32) || defined(__CYGWIN__)
4589  /* On Windows we set the backend stack size in src/backend/Makefile */
4590  return WIN32_STACK_RLIMIT;
4591 #else /* not windows ... give up */
4592  return -1;
4593 #endif
4594 #endif
4595 }
long val
Definition: informix.c:664

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3468 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3469 {
3470  switch (arg[0])
3471  {
3472  case 'p':
3473  if (optarg[1] == 'a') /* "parser" */
3474  return "log_parser_stats";
3475  else if (optarg[1] == 'l') /* "planner" */
3476  return "log_planner_stats";
3477  break;
3478 
3479  case 'e': /* "executor" */
3480  return "log_executor_stats";
3481  break;
3482  }
3483 
3484  return NULL;
3485 }
char * optarg
Definition: getopt.c:52
void * arg

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 299 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

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

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 211 of file postgres.c.

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

Referenced by ReadCommand().

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

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

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

2663 {
2664  if (parsetree && IsA(parsetree, TransactionStmt))
2665  {
2666  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2667 
2668  if (stmt->kind == TRANS_STMT_COMMIT ||
2669  stmt->kind == TRANS_STMT_PREPARE ||
2670  stmt->kind == TRANS_STMT_ROLLBACK ||
2671  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2672  return true;
2673  }
2674  return false;
2675 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
TransactionStmtKind kind
Definition: parsenodes.h:3023

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2679 of file postgres.c.

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

Referenced by exec_execute_message().

2680 {
2681  if (list_length(pstmts) == 1)
2682  {
2683  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2684 
2685  if (pstmt->commandType == CMD_UTILITY &&
2687  return true;
2688  }
2689  return false;
2690 }
#define linitial_node(type, l)
Definition: pg_list.h:198
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2662
Node * utilityStmt
Definition: plannodes.h:92
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 2694 of file postgres.c.

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

Referenced by exec_execute_message().

2695 {
2696  if (list_length(pstmts) == 1)
2697  {
2698  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2699 
2700  if (pstmt->commandType == CMD_UTILITY &&
2701  IsA(pstmt->utilityStmt, TransactionStmt))
2702  return true;
2703  }
2704  return false;
2705 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define linitial_node(type, l)
Definition: pg_list.h:198
Node * utilityStmt
Definition: plannodes.h:92
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 4711 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().

4712 {
4713  Port *port = MyProcPort;
4714  long secs;
4715  int usecs;
4716  int msecs;
4717  int hours,
4718  minutes,
4719  seconds;
4720 
4723  &secs, &usecs);
4724  msecs = usecs / 1000;
4725 
4726  hours = secs / SECS_PER_HOUR;
4727  secs %= SECS_PER_HOUR;
4728  minutes = secs / SECS_PER_MINUTE;
4729  seconds = secs % SECS_PER_MINUTE;
4730 
4731  ereport(LOG,
4732  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4733  "user=%s database=%s host=%s%s%s",
4734  hours, minutes, seconds, msecs,
4735  port->user_name, port->database_name, port->remote_host,
4736  port->remote_port[0] ? " port=" : "", port->remote_port)));
4737 }
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:91
TimestampTz MyStartTimestamp
Definition: globals.c:42
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:822
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 675 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().

678 {
679  Query *query;
680  List *querytree_list;
681 
682  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
683 
684  /*
685  * (1) Perform parse analysis.
686  */
687  if (log_parser_stats)
688  ResetUsage();
689 
690  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
691  queryEnv);
692 
693  if (log_parser_stats)
694  ShowUsage("PARSE ANALYSIS STATISTICS");
695 
696  /*
697  * (2) Rewrite the queries, as necessary
698  */
699  querytree_list = pg_rewrite_query(query);
700 
701  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
702 
703  return querytree_list;
704 }
bool log_parser_stats
Definition: guc.c:495
void ShowUsage(const char *title)
Definition: postgres.c:4609
void ResetUsage(void)
Definition: postgres.c:4602
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:764
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 712 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().

717 {
718  ParseState *pstate;
719  Query *query;
720  List *querytree_list;
721 
722  Assert(query_string != NULL); /* required as of 8.4 */
723 
724  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
725 
726  /*
727  * (1) Perform parse analysis.
728  */
729  if (log_parser_stats)
730  ResetUsage();
731 
732  pstate = make_parsestate(NULL);
733  pstate->p_sourcetext = query_string;
734  pstate->p_queryEnv = queryEnv;
735  (*parserSetup) (pstate, parserSetupArg);
736 
737  query = transformTopLevelStmt(pstate, parsetree);
738 
740  (*post_parse_analyze_hook) (pstate, query);
741 
742  free_parsestate(pstate);
743 
744  if (log_parser_stats)
745  ShowUsage("PARSE ANALYSIS STATISTICS");
746 
747  /*
748  * (2) Rewrite the queries, as necessary
749  */
750  querytree_list = pg_rewrite_query(query);
751 
752  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
753 
754  return querytree_list;
755 }
bool log_parser_stats
Definition: guc.c:495
QueryEnvironment * p_queryEnv
Definition: parse_node.h:200
void ShowUsage(const char *title)
Definition: postgres.c:4609
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void ResetUsage(void)
Definition: postgres.c:4602
const char * p_sourcetext
Definition: parse_node.h:176
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:764
#define Assert(condition)
Definition: c.h:739
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:191
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
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 627 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().

628 {
629  List *raw_parsetree_list;
630 
631  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
632 
633  if (log_parser_stats)
634  ResetUsage();
635 
636  raw_parsetree_list = raw_parser(query_string);
637 
638  if (log_parser_stats)
639  ShowUsage("PARSER STATISTICS");
640 
641 #ifdef COPY_PARSE_PLAN_TREES
642  /* Optional debugging check: pass raw parsetrees through copyObject() */
643  {
644  List *new_list = copyObject(raw_parsetree_list);
645 
646  /* This checks both copyObject() and the equal() routines... */
647  if (!equal(new_list, raw_parsetree_list))
648  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
649  else
650  raw_parsetree_list = new_list;
651  }
652 #endif
653 
654  /*
655  * Currently, outfuncs/readfuncs support is missing for many raw parse
656  * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
657  * here.
658  */
659 
660  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
661 
662  return raw_parsetree_list;
663 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:495
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3011
void ShowUsage(const char *title)
Definition: postgres.c:4609
void ResetUsage(void)
Definition: postgres.c:4602
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:228
#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 941 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().

942 {
943  List *stmt_list = NIL;
944  ListCell *query_list;
945 
946  foreach(query_list, querytrees)
947  {
948  Query *query = lfirst_node(Query, query_list);
949  PlannedStmt *stmt;
950 
951  if (query->commandType == CMD_UTILITY)
952  {
953  /* Utility commands require no planning. */
954  stmt = makeNode(PlannedStmt);
955  stmt->commandType = CMD_UTILITY;
956  stmt->canSetTag = query->canSetTag;
957  stmt->utilityStmt = query->utilityStmt;
958  stmt->stmt_location = query->stmt_location;
959  stmt->stmt_len = query->stmt_len;
960  }
961  else
962  {
963  stmt = pg_plan_query(query, cursorOptions, boundParams);
964  }
965 
966  stmt_list = lappend(stmt_list, stmt);
967  }
968 
969  return stmt_list;
970 }
#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:96
#define lfirst_node(type, lc)
Definition: pg_list.h:193
int stmt_location
Definition: plannodes.h:95
Node * utilityStmt
Definition: plannodes.h:92
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:856

◆ pg_plan_query()

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

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

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

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

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

765 {
766  List *querytree_list;
767 
768  if (Debug_print_parse)
769  elog_node_display(LOG, "parse tree", query,
771 
772  if (log_parser_stats)
773  ResetUsage();
774 
775  if (query->commandType == CMD_UTILITY)
776  {
777  /* don't rewrite utilities, just dump 'em into result list */
778  querytree_list = list_make1(query);
779  }
780  else
781  {
782  /* rewrite regular queries */
783  querytree_list = QueryRewrite(query);
784  }
785 
786  if (log_parser_stats)
787  ShowUsage("REWRITER STATISTICS");
788 
789 #ifdef COPY_PARSE_PLAN_TREES
790  /* Optional debugging check: pass querytree through copyObject() */
791  {
792  List *new_list;
793 
794  new_list = copyObject(querytree_list);
795  /* This checks both copyObject() and the equal() routines... */
796  if (!equal(new_list, querytree_list))
797  elog(WARNING, "copyObject() failed to produce equal parse tree");
798  else
799  querytree_list = new_list;
800  }
801 #endif
802 
803 #ifdef WRITE_READ_PARSE_PLAN_TREES
804  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
805  {
806  List *new_list = NIL;
807  ListCell *lc;
808 
809  /*
810  * We currently lack outfuncs/readfuncs support for most utility
811  * statement types, so only attempt to write/read non-utility queries.
812  */
813  foreach(lc, querytree_list)
814  {
815  Query *query = castNode(Query, lfirst(lc));
816 
817  if (query->commandType != CMD_UTILITY)
818  {
819  char *str = nodeToString(query);
820  Query *new_query = stringToNodeWithLocations(str);
821 
822  /*
823  * queryId is not saved in stored rules, but we must preserve
824  * it here to avoid breaking pg_stat_statements.
825  */
826  new_query->queryId = query->queryId;
827 
828  new_list = lappend(new_list, new_query);
829  pfree(str);
830  }
831  else
832  new_list = lappend(new_list, query);
833  }
834 
835  /* This checks both outfuncs/readfuncs and the equal() routines... */
836  if (!equal(new_list, querytree_list))
837  elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
838  else
839  querytree_list = new_list;
840  }
841 #endif
842 
844  elog_node_display(LOG, "rewritten parse tree", querytree_list,
846 
847  return querytree_list;
848 }
#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:495
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3011
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
void ShowUsage(const char *title)
Definition: postgres.c:4609
#define LOG
Definition: elog.h:26
#define list_make1(x1)
Definition: pg_list.h:227
void ResetUsage(void)
Definition: postgres.c:4602
void pfree(void *pointer)
Definition: mcxt.c:1056
bool Debug_print_parse
Definition: guc.c:491
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:228
bool Debug_pretty_print
Definition: guc.c:493
char * nodeToString(const void *obj)
Definition: outfuncs.c:4322
bool Debug_print_rewritten
Definition: guc.c:492
#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 3767 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, notifyInterruptPending, 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(), ProcessNotifyInterrupt(), 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(), TopMemoryContext, UnBlockSig, userDoption, username, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3770 {
3771  int firstchar;
3772  StringInfoData input_message;
3773  sigjmp_buf local_sigjmp_buf;
3774  volatile bool send_ready_for_query = true;
3775  bool disable_idle_in_transaction_timeout = false;
3776 
3777  /* Initialize startup process environment if necessary. */
3778  if (!IsUnderPostmaster)
3779  InitStandaloneProcess(argv[0]);
3780 
3782 
3783  /*
3784  * Set default values for command-line options.
3785  */
3786  if (!IsUnderPostmaster)
3788 
3789  /*
3790  * Parse command-line options.
3791  */
3793 
3794  /* Must have gotten a database name, or have a default (the username) */
3795  if (dbname == NULL)
3796  {
3797  dbname = username;
3798  if (dbname == NULL)
3799  ereport(FATAL,
3800  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3801  errmsg("%s: no database nor user name specified",
3802  progname)));
3803  }
3804 
3805  /* Acquire configuration parameters, unless inherited from postmaster */
3806  if (!IsUnderPostmaster)
3807  {
3809  proc_exit(1);
3810  }
3811 
3812  /*
3813  * Set up signal handlers and masks.
3814  *
3815  * Note that postmaster blocked all signals before forking child process,
3816  * so there is no race condition whereby we might receive a signal before
3817  * we have set up the handler.
3818  *
3819  * Also note: it's best not to use any signals that are SIG_IGNored in the
3820  * postmaster. If such a signal arrives before we are able to change the
3821  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3822  * handler in the postmaster to reserve the signal. (Of course, this isn't
3823  * an issue for signals that are locally generated, such as SIGALRM and
3824  * SIGPIPE.)
3825  */
3826  if (am_walsender)
3827  WalSndSignals();
3828  else
3829  {
3830  pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3831  * file */
3832  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3833  pqsignal(SIGTERM, die); /* cancel current query and exit */
3834 
3835  /*
3836  * In a standalone backend, SIGQUIT can be generated from the keyboard
3837  * easily, while SIGTERM cannot, so we make both signals do die()
3838  * rather than quickdie().
3839  */
3840  if (IsUnderPostmaster)
3841  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3842  else
3843  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3844  InitializeTimeouts(); /* establishes SIGALRM handler */
3845 
3846  /*
3847  * Ignore failure to write to frontend. Note: if frontend closes
3848  * connection, we will notice it and exit cleanly when control next
3849  * returns to outer loop. This seems safer than forcing exit in the
3850  * midst of output during who-knows-what operation...
3851  */
3856 
3857  /*
3858  * Reset some signals that are accepted by postmaster but not by
3859  * backend
3860  */
3861  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3862  * platforms */
3863  }
3864 
3865  pqinitmask();
3866 
3867  if (IsUnderPostmaster)
3868  {
3869  /* We allow SIGQUIT (quickdie) at all times */
3870  sigdelset(&BlockSig, SIGQUIT);
3871  }
3872 
3873  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3874 
3875  if (!IsUnderPostmaster)
3876  {
3877  /*
3878  * Validate we have been given a reasonable-looking DataDir (if under
3879  * postmaster, assume postmaster did this already).
3880  */
3881  checkDataDir();
3882 
3883  /* Change into DataDir (if under postmaster, was done already) */
3884  ChangeToDataDir();
3885 
3886  /*
3887  * Create lockfile for data directory.
3888  */
3889  CreateDataDirLockFile(false);
3890 
3891  /* read control file (error checking and contains config ) */
3892  LocalProcessControlFile(false);
3893 
3894  /* Initialize MaxBackends (if under postmaster, was done already) */
3896  }
3897 
3898  /* Early initialization */
3899  BaseInit();
3900 
3901  /*
3902  * Create a per-backend PGPROC struct in shared memory, except in the
3903  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3904  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3905  * had to do some stuff with LWLocks).
3906  */
3907 #ifdef EXEC_BACKEND
3908  if (!IsUnderPostmaster)
3909  InitProcess();
3910 #else
3911  InitProcess();
3912 #endif
3913 
3914  /* We need to allow SIGINT, etc during the initial transaction */
3916 
3917  /*
3918  * General initialization.
3919  *
3920  * NOTE: if you are tempted to add code in this vicinity, consider putting
3921  * it inside InitPostgres() instead. In particular, anything that
3922  * involves database access should be there, not here.
3923  */
3925 
3926  /*
3927  * If the PostmasterContext is still around, recycle the space; we don't
3928  * need it anymore after InitPostgres completes. Note this does not trash
3929  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3930  * ... else we'd need to copy the Port data first. Also, subsidiary data
3931  * such as the username isn't lost either; see ProcessStartupPacket().
3932  */
3933  if (PostmasterContext)
3934  {
3936  PostmasterContext = NULL;
3937  }
3938 
3940 
3941  /*
3942  * Now all GUC states are fully set up. Report them to client if
3943  * appropriate.
3944  */
3946 
3947  /*
3948  * Also set up handler to log session end; we have to wait till now to be
3949  * sure Log_disconnections has its final value.
3950  */
3953 
3954  /* Perform initialization specific to a WAL sender process. */
3955  if (am_walsender)
3956  InitWalSender();
3957 
3958  /*
3959  * process any libraries that should be preloaded at backend start (this
3960  * likewise can't be done until GUC settings are complete)
3961  */
3963 
3964  /*
3965  * Send this backend's cancellation info to the frontend.
3966  */
3968  {
3970 
3971  pq_beginmessage(&buf, 'K');
3972  pq_sendint32(&buf, (int32) MyProcPid);
3973  pq_sendint32(&buf, (int32) MyCancelKey);
3974  pq_endmessage(&buf);
3975  /* Need not flush since ReadyForQuery will do it. */
3976  }
3977 
3978  /* Welcome banner for standalone case */
3980  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3981 
3982  /*
3983  * Create the memory context we will use in the main loop.
3984  *
3985  * MessageContext is reset once per iteration of the main loop, ie, upon
3986  * completion of processing of each command message from the client.
3987  */
3989  "MessageContext",
3991 
3992  /*
3993  * Create memory context and buffer used for RowDescription messages. As
3994  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3995  * frequently executed for ever single statement, we don't want to
3996  * allocate a separate buffer every time.
3997  */
3999  "RowDescriptionContext",
4004 
4005  /*
4006  * Remember stand-alone backend startup time
4007  */
4008  if (!IsUnderPostmaster)
4010 
4011  /*
4012  * POSTGRES main processing loop begins here
4013  *
4014  * If an exception is encountered, processing resumes here so we abort the
4015  * current transaction and start a new one.
4016  *
4017  * You might wonder why this isn't coded as an infinite loop around a
4018  * PG_TRY construct. The reason is that this is the bottom of the
4019  * exception stack, and so with PG_TRY there would be no exception handler
4020  * in force at all during the CATCH part. By leaving the outermost setjmp
4021  * always active, we have at least some chance of recovering from an error
4022  * during error recovery. (If we get into an infinite loop thereby, it
4023  * will soon be stopped by overflow of elog.c's internal state stack.)
4024  *
4025  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4026  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4027  * is essential in case we longjmp'd out of a signal handler on a platform
4028  * where that leaves the signal blocked. It's not redundant with the
4029  * unblock in AbortTransaction() because the latter is only called if we
4030  * were inside a transaction.
4031  */
4032 
4033  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4034  {
4035  /*
4036  * NOTE: if you are tempted to add more code in this if-block,
4037  * consider the high probability that it should be in
4038  * AbortTransaction() instead. The only stuff done directly here
4039  * should be stuff that is guaranteed to apply *only* for outer-level
4040  * error recovery, such as adjusting the FE/BE protocol status.
4041  */
4042 
4043  /* Since not using PG_TRY, must reset error stack by hand */
4044  error_context_stack = NULL;
4045 
4046  /* Prevent interrupts while cleaning up */
4047  HOLD_INTERRUPTS();
4048 
4049  /*
4050  * Forget any pending QueryCancel request, since we're returning to
4051  * the idle loop anyway, and cancel any active timeout requests. (In
4052  * future we might want to allow some timeout requests to survive, but
4053  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4054  * we got here because of a query cancel interrupting the SIGALRM
4055  * interrupt handler.) Note in particular that we must clear the
4056  * statement and lock timeout indicators, to prevent any future plain
4057  * query cancels from being misreported as timeouts in case we're
4058  * forgetting a timeout cancel.
4059  */
4060  disable_all_timeouts(false);
4061  QueryCancelPending = false; /* second to avoid race condition */
4062 
4063  /* Not reading from the client anymore. */
4064  DoingCommandRead = false;
4065 
4066  /* Make sure libpq is in a good state */
4067  pq_comm_reset();
4068 
4069  /* Report the error to the client and/or server log */
4070  EmitErrorReport();
4071 
4072  /*
4073  * Make sure debug_query_string gets reset before we possibly clobber
4074  * the storage it points at.
4075  */
4076  debug_query_string = NULL;
4077 
4078  /*
4079  * Abort the current transaction in order to recover.
4080  */
4082 
4083  if (am_walsender)
4085 
4087  SPICleanup();
4088 
4089  /*
4090  * We can't release replication slots inside AbortTransaction() as we
4091  * need to be able to start and abort transactions while having a slot
4092  * acquired. But we never need to hold them across top level errors,
4093  * so releasing here is fine. There's another cleanup in ProcKill()
4094  * ensuring we'll correctly cleanup on FATAL errors as well.
4095  */
4096  if (MyReplicationSlot != NULL)
4098 
4099  /* We also want to cleanup temporary slots on error. */
4101 
4103 
4104  /*
4105  * Now return to normal top-level context and clear ErrorContext for
4106  * next time.
4107  */
4109  FlushErrorState();
4110 
4111  /*
4112  * If we were handling an extended-query-protocol message, initiate
4113  * skip till next Sync. This also causes us not to issue
4114  * ReadyForQuery (until we get Sync).
4115  */
4117  ignore_till_sync = true;
4118 
4119  /* We don't have a transaction command open anymore */
4120  xact_started = false;
4121 
4122  /*
4123  * If an error occurred while we were reading a message from the
4124  * client, we have potentially lost track of where the previous
4125  * message ends and the next one begins. Even though we have
4126  * otherwise recovered from the error, we cannot safely read any more
4127  * messages from the client, so there isn't much we can do with the
4128  * connection anymore.
4129  */
4130  if (pq_is_reading_msg())
4131  ereport(FATAL,
4132  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4133  errmsg("terminating connection because protocol synchronization was lost")));
4134 
4135  /* Now we can allow interrupts again */
4137  }
4138 
4139  /* We can now handle ereport(ERROR) */
4140  PG_exception_stack = &local_sigjmp_buf;
4141 
4142  if (!ignore_till_sync)
4143  send_ready_for_query = true; /* initially, or after error */
4144 
4145  /*
4146  * Non-error queries loop here.
4147  */
4148 
4149  for (;;)
4150  {
4151  /*
4152  * At top of loop, reset extended-query-message flag, so that any
4153  * errors encountered in "idle" state don't provoke skip.
4154  */
4156 
4157  /*
4158  * Release storage left over from prior query cycle, and create a new
4159  * query input buffer in the cleared MessageContext.
4160  */
4163 
4164  initStringInfo(&input_message);
4165 
4166  /*
4167  * Also consider releasing our catalog snapshot if any, so that it's
4168  * not preventing advance of global xmin while we wait for the client.
4169  */
4171 
4172  /*
4173  * (1) If we've reached idle state, tell the frontend we're ready for
4174  * a new query.
4175  *
4176  * Note: this includes fflush()'ing the last of the prior output.
4177  *
4178  * This is also a good time to send collected statistics to the
4179  * collector, and to update the PS stats display. We avoid doing
4180  * those every time through the message loop because it'd slow down
4181  * processing of batched messages, and because we don't want to report
4182  * uncommitted updates (that confuses autovacuum). The notification
4183  * processor wants a call too, if we are not in a transaction block.
4184  */
4185  if (send_ready_for_query)
4186  {
4188  {
4189  set_ps_display("idle in transaction (aborted)", false);
4191 
4192  /* Start the idle-in-transaction timer */
4194  {
4195  disable_idle_in_transaction_timeout = true;
4198  }
4199  }
4201  {
4202  set_ps_display("idle in transaction", false);
4204 
4205  /* Start the idle-in-transaction timer */
4207  {
4208  disable_idle_in_transaction_timeout = true;
4211  }
4212  }
4213  else
4214  {
4215  /* Send out notify signals and transmit self-notifies */
4217 
4218  /*
4219  * Also process incoming notifies, if any. This is mostly to
4220  * ensure stable behavior in tests: if any notifies were
4221  * received during the just-finished transaction, they'll be
4222  * seen by the client before ReadyForQuery is.
4223  */
4226 
4227  pgstat_report_stat(false);
4228 
4229  set_ps_display("idle", false);
4231  }
4232 
4234  send_ready_for_query = false;
4235  }
4236 
4237  /*
4238  * (2) Allow asynchronous signals to be executed immediately if they
4239  * come in while we are waiting for client input. (This must be
4240  * conditional since we don't want, say, reads on behalf of COPY FROM
4241  * STDIN doing the same thing.)
4242  */
4243  DoingCommandRead = true;
4244 
4245  /*
4246  * (3) read a command (loop blocks here)
4247  */
4248  firstchar = ReadCommand(&input_message);
4249 
4250  /*
4251  * (4) disable async signal conditions again.
4252  *
4253  * Query cancel is supposed to be a no-op when there is no query in
4254  * progress, so if a query cancel arrived while we were idle, just
4255  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4256  * it's called when DoingCommandRead is set, so check for interrupts
4257  * before resetting DoingCommandRead.
4258  */
4260  DoingCommandRead = false;
4261 
4262  /*
4263  * (5) turn off the idle-in-transaction timeout
4264  */
4265  if (disable_idle_in_transaction_timeout)
4266  {
4268  disable_idle_in_transaction_timeout = false;
4269  }
4270 
4271  /*
4272  * (6) check for any other interesting events that happened while we
4273  * slept.
4274  */
4275  if (ConfigReloadPending)
4276  {
4277  ConfigReloadPending = false;
4279  }
4280 
4281  /*
4282  * (7) process the command. But ignore it if we're skipping till
4283  * Sync.
4284  */
4285  if (ignore_till_sync && firstchar != EOF)
4286  continue;
4287 
4288  switch (firstchar)
4289  {
4290  case 'Q': /* simple query */
4291  {
4292  const char *query_string;
4293 
4294  /* Set statement_timestamp() */
4296 
4297  query_string = pq_getmsgstring(&input_message);
4298  pq_getmsgend(&input_message);
4299 
4300  if (am_walsender)
4301  {
4302  if (!exec_replication_command(query_string))
4303  exec_simple_query(query_string);
4304  }
4305  else
4306  exec_simple_query(query_string);
4307 
4308  send_ready_for_query = true;
4309  }
4310  break;
4311 
4312  case 'P': /* parse */
4313  {
4314  const char *stmt_name;
4315  const char *query_string;
4316  int numParams;
4317  Oid *paramTypes = NULL;
4318 
4319  forbidden_in_wal_sender(firstchar);
4320 
4321  /* Set statement_timestamp() */
4323 
4324  stmt_name = pq_getmsgstring(&input_message);
4325  query_string = pq_getmsgstring(&input_message);
4326  numParams = pq_getmsgint(&input_message, 2);
4327  if (numParams > 0)
4328  {
4329  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4330  for (int i = 0; i < numParams; i++)
4331  paramTypes[i] = pq_getmsgint(&input_message, 4);
4332  }
4333  pq_getmsgend(&input_message);
4334 
4335  exec_parse_message(query_string, stmt_name,
4336  paramTypes, numParams);
4337  }
4338  break;
4339 
4340  case 'B': /* bind */
4341  forbidden_in_wal_sender(firstchar);
4342 
4343  /* Set statement_timestamp() */
4345 
4346  /*
4347  * this message is complex enough that it seems best to put
4348  * the field extraction out-of-line
4349  */
4350  exec_bind_message(&input_message);
4351  break;
4352 
4353  case 'E': /* execute */
4354  {
4355  const char *portal_name;
4356  int max_rows;
4357 
4358  forbidden_in_wal_sender(firstchar);
4359 
4360  /* Set statement_timestamp() */
4362 
4363  portal_name = pq_getmsgstring(&input_message);
4364  max_rows = pq_getmsgint(&input_message, 4);
4365  pq_getmsgend(&input_message);
4366 
4367  exec_execute_message(portal_name, max_rows);
4368  }
4369  break;
4370 
4371  case 'F': /* fastpath function call */
4372  forbidden_in_wal_sender(firstchar);
4373 
4374  /* Set statement_timestamp() */
4376 
4377  /* Report query to various monitoring facilities. */
4379  set_ps_display("<FASTPATH>", false);
4380 
4381  /* start an xact for this function invocation */
4383 
4384  /*
4385  * Note: we may at this point be inside an aborted
4386  * transaction. We can't throw error for that until we've
4387  * finished reading the function-call message, so
4388  * HandleFunctionRequest() must check for it after doing so.
4389  * Be careful not to do anything that assumes we're inside a
4390  * valid transaction here.
4391  */
4392 
4393  /* switch back to message context */
4395 
4396  HandleFunctionRequest(&input_message);
4397 
4398  /* commit the function-invocation transaction */
4400 
4401  send_ready_for_query = true;
4402  break;
4403 
4404  case 'C': /* close */
4405  {
4406  int close_type;
4407  const char *close_target;
4408 
4409  forbidden_in_wal_sender(firstchar);
4410 
4411  close_type = pq_getmsgbyte(&input_message);
4412  close_target = pq_getmsgstring(&input_message);
4413  pq_getmsgend(&input_message);
4414 
4415  switch (close_type)
4416  {
4417  case 'S':
4418  if (close_target[0] != '\0')
4419  DropPreparedStatement(close_target, false);
4420  else
4421  {
4422  /* special-case the unnamed statement */
4424  }
4425  break;
4426  case 'P':
4427  {
4428  Portal portal;
4429 
4430  portal = GetPortalByName(close_target);
4431  if (PortalIsValid(portal))
4432  PortalDrop(portal, false);
4433  }
4434  break;
4435  default:
4436  ereport(ERROR,
4437  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4438  errmsg("invalid CLOSE message subtype %d",
4439  close_type)));
4440  break;
4441  }
4442 
4444  pq_putemptymessage('3'); /* CloseComplete */
4445  }
4446  break;
4447 
4448  case 'D': /* describe */
4449  {
4450  int describe_type;
4451  const char *describe_target;
4452 
4453  forbidden_in_wal_sender(firstchar);
4454 
4455  /* Set statement_timestamp() (needed for xact) */
4457 
4458  describe_type = pq_getmsgbyte(&input_message);
4459  describe_target = pq_getmsgstring(&input_message);
4460  pq_getmsgend(&input_message);
4461 
4462  switch (describe_type)
4463  {
4464  case 'S':
4465  exec_describe_statement_message(describe_target);
4466  break;
4467  case 'P':
4468  exec_describe_portal_message(describe_target);
4469  break;
4470  default:
4471  ereport(ERROR,
4472  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4473  errmsg("invalid DESCRIBE message subtype %d",
4474  describe_type)));
4475  break;
4476  }
4477  }
4478  break;
4479 
4480  case 'H': /* flush */
4481  pq_getmsgend(&input_message);
4483  pq_flush();
4484  break;
4485 
4486  case 'S': /* sync */
4487  pq_getmsgend(&input_message);
4489  send_ready_for_query = true;
4490  break;
4491 
4492  /*
4493  * 'X' means that the frontend is closing down the socket. EOF
4494  * means unexpected loss of frontend connection. Either way,
4495  * perform normal shutdown.
4496  */
4497  case 'X':
4498  case EOF:
4499 
4500  /*
4501  * Reset whereToSendOutput to prevent ereport from attempting
4502  * to send any more messages to client.
4503  */
4506 
4507  /*
4508  * NOTE: if you are tempted to add more code here, DON'T!
4509  * Whatever you had in mind to do should be set up as an
4510  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4511  * it will fail to be called during other backend-shutdown
4512  * scenarios.
4513  */
4514  proc_exit(0);
4515 
4516  case 'd': /* copy data */
4517  case 'c': /* copy done */
4518  case 'f': /* copy fail */
4519 
4520  /*
4521  * Accept but ignore these messages, per protocol spec; we
4522  * probably got here because a COPY failed, and the frontend
4523  * is still sending data.
4524  */
4525  break;
4526 
4527  default:
4528  ereport(FATAL,
4529  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4530  errmsg("invalid frontend message type %d",
4531  firstchar)));
4532  }
4533  } /* end of input-reading loop */
4534 }
void InitializeTimeouts(void)
Definition: timeout.c:346
void AbortCurrentTransaction(void)
Definition: xact.c:3162
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2558
#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:6074
int MyProcPid
Definition: globals.c:40
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:504
static void finish_xact_command(void)
Definition: postgres.c:2630
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1461
#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:3119
#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:375
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:4544
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:608
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4653
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:380
void BaseInit(void)
Definition: postinit.c:547
#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:36
void FlushErrorState(void)
Definition: elog.c:1678
#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:2832
signed int int32
Definition: c.h:347
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2018
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4711
void jit_reset_after_error(void)
Definition: jit.c:128
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:91
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:598
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1177
void ProcessNotifyInterrupt(void)
Definition: async.c:1895
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1251
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:44
void WalSndSignals(void)
Definition: walsender.c:2969
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void InitProcess(void)
Definition: proc.c:304
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:67
bool IsUnderPostmaster
Definition: globals.c:109
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1598
Definition: dest.h:89
#define SIGHUP
Definition: win32_port.h:154
void PostgresSigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2872
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4919
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 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:59
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:1336
#define PortalIsValid(p)
Definition: portal.h:201
static void start_xact_command(void)
Definition: postgres.c:2610
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:299
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5402
void EmitErrorReport(void)
Definition: elog.c:1533
static StringInfoData row_description_buf
Definition: postgres.c:167
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:589
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:435
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:1223
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:525
char * dbname
Definition: streamutil.c:50
MemoryContext MessageContext
Definition: mcxt.c:48
sigjmp_buf * PG_exception_stack
Definition: elog.c:93
static const char * userDoption
Definition: postgres.c:156
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:817
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
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:2801
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2853
static void drop_unnamed_stmt(void)
Definition: postgres.c:2709
void ReplicationSlotCleanup(void)
Definition: slot.c:479
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:415
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:3508
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:532
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:260
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool ignore_till_sync
Definition: postgres.c:146
static MemoryContext row_description_context
Definition: postgres.c:166
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2734
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void exec_simple_query(const char *query_string)
Definition: postgres.c:979
void InitializeGUCOptions(void)
Definition: guc.c:5180
void pgstat_report_stat(bool force)
Definition: pgstat.c:811
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:571
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2463

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2872 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

2873 {
2874  int save_errno = errno;
2875 
2876  ConfigReloadPending = true;
2877  SetLatch(MyLatch);
2878 
2879  errno = save_errno;
2880 }
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 3508 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().

3510 {
3511  bool secure = (ctx == PGC_POSTMASTER);
3512  int errs = 0;
3513  GucSource gucsource;
3514  int flag;
3515 
3516  if (secure)
3517  {
3518  gucsource = PGC_S_ARGV; /* switches came from command line */
3519 
3520  /* Ignore the initial --single argument, if present */
3521  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3522  {
3523  argv++;
3524  argc--;
3525  }
3526  }
3527  else
3528  {
3529  gucsource = PGC_S_CLIENT; /* switches came from client */
3530  }
3531 
3532 #ifdef HAVE_INT_OPTERR
3533 
3534  /*
3535  * Turn this off because it's either printed to stderr and not the log
3536  * where we'd want it, or argv[0] is now "--single", which would make for
3537  * a weird error message. We print our own error message below.
3538  */
3539  opterr = 0;
3540 #endif
3541 
3542  /*
3543  * Parse command-line options. CAUTION: keep this in sync with
3544  * postmaster/postmaster.c (the option sets should not conflict) and with
3545  * the common help() function in main/main.c.
3546  */
3547  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3548  {
3549  switch (flag)
3550  {
3551  case 'B':
3552  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3553  break;
3554 
3555  case 'b':
3556  /* Undocumented flag used for binary upgrades */
3557  if (secure)
3558  IsBinaryUpgrade = true;
3559  break;
3560 
3561  case 'C':
3562  /* ignored for consistency with the postmaster */
3563  break;
3564 
3565  case 'D':
3566  if (secure)
3567  userDoption = strdup(optarg);
3568  break;
3569 
3570  case 'd':
3571  set_debug_options(atoi(optarg), ctx, gucsource);
3572  break;
3573 
3574  case 'E':
3575  if (secure)
3576  EchoQuery = true;
3577  break;
3578 
3579  case 'e':
3580  SetConfigOption("datestyle", "euro", ctx, gucsource);
3581  break;
3582 
3583  case 'F':
3584  SetConfigOption("fsync", "false", ctx, gucsource);
3585  break;
3586 
3587  case 'f':
3588  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3589  errs++;
3590  break;
3591 
3592  case 'h':
3593  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3594  break;
3595 
3596  case 'i':
3597  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3598  break;
3599 
3600  case 'j':
3601  if (secure)
3602  UseSemiNewlineNewline = true;
3603  break;
3604 
3605  case 'k':
3606  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3607  break;
3608 
3609  case 'l':
3610  SetConfigOption("ssl", "true", ctx, gucsource);
3611  break;
3612 
3613  case 'N':
3614  SetConfigOption("max_connections", optarg, ctx, gucsource);
3615  break;
3616 
3617  case 'n':
3618  /* ignored for consistency with postmaster */
3619  break;
3620 
3621  case 'O':
3622  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3623  break;
3624 
3625  case 'o':
3626  errs++;
3627  break;
3628 
3629  case 'P':
3630  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3631  break;
3632 
3633  case 'p':
3634  SetConfigOption("port", optarg, ctx, gucsource);
3635  break;
3636 
3637  case 'r':
3638  /* send output (stdout and stderr) to the given file */
3639  if (secure)
3641  break;
3642 
3643  case 'S':
3644  SetConfigOption("work_mem", optarg, ctx, gucsource);
3645  break;
3646 
3647  case 's':
3648  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3649  break;
3650 
3651  case 'T':
3652  /* ignored for consistency with the postmaster */
3653  break;
3654 
3655  case 't':
3656  {
3657  const char *tmp = get_stats_option_name(optarg);
3658 
3659  if (tmp)
3660  SetConfigOption(tmp, "true", ctx, gucsource);
3661  else
3662  errs++;
3663  break;
3664  }
3665 
3666  case 'v':
3667 
3668  /*
3669  * -v is no longer used in normal operation, since
3670  * FrontendProtocol is already set before we get here. We keep
3671  * the switch only for possible use in standalone operation,
3672  * in case we ever support using normal FE/BE protocol with a
3673  * standalone backend.
3674  */
3675  if (secure)
3677  break;
3678 
3679  case 'W':
3680  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3681  break;
3682 
3683  case 'c':
3684  case '-':
3685  {
3686  char *name,
3687  *value;
3688 
3689  ParseLongOption(optarg, &name, &value);
3690  if (!value)
3691  {
3692  if (flag == '-')
3693  ereport(ERROR,
3694  (errcode(ERRCODE_SYNTAX_ERROR),
3695  errmsg("--%s requires a value",
3696  optarg)));
3697  else
3698  ereport(ERROR,
3699  (errcode(ERRCODE_SYNTAX_ERROR),
3700  errmsg("-c %s requires a value",
3701  optarg)));
3702  }
3703  SetConfigOption(name, value, ctx, gucsource);
3704  free(name);
3705  if (value)
3706  free(value);
3707  break;
3708  }
3709 
3710  default:
3711  errs++;
3712  break;
3713  }
3714 
3715  if (errs)
3716  break;
3717  }
3718 
3719  /*
3720  * Optional database name should be there only if *dbname is NULL.
3721  */
3722  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3723  *dbname = strdup(argv[optind++]);
3724 
3725  if (errs || argc != optind)
3726  {
3727  if (errs)
3728  optind--; /* complain about the previous argument */
3729 
3730  /* spell the error message a bit differently depending on context */
3731  if (IsUnderPostmaster)
3732  ereport(FATAL,
3733  (errcode(ERRCODE_SYNTAX_ERROR),
3734  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3735  errhint("Try \"%s --help\" for more information.", progname)));
3736  else
3737  ereport(FATAL,
3738  (errcode(ERRCODE_SYNTAX_ERROR),
3739  errmsg("%s: invalid command-line argument: %s",
3740  progname, argv[optind]),
3741  errhint("Try \"%s --help\" for more information.", progname)));
3742  }
3743 
3744  /*
3745  * Reset getopt(3) library so that it will work correctly in subprocesses
3746  * or when this function is called a second time with another array.
3747  */
3748  optind = 1;
3749 #ifdef HAVE_INT_OPTRESET
3750  optreset = 1; /* some systems need this too */
3751 #endif
3752 }
int errhint(const char *fmt,...)
Definition: elog.c:1069
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:10370
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3426
static struct @145 value
int errcode(int sqlerrcode)
Definition: elog.c:608
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3468
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3397
const char * progname
Definition: pg_standby.c:36
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:7550
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:50
const char * name
Definition: encode.c:521
static bool EchoQuery
Definition: postgres.c:157
static const char * userDoption
Definition: postgres.c:156
static bool UseSemiNewlineNewline
Definition: postgres.c:158
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * optarg
Definition: getopt.c:52
ProtocolVersion FrontendProtocol
Definition: globals.c:28

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 525 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

526 {
527  int save_errno = errno;
528 
529  if (DoingCommandRead)
530  {
531  /* Check for general interrupts that arrived before/while reading */
533 
534  /* Process sinval catchup interrupts, if any */
537 
538  /* Process notify interrupts, if any */
541  }
542  else if (ProcDiePending)
543  {
544  /*
545  * We're dying. If there is no data available to read, then it's safe
546  * (and sane) to handle that now. If we haven't tried to read yet,
547  * make sure the process latch is set, so that if there is no data
548  * then we'll come back here and die. If we're done reading, also
549  * make sure the process latch is set, as we might've undesirably
550  * cleared it while reading.
551  */
552  if (blocked)
554  else
555  SetLatch(MyLatch);
556  }
557 
558  errno = save_errno;
559 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessNotifyInterrupt(void)
Definition: async.c:1895
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 571 of file postgres.c.

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

Referenced by secure_write().

572 {
573  int save_errno = errno;
574 
575  if (ProcDiePending)
576  {
577  /*
578  * We're dying. If it's not possible to write, then we should handle
579  * that immediately, else a stuck client could indefinitely delay our
580  * response to the signal. If we haven't tried to write yet, make
581  * sure the process latch is set, so that if the write would block
582  * then we'll come back here and die. If we're done writing, also
583  * make sure the process latch is set, as we might've undesirably
584  * cleared it while writing.
585  */
586  if (blocked)
587  {
588  /*
589  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
590  * do anything.
591  */
592  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
593  {
594  /*
595  * We don't want to send the client the error message, as a)
596  * that would possibly block again, and b) it would likely
597  * lead to loss of protocol sync because we may have already
598  * sent a partial protocol message.
599  */
602 
604  }
605  }
606  else
607  SetLatch(MyLatch);
608  }
609 
610  errno = save_errno;
611 }
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 3012 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().

3013 {
3014  /* OK to accept any interrupts now? */
3015  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3016  return;
3017  InterruptPending = false;
3018 
3019  if (ProcDiePending)
3020  {
3021  ProcDiePending = false;
3022  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3023  LockErrorCleanup();
3024  /* As in quickdie, don't risk sending to client during auth */
3028  ereport(FATAL,
3029  (errcode(ERRCODE_QUERY_CANCELED),
3030  errmsg("canceling authentication due to timeout")));
3031  else if (IsAutoVacuumWorkerProcess())
3032  ereport(FATAL,
3033  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3034  errmsg("terminating autovacuum process due to administrator command")));
3035  else if (IsLogicalWorker())
3036  ereport(FATAL,
3037  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3038  errmsg("terminating logical replication worker due to administrator command")));
3039  else if (IsLogicalLauncher())
3040  {
3041  ereport(DEBUG1,
3042  (errmsg("logical replication launcher shutting down")));
3043 
3044  /*
3045  * The logical replication launcher can be stopped at any time.
3046  * Use exit status 1 so the background worker is restarted.
3047  */
3048  proc_exit(1);
3049  }
3051  {
3053  ereport(FATAL,
3054  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3055  errmsg("terminating connection due to conflict with recovery"),
3057  }
3058  else if (RecoveryConflictPending)
3059  {
3060  /* Currently there is only one non-retryable recovery conflict */
3063  ereport(FATAL,
3064  (errcode(ERRCODE_DATABASE_DROPPED),
3065  errmsg("terminating connection due to conflict with recovery"),
3067  }
3068  else
3069  ereport(FATAL,
3070  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3071  errmsg("terminating connection due to administrator command")));
3072  }
3074  {
3075  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3076  LockErrorCleanup();
3077  /* don't send to client, we already know the connection to be dead. */
3079  ereport(FATAL,
3080  (errcode(ERRCODE_CONNECTION_FAILURE),
3081  errmsg("connection to client lost")));
3082  }
3083 
3084  /*
3085  * If a recovery conflict happens while we are waiting for input from the
3086  * client, the client is presumably just sitting idle in a transaction,
3087  * preventing recovery from making progress. Terminate the connection to
3088  * dislodge it.
3089  */
3091  {
3092  QueryCancelPending = false; /* this trumps QueryCancel */
3093  RecoveryConflictPending = false;
3094  LockErrorCleanup();
3096  ereport(FATAL,
3097  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3098  errmsg("terminating connection due to conflict with recovery"),
3100  errhint("In a moment you should be able to reconnect to the"
3101  " database and repeat your command.")));
3102  }
3103 
3104  /*
3105  * Don't allow query cancel interrupts while reading input from the
3106  * client, because we might lose sync in the FE/BE protocol. (Die
3107  * interrupts are OK, because we won't read any further messages from the
3108  * client in that case.)
3109  */
3111  {
3112  /*
3113  * Re-arm InterruptPending so that we process the cancel request as
3114  * soon as we're done reading the message.
3115  */
3116  InterruptPending = true;
3117  }
3118  else if (QueryCancelPending)
3119  {
3120  bool lock_timeout_occurred;
3121  bool stmt_timeout_occurred;
3122 
3123  QueryCancelPending = false;
3124 
3125  /*
3126  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3127  * need to clear both, so always fetch both.
3128  */
3129  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3130  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3131 
3132  /*
3133  * If both were set, we want to report whichever timeout completed
3134  * earlier; this ensures consistent behavior if the machine is slow
3135  * enough that the second timeout triggers before we get here. A tie
3136  * is arbitrarily broken in favor of reporting a lock timeout.
3137  */
3138  if (lock_timeout_occurred && stmt_timeout_occurred &&
3140  lock_timeout_occurred = false; /* report stmt timeout */
3141 
3142  if (lock_timeout_occurred)
3143  {
3144  LockErrorCleanup();
3145  ereport(ERROR,
3146  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3147  errmsg("canceling statement due to lock timeout")));
3148  }
3149  if (stmt_timeout_occurred)
3150  {
3151  LockErrorCleanup();
3152  ereport(ERROR,
3153  (errcode(ERRCODE_QUERY_CANCELED),
3154  errmsg("canceling statement due to statement timeout")));
3155  }
3157  {
3158  LockErrorCleanup();
3159  ereport(ERROR,
3160  (errcode(ERRCODE_QUERY_CANCELED),
3161  errmsg("canceling autovacuum task")));
3162  }
3164  {
3165  RecoveryConflictPending = false;
3166  LockErrorCleanup();
3168  ereport(ERROR,
3169  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3170  errmsg("canceling statement due to conflict with recovery"),
3172  }
3173 
3174  /*
3175  * If we are reading a command from the client, just ignore the cancel
3176  * request --- sending an extra error message won't accomplish
3177  * anything. Otherwise, go ahead and throw the error.
3178  */
3179  if (!DoingCommandRead)
3180  {
3181  LockErrorCleanup();
3182  ereport(ERROR,
3183  (errcode(ERRCODE_QUERY_CANCELED),
3184  errmsg("canceling statement due to user request")));
3185  }
3186  }
3187 
3189  {
3190  /* Has the timeout setting changed since last we looked? */
3192  ereport(FATAL,
3193  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3194  errmsg("terminating connection due to idle-in-transaction timeout")));
3195  else
3197 
3198  }
3199 
3202 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:36
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:682
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1069
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1489
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:37
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:608
bool IsLogicalWorker(void)
Definition: worker.c:1759
volatile bool ParallelMessagePending
Definition: parallel.c:112
bool ClientAuthInProgress
Definition: postmaster.c:352
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:968
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:3281
#define ereport(elevel, rest)
Definition: elog.h:141
void LockErrorCleanup(void)
Definition: proc.c:711
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:163
static bool RecoveryConflictPending
Definition: postgres.c:161
static bool RecoveryConflictRetryable
Definition: postgres.c:162
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:648
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2427
#define Assert(condition)
Definition: c.h:739
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:822
bool IsLogicalLauncher(void)
Definition: launcher.c:1078