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/interrupt.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 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 3368 of file postgres.c.

References max_stack_depth_bytes.

3369 {
3370  long newval_bytes = newval * 1024L;
3371 
3372  max_stack_depth_bytes = newval_bytes;
3373 }
static long max_stack_depth_bytes
Definition: postgres.c:112
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

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

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

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

Referenced by exec_execute_message(), and exec_simple_query().

2262 {
2263  ListCell *stmt_item;
2264 
2265  if (log_statement == LOGSTMT_NONE)
2266  return false;
2267  if (log_statement == LOGSTMT_ALL)
2268  return true;
2269 
2270  /* Else we have to inspect the statement(s) to see whether to log */
2271  foreach(stmt_item, stmt_list)
2272  {
2273  Node *stmt = (Node *) lfirst(stmt_item);
2274 
2275  if (GetCommandLogLevel(stmt) <= log_statement)
2276  return true;
2277  }
2278 
2279  return false;
2280 }
Definition: nodes.h:525
#define lfirst(lc)
Definition: pg_list.h:190
int log_statement
Definition: postgres.c:96
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3121

◆ check_max_stack_depth()

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

Definition at line 3351 of file postgres.c.

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

3352 {
3353  long newval_bytes = *newval * 1024L;
3354  long stack_rlimit = get_stack_depth_rlimit();
3355 
3356  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3357  {
3358  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3359  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3360  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3361  return false;
3362  }
3363  return true;
3364 }
#define GUC_check_errdetail
Definition: guc.h:414
long get_stack_depth_rlimit(void)
Definition: postgres.c:4551
#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 3288 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().

3289 {
3290  if (stack_is_too_deep())
3291  {
3292  ereport(ERROR,
3293  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3294  errmsg("stack depth limit exceeded"),
3295  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3296  "after ensuring the platform's stack depth limit is adequate.",
3297  max_stack_depth)));
3298  }
3299 }
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:99
int errmsg(const char *fmt,...)
Definition: elog.c:822
bool stack_is_too_deep(void)
Definition: postgres.c:3302

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2802 of file postgres.c.

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

Referenced by PostgresMain().

2803 {
2804  int save_errno = errno;
2805 
2806  /* Don't joggle the elbow of proc_exit */
2807  if (!proc_exit_inprogress)
2808  {
2809  InterruptPending = true;
2810  ProcDiePending = true;
2811  }
2812 
2813  /* If we're still here, waken anything waiting on the process latch */
2814  SetLatch(MyLatch);
2815 
2816  /*
2817  * If we're in single user mode, we want to quit immediately - we can't
2818  * rely on latches as they wouldn't work when stdin/stdout is a file.
2819  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2820  * effort just for the benefit of single user mode.
2821  */
2824 
2825  errno = save_errno;
2826 }
void SetLatch(Latch *latch)
Definition: latch.c:436
void ProcessInterrupts(void)
Definition: postgres.c:2995
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:140
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:54
CommandDest whereToSendOutput
Definition: postgres.c:91

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

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

4754 {
4757 }
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 2710 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

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

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

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

4733 {
4734  /* must be within an xact */
4736 
4737  if (StatementTimeout > 0)
4738  {
4741  }
4742  else
4743  {
4746  }
4747 }
static bool xact_started
Definition: postgres.c:133
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 2414 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().

2415 {
2417  errdetail("abort reason: recovery conflict");
2418 
2419  return 0;
2420 }
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 2363 of file postgres.c.

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

Referenced by exec_simple_query().

