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, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, const char *query_string, 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 3392 of file postgres.c.

References max_stack_depth_bytes.

3393 {
3394  long newval_bytes = newval * 1024L;
3395 
3396  max_stack_depth_bytes = newval_bytes;
3397 }
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 2322 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().

2323 {
2324  if (log_duration || log_min_duration_sample >= 0 ||
2326  {
2327  long secs;
2328  int usecs;
2329  int msecs;
2330  bool exceeded_duration;
2331  bool exceeded_sample_duration;
2332  bool in_sample = false;
2333 
2336  &secs, &usecs);
2337  msecs = usecs / 1000;
2338 
2339  /*
2340  * This odd-looking test for log_min_duration_* being exceeded is
2341  * designed to avoid integer overflow with very long durations: don't
2342  * compute secs * 1000 until we've verified it will fit in int.
2343  */
2344  exceeded_duration = (log_min_duration_statement == 0 ||
2346  (secs > log_min_duration_statement / 1000 ||
2347  secs * 1000 + msecs >= log_min_duration_statement)));
2348 
2349  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2350  (log_min_duration_sample > 0 &&
2351  (secs > log_min_duration_sample / 1000 ||
2352  secs * 1000 + msecs >= log_min_duration_sample)));
2353 
2354  /*
2355  * Do not log if log_statement_sample_rate = 0. Log a sample if
2356  * log_statement_sample_rate <= 1 and avoid unnecessary random() call
2357  * if log_statement_sample_rate = 1.
2358  */
2359  if (exceeded_sample_duration)
2360  in_sample = log_statement_sample_rate != 0 &&
2361  (log_statement_sample_rate == 1 ||
2363 
2364  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2365  {
2366  snprintf(msec_str, 32, "%ld.%03d",
2367  secs * 1000 + msecs, usecs % 1000);
2368  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2369  return 2;
2370  else
2371  return 1;
2372  }
2373  }
2374 
2375  return 0;
2376 }
int log_min_duration_statement
Definition: guc.c:546
double log_statement_sample_rate
Definition: guc.c:550
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
long random(void)
Definition: random.c:22
int log_min_duration_sample
Definition: guc.c:545
#define MAX_RANDOM_VALUE
bool xact_is_sampled
Definition: xact.c:267
bool log_duration
Definition: guc.c:518
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1657
#define snprintf
Definition: port.h:193
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:791

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2283 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

2284 {
2285  ListCell *stmt_item;
2286 
2287  if (log_statement == LOGSTMT_NONE)
2288  return false;
2289  if (log_statement == LOGSTMT_ALL)
2290  return true;
2291 
2292  /* Else we have to inspect the statement(s) to see whether to log */
2293  foreach(stmt_item, stmt_list)
2294  {
2295  Node *stmt = (Node *) lfirst(stmt_item);
2296 
2297  if (GetCommandLogLevel(stmt) <= log_statement)
2298  return true;
2299  }
2300 
2301  return false;
2302 }
Definition: nodes.h:526
#define lfirst(lc)
Definition: pg_list.h:190
int log_statement
Definition: postgres.c:96
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3119

◆ check_max_stack_depth()

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

Definition at line 3375 of file postgres.c.

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

3376 {
3377  long newval_bytes = *newval * 1024L;
3378  long stack_rlimit = get_stack_depth_rlimit();
3379 
3380  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3381  {
3382  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3383  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3384  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3385  return false;
3386  }
3387  return true;
3388 }
#define GUC_check_errdetail
Definition: guc.h:415
long get_stack_depth_rlimit(void)
Definition: postgres.c:4575
#define newval
#define GUC_check_errhint
Definition: guc.h:419
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3312 of file postgres.c.

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

Referenced by AlterTypeRecurse(), apply_scanjoin_target_to_paths(), checkCond(), 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().

3313 {
3314  if (stack_is_too_deep())
3315  {
3316  ereport(ERROR,
3317  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3318  errmsg("stack depth limit exceeded"),
3319  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3320  "after ensuring the platform's stack depth limit is adequate.",
3321  max_stack_depth)));
3322  }
3323 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
int max_stack_depth
Definition: postgres.c:99
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
bool stack_is_too_deep(void)
Definition: postgres.c:3326

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2826 of file postgres.c.

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

Referenced by PostgresMain().

2827 {
2828  int save_errno = errno;
2829 
2830  /* Don't joggle the elbow of proc_exit */
2831  if (!proc_exit_inprogress)
2832  {
2833  InterruptPending = true;
2834  ProcDiePending = true;
2835  }
2836 
2837  /* If we're still here, waken anything waiting on the process latch */
2838  SetLatch(MyLatch);
2839 
2840  /*
2841  * If we're in single user mode, we want to quit immediately - we can't
2842  * rely on latches as they wouldn't work when stdin/stdout is a file.
2843  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2844  * effort just for the benefit of single user mode.
2845  */
2848 
2849  errno = save_errno;
2850 }
void SetLatch(Latch *latch)
Definition: latch.c:457
void ProcessInterrupts(void)
Definition: postgres.c:3019
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 4777 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().

4778 {
4781 }
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 2734 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2735 {
2736  /* paranoia to avoid a dangling pointer in case of error */
2737  if (unnamed_stmt_psrc)
2738  {
2740 
2741  unnamed_stmt_psrc = NULL;
2742  DropCachedPlan(psrc);
2743  }
2744 }
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 4756 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().

4757 {
4758  /* must be within an xact */
4760 
4761  if (StatementTimeout > 0)
4762  {
4765  }
4766  else
4767  {
4770  }
4771 }
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:738
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 2438 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().

2439 {
2441  errdetail("abort reason: recovery conflict");
2442 
2443  return 0;
2444 }
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:127
int errdetail(const char *fmt,...)
Definition: elog.c:957

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2385 of file postgres.c.

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

Referenced by exec_simple_query().

