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/pmsignal.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 3457 of file postgres.c.

References max_stack_depth_bytes.

3458 {
3459  long newval_bytes = newval * 1024L;
3460 
3461  max_stack_depth_bytes = newval_bytes;
3462 }
static long max_stack_depth_bytes
Definition: postgres.c:113
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

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

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

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2284 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

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

◆ check_max_stack_depth()

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

Definition at line 3440 of file postgres.c.

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

3441 {
3442  long newval_bytes = *newval * 1024L;
3443  long stack_rlimit = get_stack_depth_rlimit();
3444 
3445  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3446  {
3447  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3448  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3449  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3450  return false;
3451  }
3452  return true;
3453 }
#define GUC_check_errdetail
Definition: guc.h:417
long get_stack_depth_rlimit(void)
Definition: postgres.c:4660
#define newval
#define GUC_check_errhint
Definition: guc.h:421
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3377 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(), 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(), hash_record(), hash_record_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_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3378 {
3379  if (stack_is_too_deep())
3380  {
3381  ereport(ERROR,
3382  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3383  errmsg("stack depth limit exceeded"),
3384  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3385  "after ensuring the platform's stack depth limit is adequate.",
3386  max_stack_depth)));
3387  }
3388 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
int max_stack_depth
Definition: postgres.c:100
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:915
bool stack_is_too_deep(void)
Definition: postgres.c:3391

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2857 of file postgres.c.

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

Referenced by PostgresMain().

2858 {
2859  int save_errno = errno;
2860 
2861  /* Don't joggle the elbow of proc_exit */
2862  if (!proc_exit_inprogress)
2863  {
2864  InterruptPending = true;
2865  ProcDiePending = true;
2866  }
2867 
2868  /* for the statistics collector */
2870 
2871  /* If we're still here, waken anything waiting on the process latch */
2872  SetLatch(MyLatch);
2873 
2874  /*
2875  * If we're in single user mode, we want to quit immediately - we can't
2876  * rely on latches as they wouldn't work when stdin/stdout is a file.
2877  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2878  * effort just for the benefit of single user mode.
2879  */
2882 
2883  errno = save_errno;
2884 }
SessionEndType pgStatSessionEndCause
Definition: pgstat.c:263
void SetLatch(Latch *latch)
Definition: latch.c:505
void ProcessInterrupts(void)
Definition: postgres.c:3065
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:141
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:55
CommandDest whereToSendOutput
Definition: postgres.c:92

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

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

4863 {
4866 }
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:716

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2735 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

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

2736 {
2737  /* paranoia to avoid a dangling pointer in case of error */
2738  if (unnamed_stmt_psrc)
2739  {
2741 
2742  unnamed_stmt_psrc = NULL;
2743  DropCachedPlan(psrc);
2744  }
2745 }
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:155
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:498

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

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

4842 {
4843  /* must be within an xact */
4845 
4846  if (StatementTimeout > 0)
4847  {
4850  }
4851  else
4852  {
4855  }
4856 }
static bool xact_started
Definition: postgres.c:134
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:524
#define Assert(condition)
Definition: c.h:792
int StatementTimeout
Definition: proc.c:61
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:716

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

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

2440 {
2442  errdetail("abort reason: recovery conflict");
2443 
2444  return 0;
2445 }
PGPROC * MyProc
Definition: proc.c:68
bool recoveryConflictPending
Definition: proc.h:167
int errdetail(const char *fmt,...)
Definition: elog.c:1048

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2386 of file postgres.c.

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

Referenced by exec_simple_query().

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

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

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

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

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

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

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

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

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

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

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

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

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

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

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

◆ exec_parse_message()

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

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

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

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 984 of file postgres.c.

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

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

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2656 of file postgres.c.

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

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

2657 {
2658  /* cancel active statement timeout after each command */
2660 
2661  if (xact_started)
2662  {
2664 
2665 #ifdef MEMORY_CONTEXT_CHECKING
2666  /* Check all memory contexts that weren't freed during commit */
2667  /* (those that were, were checked before being deleted) */
2668  MemoryContextCheck(TopMemoryContext);
2669 #endif
2670 
2671 #ifdef SHOW_MEMORY_STATS
2672  /* Print mem stats after each commit for leak tracking */
2674 #endif
2675 
2676  xact_started = false;
2677  }
2678 }
void CommitTransactionCommand(void)
Definition: xact.c:2948
static void disable_statement_timeout(void)
Definition: postgres.c:4862
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:499
static bool xact_started
Definition: postgres.c:134
MemoryContext TopMemoryContext
Definition: mcxt.c:44

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2912 of file postgres.c.

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

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

2913 {
2914  /* We're not returning, so no need to save errno */
2915  ereport(ERROR,
2916  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2917  errmsg("floating-point exception"),
2918  errdetail("An invalid floating-point operation was signaled. "
2919  "This probably means an out-of-range result or an "
2920  "invalid operation, such as division by zero.")));
2921 }
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4638 of file postgres.c.

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

Referenced by PostgresMain().

4639 {
4640  if (am_walsender)
4641  {
4642  if (firstchar == 'F')
4643  ereport(ERROR,
4644  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4645  errmsg("fastpath function calls not supported in a replication connection")));
4646  else
4647  ereport(ERROR,
4648  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4649  errmsg("extended query protocol not supported in a replication connection")));
4650  }
4651 }
int errcode(int sqlerrcode)
Definition: elog.c:704
bool am_walsender
Definition: walsender.c:115
#define ERROR
Definition: elog.h:45
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4660 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4661 {
4662 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4663  static long val = 0;
4664 
4665  /* This won't change after process launch, so check just once */
4666  if (val == 0)
4667  {
4668  struct rlimit rlim;
4669 
4670  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4671  val = -1;
4672  else if (rlim.rlim_cur == RLIM_INFINITY)
4673  val = LONG_MAX;
4674  /* rlim_cur is probably of an unsigned type, so check for overflow */
4675  else if (rlim.rlim_cur >= LONG_MAX)
4676  val = LONG_MAX;
4677  else
4678  val = rlim.rlim_cur;
4679  }
4680  return val;
4681 #else /* no getrlimit */
4682 #if defined(WIN32) || defined(__CYGWIN__)
4683  /* On Windows we set the backend stack size in src/backend/Makefile */
4684  return WIN32_STACK_RLIMIT;
4685 #else /* not windows ... give up */
4686  return -1;
4687 #endif
4688 #endif
4689 }
long val
Definition: informix.c:664

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3543 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3544 {
3545  switch (arg[0])
3546  {
3547  case 'p':
3548  if (optarg[1] == 'a') /* "parser" */
3549  return "log_parser_stats";
3550  else if (optarg[1] == 'l') /* "planner" */
3551  return "log_planner_stats";
3552  break;
3553 
3554  case 'e': /* "executor" */
3555  return "log_executor_stats";
3556  break;
3557  }
3558 
3559  return NULL;
3560 }
char * optarg
Definition: getopt.c:52
void * arg

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 301 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

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

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 213 of file postgres.c.

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