2364 {
2365  ListCell *parsetree_item;
2366 
2367  foreach(parsetree_item, raw_parsetree_list)
2368  {
2369  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2370 
2371  if (IsA(parsetree->stmt, ExecuteStmt))
2372  {
2373  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2374  PreparedStatement *pstmt;
2375 
2376  pstmt = FetchPreparedStatement(stmt->name, false);
2377  if (pstmt)
2378  {
2379  errdetail("prepare: %s", pstmt->plansource->query_string);
2380  return 0;
2381  }
2382  }
2383  }
2384 
2385  return 0;
2386 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Node * stmt
Definition: parsenodes.h:1506
int errdetail(const char *fmt,...)
Definition: elog.c:955
char * name
Definition: parsenodes.h:3422
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:469

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2394 of file postgres.c.

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

Referenced by exec_bind_message(), and exec_execute_message().

2395 {
2396  if (params && params->numParams > 0)
2397  {
2398  char *str;
2399 
2400  str = BuildParamLogString(params, NULL, 0);
2401  if (str && str[0] != '\0')
2402  errdetail("parameters: %s", str);
2403  }
2404 
2405  return 0;
2406 }
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 2428 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().

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

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

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

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

2560 {
2561  Portal portal;
2562 
2563  /*
2564  * Start up a transaction command. (Note that this will normally change
2565  * current memory context.) Nothing happens if we are already in one.
2566  */
2568 
2569  /* Switch back to message context */
2571 
2572  portal = GetPortalByName(portal_name);
2573  if (!PortalIsValid(portal))
2574  ereport(ERROR,
2575  (errcode(ERRCODE_UNDEFINED_CURSOR),
2576  errmsg("portal \"%s\" does not exist", portal_name)));
2577 
2578  /*
2579  * If we are in aborted transaction state, we can't run
2580  * SendRowDescriptionMessage(), because that needs catalog accesses.
2581  * Hence, refuse to Describe portals that return data. (We shouldn't just
2582  * refuse all Describes, since that might break the ability of some
2583  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2584  * blindly Describes whatever it does.)
2585  */
2587  portal->tupDesc)
2588  ereport(ERROR,
2589  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2590  errmsg("current transaction is aborted, "
2591  "commands ignored until end of transaction block"),
2592  errdetail_abort()));
2593 
2595  return; /* can't actually do anything... */
2596 
2597  if (portal->tupDesc)
2599  portal->tupDesc,
2600  FetchPortalTargetList(portal),
2601  portal->formats);
2602  else
2603  pq_putemptymessage('n'); /* NoData */
2604 }
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:2414
#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:2611
int16 * formats
Definition: portal.h:159
static StringInfoData row_description_buf
Definition: postgres.c:168
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:91
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 2464 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().

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

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

◆ exec_parse_message()

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

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

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

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

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

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

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2631 of file postgres.c.

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

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

2632 {
2633  /* cancel active statement timeout after each command */
2635 
2636  if (xact_started)
2637  {
2639 
2640 #ifdef MEMORY_CONTEXT_CHECKING
2641  /* Check all memory contexts that weren't freed during commit */
2642  /* (those that were, were checked before being deleted) */
2643  MemoryContextCheck(TopMemoryContext);
2644 #endif
2645 
2646 #ifdef SHOW_MEMORY_STATS
2647  /* Print mem stats after each commit for leak tracking */
2649 #endif
2650 
2651  xact_started = false;
2652  }
2653 }
void CommitTransactionCommand(void)
Definition: xact.c:2898
static void disable_statement_timeout(void)
Definition: postgres.c:4753
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:498
static bool xact_started
Definition: postgres.c:133
MemoryContext TopMemoryContext
Definition: mcxt.c:44

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2854 of file postgres.c.

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

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

2855 {
2856  /* We're not returning, so no need to save errno */
2857  ereport(ERROR,
2858  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2859  errmsg("floating-point exception"),
2860  errdetail("An invalid floating-point operation was signaled. "
2861  "This probably means an out-of-range result or an "
2862  "invalid operation, such as division by zero.")));
2863 }
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 4529 of file postgres.c.

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

Referenced by PostgresMain().

4530 {
4531  if (am_walsender)
4532  {
4533  if (firstchar == 'F')
4534  ereport(ERROR,
4535  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4536  errmsg("fastpath function calls not supported in a replication connection")));
4537  else
4538  ereport(ERROR,
4539  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4540  errmsg("extended query protocol not supported in a replication connection")));
4541  }
4542 }
int errcode(int sqlerrcode)
Definition: elog.c:608
bool am_walsender
Definition: walsender.c:115
#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 4551 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4552 {
4553 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4554  static long val = 0;
4555 
4556  /* This won't change after process launch, so check just once */
4557  if (val == 0)
4558  {
4559  struct rlimit rlim;
4560 
4561  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4562  val = -1;
4563  else if (rlim.rlim_cur == RLIM_INFINITY)
4564  val = LONG_MAX;
4565  /* rlim_cur is probably of an unsigned type, so check for overflow */
4566  else if (rlim.rlim_cur >= LONG_MAX)
4567  val = LONG_MAX;
4568  else
4569  val = rlim.rlim_cur;
4570  }
4571  return val;
4572 #else /* no getrlimit */
4573 #if defined(WIN32) || defined(__CYGWIN__)
4574  /* On Windows we set the backend stack size in src/backend/Makefile */
4575  return WIN32_STACK_RLIMIT;
4576 #else /* not windows ... give up */
4577  return -1;
4578 #endif
4579 #endif
4580 }
long val
Definition: informix.c:664

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3454 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3455 {
3456  switch (arg[0])
3457  {
3458  case 'p':
3459  if (optarg[1] == 'a') /* "parser" */
3460  return "log_parser_stats";
3461  else if (optarg[1] == 'l') /* "planner" */
3462  return "log_planner_stats";
3463  break;
3464 
3465  case 'e': /* "executor" */
3466  return "log_executor_stats";
3467  break;
3468  }
3469 
3470  return NULL;
3471 }
char * optarg
Definition: getopt.c:52
void * arg

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 300 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

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

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 212 of file postgres.c.

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