2386 {
2387  ListCell *parsetree_item;
2388 
2389  foreach(parsetree_item, raw_parsetree_list)
2390  {
2391  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2392 
2393  if (IsA(parsetree->stmt, ExecuteStmt))
2394  {
2395  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2396  PreparedStatement *pstmt;
2397 
2398  pstmt = FetchPreparedStatement(stmt->name, false);
2399  if (pstmt)
2400  {
2401  errdetail("prepare: %s", pstmt->plansource->query_string);
2402  return 0;
2403  }
2404  }
2405  }
2406 
2407  return 0;
2408 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Node * stmt
Definition: parsenodes.h:1507
int errdetail(const char *fmt,...)
Definition: elog.c:957
char * name
Definition: parsenodes.h:3435
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:469

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2418 of file postgres.c.

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

Referenced by exec_bind_message(), and exec_execute_message().

2419 {
2420  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2421  {
2422  char *str;
2423 
2424  str = BuildParamLogString(params, NULL, log_parameter_max_length);
2425  if (str && str[0] != '\0')
2426  errdetail("parameters: %s", str);
2427  }
2428 
2429  return 0;
2430 }
int log_parameter_max_length
Definition: guc.c:547
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:277
int errdetail(const char *fmt,...)
Definition: elog.c:957

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

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

2453 {
2454  switch (RecoveryConflictReason)
2455  {
2457  errdetail("User was holding shared buffer pin for too long.");
2458  break;
2460  errdetail("User was holding a relation lock for too long.");
2461  break;
2463  errdetail("User was or might have been using tablespace that must be dropped.");
2464  break;
2466  errdetail("User query might have needed to see row versions that must be removed.");
2467  break;
2469  errdetail("User transaction caused buffer deadlock with recovery.");
2470  break;
2472  errdetail("User was connected to a database that must be dropped.");
2473  break;
2474  default:
2475  break;
2476  /* no errdetail */
2477  }
2478 
2479  return 0;
2480 }
int errdetail(const char *fmt,...)
Definition: elog.c:957
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:164

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

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

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

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

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

2584 {
2585  Portal portal;
2586 
2587  /*
2588  * Start up a transaction command. (Note that this will normally change
2589  * current memory context.) Nothing happens if we are already in one.
2590  */
2592 
2593  /* Switch back to message context */
2595 
2596  portal = GetPortalByName(portal_name);
2597  if (!PortalIsValid(portal))
2598  ereport(ERROR,
2599  (errcode(ERRCODE_UNDEFINED_CURSOR),
2600  errmsg("portal \"%s\" does not exist", portal_name)));
2601 
2602  /*
2603  * If we are in aborted transaction state, we can't run
2604  * SendRowDescriptionMessage(), because that needs catalog accesses.
2605  * Hence, refuse to Describe portals that return data. (We shouldn't just
2606  * refuse all Describes, since that might break the ability of some
2607  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2608  * blindly Describes whatever it does.)
2609  */
2611  portal->tupDesc)
2612  ereport(ERROR,
2613  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2614  errmsg("current transaction is aborted, "
2615  "commands ignored until end of transaction block"),
2616  errdetail_abort()));
2617 
2619  return; /* can't actually do anything... */
2620 
2621  if (portal->tupDesc)
2623  portal->tupDesc,
2624  FetchPortalTargetList(portal),
2625  portal->formats);
2626  else
2627  pq_putemptymessage('n'); /* NoData */
2628 }
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:610
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2438
#define ERROR
Definition: elog.h:43
#define PortalIsValid(p)
Definition: portal.h:203
static void start_xact_command(void)
Definition: postgres.c:2635
int16 * formats
Definition: portal.h:161
static StringInfoData row_description_buf
Definition: postgres.c:168
TupleDesc tupDesc
Definition: portal.h:159
#define ereport(elevel,...)
Definition: elog.h:144
MemoryContext MessageContext
Definition: mcxt.c:48
int errmsg(const char *fmt,...)
Definition: elog.c:824
CommandDest whereToSendOutput
Definition: postgres.c:91
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:323
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 2488 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().

2489 {
2490  CachedPlanSource *psrc;
2491 
2492  /*
2493  * Start up a transaction command. (Note that this will normally change
2494  * current memory context.) Nothing happens if we are already in one.
2495  */
2497 
2498  /* Switch back to message context */
2500 
2501  /* Find prepared statement */
2502  if (stmt_name[0] != '\0')
2503  {
2504  PreparedStatement *pstmt;
2505 
2506  pstmt = FetchPreparedStatement(stmt_name, true);
2507  psrc = pstmt->plansource;
2508  }
2509  else
2510  {
2511  /* special-case the unnamed statement */
2512  psrc = unnamed_stmt_psrc;
2513  if (!psrc)
2514  ereport(ERROR,
2515  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2516  errmsg("unnamed prepared statement does not exist")));
2517  }
2518 
2519  /* Prepared statements shouldn't have changeable result descs */
2520  Assert(psrc->fixed_result);
2521 
2522  /*
2523  * If we are in aborted transaction state, we can't run
2524  * SendRowDescriptionMessage(), because that needs catalog accesses.
2525  * Hence, refuse to Describe statements that return data. (We shouldn't
2526  * just refuse all Describes, since that might break the ability of some
2527  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2528  * blindly Describes whatever it does.) We can Describe parameters
2529  * without doing anything dangerous, so we don't restrict that.
2530  */
2532  psrc->resultDesc)
2533  ereport(ERROR,
2534  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2535  errmsg("current transaction is aborted, "
2536  "commands ignored until end of transaction block"),
2537  errdetail_abort()));
2538 
2540  return; /* can't actually do anything... */
2541 
2542  /*
2543  * First describe the parameters...
2544  */
2545  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2546  * message type */
2548 
2549  for (int i = 0; i < psrc->num_params; i++)
2550  {
2551  Oid ptype = psrc->param_types[i];
2552 
2553  pq_sendint32(&row_description_buf, (int) ptype);
2554  }
2556 
2557  /*
2558  * Next send RowDescription or NoData to describe the result...
2559  */
2560  if (psrc->resultDesc)
2561  {
2562  List *tlist;
2563 
2564  /* Get the plan's primary targetlist */
2565  tlist = CachedPlanGetTargetList(psrc, NULL);
2566 
2568  psrc->resultDesc,
2569  tlist,
2570  NULL);
2571  }
2572  else
2573  pq_putemptymessage('n'); /* NoData */
2574 
2575 }
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:610
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2438
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc resultDesc
Definition: plancache.h:108
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define ERROR
Definition: elog.h:43
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1606
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:154
static void start_xact_command(void)
Definition: postgres.c:2635
static StringInfoData row_description_buf
Definition: postgres.c:168
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
MemoryContext MessageContext
Definition: mcxt.c:48
int errmsg(const char *fmt,...)
Definition: elog.c:824
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 2041 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, 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(), GetCommandTagName(), 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().