Referenced by ReadCommand().

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

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

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

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

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2705 of file postgres.c.

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

Referenced by exec_execute_message().

2706 {
2707  if (list_length(pstmts) == 1)
2708  {
2709  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2710 
2711  if (pstmt->commandType == CMD_UTILITY &&
2713  return true;
2714  }
2715  return false;
2716 }
#define linitial_node(type, l)
Definition: pg_list.h:177
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2688
Node * utilityStmt
Definition: plannodes.h:86
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:149

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2720 of file postgres.c.

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

Referenced by exec_execute_message().

2721 {
2722  if (list_length(pstmts) == 1)
2723  {
2724  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2725 
2726  if (pstmt->commandType == CMD_UTILITY &&
2727  IsA(pstmt->utilityStmt, TransactionStmt))
2728  return true;
2729  }
2730  return false;
2731 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define linitial_node(type, l)
Definition: pg_list.h:177
Node * utilityStmt
Definition: plannodes.h:86
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:149

◆ log_disconnections()

static void log_disconnections ( int  code,
Datum  arg 
)
static

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

4806 {
4807  Port *port = MyProcPort;
4808  long secs;
4809  int usecs;
4810  int msecs;
4811  int hours,
4812  minutes,
4813  seconds;
4814 
4817  &secs, &usecs);
4818  msecs = usecs / 1000;
4819 
4820  hours = secs / SECS_PER_HOUR;
4821  secs %= SECS_PER_HOUR;
4822  minutes = secs / SECS_PER_MINUTE;
4823  seconds = secs % SECS_PER_MINUTE;
4824 
4825  ereport(LOG,
4826  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4827  "user=%s database=%s host=%s%s%s",
4828  hours, minutes, seconds, msecs,
4829  port->user_name, port->database_name, port->remote_host,
4830  port->remote_port[0] ? " port=" : "", port->remote_port)));
4831 }
struct Port * MyProcPort
Definition: globals.c:44
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
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:92
TimestampTz MyStartTimestamp
Definition: globals.c:43
#define ereport(elevel,...)
Definition: elog.h:155
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:915
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1654
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 677 of file postgres.c.