Referenced by ReadCommand().

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

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

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

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

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2680 of file postgres.c.

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

Referenced by exec_execute_message().

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

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

Referenced by exec_execute_message().

2696 {
2697  if (list_length(pstmts) == 1)
2698  {
2699  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2700 
2701  if (pstmt->commandType == CMD_UTILITY &&
2702  IsA(pstmt->utilityStmt, TransactionStmt))
2703  return true;
2704  }
2705  return false;
2706 }
#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 4696 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().

4697 {
4698  Port *port = MyProcPort;
4699  long secs;
4700  int usecs;
4701  int msecs;
4702  int hours,
4703  minutes,
4704  seconds;
4705 
4708  &secs, &usecs);
4709  msecs = usecs / 1000;
4710 
4711  hours = secs / SECS_PER_HOUR;
4712  secs %= SECS_PER_HOUR;
4713  minutes = secs / SECS_PER_MINUTE;
4714  seconds = secs % SECS_PER_MINUTE;
4715 
4716  ereport(LOG,
4717  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4718  "user=%s database=%s host=%s%s%s",
4719  hours, minutes, seconds, msecs,
4720  port->user_name, port->database_name, port->remote_host,
4721  port->remote_port[0] ? " port=" : "", port->remote_port)));
4722 }
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 676 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().

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

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

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

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

◆ pg_plan_query()

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

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

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

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

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

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

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

◆ process_postgres_switches()

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

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

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

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

Referenced by interactive_getc(), and secure_read().

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

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

Referenced by secure_write().

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

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 2995 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, ProcessProcSignalBarrier(), PROCSIG_RECOVERY_CONFLICT_DATABASE, ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