2042 {
2043  CommandDest dest;
2044  DestReceiver *receiver;
2045  Portal portal;
2046  bool completed;
2047  QueryCompletion qc;
2048  const char *sourceText;
2049  const char *prepStmtName;
2050  ParamListInfo portalParams;
2051  bool save_log_statement_stats = log_statement_stats;
2052  bool is_xact_command;
2053  bool execute_is_fetch;
2054  bool was_logged = false;
2055  char msec_str[32];
2056  ParamsErrorCbData params_data;
2057  ErrorContextCallback params_errcxt;
2058 
2059  /* Adjust destination to tell printtup.c what to do */
2060  dest = whereToSendOutput;
2061  if (dest == DestRemote)
2062  dest = DestRemoteExecute;
2063 
2064  portal = GetPortalByName(portal_name);
2065  if (!PortalIsValid(portal))
2066  ereport(ERROR,
2067  (errcode(ERRCODE_UNDEFINED_CURSOR),
2068  errmsg("portal \"%s\" does not exist", portal_name)));
2069 
2070  /*
2071  * If the original query was a null string, just return
2072  * EmptyQueryResponse.
2073  */
2074  if (portal->commandTag == CMDTAG_UNKNOWN)
2075  {
2076  Assert(portal->stmts == NIL);
2077  NullCommand(dest);
2078  return;
2079  }
2080 
2081  /* Does the portal contain a transaction command? */
2082  is_xact_command = IsTransactionStmtList(portal->stmts);
2083 
2084  /*
2085  * We must copy the sourceText and prepStmtName into MessageContext in
2086  * case the portal is destroyed during finish_xact_command. Can avoid the
2087  * copy if it's not an xact command, though.
2088  */
2089  if (is_xact_command)
2090  {
2091  sourceText = pstrdup(portal->sourceText);
2092  if (portal->prepStmtName)
2093  prepStmtName = pstrdup(portal->prepStmtName);
2094  else
2095  prepStmtName = "<unnamed>";
2096 
2097  /*
2098  * An xact command shouldn't have any parameters, which is a good
2099  * thing because they wouldn't be around after finish_xact_command.
2100  */
2101  portalParams = NULL;
2102  }
2103  else
2104  {
2105  sourceText = portal->sourceText;
2106  if (portal->prepStmtName)
2107  prepStmtName = portal->prepStmtName;
2108  else
2109  prepStmtName = "<unnamed>";
2110  portalParams = portal->portalParams;
2111  }
2112 
2113  /*
2114  * Report query to various monitoring facilities.
2115  */
2116  debug_query_string = sourceText;
2117 
2119 
2121 
2122  if (save_log_statement_stats)
2123  ResetUsage();
2124 
2125  BeginCommand(portal->commandTag, dest);
2126 
2127  /*
2128  * Create dest receiver in MessageContext (we don't want it in transaction
2129  * context, because that may get deleted if portal contains VACUUM).
2130  */
2131  receiver = CreateDestReceiver(dest);
2132  if (dest == DestRemoteExecute)
2133  SetRemoteDestReceiverParams(receiver, portal);
2134 
2135  /*
2136  * Ensure we are in a transaction command (this should normally be the
2137  * case already due to prior BIND).
2138  */
2140 
2141  /*
2142  * If we re-issue an Execute protocol request against an existing portal,
2143  * then we are only fetching more rows rather than completely re-executing
2144  * the query from the start. atStart is never reset for a v3 portal, so we
2145  * are safe to use this check.
2146  */
2147  execute_is_fetch = !portal->atStart;
2148 
2149  /* Log immediately if dictated by log_statement */
2150  if (check_log_statement(portal->stmts))
2151  {
2152  ereport(LOG,
2153  (errmsg("%s %s%s%s: %s",
2154  execute_is_fetch ?
2155  _("execute fetch from") :
2156  _("execute"),
2157  prepStmtName,
2158  *portal_name ? "/" : "",
2159  *portal_name ? portal_name : "",
2160  sourceText),
2161  errhidestmt(true),
2162  errdetail_params(portalParams)));
2163  was_logged = true;
2164  }
2165 
2166  /*
2167  * If we are in aborted transaction state, the only portals we can
2168  * actually run are those containing COMMIT or ROLLBACK commands.
2169  */
2171  !IsTransactionExitStmtList(portal->stmts))
2172  ereport(ERROR,
2173  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2174  errmsg("current transaction is aborted, "
2175  "commands ignored until end of transaction block"),
2176  errdetail_abort()));
2177 
2178  /* Check for cancel signal before we start execution */
2180 
2181  /*
2182  * Okay to run the portal. Set the error callback so that parameters are
2183  * logged. The parameters must have been saved during the bind phase.
2184  */
2185  params_data.portalName = portal->name;
2186  params_data.params = portalParams;
2187  params_errcxt.previous = error_context_stack;
2188  params_errcxt.callback = ParamsErrorCallback;
2189  params_errcxt.arg = (void *) &params_data;
2190  error_context_stack = &params_errcxt;
2191 
2192  if (max_rows <= 0)
2193  max_rows = FETCH_ALL;
2194 
2195  completed = PortalRun(portal,
2196  max_rows,
2197  true, /* always top level */
2198  !execute_is_fetch && max_rows == FETCH_ALL,
2199  receiver,
2200  receiver,
2201  &qc);
2202 
2203  receiver->rDestroy(receiver);
2204 
2205  /* Done executing; remove the params error callback */
2207 
2208  if (completed)
2209  {
2210  if (is_xact_command)
2211  {
2212  /*
2213  * If this was a transaction control statement, commit it. We
2214  * will start a new xact command for the next command (if any).
2215  */
2217  }
2218  else
2219  {
2220  /*
2221  * We need a CommandCounterIncrement after every query, except
2222  * those that start or end a transaction block.
2223  */
2225 
2226  /*
2227  * Disable statement timeout whenever we complete an Execute
2228  * message. The next protocol message will start a fresh timeout.
2229  */
2231  }
2232 
2233  /* Send appropriate CommandComplete to client */
2234  EndCommand(&qc, dest, false);
2235  }
2236  else
2237  {
2238  /* Portal run not complete, so send PortalSuspended */
2240  pq_putemptymessage('s');
2241  }
2242 
2243  /*
2244  * Emit duration logging if appropriate.
2245  */
2246  switch (check_log_duration(msec_str, was_logged))
2247  {
2248  case 1:
2249  ereport(LOG,
2250  (errmsg("duration: %s ms", msec_str),
2251  errhidestmt(true)));
2252  break;
2253  case 2:
2254  ereport(LOG,
2255  (errmsg("duration: %s ms %s %s%s%s: %s",
2256  msec_str,
2257  execute_is_fetch ?
2258  _("execute fetch from") :
2259  _("execute"),
2260  prepStmtName,
2261  *portal_name ? "/" : "",
2262  *portal_name ? portal_name : "",
2263  sourceText),
2264  errhidestmt(true),
2265  errdetail_params(portalParams)));
2266  break;
2267  }
2268 
2269  if (save_log_statement_stats)
2270  ShowUsage("EXECUTE MESSAGE STATISTICS");
2271 
2272  debug_query_string = NULL;
2273 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2719
#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:2655
CommandTag commandTag
Definition: portal.h:136
CommandDest
Definition: dest.h:87
bool log_statement_stats
Definition: guc.c:527
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3130
void ShowUsage(const char *title)
Definition: postgres.c:4618
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
int errcode(int sqlerrcode)
Definition: elog.c:610
int errhidestmt(bool hide_stmt)
Definition: elog.c:1142
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2438
#define LOG
Definition: elog.h:26
List * stmts
Definition: portal.h:138
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
ErrorContextCallback * error_context_stack
Definition: elog.c:92
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2322
void set_ps_display(const char *activity)
Definition: ps_status.c:349
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:672
void ResetUsage(void)
Definition: postgres.c:4611
static void disable_statement_timeout(void)
Definition: postgres.c:4777
ParamListInfo portalParams
Definition: portal.h:141
const char * name
Definition: portal.h:118
#define ERROR
Definition: elog.h:43
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:166
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2418
const char * debug_query_string
Definition: postgres.c:88
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2283
#define PortalIsValid(p)
Definition: portal.h:203
static void start_xact_command(void)
Definition: postgres.c:2635
void CommandCounterIncrement(void)
Definition: xact.c:1005
const char * sourceText
Definition: portal.h:135
#define ereport(elevel,...)
Definition: elog.h:144
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
const char * portalName
Definition: params.h:156
#define Assert(condition)
Definition: c.h:738
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2704
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:45
bool atStart
Definition: portal.h:190
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:103
int errmsg(const char *fmt,...)
Definition: elog.c:824
void ParamsErrorCallback(void *arg)
Definition: params.c:349
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandDest whereToSendOutput
Definition: postgres.c:91
#define _(x)
Definition: elog.c:88
const char * prepStmtName
Definition: portal.h:119
void NullCommand(CommandDest dest)
Definition: dest.c:227
#define FETCH_ALL
Definition: parsenodes.h:2748