References log_parser_stats, parse_analyze(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopyTo(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

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

719 {
720  ParseState *pstate;
721  Query *query;
722  List *querytree_list;
723 
724  Assert(query_string != NULL); /* required as of 8.4 */
725 
726  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
727 
728  /*
729  * (1) Perform parse analysis.
730  */
731  if (log_parser_stats)
732  ResetUsage();
733 
734  pstate = make_parsestate(NULL);
735  pstate->p_sourcetext = query_string;
736  pstate->p_queryEnv = queryEnv;
737  (*parserSetup) (pstate, parserSetupArg);
738 
739  query = transformTopLevelStmt(pstate, parsetree);
740 
742  (*post_parse_analyze_hook) (pstate, query);
743 
744  free_parsestate(pstate);
745 
746  if (log_parser_stats)
747  ShowUsage("PARSE ANALYSIS STATISTICS");
748 
749  /*
750  * (2) Rewrite the queries, as necessary
751  */
752  querytree_list = pg_rewrite_query(query);
753 
754  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
755 
756  return querytree_list;
757 }
bool log_parser_stats
Definition: guc.c:521
QueryEnvironment * p_queryEnv
Definition: parse_node.h:203
void ShowUsage(const char *title)
Definition: postgres.c:4703
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4696
const char * p_sourcetext
Definition: parse_node.h:179
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:766
#define Assert(condition)
Definition: c.h:792
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:195
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:50
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:53

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 629 of file postgres.c.

References copyObject, elog, equal(), log_parser_stats, new_list(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

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

◆ pg_plan_queries()

List* pg_plan_queries ( List querytrees,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

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

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

◆ pg_plan_query()

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

Definition at line 858 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 BeginCopyTo(), ExecCreateTableAs(), ExplainOneQuery(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), and refresh_matview_datafill().

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

◆ pg_rewrite_query()

static List * pg_rewrite_query ( Query query)
static

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

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

◆ PostgresMain()

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

Definition at line 3838 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, BaseInit(), BeginReportingGUCOptions(), buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, checkDataDir(), ConfigReloadPending, CreateDataDirLockFile(), debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), DISCONNECT_CLIENT_EOF, 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, IDLE_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, IdleSessionTimeout, 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(), pgStatSessionEndCause, 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(), pqsignal(), printf, proc_exit(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), progname, QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), 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().

3841 {
3842  int firstchar;
3843  StringInfoData input_message;
3844  sigjmp_buf local_sigjmp_buf;
3845  volatile bool send_ready_for_query = true;
3846  bool idle_in_transaction_timeout_enabled = false;
3847  bool idle_session_timeout_enabled = false;
3848 
3849  /* Initialize startup process environment if necessary. */
3850  if (!IsUnderPostmaster)
3851  InitStandaloneProcess(argv[0]);
3852 
3854 
3855  /*
3856  * Set default values for command-line options.
3857  */
3858  if (!IsUnderPostmaster)
3860 
3861  /*
3862  * Parse command-line options.
3863  */
3865 
3866  /* Must have gotten a database name, or have a default (the username) */
3867  if (dbname == NULL)
3868  {
3869  dbname = username;
3870  if (dbname == NULL)
3871  ereport(FATAL,
3872  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3873  errmsg("%s: no database nor user name specified",
3874  progname)));
3875  }
3876 
3877  /* Acquire configuration parameters, unless inherited from postmaster */
3878  if (!IsUnderPostmaster)
3879  {
3881  proc_exit(1);
3882  }
3883 
3884  /*
3885  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
3886  * has already set up BlockSig and made that the active signal mask.)
3887  *
3888  * Note that postmaster blocked all signals before forking child process,
3889  * so there is no race condition whereby we might receive a signal before
3890  * we have set up the handler.
3891  *
3892  * Also note: it's best not to use any signals that are SIG_IGNored in the
3893  * postmaster. If such a signal arrives before we are able to change the
3894  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3895  * handler in the postmaster to reserve the signal. (Of course, this isn't
3896  * an issue for signals that are locally generated, such as SIGALRM and
3897  * SIGPIPE.)
3898  */
3899  if (am_walsender)
3900  WalSndSignals();
3901  else
3902  {
3904  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3905  pqsignal(SIGTERM, die); /* cancel current query and exit */
3906 
3907  /*
3908  * In a postmaster child backend, replace SignalHandlerForCrashExit
3909  * with quickdie, so we can tell the client we're dying.
3910  *
3911  * In a standalone backend, SIGQUIT can be generated from the keyboard
3912  * easily, while SIGTERM cannot, so we make both signals do die()
3913  * rather than quickdie().
3914  */
3915  if (IsUnderPostmaster)
3916  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3917  else
3918  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3919  InitializeTimeouts(); /* establishes SIGALRM handler */
3920 
3921  /*
3922  * Ignore failure to write to frontend. Note: if frontend closes
3923  * connection, we will notice it and exit cleanly when control next
3924  * returns to outer loop. This seems safer than forcing exit in the
3925  * midst of output during who-knows-what operation...
3926  */
3931 
3932  /*
3933  * Reset some signals that are accepted by postmaster but not by
3934  * backend
3935  */
3936  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3937  * platforms */
3938  }
3939 
3940  if (!IsUnderPostmaster)
3941  {
3942  /*
3943  * Validate we have been given a reasonable-looking DataDir (if under
3944  * postmaster, assume postmaster did this already).
3945  */
3946  checkDataDir();
3947 
3948  /* Change into DataDir (if under postmaster, was done already) */
3949  ChangeToDataDir();
3950 
3951  /*
3952  * Create lockfile for data directory.
3953  */
3954  CreateDataDirLockFile(false);
3955 
3956  /* read control file (error checking and contains config ) */
3957  LocalProcessControlFile(false);
3958 
3959  /* Initialize MaxBackends (if under postmaster, was done already) */
3961  }
3962 
3963  /* Early initialization */
3964  BaseInit();
3965 
3966  /*
3967  * Create a per-backend PGPROC struct in shared memory, except in the
3968  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3969  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3970  * had to do some stuff with LWLocks).
3971  */
3972 #ifdef EXEC_BACKEND
3973  if (!IsUnderPostmaster)
3974  InitProcess();
3975 #else
3976  InitProcess();
3977 #endif
3978 
3979  /* We need to allow SIGINT, etc during the initial transaction */
3981 
3982  /*
3983  * General initialization.
3984  *
3985  * NOTE: if you are tempted to add code in this vicinity, consider putting
3986  * it inside InitPostgres() instead. In particular, anything that
3987  * involves database access should be there, not here.
3988  */
3990 
3991  /*
3992  * If the PostmasterContext is still around, recycle the space; we don't
3993  * need it anymore after InitPostgres completes. Note this does not trash
3994  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3995  * ... else we'd need to copy the Port data first. Also, subsidiary data
3996  * such as the username isn't lost either; see ProcessStartupPacket().
3997  */
3998  if (PostmasterContext)
3999  {
4001  PostmasterContext = NULL;
4002  }
4003 
4005 
4006  /*
4007  * Now all GUC states are fully set up. Report them to client if
4008  * appropriate.
4009  */
4011 
4012  /*
4013  * Also set up handler to log session end; we have to wait till now to be
4014  * sure Log_disconnections has its final value.
4015  */
4018 
4019  /* Perform initialization specific to a WAL sender process. */
4020  if (am_walsender)
4021  InitWalSender();
4022 
4023  /*
4024  * process any libraries that should be preloaded at backend start (this
4025  * likewise can't be done until GUC settings are complete)
4026  */
4028 
4029  /*
4030  * Send this backend's cancellation info to the frontend.
4031  */
4033  {
4035 
4036  pq_beginmessage(&buf, 'K');
4037  pq_sendint32(&buf, (int32) MyProcPid);
4038  pq_sendint32(&buf, (int32) MyCancelKey);
4039  pq_endmessage(&buf);
4040  /* Need not flush since ReadyForQuery will do it. */
4041  }
4042 
4043  /* Welcome banner for standalone case */
4045  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4046 
4047  /*
4048  * Create the memory context we will use in the main loop.
4049  *
4050  * MessageContext is reset once per iteration of the main loop, ie, upon
4051  * completion of processing of each command message from the client.
4052  */
4054  "MessageContext",
4056 
4057  /*
4058  * Create memory context and buffer used for RowDescription messages. As
4059  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4060  * frequently executed for ever single statement, we don't want to
4061  * allocate a separate buffer every time.
4062  */
4064  "RowDescriptionContext",
4069 
4070  /*
4071  * Remember stand-alone backend startup time
4072  */
4073  if (!IsUnderPostmaster)
4075 
4076  /*
4077  * POSTGRES main processing loop begins here
4078  *
4079  * If an exception is encountered, processing resumes here so we abort the
4080  * current transaction and start a new one.
4081  *
4082  * You might wonder why this isn't coded as an infinite loop around a
4083  * PG_TRY construct. The reason is that this is the bottom of the
4084  * exception stack, and so with PG_TRY there would be no exception handler
4085  * in force at all during the CATCH part. By leaving the outermost setjmp
4086  * always active, we have at least some chance of recovering from an error
4087  * during error recovery. (If we get into an infinite loop thereby, it
4088  * will soon be stopped by overflow of elog.c's internal state stack.)
4089  *
4090  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4091  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4092  * is essential in case we longjmp'd out of a signal handler on a platform
4093  * where that leaves the signal blocked. It's not redundant with the
4094  * unblock in AbortTransaction() because the latter is only called if we
4095  * were inside a transaction.
4096  */
4097 
4098  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4099  {
4100  /*
4101  * NOTE: if you are tempted to add more code in this if-block,
4102  * consider the high probability that it should be in
4103  * AbortTransaction() instead. The only stuff done directly here
4104  * should be stuff that is guaranteed to apply *only* for outer-level
4105  * error recovery, such as adjusting the FE/BE protocol status.
4106  */
4107 
4108  /* Since not using PG_TRY, must reset error stack by hand */
4109  error_context_stack = NULL;
4110 
4111  /* Prevent interrupts while cleaning up */
4112  HOLD_INTERRUPTS();
4113 
4114  /*
4115  * Forget any pending QueryCancel request, since we're returning to
4116  * the idle loop anyway, and cancel any active timeout requests. (In
4117  * future we might want to allow some timeout requests to survive, but
4118  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4119  * we got here because of a query cancel interrupting the SIGALRM
4120  * interrupt handler.) Note in particular that we must clear the
4121  * statement and lock timeout indicators, to prevent any future plain
4122  * query cancels from being misreported as timeouts in case we're
4123  * forgetting a timeout cancel.
4124  */
4125  disable_all_timeouts(false);
4126  QueryCancelPending = false; /* second to avoid race condition */
4127 
4128  /* Not reading from the client anymore. */
4129  DoingCommandRead = false;
4130 
4131  /* Make sure libpq is in a good state */
4132  pq_comm_reset();
4133 
4134  /* Report the error to the client and/or server log */
4135  EmitErrorReport();
4136 
4137  /*
4138  * Make sure debug_query_string gets reset before we possibly clobber
4139  * the storage it points at.
4140  */
4141  debug_query_string = NULL;
4142 
4143  /*
4144  * Abort the current transaction in order to recover.
4145  */
4147 
4148  if (am_walsender)
4150 
4152  SPICleanup();
4153 
4154  /*
4155  * We can't release replication slots inside AbortTransaction() as we
4156  * need to be able to start and abort transactions while having a slot
4157  * acquired. But we never need to hold them across top level errors,
4158  * so releasing here is fine. There's another cleanup in ProcKill()
4159  * ensuring we'll correctly cleanup on FATAL errors as well.
4160  */
4161  if (MyReplicationSlot != NULL)
4163 
4164  /* We also want to cleanup temporary slots on error. */
4166 
4168 
4169  /*
4170  * Now return to normal top-level context and clear ErrorContext for
4171  * next time.
4172  */
4174  FlushErrorState();
4175 
4176  /*
4177  * If we were handling an extended-query-protocol message, initiate
4178  * skip till next Sync. This also causes us not to issue
4179  * ReadyForQuery (until we get Sync).
4180  */
4182  ignore_till_sync = true;
4183 
4184  /* We don't have a transaction command open anymore */
4185  xact_started = false;
4186 
4187  /*
4188  * If an error occurred while we were reading a message from the
4189  * client, we have potentially lost track of where the previous
4190  * message ends and the next one begins. Even though we have
4191  * otherwise recovered from the error, we cannot safely read any more
4192  * messages from the client, so there isn't much we can do with the
4193  * connection anymore.
4194  */
4195  if (pq_is_reading_msg())
4196  ereport(FATAL,
4197  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4198  errmsg("terminating connection because protocol synchronization was lost")));
4199 
4200  /* Now we can allow interrupts again */
4202  }
4203 
4204  /* We can now handle ereport(ERROR) */
4205  PG_exception_stack = &local_sigjmp_buf;
4206 
4207  if (!ignore_till_sync)
4208  send_ready_for_query = true; /* initially, or after error */
4209 
4210  /*
4211  * Non-error queries loop here.
4212  */
4213 
4214  for (;;)
4215  {
4216  /*
4217  * At top of loop, reset extended-query-message flag, so that any
4218  * errors encountered in "idle" state don't provoke skip.
4219  */
4221 
4222  /*
4223  * Release storage left over from prior query cycle, and create a new
4224  * query input buffer in the cleared MessageContext.
4225  */
4228 
4229  initStringInfo(&input_message);
4230 
4231  /*
4232  * Also consider releasing our catalog snapshot if any, so that it's
4233  * not preventing advance of global xmin while we wait for the client.
4234  */
4236 
4237  /*
4238  * (1) If we've reached idle state, tell the frontend we're ready for
4239  * a new query.
4240  *
4241  * Note: this includes fflush()'ing the last of the prior output.
4242  *
4243  * This is also a good time to send collected statistics to the
4244  * collector, and to update the PS stats display. We avoid doing
4245  * those every time through the message loop because it'd slow down
4246  * processing of batched messages, and because we don't want to report
4247  * uncommitted updates (that confuses autovacuum). The notification
4248  * processor wants a call too, if we are not in a transaction block.
4249  *
4250  * Also, if an idle timeout is enabled, start the timer for that.
4251  */
4252  if (send_ready_for_query)
4253  {
4255  {
4256  set_ps_display("idle in transaction (aborted)");
4258 
4259  /* Start the idle-in-transaction timer */
4261  {
4262  idle_in_transaction_timeout_enabled = true;
4265  }
4266  }
4268  {
4269  set_ps_display("idle in transaction");
4271 
4272  /* Start the idle-in-transaction timer */
4274  {
4275  idle_in_transaction_timeout_enabled = true;
4278  }
4279  }
4280  else
4281  {
4282  /* Send out notify signals and transmit self-notifies */
4284 
4285  /*
4286  * Also process incoming notifies, if any. This is mostly to
4287  * ensure stable behavior in tests: if any notifies were
4288  * received during the just-finished transaction, they'll be
4289  * seen by the client before ReadyForQuery is.
4290  */
4293 
4294  pgstat_report_stat(false);
4295 
4296  set_ps_display("idle");
4298 
4299  /* Start the idle-session timer */
4300  if (IdleSessionTimeout > 0)
4301  {
4302  idle_session_timeout_enabled = true;
4305  }
4306  }
4307 
4308  /* Report any recently-changed GUC options */
4310 
4312  send_ready_for_query = false;
4313  }
4314 
4315  /*
4316  * (2) Allow asynchronous signals to be executed immediately if they
4317  * come in while we are waiting for client input. (This must be
4318  * conditional since we don't want, say, reads on behalf of COPY FROM
4319  * STDIN doing the same thing.)
4320  */
4321  DoingCommandRead = true;
4322 
4323  /*
4324  * (3) read a command (loop blocks here)
4325  */
4326  firstchar = ReadCommand(&input_message);
4327 
4328  /*
4329  * (4) turn off the idle-in-transaction and idle-session timeouts, if
4330  * active. We do this before step (5) so that any last-moment timeout
4331  * is certain to be detected in step (5).
4332  *
4333  * At most one of these timeouts will be active, so there's no need to
4334  * worry about combining the timeout.c calls into one.
4335  */
4336  if (idle_in_transaction_timeout_enabled)
4337  {
4339  idle_in_transaction_timeout_enabled = false;
4340  }
4341  if (idle_session_timeout_enabled)
4342  {
4344  idle_session_timeout_enabled = false;
4345  }
4346 
4347  /*
4348  * (5) disable async signal conditions again.
4349  *
4350  * Query cancel is supposed to be a no-op when there is no query in
4351  * progress, so if a query cancel arrived while we were idle, just
4352  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4353  * it's called when DoingCommandRead is set, so check for interrupts
4354  * before resetting DoingCommandRead.
4355  */
4357  DoingCommandRead = false;
4358 
4359  /*
4360  * (6) check for any other interesting events that happened while we
4361  * slept.
4362  */
4363  if (ConfigReloadPending)
4364  {
4365  ConfigReloadPending = false;
4367  }
4368 
4369  /*
4370  * (7) process the command. But ignore it if we're skipping till
4371  * Sync.
4372  */
4373  if (ignore_till_sync && firstchar != EOF)
4374  continue;
4375 
4376  switch (firstchar)
4377  {
4378  case 'Q': /* simple query */
4379  {
4380  const char *query_string;
4381 
4382  /* Set statement_timestamp() */
4384 
4385  query_string = pq_getmsgstring(&input_message);
4386  pq_getmsgend(&input_message);
4387 
4388  if (am_walsender)
4389  {
4390  if (!exec_replication_command(query_string))
4391  exec_simple_query(query_string);
4392  }
4393  else
4394  exec_simple_query(query_string);
4395 
4396  send_ready_for_query = true;
4397  }
4398  break;
4399 
4400  case 'P': /* parse */
4401  {
4402  const char *stmt_name;
4403  const char *query_string;
4404  int numParams;
4405  Oid *paramTypes = NULL;
4406 
4407  forbidden_in_wal_sender(firstchar);
4408 
4409  /* Set statement_timestamp() */
4411 
4412  stmt_name = pq_getmsgstring(&input_message);
4413  query_string = pq_getmsgstring(&input_message);
4414  numParams = pq_getmsgint(&input_message, 2);
4415  if (numParams > 0)
4416  {
4417  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4418  for (int i = 0; i < numParams; i++)
4419  paramTypes[i] = pq_getmsgint(&input_message, 4);
4420  }
4421  pq_getmsgend(&input_message);
4422 
4423  exec_parse_message(query_string, stmt_name,
4424  paramTypes, numParams);
4425  }
4426  break;
4427 
4428  case 'B': /* bind */
4429  forbidden_in_wal_sender(firstchar);
4430 
4431  /* Set statement_timestamp() */
4433 
4434  /*
4435  * this message is complex enough that it seems best to put
4436  * the field extraction out-of-line
4437  */
4438  exec_bind_message(&input_message);
4439  break;
4440 
4441  case 'E': /* execute */
4442  {
4443  const char *portal_name;
4444  int max_rows;
4445 
4446  forbidden_in_wal_sender(firstchar);
4447 
4448  /* Set statement_timestamp() */
4450 
4451  portal_name = pq_getmsgstring(&input_message);
4452  max_rows = pq_getmsgint(&input_message, 4);
4453  pq_getmsgend(&input_message);
4454 
4455  exec_execute_message(portal_name, max_rows);
4456  }
4457  break;
4458 
4459  case 'F': /* fastpath function call */
4460  forbidden_in_wal_sender(firstchar);
4461 
4462  /* Set statement_timestamp() */
4464 
4465  /* Report query to various monitoring facilities. */
4467  set_ps_display("<FASTPATH>");
4468 
4469  /* start an xact for this function invocation */
4471 
4472  /*
4473  * Note: we may at this point be inside an aborted
4474  * transaction. We can't throw error for that until we've
4475  * finished reading the function-call message, so
4476  * HandleFunctionRequest() must check for it after doing so.
4477  * Be careful not to do anything that assumes we're inside a
4478  * valid transaction here.
4479  */
4480 
4481  /* switch back to message context */
4483 
4484  HandleFunctionRequest(&input_message);
4485 
4486  /* commit the function-invocation transaction */
4488 
4489  send_ready_for_query = true;
4490  break;
4491 
4492  case 'C': /* close */
4493  {
4494  int close_type;
4495  const char *close_target;
4496 
4497  forbidden_in_wal_sender(firstchar);
4498 
4499  close_type = pq_getmsgbyte(&input_message);
4500  close_target = pq_getmsgstring(&input_message);
4501  pq_getmsgend(&input_message);
4502 
4503  switch (close_type)
4504  {
4505  case 'S':
4506  if (close_target[0] != '\0')
4507  DropPreparedStatement(close_target, false);
4508  else
4509  {
4510  /* special-case the unnamed statement */
4512  }
4513  break;
4514  case 'P':
4515  {
4516  Portal portal;
4517 
4518  portal = GetPortalByName(close_target);
4519  if (PortalIsValid(portal))
4520  PortalDrop(portal, false);
4521  }
4522  break;
4523  default:
4524  ereport(ERROR,
4525  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4526  errmsg("invalid CLOSE message subtype %d",
4527  close_type)));
4528  break;
4529  }
4530 
4532  pq_putemptymessage('3'); /* CloseComplete */
4533  }
4534  break;
4535 
4536  case 'D': /* describe */
4537  {
4538  int describe_type;
4539  const char *describe_target;
4540 
4541  forbidden_in_wal_sender(firstchar);
4542 
4543  /* Set statement_timestamp() (needed for xact) */
4545 
4546  describe_type = pq_getmsgbyte(&input_message);
4547  describe_target = pq_getmsgstring(&input_message);
4548  pq_getmsgend(&input_message);
4549 
4550  switch (describe_type)
4551  {
4552  case 'S':
4553  exec_describe_statement_message(describe_target);
4554  break;
4555  case 'P':
4556  exec_describe_portal_message(describe_target);
4557  break;
4558  default:
4559  ereport(ERROR,
4560  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4561  errmsg("invalid DESCRIBE message subtype %d",
4562  describe_type)));
4563  break;
4564  }
4565  }
4566  break;
4567 
4568  case 'H': /* flush */
4569  pq_getmsgend(&input_message);
4571  pq_flush();
4572  break;
4573 
4574  case 'S': /* sync */
4575  pq_getmsgend(&input_message);
4577  send_ready_for_query = true;
4578  break;
4579 
4580  /*
4581  * 'X' means that the frontend is closing down the socket. EOF
4582  * means unexpected loss of frontend connection. Either way,
4583  * perform normal shutdown.
4584  */
4585  case EOF:
4586 
4587  /* for the statistics collector */
4589 
4590  /* FALLTHROUGH */
4591 
4592  case 'X':
4593 
4594  /*
4595  * Reset whereToSendOutput to prevent ereport from attempting
4596  * to send any more messages to client.
4597  */
4600 
4601  /*
4602  * NOTE: if you are tempted to add more code here, DON'T!
4603  * Whatever you had in mind to do should be set up as an
4604  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4605  * it will fail to be called during other backend-shutdown
4606  * scenarios.
4607  */
4608  proc_exit(0);
4609 
4610  case 'd': /* copy data */
4611  case 'c': /* copy done */
4612  case 'f': /* copy fail */
4613 
4614  /*
4615  * Accept but ignore these messages, per protocol spec; we
4616  * probably got here because a COPY failed, and the frontend
4617  * is still sending data.
4618  */
4619  break;
4620 
4621  default:
4622  ereport(FATAL,
4623  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4624  errmsg("invalid frontend message type %d",
4625  firstchar)));
4626  }
4627  } /* end of input-reading loop */
4628 }
void InitializeTimeouts(void)
Definition: timeout.c:435
void AbortCurrentTransaction(void)
Definition: xact.c:3212
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2584
#define SIGQUIT
Definition: win32_port.h:160
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void BeginReportingGUCOptions(void)
Definition: guc.c:6293
int MyProcPid
Definition: globals.c:41
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:506
static void finish_xact_command(void)
Definition: postgres.c:2656
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1512
#define SIGUSR1
Definition: win32_port.h:171
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
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:3355
#define SIGCHLD
Definition: win32_port.h:169
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:165
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPICleanup(void)
Definition: spi.c:356
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4638
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:704
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4703
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:400
void BaseInit(void)
Definition: postinit.c:537
#define printf(...)
Definition: port.h:221
void checkDataDir(void)
Definition: miscinit.c:302
SessionEndType pgStatSessionEndCause
Definition: pgstat.c:263
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:870
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
unsigned int Oid
Definition: postgres_ext.h:31
const char * progname
Definition: pg_standby.c:36
void FlushErrorState(void)
Definition: elog.c:1659
#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:2891
signed int int32
Definition: c.h:417
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2042
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4805
void jit_reset_after_error(void)
Definition: jit.c:128
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:119
ErrorContextCallback * error_context_stack
Definition: elog.c:93
int IdleSessionTimeout
Definition: proc.c:64
void set_ps_display(const char *activity)
Definition: ps_status.c:349
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
bool am_walsender
Definition: walsender.c:115
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:687
#define ERROR
Definition: elog.h:45
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1273
void ProcessNotifyInterrupt(void)
Definition: async.c:1915
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1249
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:45
void WalSndSignals(void)
Definition: walsender.c:3045
#define FATAL
Definition: elog.h:54
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void ReportChangedGUCOptions(void)
Definition: guc.c:6341
void InitProcess(void)
Definition: proc.c:302
Definition: dest.h:89
static char * buf
Definition: pg_test_fsync.c:68
bool IsUnderPostmaster
Definition: globals.c:110
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1607
Definition: dest.h:90
#define SIGHUP
Definition: win32_port.h:159
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5061
void ChangeToDataDir(void)
Definition: miscinit.c:416
void ReplicationSlotRelease(void)
Definition: slot.c:484
sigset_t UnBlockSig
Definition: pqsignal.c:22
void PortalErrorCleanup(void)
Definition: portalmem.c:910
static bool xact_started
Definition: postgres.c:134
void InitWalSender(void)
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
#define SIG_IGN
Definition: win32_port.h:156
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
const char * debug_query_string
Definition: postgres.c:89
#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:1350
#define PortalIsValid(p)
Definition: portal.h:203
static void start_xact_command(void)
Definition: postgres.c:2636
static bool doing_extended_query_message
Definition: postgres.c:147
void process_session_preload_libraries(void)
Definition: miscinit.c:1670
void WalSndErrorCleanup(void)
Definition: walsender.c:295
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5615
void EmitErrorReport(void)
Definition: elog.c:1514
static StringInfoData row_description_buf
Definition: postgres.c:169
TimestampTz PgStartTime
Definition: timestamp.c:50
static char * username
Definition: initdb.c:134
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:579
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:524
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:38
#define SIG_DFL
Definition: win32_port.h:154
void ProcessCompletedNotifies(void)
Definition: async.c:1226
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:259
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:477
static bool DoingCommandRead
Definition: postgres.c:141
void InitializeMaxBackends(void)
Definition: postinit.c:515
char * dbname
Definition: streamutil.c:51
MemoryContext MessageContext
Definition: mcxt.c:48
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
static const char * userDoption
Definition: postgres.c:158
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:915
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:467
void ReadyForQuery(CommandDest dest)
Definition: dest.c:282
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2857
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:117
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2912
static void drop_unnamed_stmt(void)
Definition: postgres.c:2735
void ReplicationSlotCleanup(void)
Definition: slot.c:540
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:421
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
bool Log_disconnections
Definition: postgres.c:95
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3583
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:652
CommandDest whereToSendOutput
Definition: postgres.c:92
static bool ignore_till_sync
Definition: postgres.c:148
static MemoryContext row_description_context
Definition: postgres.c:168
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2760
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void exec_simple_query(const char *query_string)
Definition: postgres.c:984
void InitializeGUCOptions(void)
Definition: guc.c:5392
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:552
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2489