2996 {
2997  /* OK to accept any interrupts now? */
2998  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2999  return;
3000  InterruptPending = false;
3001 
3002  if (ProcDiePending)
3003  {
3004  ProcDiePending = false;
3005  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3006  LockErrorCleanup();
3007  /* As in quickdie, don't risk sending to client during auth */
3011  ereport(FATAL,
3012  (errcode(ERRCODE_QUERY_CANCELED),
3013  errmsg("canceling authentication due to timeout")));
3014  else if (IsAutoVacuumWorkerProcess())
3015  ereport(FATAL,
3016  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3017  errmsg("terminating autovacuum process due to administrator command")));
3018  else if (IsLogicalWorker())
3019  ereport(FATAL,
3020  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3021  errmsg("terminating logical replication worker due to administrator command")));
3022  else if (IsLogicalLauncher())
3023  {
3024  ereport(DEBUG1,
3025  (errmsg("logical replication launcher shutting down")));
3026 
3027  /*
3028  * The logical replication launcher can be stopped at any time.
3029  * Use exit status 1 so the background worker is restarted.
3030  */
3031  proc_exit(1);
3032  }
3034  {
3036  ereport(FATAL,
3037  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3038  errmsg("terminating connection due to conflict with recovery"),
3040  }
3041  else if (RecoveryConflictPending)
3042  {
3043  /* Currently there is only one non-retryable recovery conflict */
3046  ereport(FATAL,
3047  (errcode(ERRCODE_DATABASE_DROPPED),
3048  errmsg("terminating connection due to conflict with recovery"),
3050  }
3051  else
3052  ereport(FATAL,
3053  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3054  errmsg("terminating connection due to administrator command")));
3055  }
3057  {
3058  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3059  LockErrorCleanup();
3060  /* don't send to client, we already know the connection to be dead. */
3062  ereport(FATAL,
3063  (errcode(ERRCODE_CONNECTION_FAILURE),
3064  errmsg("connection to client lost")));
3065  }
3066 
3067  /*
3068  * If a recovery conflict happens while we are waiting for input from the
3069  * client, the client is presumably just sitting idle in a transaction,
3070  * preventing recovery from making progress. Terminate the connection to
3071  * dislodge it.
3072  */
3074  {
3075  QueryCancelPending = false; /* this trumps QueryCancel */
3076  RecoveryConflictPending = false;
3077  LockErrorCleanup();
3079  ereport(FATAL,
3080  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3081  errmsg("terminating connection due to conflict with recovery"),
3083  errhint("In a moment you should be able to reconnect to the"
3084  " database and repeat your command.")));
3085  }
3086 
3087  /*
3088  * Don't allow query cancel interrupts while reading input from the
3089  * client, because we might lose sync in the FE/BE protocol. (Die
3090  * interrupts are OK, because we won't read any further messages from the
3091  * client in that case.)
3092  */
3094  {
3095  /*
3096  * Re-arm InterruptPending so that we process the cancel request as
3097  * soon as we're done reading the message.
3098  */
3099  InterruptPending = true;
3100  }
3101  else if (QueryCancelPending)
3102  {
3103  bool lock_timeout_occurred;
3104  bool stmt_timeout_occurred;
3105 
3106  QueryCancelPending = false;
3107 
3108  /*
3109  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3110  * need to clear both, so always fetch both.
3111  */
3112  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3113  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3114 
3115  /*
3116  * If both were set, we want to report whichever timeout completed
3117  * earlier; this ensures consistent behavior if the machine is slow
3118  * enough that the second timeout triggers before we get here. A tie
3119  * is arbitrarily broken in favor of reporting a lock timeout.
3120  */
3121  if (lock_timeout_occurred && stmt_timeout_occurred &&
3123  lock_timeout_occurred = false; /* report stmt timeout */
3124 
3125  if (lock_timeout_occurred)
3126  {
3127  LockErrorCleanup();
3128  ereport(ERROR,
3129  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3130  errmsg("canceling statement due to lock timeout")));
3131  }
3132  if (stmt_timeout_occurred)
3133  {
3134  LockErrorCleanup();
3135  ereport(ERROR,
3136  (errcode(ERRCODE_QUERY_CANCELED),
3137  errmsg("canceling statement due to statement timeout")));
3138  }
3140  {
3141  LockErrorCleanup();
3142  ereport(ERROR,
3143  (errcode(ERRCODE_QUERY_CANCELED),
3144  errmsg("canceling autovacuum task")));
3145  }
3147  {
3148  RecoveryConflictPending = false;
3149  LockErrorCleanup();
3151  ereport(ERROR,
3152  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3153  errmsg("canceling statement due to conflict with recovery"),
3155  }
3156 
3157  /*
3158  * If we are reading a command from the client, just ignore the cancel
3159  * request --- sending an extra error message won't accomplish
3160  * anything. Otherwise, go ahead and throw the error.
3161  */
3162  if (!DoingCommandRead)
3163  {
3164  LockErrorCleanup();
3165  ereport(ERROR,
3166  (errcode(ERRCODE_QUERY_CANCELED),
3167  errmsg("canceling statement due to user request")));
3168  }
3169  }
3170 
3172  {
3173  /* Has the timeout setting changed since last we looked? */
3175  ereport(FATAL,
3176  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3177  errmsg("terminating connection due to idle-in-transaction timeout")));
3178  else
3180 
3181  }
3182 
3185 
3188 }
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:1484
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:429
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:1762
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:3276
#define ereport(elevel, rest)
Definition: elog.h:141
void LockErrorCleanup(void)
Definition: proc.c:711
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:164
static bool RecoveryConflictPending
Definition: postgres.c:162
static bool RecoveryConflictRetryable
Definition: postgres.c:163
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:648
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2428
#define Assert(condition)
Definition: c.h:739
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:35
static bool DoingCommandRead
Definition: postgres.c:140
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
int errmsg(const char *fmt,...)
Definition: elog.c:822
bool IsLogicalLauncher(void)
Definition: launcher.c:1062
CommandDest whereToSendOutput
Definition: postgres.c:91

◆ quickdie()