◆ exec_parse_message()

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

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

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

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_requires_snapshot(), BeginCommand(), BeginImplicitTransactionBlock(), CHECK_FOR_INTERRUPTS, check_log_duration(), check_log_statement(), CommandCounterIncrement(), 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, GetCommandTagName(), 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().

984 {
986  MemoryContext oldcontext;
987  List *parsetree_list;
988  ListCell *parsetree_item;
989  bool save_log_statement_stats = log_statement_stats;
990  bool was_logged = false;
991  bool use_implicit_block;
992  char msec_str[32];
993 
994  /*
995  * Report query to various monitoring facilities.
996  */
997  debug_query_string = query_string;
998 
999  pgstat_report_activity(STATE_RUNNING, query_string);
1000 
1001  TRACE_POSTGRESQL_QUERY_START(query_string);
1002 
1003  /*
1004  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1005  * results because ResetUsage wasn't called.
1006  */
1007  if (save_log_statement_stats)
1008  ResetUsage();
1009 
1010  /*
1011  * Start up a transaction command. All queries generated by the
1012  * query_string will be in this same command block, *unless* we find a
1013  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1014  * one of those, else bad things will happen in xact.c. (Note that this
1015  * will normally change current memory context.)
1016  */
1018 
1019  /*
1020  * Zap any pre-existing unnamed statement. (While not strictly necessary,
1021  * it seems best to define simple-Query mode as if it used the unnamed
1022  * statement and portal; this ensures we recover any storage used by prior
1023  * unnamed operations.)
1024  */
1026 
1027  /*
1028  * Switch to appropriate context for constructing parsetrees.
1029  */
1030  oldcontext = MemoryContextSwitchTo(MessageContext);
1031 
1032  /*
1033  * Do basic parsing of the query or queries (this should be safe even if
1034  * we are in aborted transaction state!)
1035  */
1036  parsetree_list = pg_parse_query(query_string);
1037 
1038  /* Log immediately if dictated by log_statement */
1039  if (check_log_statement(parsetree_list))
1040  {
1041  ereport(LOG,
1042  (errmsg("statement: %s", query_string),
1043  errhidestmt(true),
1044  errdetail_execute(parsetree_list)));
1045  was_logged = true;
1046  }
1047 
1048  /*
1049  * Switch back to transaction context to enter the loop.
1050  */
1051  MemoryContextSwitchTo(oldcontext);
1052 
1053  /*
1054  * For historical reasons, if multiple SQL statements are given in a
1055  * single "simple Query" message, we execute them as a single transaction,
1056  * unless explicit transaction control commands are included to make
1057  * portions of the list be separate transactions. To represent this
1058  * behavior properly in the transaction machinery, we use an "implicit"
1059  * transaction block.
1060  */
1061  use_implicit_block = (list_length(parsetree_list) > 1);
1062 
1063  /*
1064  * Run through the raw parsetree(s) and process each one.
1065  */
1066  foreach(parsetree_item, parsetree_list)
1067  {
1068  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1069  bool snapshot_set = false;
1070  CommandTag commandTag;
1071  QueryCompletion qc;
1072  MemoryContext per_parsetree_context = NULL;
1073  List *querytree_list,
1074  *plantree_list;
1075  Portal portal;
1076  DestReceiver *receiver;
1077  int16 format;
1078 
1079  /*
1080  * Get the command name for use in status display (it also becomes the
1081  * default completion tag, down inside PortalRun). Set ps_status and
1082  * do any special start-of-SQL-command processing needed by the
1083  * destination.
1084  */
1085  commandTag = CreateCommandTag(parsetree->stmt);
1086 
1087  set_ps_display(GetCommandTagName(commandTag));
1088 
1089  BeginCommand(commandTag, dest);
1090 
1091  /*
1092  * If we are in an aborted transaction, reject all commands except
1093  * COMMIT/ABORT. It is important that this test occur before we try
1094  * to do parse analysis, rewrite, or planning, since all those phases
1095  * try to do database accesses, which may fail in abort state. (It
1096  * might be safe to allow some additional utility commands in this
1097  * state, but not many...)
1098  */
1100  !IsTransactionExitStmt(parsetree->stmt))
1101  ereport(ERROR,
1102  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1103  errmsg("current transaction is aborted, "
1104  "commands ignored until end of transaction block"),
1105  errdetail_abort()));
1106 
1107  /* Make sure we are in a transaction command */
1109 
1110  /*
1111  * If using an implicit transaction block, and we're not already in a
1112  * transaction block, start an implicit block to force this statement
1113  * to be grouped together with any following ones. (We must do this
1114  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1115  * list would cause later statements to not be grouped.)
1116  */
1117  if (use_implicit_block)
1119 
1120  /* If we got a cancel signal in parsing or prior command, quit */
1122 
1123  /*
1124  * Set up a snapshot if parse analysis/planning will need one.
1125  */
1126  if (analyze_requires_snapshot(parsetree))
1127  {
1129  snapshot_set = true;
1130  }
1131 
1132  /*
1133  * OK to analyze, rewrite, and plan this query.
1134  *
1135  * Switch to appropriate context for constructing query and plan trees
1136  * (these can't be in the transaction context, as that will get reset
1137  * when the command is COMMIT/ROLLBACK). If we have multiple
1138  * parsetrees, we use a separate context for each one, so that we can
1139  * free that memory before moving on to the next one. But for the
1140  * last (or only) parsetree, just use MessageContext, which will be
1141  * reset shortly after completion anyway. In event of an error, the
1142  * per_parsetree_context will be deleted when MessageContext is reset.
1143  */
1144  if (lnext(parsetree_list, parsetree_item) != NULL)
1145  {
1146  per_parsetree_context =
1148  "per-parsetree message context",
1150  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1151  }
1152  else
1153  oldcontext = MemoryContextSwitchTo(MessageContext);
1154 
1155  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1156  NULL, 0, NULL);
1157 
1158  plantree_list = pg_plan_queries(querytree_list, query_string,
1159  CURSOR_OPT_PARALLEL_OK, NULL);
1160 
1161  /*
1162  * Done with the snapshot used for parsing/planning.
1163  *
1164  * While it looks promising to reuse the same snapshot for query
1165  * execution (at least for simple protocol), unfortunately it causes
1166  * execution to use a snapshot that has been acquired before locking
1167  * any of the tables mentioned in the query. This creates user-
1168  * visible anomalies, so refrain. Refer to
1169  * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1170  */
1171  if (snapshot_set)
1173 
1174  /* If we got a cancel signal in analysis or planning, quit */
1176 
1177  /*
1178  * Create unnamed portal to run the query or queries in. If there
1179  * already is one, silently drop it.
1180  */
1181  portal = CreatePortal("", true, true);
1182  /* Don't display the portal in pg_cursors */
1183  portal->visible = false;
1184 
1185  /*
1186  * We don't have to copy anything into the portal, because everything
1187  * we are passing here is in MessageContext or the
1188  * per_parsetree_context, and so will outlive the portal anyway.
1189  */
1190  PortalDefineQuery(portal,
1191  NULL,
1192  query_string,
1193  commandTag,
1194  plantree_list,
1195  NULL);
1196 
1197  /*
1198  * Start the portal. No parameters here.
1199  */
1200  PortalStart(portal, NULL, 0, InvalidSnapshot);
1201 
1202  /*
1203  * Select the appropriate output format: text unless we are doing a
1204  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1205  * --- but it avoids grottiness in other places. Ah, the joys of
1206  * backward compatibility...)
1207  */
1208  format = 0; /* TEXT is default */
1209  if (IsA(parsetree->stmt, FetchStmt))
1210  {
1211  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1212 
1213  if (!stmt->ismove)
1214  {
1215  Portal fportal = GetPortalByName(stmt->portalname);
1216 
1217  if (PortalIsValid(fportal) &&
1218  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1219  format = 1; /* BINARY */
1220  }
1221  }
1222  PortalSetResultFormat(portal, 1, &format);
1223 
1224  /*
1225  * Now we can create the destination receiver object.
1226  */
1227  receiver = CreateDestReceiver(dest);
1228  if (dest == DestRemote)
1229  SetRemoteDestReceiverParams(receiver, portal);
1230 
1231  /*
1232  * Switch back to transaction context for execution.
1233  */
1234  MemoryContextSwitchTo(oldcontext);
1235 
1236  /*
1237  * Run the portal to completion, and then drop it (and the receiver).
1238  */
1239  (void) PortalRun(portal,
1240  FETCH_ALL,
1241  true, /* always top level */
1242  true,
1243  receiver,
1244  receiver,
1245  &qc);
1246 
1247  receiver->rDestroy(receiver);
1248 
1249  PortalDrop(portal, false);
1250 
1251  if (lnext(parsetree_list, parsetree_item) == NULL)
1252  {
1253  /*
1254  * If this is the last parsetree of the query string, close down
1255  * transaction statement before reporting command-complete. This
1256  * is so that any end-of-transaction errors are reported before
1257  * the command-complete message is issued, to avoid confusing
1258  * clients who will expect either a command-complete message or an
1259  * error, not one and then the other. Also, if we're using an
1260  * implicit transaction block, we must close that out first.
1261  */
1262  if (use_implicit_block)
1265  }
1266  else if (IsA(parsetree->stmt, TransactionStmt))
1267  {
1268  /*
1269  * If this was a transaction control statement, commit it. We will
1270  * start a new xact command for the next command.
1271  */
1273  }
1274  else
1275  {
1276  /*
1277  * We need a CommandCounterIncrement after every query, except
1278  * those that start or end a transaction block.
1279  */
1281 
1282  /*
1283  * Disable statement timeout between queries of a multi-query
1284  * string, so that the timeout applies separately to each query.
1285  * (Our next loop iteration will start a fresh timeout.)
1286  */
1288  }
1289 
1290  /*
1291  * Tell client that we're done with this query. Note we emit exactly
1292  * one EndCommand report for each raw parsetree, thus one for each SQL
1293  * command the client sent, regardless of rewriting. (But a command
1294  * aborted by error will not send an EndCommand report at all.)
1295  */
1296  EndCommand(&qc, dest, false);
1297 
1298  /* Now we may drop the per-parsetree context, if one was created. */
1299  if (per_parsetree_context)
1300  MemoryContextDelete(per_parsetree_context);
1301  } /* end loop over parsetrees */
1302 
1303  /*
1304  * Close down transaction statement, if one is open. (This will only do
1305  * something if the parsetree list was empty; otherwise the last loop
1306  * iteration already did it.)
1307  */
1309 
1310  /*
1311  * If there were no parsetrees, return EmptyQueryResponse message.
1312  */
1313  if (!parsetree_list)
1314  NullCommand(dest);
1315 
1316  /*
1317  * Emit duration logging if appropriate.
1318  */
1319  switch (check_log_duration(msec_str, was_logged))
1320  {
1321  case 1:
1322  ereport(LOG,
1323  (errmsg("duration: %s ms", msec_str),
1324  errhidestmt(true)));
1325  break;
1326  case 2:
1327  ereport(LOG,
1328  (errmsg("duration: %s ms statement: %s",
1329  msec_str, query_string),
1330  errhidestmt(true),
1331  errdetail_execute(parsetree_list)));
1332  break;
1333  }
1334 
1335  if (save_log_statement_stats)
1336  ShowUsage("QUERY STATISTICS");
1337 
1338  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1339 
1340  debug_query_string = NULL;
1341 }
signed short int16
Definition: c.h:354
CommandTag
Definition: cmdtag.h:20
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:577
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:611
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:357
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:430
static void finish_xact_command(void)
Definition: postgres.c:2655
bool visible
Definition: portal.h:196
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
CommandDest
Definition: dest.h:87
bool log_statement_stats
Definition: guc.c:527
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3130
void ShowUsage(const char *title)
Definition: postgres.c:4618
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:943
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2704
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:375
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
int errhidestmt(bool hide_stmt)
Definition: elog.c:1142
static int errdetail_abort(void)
Definition: postgres.c:2438
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define LOG
Definition: elog.h:26
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, CommandTag commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:281
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:2687
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2322
void set_ps_display(const char *activity)
Definition: ps_status.c:349
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:672
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2385
void ResetUsage(void)
Definition: postgres.c:4611
static void disable_statement_timeout(void)
Definition: postgres.c:4777
#define ERROR
Definition: elog.h:43
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:166
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:1507
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
void BeginImplicitTransactionBlock(void)
Definition: xact.c:4006
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
char * portalname
Definition: parsenodes.h:2755
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:2283
#define PortalIsValid(p)
Definition: portal.h:203
static void start_xact_command(void)
Definition: postgres.c:2635
void EndImplicitTransactionBlock(void)
Definition: xact.c:4031
bool ismove
Definition: parsenodes.h:2756
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define ereport(elevel,...)
Definition: elog.h:144
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2244
static int list_length(const List *l)
Definition: pg_list.h:169
MemoryContext MessageContext
Definition: mcxt.c:48
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:45
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2713
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:103
int errmsg(const char *fmt,...)
Definition: elog.c:824
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:467
static void drop_unnamed_stmt(void)
Definition: postgres.c:2734
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static char format
int cursorOptions
Definition: portal.h:146
CommandDest whereToSendOutput
Definition: postgres.c:91
Definition: pg_list.h:50
void NullCommand(CommandDest dest)
Definition: dest.c:227
#define FETCH_ALL
Definition: parsenodes.h:2748

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2655 of file postgres.c.

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

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