◆ process_postgres_switches()

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

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

3585 {
3586  bool secure = (ctx == PGC_POSTMASTER);
3587  int errs = 0;
3588  GucSource gucsource;
3589  int flag;
3590 
3591  if (secure)
3592  {
3593  gucsource = PGC_S_ARGV; /* switches came from command line */
3594 
3595  /* Ignore the initial --single argument, if present */
3596  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3597  {
3598  argv++;
3599  argc--;
3600  }
3601  }
3602  else
3603  {
3604  gucsource = PGC_S_CLIENT; /* switches came from client */
3605  }
3606 
3607 #ifdef HAVE_INT_OPTERR
3608 
3609  /*
3610  * Turn this off because it's either printed to stderr and not the log
3611  * where we'd want it, or argv[0] is now "--single", which would make for
3612  * a weird error message. We print our own error message below.
3613  */
3614  opterr = 0;
3615 #endif
3616 
3617  /*
3618  * Parse command-line options. CAUTION: keep this in sync with
3619  * postmaster/postmaster.c (the option sets should not conflict) and with
3620  * the common help() function in main/main.c.
3621  */
3622  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3623  {
3624  switch (flag)
3625  {
3626  case 'B':
3627  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3628  break;
3629 
3630  case 'b':
3631  /* Undocumented flag used for binary upgrades */
3632  if (secure)
3633  IsBinaryUpgrade = true;
3634  break;
3635 
3636  case 'C':
3637  /* ignored for consistency with the postmaster */
3638  break;
3639 
3640  case 'D':
3641  if (secure)
3642  userDoption = strdup(optarg);
3643  break;
3644 
3645  case 'd':
3646  set_debug_options(atoi(optarg), ctx, gucsource);
3647  break;
3648 
3649  case 'E':
3650  if (secure)
3651  EchoQuery = true;
3652  break;
3653 
3654  case 'e':
3655  SetConfigOption("datestyle", "euro", ctx, gucsource);
3656  break;
3657 
3658  case 'F':
3659  SetConfigOption("fsync", "false", ctx, gucsource);
3660  break;
3661 
3662  case 'f':
3663  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3664  errs++;
3665  break;
3666 
3667  case 'h':
3668  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3669  break;
3670 
3671  case 'i':
3672  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3673  break;
3674 
3675  case 'j':
3676  if (secure)
3677  UseSemiNewlineNewline = true;
3678  break;
3679 
3680  case 'k':
3681  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3682  break;
3683 
3684  case 'l':
3685  SetConfigOption("ssl", "true", ctx, gucsource);
3686  break;
3687 
3688  case 'N':
3689  SetConfigOption("max_connections", optarg, ctx, gucsource);
3690  break;
3691 
3692  case 'n':
3693  /* ignored for consistency with postmaster */
3694  break;
3695 
3696  case 'O':
3697  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3698  break;
3699 
3700  case 'P':
3701  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3702  break;
3703 
3704  case 'p':
3705  SetConfigOption("port", optarg, ctx, gucsource);
3706  break;
3707 
3708  case 'r':
3709  /* send output (stdout and stderr) to the given file */
3710  if (secure)
3712  break;
3713 
3714  case 'S':
3715  SetConfigOption("work_mem", optarg, ctx, gucsource);
3716  break;
3717 
3718  case 's':
3719  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3720  break;
3721 
3722  case 'T':
3723  /* ignored for consistency with the postmaster */
3724  break;
3725 
3726  case 't':
3727  {
3728  const char *tmp = get_stats_option_name(optarg);
3729 
3730  if (tmp)
3731  SetConfigOption(tmp, "true", ctx, gucsource);
3732  else
3733  errs++;
3734  break;
3735  }
3736 
3737  case 'v':
3738 
3739  /*
3740  * -v is no longer used in normal operation, since
3741  * FrontendProtocol is already set before we get here. We keep
3742  * the switch only for possible use in standalone operation,
3743  * in case we ever support using normal FE/BE protocol with a
3744  * standalone backend.
3745  */
3746  if (secure)
3748  break;
3749 
3750  case 'W':
3751  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3752  break;
3753 
3754  case 'c':
3755  case '-':
3756  {
3757  char *name,
3758  *value;
3759 
3760  ParseLongOption(optarg, &name, &value);
3761  if (!value)
3762  {
3763  if (flag == '-')
3764  ereport(ERROR,
3765  (errcode(ERRCODE_SYNTAX_ERROR),
3766  errmsg("--%s requires a value",
3767  optarg)));
3768  else
3769  ereport(ERROR,
3770  (errcode(ERRCODE_SYNTAX_ERROR),
3771  errmsg("-c %s requires a value",
3772  optarg)));
3773  }
3774  SetConfigOption(name, value, ctx, gucsource);
3775  free(name);
3776  if (value)
3777  free(value);
3778  break;
3779  }
3780 
3781  default:
3782  errs++;
3783  break;
3784  }
3785 
3786  if (errs)
3787  break;
3788  }
3789 
3790  /*
3791  * Optional database name should be there only if *dbname is NULL.
3792  */
3793  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3794  *dbname = strdup(argv[optind++]);
3795 
3796  if (errs || argc != optind)
3797  {
3798  if (errs)
3799  optind--; /* complain about the previous argument */
3800 
3801  /* spell the error message a bit differently depending on context */
3802  if (IsUnderPostmaster)
3803  ereport(FATAL,
3804  errcode(ERRCODE_SYNTAX_ERROR),
3805  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3806  errhint("Try \"%s --help\" for more information.", progname));
3807  else
3808  ereport(FATAL,
3809  errcode(ERRCODE_SYNTAX_ERROR),
3810  errmsg("%s: invalid command-line argument: %s",
3811  progname, argv[optind]),
3812  errhint("Try \"%s --help\" for more information.", progname));
3813  }
3814 
3815  /*
3816  * Reset getopt(3) library so that it will work correctly in subprocesses
3817  * or when this function is called a second time with another array.
3818  */
3819  optind = 1;
3820 #ifdef HAVE_INT_OPTRESET
3821  optreset = 1; /* some systems need this too */
3822 #endif
3823 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:10694
static struct @144 value
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3501
int errcode(int sqlerrcode)
Definition: elog.c:704
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3543
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3472
const char * progname
Definition: pg_standby.c:36
bool IsBinaryUpgrade
Definition: globals.c:111
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:45
#define FATAL
Definition: elog.h:54
#define MAXPGPATH
char OutputFileName[MAXPGPATH]
Definition: globals.c:71
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7879
bool IsUnderPostmaster
Definition: globals.c:110
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:49
uint32 ProtocolVersion
Definition: pqcomm.h:122
#define ereport(elevel,...)
Definition: elog.h:155
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * dbname
Definition: streamutil.c:51
const char * name
Definition: encode.c:515
static bool EchoQuery
Definition: postgres.c:159
static const char * userDoption
Definition: postgres.c:158
static bool UseSemiNewlineNewline
Definition: postgres.c:160
int errmsg(const char *fmt,...)
Definition: elog.c:915
char * optarg
Definition: getopt.c:52
ProtocolVersion FrontendProtocol
Definition: globals.c:28

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 527 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

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

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 573 of file postgres.c.

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

Referenced by secure_write().

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

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3065 of file postgres.c.

References Assert, BackgroundWorker::bgw_type, 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, IdleSessionTimeout, IdleSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsLogicalLauncher(), IsLogicalWorker(), LOCK_TIMEOUT, LockErrorCleanup(), MyBgworkerEntry, 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().

3066 {
3067  /* OK to accept any interrupts now? */
3068  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3069  return;
3070  InterruptPending = false;
3071 
3072  if (ProcDiePending)
3073  {
3074  ProcDiePending = false;
3075  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3076  LockErrorCleanup();
3077  /* As in quickdie, don't risk sending to client during auth */
3081  ereport(FATAL,
3082  (errcode(ERRCODE_QUERY_CANCELED),
3083  errmsg("canceling authentication due to timeout")));
3084  else if (IsAutoVacuumWorkerProcess())
3085  ereport(FATAL,
3086  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3087  errmsg("terminating autovacuum process due to administrator command")));
3088  else if (IsLogicalWorker())
3089  ereport(FATAL,
3090  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3091  errmsg("terminating logical replication worker due to administrator command")));
3092  else if (IsLogicalLauncher())
3093  {
3094  ereport(DEBUG1,
3095  (errmsg("logical replication launcher shutting down")));
3096 
3097  /*
3098  * The logical replication launcher can be stopped at any time.
3099  * Use exit status 1 so the background worker is restarted.
3100  */
3101  proc_exit(1);
3102  }
3104  {
3106  ereport(FATAL,
3107  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3108  errmsg("terminating connection due to conflict with recovery"),
3110  }
3111  else if (RecoveryConflictPending)
3112  {
3113  /* Currently there is only one non-retryable recovery conflict */
3116  ereport(FATAL,
3117  (errcode(ERRCODE_DATABASE_DROPPED),
3118  errmsg("terminating connection due to conflict with recovery"),
3120  }
3121  else if (IsBackgroundWorker)
3122  ereport(FATAL,
3123  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3124  errmsg("terminating background worker \"%s\" due to administrator command",
3126  else
3127  ereport(FATAL,
3128  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3129  errmsg("terminating connection due to administrator command")));
3130  }
3132  {
3133  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3134  LockErrorCleanup();
3135  /* don't send to client, we already know the connection to be dead. */
3137  ereport(FATAL,
3138  (errcode(ERRCODE_CONNECTION_FAILURE),
3139  errmsg("connection to client lost")));
3140  }
3141 
3142  /*
3143  * If a recovery conflict happens while we are waiting for input from the
3144  * client, the client is presumably just sitting idle in a transaction,
3145  * preventing recovery from making progress. Terminate the connection to
3146  * dislodge it.
3147  */
3149  {
3150  QueryCancelPending = false; /* this trumps QueryCancel */
3151  RecoveryConflictPending = false;
3152  LockErrorCleanup();
3154  ereport(FATAL,
3155  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3156  errmsg("terminating connection due to conflict with recovery"),
3158  errhint("In a moment you should be able to reconnect to the"
3159  " database and repeat your command.")));
3160  }
3161 
3162  /*
3163  * Don't allow query cancel interrupts while reading input from the
3164  * client, because we might lose sync in the FE/BE protocol. (Die
3165  * interrupts are OK, because we won't read any further messages from the
3166  * client in that case.)
3167  */
3169  {
3170  /*
3171  * Re-arm InterruptPending so that we process the cancel request as
3172  * soon as we're done reading the message.
3173  */
3174  InterruptPending = true;
3175  }
3176  else if (QueryCancelPending)
3177  {
3178  bool lock_timeout_occurred;
3179  bool stmt_timeout_occurred;
3180 
3181  QueryCancelPending = false;
3182 
3183  /*
3184  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3185  * need to clear both, so always fetch both.
3186  */
3187  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3188  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3189 
3190  /*
3191  * If both were set, we want to report whichever timeout completed
3192  * earlier; this ensures consistent behavior if the machine is slow
3193  * enough that the second timeout triggers before we get here. A tie
3194  * is arbitrarily broken in favor of reporting a lock timeout.
3195  */
3196  if (lock_timeout_occurred && stmt_timeout_occurred &&
3198  lock_timeout_occurred = false; /* report stmt timeout */
3199 
3200  if (lock_timeout_occurred)
3201  {
3202  LockErrorCleanup();
3203  ereport(ERROR,
3204  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3205  errmsg("canceling statement due to lock timeout")));
3206  }
3207  if (stmt_timeout_occurred)
3208  {
3209  LockErrorCleanup();
3210  ereport(ERROR,
3211  (errcode(ERRCODE_QUERY_CANCELED),
3212  errmsg("canceling statement due to statement timeout")));
3213  }
3215  {
3216  LockErrorCleanup();
3217  ereport(ERROR,
3218  (errcode(ERRCODE_QUERY_CANCELED),
3219  errmsg("canceling autovacuum task")));
3220  }
3222  {
3223  RecoveryConflictPending = false;
3224  LockErrorCleanup();
3226  ereport(ERROR,
3227  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3228  errmsg("canceling statement due to conflict with recovery"),
3230  }
3231 
3232  /*
3233  * If we are reading a command from the client, just ignore the cancel
3234  * request --- sending an extra error message won't accomplish
3235  * anything. Otherwise, go ahead and throw the error.
3236  */
3237  if (!DoingCommandRead)
3238  {
3239  LockErrorCleanup();
3240  ereport(ERROR,
3241  (errcode(ERRCODE_QUERY_CANCELED),
3242  errmsg("canceling statement due to user request")));
3243  }
3244  }
3245 
3247  {
3248  /*
3249  * If the GUC has been reset to zero, ignore the signal. This is
3250  * important because the GUC update itself won't disable any pending
3251  * interrupt.
3252  */
3254  ereport(FATAL,
3255  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3256  errmsg("terminating connection due to idle-in-transaction timeout")));
3257  else
3259  }
3260 
3262  {
3263  /* As above, ignore the signal if the GUC has been reset to zero. */
3264  if (IdleSessionTimeout > 0)
3265  ereport(FATAL,
3266  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3267  errmsg("terminating connection due to idle-session timeout")));
3268  else
3269  IdleSessionTimeoutPending = false;
3270  }
3271 
3274 
3277 }