2656 {
2657  /* cancel active statement timeout after each command */
2659 
2660  if (xact_started)
2661  {
2663 
2664 #ifdef MEMORY_CONTEXT_CHECKING
2665  /* Check all memory contexts that weren't freed during commit */
2666  /* (those that were, were checked before being deleted) */
2667  MemoryContextCheck(TopMemoryContext);
2668 #endif
2669 
2670 #ifdef SHOW_MEMORY_STATS
2671  /* Print mem stats after each commit for leak tracking */
2673 #endif
2674 
2675  xact_started = false;
2676  }
2677 }
void CommitTransactionCommand(void)
Definition: xact.c:2913
static void disable_statement_timeout(void)
Definition: postgres.c:4777
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 2878 of file postgres.c.

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

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

2879 {
2880  /* We're not returning, so no need to save errno */
2881  ereport(ERROR,
2882  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2883  errmsg("floating-point exception"),
2884  errdetail("An invalid floating-point operation was signaled. "
2885  "This probably means an out-of-range result or an "
2886  "invalid operation, such as division by zero.")));
2887 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4553 of file postgres.c.

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

Referenced by PostgresMain().

4554 {
4555  if (am_walsender)
4556  {
4557  if (firstchar == 'F')
4558  ereport(ERROR,
4559  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4560  errmsg("fastpath function calls not supported in a replication connection")));
4561  else
4562  ereport(ERROR,
4563  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4564  errmsg("extended query protocol not supported in a replication connection")));
4565  }
4566 }
int errcode(int sqlerrcode)
Definition: elog.c:610
bool am_walsender
Definition: walsender.c:115
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4575 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3478 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3479 {
3480  switch (arg[0])
3481  {
3482  case 'p':
3483  if (optarg[1] == 'a') /* "parser" */
3484  return "log_parser_stats";
3485  else if (optarg[1] == 'l') /* "planner" */
3486  return "log_planner_stats";
3487  break;
3488 
3489  case 'e': /* "executor" */
3490  return "log_executor_stats";
3491  break;
3492  }
3493 
3494  return NULL;
3495 }
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:199
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 2687 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().

2688 {
2689  if (parsetree && IsA(parsetree, TransactionStmt))
2690  {
2691  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2692 
2693  if (stmt->kind == TRANS_STMT_COMMIT ||
2694  stmt->kind == TRANS_STMT_PREPARE ||
2695  stmt->kind == TRANS_STMT_ROLLBACK ||
2696  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2697  return true;
2698  }
2699  return false;
2700 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
TransactionStmtKind kind
Definition: parsenodes.h:3056

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2704 of file postgres.c.

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

Referenced by exec_execute_message().

2705 {
2706  if (list_length(pstmts) == 1)
2707  {
2708  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2709 
2710  if (pstmt->commandType == CMD_UTILITY &&
2712  return true;
2713  }
2714  return false;
2715 }
#define linitial_node(type, l)
Definition: pg_list.h:198
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2687
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 2719 of file postgres.c.

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

Referenced by exec_execute_message().

2720 {
2721  if (list_length(pstmts) == 1)
2722  {
2723  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2724 
2725  if (pstmt->commandType == CMD_UTILITY &&
2726  IsA(pstmt->utilityStmt, TransactionStmt))
2727  return true;
2728  }
2729  return false;
2730 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
#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 4720 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().

4721 {
4722  Port *port = MyProcPort;
4723  long secs;
4724  int usecs;
4725  int msecs;
4726  int hours,
4727  minutes,
4728  seconds;
4729 
4732  &secs, &usecs);
4733  msecs = usecs / 1000;
4734 
4735  hours = secs / SECS_PER_HOUR;
4736  secs %= SECS_PER_HOUR;
4737  minutes = secs / SECS_PER_MINUTE;
4738  seconds = secs % SECS_PER_MINUTE;
4739 
4740  ereport(LOG,
4741  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4742  "user=%s database=%s host=%s%s%s",
4743  hours, minutes, seconds, msecs,
4744  port->user_name, port->database_name, port->remote_host,
4745  port->remote_port[0] ? " port=" : "", port->remote_port)));
4746 }
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 SECS_PER_HOUR
Definition: timestamp.h:87
static int port
Definition: pg_regress.c:90
TimestampTz MyStartTimestamp
Definition: globals.c:42
#define ereport(elevel,...)
Definition: elog.h:144
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:824
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:524
void ShowUsage(const char *title)
Definition: postgres.c:4618
void ResetUsage(void)
Definition: postgres.c:4611
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:524
QueryEnvironment * p_queryEnv
Definition: parse_node.h:203
void ShowUsage(const char *title)
Definition: postgres.c:4618
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void ResetUsage(void)
Definition: postgres.c:4611
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:738
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:524
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3030
void ShowUsage(const char *title)
Definition: postgres.c:4618
void ResetUsage(void)
Definition: postgres.c:4611
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:214
#define copyObject(obj)
Definition: nodes.h:642
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,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

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

945 {
946  List *stmt_list = NIL;
947  ListCell *query_list;
948 
949  foreach(query_list, querytrees)
950  {
951  Query *query = lfirst_node(Query, query_list);
952  PlannedStmt *stmt;
953 
954  if (query->commandType == CMD_UTILITY)
955  {
956  /* Utility commands require no planning. */
957  stmt = makeNode(PlannedStmt);
958  stmt->commandType = CMD_UTILITY;
959  stmt->canSetTag = query->canSetTag;
960  stmt->utilityStmt = query->utilityStmt;
961  stmt->stmt_location = query->stmt_location;
962  stmt->stmt_len = query->stmt_len;
963  }
964  else
965  {
966  stmt = pg_plan_query(query, query_string, cursorOptions,
967  boundParams);
968  }
969 
970  stmt_list = lappend(stmt_list, stmt);
971  }
972 
973  return stmt_list;
974 }
#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:574
bool canSetTag
Definition: parsenodes.h:118
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857
Definition: pg_list.h:50
int stmt_len
Definition: parsenodes.h:181

◆ pg_plan_query()

PlannedStmt* pg_plan_query ( Query querytree,
const char *  query_string,
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().

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

◆ 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:524
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3030
#define castNode(_type_, nodeptr)
Definition: nodes.h:595
void ShowUsage(const char *title)
Definition: postgres.c:4618
#define LOG
Definition: elog.h:26
#define list_make1(x1)
Definition: pg_list.h:227
void ResetUsage(void)
Definition: postgres.c:4611
void pfree(void *pointer)
Definition: mcxt.c:1056
bool Debug_print_parse
Definition: guc.c:520
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:214
bool Debug_pretty_print
Definition: guc.c:522
char * nodeToString(const void *obj)
Definition: outfuncs.c:4331
bool Debug_print_rewritten
Definition: guc.c:521
#define copyObject(obj)
Definition: nodes.h:642
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 3777 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().

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

◆ process_postgres_switches()

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

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

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

3020 {
3021  /* OK to accept any interrupts now? */
3022  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3023  return;
3024  InterruptPending = false;
3025 
3026  if (ProcDiePending)
3027  {
3028  ProcDiePending = false;
3029  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3030  LockErrorCleanup();
3031  /* As in quickdie, don't risk sending to client during auth */
3035  ereport(FATAL,
3036  (errcode(ERRCODE_QUERY_CANCELED),
3037  errmsg("canceling authentication due to timeout")));
3038  else if (IsAutoVacuumWorkerProcess())
3039  ereport(FATAL,
3040  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3041  errmsg("terminating autovacuum process due to administrator command")));
3042  else if (IsLogicalWorker())
3043  ereport(FATAL,
3044  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3045  errmsg("terminating logical replication worker due to administrator command")));
3046  else if (IsLogicalLauncher())
3047  {
3048  ereport(DEBUG1,
3049  (errmsg("logical replication launcher shutting down")));
3050 
3051  /*
3052  * The logical replication launcher can be stopped at any time.
3053  * Use exit status 1 so the background worker is restarted.
3054  */
3055  proc_exit(1);
3056  }
3058  {
3060  ereport(FATAL,
3061  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3062  errmsg("terminating connection due to conflict with recovery"),
3064  }
3065  else if (RecoveryConflictPending)
3066  {
3067  /* Currently there is only one non-retryable recovery conflict */
3070  ereport(FATAL,
3071  (errcode(ERRCODE_DATABASE_DROPPED),
3072  errmsg("terminating connection due to conflict with recovery"),
3074  }
3075  else
3076  ereport(FATAL,
3077  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3078  errmsg("terminating connection due to administrator command")));
3079  }
3081  {
3082  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3083  LockErrorCleanup();
3084  /* don't send to client, we already know the connection to be dead. */
3086  ereport(FATAL,
3087  (errcode(ERRCODE_CONNECTION_FAILURE),
3088  errmsg("connection to client lost")));
3089  }
3090 
3091  /*
3092  * If a recovery conflict happens while we are waiting for input from the
3093  * client, the client is presumably just sitting idle in a transaction,
3094  * preventing recovery from making progress. Terminate the connection to
3095  * dislodge it.
3096  */
3098  {
3099  QueryCancelPending = false; /* this trumps QueryCancel */
3100  RecoveryConflictPending = false;
3101  LockErrorCleanup();
3103  ereport(FATAL,
3104  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3105  errmsg("terminating connection due to conflict with recovery"),
3107  errhint("In a moment you should be able to reconnect to the"
3108  " database and repeat your command.")));
3109  }
3110 
3111  /*
3112  * Don't allow query cancel interrupts while reading input from the
3113  * client, because we might lose sync in the FE/BE protocol. (Die
3114  * interrupts are OK, because we won't read any further messages from the
3115  * client in that case.)
3116  */
3118  {
3119  /*
3120  * Re-arm InterruptPending so that we process the cancel request as
3121  * soon as we're done reading the message.
3122  */
3123  InterruptPending = true;
3124  }
3125  else if (QueryCancelPending)
3126  {
3127  bool lock_timeout_occurred;
3128  bool stmt_timeout_occurred;
3129 
3130  QueryCancelPending = false;
3131 
3132  /*
3133  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3134  * need to clear both, so always fetch both.
3135  */
3136  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3137  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3138 
3139  /*
3140  * If both were set, we want to report whichever timeout completed
3141  * earlier; this ensures consistent behavior if the machine is slow
3142  * enough that the second timeout triggers before we get here. A tie
3143  * is arbitrarily broken in favor of reporting a lock timeout.
3144  */
3145  if (lock_timeout_occurred && stmt_timeout_occurred &&
3147  lock_timeout_occurred = false; /* report stmt timeout */
3148 
3149  if (lock_timeout_occurred)
3150  {
3151  LockErrorCleanup();
3152  ereport(ERROR,
3153  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3154  errmsg("canceling statement due to lock timeout")));
3155  }
3156  if (stmt_timeout_occurred)
3157  {
3158  LockErrorCleanup();
3159  ereport(ERROR,
3160  (errcode(ERRCODE_QUERY_CANCELED),
3161  errmsg("canceling statement due to statement timeout")));
3162  }
3164  {
3165  LockErrorCleanup();
3166  ereport(ERROR,
3167  (errcode(ERRCODE_QUERY_CANCELED),
3168  errmsg("canceling autovacuum task")));
3169  }
3171  {
3172  RecoveryConflictPending = false;
3173  LockErrorCleanup();
3175  ereport(ERROR,
3176  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3177  errmsg("canceling statement due to conflict with recovery"),
3179  }
3180 
3181  /*
3182  * If we are reading a command from the client, just ignore the cancel
3183  * request --- sending an extra error message won't accomplish
3184  * anything. Otherwise, go ahead and throw the error.
3185  */
3186  if (!DoingCommandRead)
3187  {
3188  LockErrorCleanup();
3189  ereport(ERROR,
3190  (errcode(ERRCODE_QUERY_CANCELED),
3191  errmsg("canceling statement due to user request")));
3192  }
3193  }
3194 
3196  {
3197  /* Has the timeout setting changed since last we looked? */
3199  ereport(FATAL,
3200  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3201  errmsg("terminating connection due to idle-in-transaction timeout")));
3202  else
3204 
3205  }
3206 
3209 
3212 }
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:1071
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1538
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:610
bool IsLogicalWorker(void)
Definition: worker.c:1825
volatile bool ParallelMessagePending
Definition: parallel.c:115
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:1002
Definition: dest.h:89
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:3302
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:2452
#define ereport(elevel,...)
Definition: elog.h:144