PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
postgres.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/time.h>
#include "access/parallel.h"
#include "access/printtup.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/async.h"
#include "commands/event_trigger.h"
#include "commands/prepare.h"
#include "common/pg_prng.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/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/guc_hooks.h"
#include "utils/injection_point.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 "utils/varlena.h"
Include dependency graph for postgres.c:

Go to the source code of this file.

Data Structures

struct  BindParamCbData
 

Macros

#define valgrind_report_error_query(query)   ((void) 0)
 

Typedefs

typedef struct BindParamCbData BindParamCbData
 

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 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 void bind_param_error_callback (void *arg)
 
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_fixedparams (RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_varparams (RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_withcb (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
Listpg_rewrite_query (Query *query)
 
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 int errdetail_recovery_conflict (ProcSignalReason reason)
 
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 HandleRecoveryConflictInterrupt (ProcSignalReason reason)
 
static void ProcessRecoveryConflictInterrupt (ProcSignalReason reason)
 
static void ProcessRecoveryConflictInterrupts (void)
 
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)
 
bool check_client_connection_check_interval (int *newval, void **extra, GucSource source)
 
bool check_stage_log_stats (bool *newval, void **extra, GucSource source)
 
bool check_log_stats (bool *newval, void **extra, GucSource source)
 
void assign_transaction_timeout (int newval, void *extra)
 
bool check_restrict_nonsystem_relation_kind (char **newval, void **extra, GucSource source)
 
void assign_restrict_nonsystem_relation_kind (const char *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 PostgresSingleUserMain (int argc, char *argv[], const char *username)
 
void PostgresMain (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
 
int client_connection_check_interval = 0
 
int restrict_nonsystem_relation_kind
 
static long max_stack_depth_bytes = 100 * 1024L
 
static 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 volatile sig_atomic_t RecoveryConflictPending = false
 
static volatile sig_atomic_t RecoveryConflictPendingReasons [NUM_PROCSIGNALS]
 
static MemoryContext row_description_context = NULL
 
static StringInfoData row_description_buf
 
static struct rusage Save_r
 
static struct timeval Save_t
 

Macro Definition Documentation

◆ valgrind_report_error_query

#define valgrind_report_error_query (   query)    ((void) 0)

Definition at line 227 of file postgres.c.

Typedef Documentation

◆ BindParamCbData

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3627 of file postgres.c.

3628 {
3629  long newval_bytes = newval * 1024L;
3630 
3631  max_stack_depth_bytes = newval_bytes;
3632 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:128

References max_stack_depth_bytes, and newval.

◆ assign_restrict_nonsystem_relation_kind()

void assign_restrict_nonsystem_relation_kind ( const char *  newval,
void *  extra 
)

Definition at line 3757 of file postgres.c.

3758 {
3759  int *flags = (int *) extra;
3760 
3762 }
int restrict_nonsystem_relation_kind
Definition: postgres.c:107

References restrict_nonsystem_relation_kind.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3688 of file postgres.c.

3689 {
3690  if (IsTransactionState())
3691  {
3692  /*
3693  * If transaction_timeout GUC has changed within the transaction block
3694  * enable or disable the timer correspondingly.
3695  */
3698  else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3700  }
3701 }
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:780
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
bool IsTransactionState(void)
Definition: xact.c:386

References disable_timeout(), enable_timeout_after(), get_timeout_active(), IsTransactionState(), newval, and TRANSACTION_TIMEOUT.

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2581 of file postgres.c.

2582 {
2585  char *quotedval;
2586 
2587  if (data->paramno < 0)
2588  return;
2589 
2590  /* If we have a textual value, quote it, and trim if necessary */
2591  if (data->paramval)
2592  {
2593  initStringInfo(&buf);
2596  quotedval = buf.data;
2597  }
2598  else
2599  quotedval = NULL;
2600 
2601  if (data->portalName && data->portalName[0] != '\0')
2602  {
2603  if (quotedval)
2604  errcontext("portal \"%s\" parameter $%d = %s",
2605  data->portalName, data->paramno + 1, quotedval);
2606  else
2607  errcontext("portal \"%s\" parameter $%d",
2608  data->portalName, data->paramno + 1);
2609  }
2610  else
2611  {
2612  if (quotedval)
2613  errcontext("unnamed portal parameter $%d = %s",
2614  data->paramno + 1, quotedval);
2615  else
2616  errcontext("unnamed portal parameter $%d",
2617  data->paramno + 1);
2618  }
2619 
2620  if (quotedval)
2621  pfree(quotedval);
2622 }
#define errcontext
Definition: elog.h:196
int log_parameter_max_length_on_error
Definition: guc_tables.c:527
void pfree(void *pointer)
Definition: mcxt.c:1521
void * arg
const void * data
static char * buf
Definition: pg_test_fsync.c:72
void initStringInfo(StringInfo str)
Definition: stringinfo.c:56
void appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen)
Definition: stringinfo_mb.c:34

References appendStringInfoStringQuoted(), arg, buf, data, errcontext, initStringInfo(), log_parameter_max_length_on_error, and pfree().

Referenced by exec_bind_message().

◆ check_client_connection_check_interval()

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

Definition at line 3638 of file postgres.c.

3639 {
3640  if (!WaitEventSetCanReportClosed() && *newval != 0)
3641  {
3642  GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3643  return false;
3644  }
3645  return true;
3646 }
#define GUC_check_errdetail
Definition: guc.h:476
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2247

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2412 of file postgres.c.

2413 {
2414  if (log_duration || log_min_duration_sample >= 0 ||
2416  {
2417  long secs;
2418  int usecs;
2419  int msecs;
2420  bool exceeded_duration;
2421  bool exceeded_sample_duration;
2422  bool in_sample = false;
2423 
2426  &secs, &usecs);
2427  msecs = usecs / 1000;
2428 
2429  /*
2430  * This odd-looking test for log_min_duration_* being exceeded is
2431  * designed to avoid integer overflow with very long durations: don't
2432  * compute secs * 1000 until we've verified it will fit in int.
2433  */
2434  exceeded_duration = (log_min_duration_statement == 0 ||
2436  (secs > log_min_duration_statement / 1000 ||
2437  secs * 1000 + msecs >= log_min_duration_statement)));
2438 
2439  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2440  (log_min_duration_sample > 0 &&
2441  (secs > log_min_duration_sample / 1000 ||
2442  secs * 1000 + msecs >= log_min_duration_sample)));
2443 
2444  /*
2445  * Do not log if log_statement_sample_rate = 0. Log a sample if
2446  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2447  * log_statement_sample_rate = 1.
2448  */
2449  if (exceeded_sample_duration)
2450  in_sample = log_statement_sample_rate != 0 &&
2451  (log_statement_sample_rate == 1 ||
2453 
2454  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2455  {
2456  snprintf(msec_str, 32, "%ld.%03d",
2457  secs * 1000 + msecs, usecs % 1000);
2458  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2459  return 2;
2460  else
2461  return 1;
2462  }
2463  }
2464 
2465  return 0;
2466 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1720
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
int log_min_duration_statement
Definition: guc_tables.c:525
int log_min_duration_sample
Definition: guc_tables.c:524
double log_statement_sample_rate
Definition: guc_tables.c:529
bool log_duration
Definition: guc_tables.c:490
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define snprintf
Definition: port.h:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:878
bool xact_is_sampled
Definition: xact.c:295

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, pg_global_prng_state, pg_prng_double(), snprintf, TimestampDifference(), and xact_is_sampled.

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

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2373 of file postgres.c.

2374 {
2375  ListCell *stmt_item;
2376 
2377  if (log_statement == LOGSTMT_NONE)
2378  return false;
2379  if (log_statement == LOGSTMT_ALL)
2380  return true;
2381 
2382  /* Else we have to inspect the statement(s) to see whether to log */
2383  foreach(stmt_item, stmt_list)
2384  {
2385  Node *stmt = (Node *) lfirst(stmt_item);
2386 
2388  return true;
2389  }
2390 
2391  return false;
2392 }
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:95
Definition: nodes.h:129
@ LOGSTMT_NONE
Definition: tcopprot.h:37
@ LOGSTMT_ALL
Definition: tcopprot.h:40
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3249

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

Referenced by exec_execute_message(), and exec_simple_query().

◆ check_log_stats()

bool check_log_stats ( bool newval,
void **  extra,
GucSource  source 
)

Definition at line 3673 of file postgres.c.

3674 {
3675  if (*newval &&
3677  {
3678  GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3679  "\"log_parser_stats\", \"log_planner_stats\", "
3680  "or \"log_executor_stats\" is true.");
3681  return false;
3682  }
3683  return true;
3684 }
bool log_parser_stats
Definition: guc_tables.c:502
bool log_planner_stats
Definition: guc_tables.c:503
bool log_executor_stats
Definition: guc_tables.c:504

References GUC_check_errdetail, log_executor_stats, log_parser_stats, log_planner_stats, and newval.

◆ check_max_stack_depth()

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

Definition at line 3610 of file postgres.c.

3611 {
3612  long newval_bytes = *newval * 1024L;
3613  long stack_rlimit = get_stack_depth_rlimit();
3614 
3615  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3616  {
3617  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3618  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3619  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3620  return false;
3621  }
3622  return true;
3623 }
#define GUC_check_errhint
Definition: guc.h:480
long get_stack_depth_rlimit(void)
Definition: postgres.c:5079
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:25

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

◆ check_restrict_nonsystem_relation_kind()

bool check_restrict_nonsystem_relation_kind ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 3707 of file postgres.c.

3708 {
3709  char *rawstring;
3710  List *elemlist;
3711  ListCell *l;
3712  int flags = 0;
3713 
3714  /* Need a modifiable copy of string */
3715  rawstring = pstrdup(*newval);
3716 
3717  if (!SplitIdentifierString(rawstring, ',', &elemlist))
3718  {
3719  /* syntax error in list */
3720  GUC_check_errdetail("List syntax is invalid.");
3721  pfree(rawstring);
3722  list_free(elemlist);
3723  return false;
3724  }
3725 
3726  foreach(l, elemlist)
3727  {
3728  char *tok = (char *) lfirst(l);
3729 
3730  if (pg_strcasecmp(tok, "view") == 0)
3731  flags |= RESTRICT_RELKIND_VIEW;
3732  else if (pg_strcasecmp(tok, "foreign-table") == 0)
3734  else
3735  {
3736  GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3737  pfree(rawstring);
3738  list_free(elemlist);
3739  return false;
3740  }
3741  }
3742 
3743  pfree(rawstring);
3744  list_free(elemlist);
3745 
3746  /* Save the flags in *extra, for use by the assign function */
3747  *extra = guc_malloc(ERROR, sizeof(int));
3748  *((int *) *extra) = flags;
3749 
3750  return true;
3751 }
#define ERROR
Definition: elog.h:39
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:638
void list_free(List *list)
Definition: list.c:1546
char * pstrdup(const char *in)
Definition: mcxt.c:1696
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
Definition: pg_list.h:54
#define RESTRICT_RELKIND_FOREIGN_TABLE
Definition: tcopprot.h:48
#define RESTRICT_RELKIND_VIEW
Definition: tcopprot.h:47
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3432

References ERROR, GUC_check_errdetail, guc_malloc(), lfirst, list_free(), newval, pfree(), pg_strcasecmp(), pstrdup(), RESTRICT_RELKIND_FOREIGN_TABLE, RESTRICT_RELKIND_VIEW, and SplitIdentifierString().

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3563 of file postgres.c.

3564 {
3565  if (stack_is_too_deep())
3566  {
3567  ereport(ERROR,
3568  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3569  errmsg("stack depth limit exceeded"),
3570  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3571  "after ensuring the platform's stack depth limit is adequate.",
3572  max_stack_depth)));
3573  }
3574 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
int max_stack_depth
Definition: postgres.c:98
bool stack_is_too_deep(void)
Definition: postgres.c:3577

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

Referenced by _jumbleNode(), AlterTypeRecurse(), apply_scanjoin_target_to_paths(), ATAddCheckNNConstraint(), ATExecAddColumn(), ATExecAlterConstrRecurse(), ATExecDropColumn(), ATExecSetNotNull(), CheckAttributeType(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json_internal(), datum_to_jsonb_internal(), dofindsubquery(), dropconstraint_internal(), emit_jsp_gin_entries(), equal(), eval_const_expressions_mutator(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), executeBoolItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator_impl(), expression_tree_walker_impl(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findDependentObjects(), 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(), is_simple_union_all_recurse(), JsonbDeepContains(), lseg_inside_poly(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), p_ishost(), p_isURLPath(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker_impl(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), pull_up_sublinks_jointree_recurse(), pull_up_subqueries_recurse(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker_impl(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), regex_selectivity_sub(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), setPath(), split_array(), SplitToVariants(), standard_ProcessUtility(), transformExprRecurse(), transformFromClauseItem(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute_locations_recurse(), TS_execute_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

◆ check_stage_log_stats()

bool check_stage_log_stats ( bool newval,
void **  extra,
GucSource  source 
)

Definition at line 3659 of file postgres.c.

3660 {
3661  if (*newval && log_statement_stats)
3662  {
3663  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3664  return false;
3665  }
3666  return true;
3667 }
bool log_statement_stats
Definition: guc_tables.c:505

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 3004 of file postgres.c.

3005 {
3006  /* Don't joggle the elbow of proc_exit */
3007  if (!proc_exit_inprogress)
3008  {
3009  InterruptPending = true;
3010  ProcDiePending = true;
3011  }
3012 
3013  /* for the cumulative stats system */
3015 
3016  /* If we're still here, waken anything waiting on the process latch */
3017  SetLatch(MyLatch);
3018 
3019  /*
3020  * If we're in single user mode, we want to quit immediately - we can't
3021  * rely on latches as they wouldn't work when stdin/stdout is a file.
3022  * Rather ugly, but it's unlikely to be worthwhile to invest much more
3023  * effort just for the benefit of single user mode.
3024  */
3027 }
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:62
volatile sig_atomic_t ProcDiePending
Definition: globals.c:33
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:632
@ DISCONNECT_KILLED
Definition: pgstat.h:113
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool DoingCommandRead
Definition: postgres.c:147
void ProcessInterrupts(void)
Definition: postgres.c:3276

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

Referenced by PostgresMain().

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

Definition at line 5285 of file postgres.c.

5286 {
5289 }
@ STATEMENT_TIMEOUT
Definition: timeout.h:29

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

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

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2882 of file postgres.c.

2883 {
2884  /* paranoia to avoid a dangling pointer in case of error */
2885  if (unnamed_stmt_psrc)
2886  {
2888 
2889  unnamed_stmt_psrc = NULL;
2890  DropCachedPlan(psrc);
2891  }
2892 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:526
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:161

References DropCachedPlan(), and unnamed_stmt_psrc.

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

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

Definition at line 5263 of file postgres.c.

5264 {
5265  /* must be within an xact */
5267 
5268  if (StatementTimeout > 0
5270  {
5273  }
5274  else
5275  {
5278  }
5279 }
#define Assert(condition)
Definition: c.h:861
static bool xact_started
Definition: postgres.c:140
int StatementTimeout
Definition: proc.c:58
int TransactionTimeout
Definition: proc.c:61

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

Referenced by start_xact_command().

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2528 of file postgres.c.

2529 {
2531  errdetail("Abort reason: recovery conflict");
2532 
2533  return 0;
2534 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
PGPROC * MyProc
Definition: proc.c:66
bool recoveryConflictPending
Definition: proc.h:220

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

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2475 of file postgres.c.

2476 {
2477  ListCell *parsetree_item;
2478 
2479  foreach(parsetree_item, raw_parsetree_list)
2480  {
2481  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2482 
2483  if (IsA(parsetree->stmt, ExecuteStmt))
2484  {
2485  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2486  PreparedStatement *pstmt;
2487 
2488  pstmt = FetchPreparedStatement(stmt->name, false);
2489  if (pstmt)
2490  {
2491  errdetail("prepare: %s", pstmt->plansource->query_string);
2492  return 0;
2493  }
2494  }
2495  }
2496 
2497  return 0;
2498 }
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:431
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define lfirst_node(type, lc)
Definition: pg_list.h:176
Node * stmt
Definition: parsenodes.h:2022

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

Referenced by exec_simple_query().

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2508 of file postgres.c.

2509 {
2510  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2511  {
2512  char *str;
2513 
2515  if (str && str[0] != '\0')
2516  errdetail("Parameters: %s", str);
2517  }
2518 
2519  return 0;
2520 }
int log_parameter_max_length
Definition: guc_tables.c:526
const char * str
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335

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

Referenced by exec_bind_message(), and exec_execute_message().

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( ProcSignalReason  reason)
static

Definition at line 2542 of file postgres.c.

2543 {
2544  switch (reason)
2545  {
2547  errdetail("User was holding shared buffer pin for too long.");
2548  break;
2550  errdetail("User was holding a relation lock for too long.");
2551  break;
2553  errdetail("User was or might have been using tablespace that must be dropped.");
2554  break;
2556  errdetail("User query might have needed to see row versions that must be removed.");
2557  break;
2559  errdetail("User was using a logical replication slot that must be invalidated.");
2560  break;
2562  errdetail("User transaction caused buffer deadlock with recovery.");
2563  break;
2565  errdetail("User was connected to a database that must be dropped.");
2566  break;
2567  default:
2568  break;
2569  /* no errdetail */
2570  }
2571 
2572  return 0;
2573 }
@ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
Definition: procsignal.h:47
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:44
@ PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT
Definition: procsignal.h:46
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:42
@ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
Definition: procsignal.h:45
@ PROCSIG_RECOVERY_CONFLICT_TABLESPACE
Definition: procsignal.h:43
@ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition: procsignal.h:48

References errdetail(), PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, and PROCSIG_RECOVERY_CONFLICT_TABLESPACE.

Referenced by ProcessRecoveryConflictInterrupt().

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1635 of file postgres.c.

1636 {
1637  const char *portal_name;
1638  const char *stmt_name;
1639  int numPFormats;
1640  int16 *pformats = NULL;
1641  int numParams;
1642  int numRFormats;
1643  int16 *rformats = NULL;
1644  CachedPlanSource *psrc;
1645  CachedPlan *cplan;
1646  Portal portal;
1647  char *query_string;
1648  char *saved_stmt_name;
1649  ParamListInfo params;
1650  MemoryContext oldContext;
1651  bool save_log_statement_stats = log_statement_stats;
1652  bool snapshot_set = false;
1653  char msec_str[32];
1654  ParamsErrorCbData params_data;
1655  ErrorContextCallback params_errcxt;
1656  ListCell *lc;
1657 
1658  /* Get the fixed part of the message */
1659  portal_name = pq_getmsgstring(input_message);
1660  stmt_name = pq_getmsgstring(input_message);
1661 
1662  ereport(DEBUG2,
1663  (errmsg_internal("bind %s to %s",
1664  *portal_name ? portal_name : "<unnamed>",
1665  *stmt_name ? stmt_name : "<unnamed>")));
1666 
1667  /* Find prepared statement */
1668  if (stmt_name[0] != '\0')
1669  {
1670  PreparedStatement *pstmt;
1671 
1672  pstmt = FetchPreparedStatement(stmt_name, true);
1673  psrc = pstmt->plansource;
1674  }
1675  else
1676  {
1677  /* special-case the unnamed statement */
1678  psrc = unnamed_stmt_psrc;
1679  if (!psrc)
1680  ereport(ERROR,
1681  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1682  errmsg("unnamed prepared statement does not exist")));
1683  }
1684 
1685  /*
1686  * Report query to various monitoring facilities.
1687  */
1689 
1691 
1692  foreach(lc, psrc->query_list)
1693  {
1694  Query *query = lfirst_node(Query, lc);
1695 
1696  if (query->queryId != UINT64CONST(0))
1697  {
1698  pgstat_report_query_id(query->queryId, false);
1699  break;
1700  }
1701  }
1702 
1703  set_ps_display("BIND");
1704 
1705  if (save_log_statement_stats)
1706  ResetUsage();
1707 
1708  /*
1709  * Start up a transaction command so we can call functions etc. (Note that
1710  * this will normally change current memory context.) Nothing happens if
1711  * we are already in one. This also arms the statement timeout if
1712  * necessary.
1713  */
1715 
1716  /* Switch back to message context */
1718 
1719  /* Get the parameter format codes */
1720  numPFormats = pq_getmsgint(input_message, 2);
1721  if (numPFormats > 0)
1722  {
1723  pformats = palloc_array(int16, numPFormats);
1724  for (int i = 0; i < numPFormats; i++)
1725  pformats[i] = pq_getmsgint(input_message, 2);
1726  }
1727 
1728  /* Get the parameter value count */
1729  numParams = pq_getmsgint(input_message, 2);
1730 
1731  if (numPFormats > 1 && numPFormats != numParams)
1732  ereport(ERROR,
1733  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1734  errmsg("bind message has %d parameter formats but %d parameters",
1735  numPFormats, numParams)));
1736 
1737  if (numParams != psrc->num_params)
1738  ereport(ERROR,
1739  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1740  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1741  numParams, stmt_name, psrc->num_params)));
1742 
1743  /*
1744  * If we are in aborted transaction state, the only portals we can
1745  * actually run are those containing COMMIT or ROLLBACK commands. We
1746  * disallow binding anything else to avoid problems with infrastructure
1747  * that expects to run inside a valid transaction. We also disallow
1748  * binding any parameters, since we can't risk calling user-defined I/O
1749  * functions.
1750  */
1752  (!(psrc->raw_parse_tree &&
1754  numParams != 0))
1755  ereport(ERROR,
1756  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1757  errmsg("current transaction is aborted, "
1758  "commands ignored until end of transaction block"),
1759  errdetail_abort()));
1760 
1761  /*
1762  * Create the portal. Allow silent replacement of an existing portal only
1763  * if the unnamed portal is specified.
1764  */
1765  if (portal_name[0] == '\0')
1766  portal = CreatePortal(portal_name, true, true);
1767  else
1768  portal = CreatePortal(portal_name, false, false);
1769 
1770  /*
1771  * Prepare to copy stuff into the portal's memory context. We do all this
1772  * copying first, because it could possibly fail (out-of-memory) and we
1773  * don't want a failure to occur between GetCachedPlan and
1774  * PortalDefineQuery; that would result in leaking our plancache refcount.
1775  */
1776  oldContext = MemoryContextSwitchTo(portal->portalContext);
1777 
1778  /* Copy the plan's query string into the portal */
1779  query_string = pstrdup(psrc->query_string);
1780 
1781  /* Likewise make a copy of the statement name, unless it's unnamed */
1782  if (stmt_name[0])
1783  saved_stmt_name = pstrdup(stmt_name);
1784  else
1785  saved_stmt_name = NULL;
1786 
1787  /*
1788  * Set a snapshot if we have parameters to fetch (since the input
1789  * functions might need it) or the query isn't a utility command (and
1790  * hence could require redoing parse analysis and planning). We keep the
1791  * snapshot active till we're done, so that plancache.c doesn't have to
1792  * take new ones.
1793  */
1794  if (numParams > 0 ||
1795  (psrc->raw_parse_tree &&
1797  {
1799  snapshot_set = true;
1800  }
1801 
1802  /*
1803  * Fetch parameters, if any, and store in the portal's memory context.
1804  */
1805  if (numParams > 0)
1806  {
1807  char **knownTextValues = NULL; /* allocate on first use */
1808  BindParamCbData one_param_data;
1809 
1810  /*
1811  * Set up an error callback so that if there's an error in this phase,
1812  * we can report the specific parameter causing the problem.
1813  */
1814  one_param_data.portalName = portal->name;
1815  one_param_data.paramno = -1;
1816  one_param_data.paramval = NULL;
1817  params_errcxt.previous = error_context_stack;
1818  params_errcxt.callback = bind_param_error_callback;
1819  params_errcxt.arg = (void *) &one_param_data;
1820  error_context_stack = &params_errcxt;
1821 
1822  params = makeParamList(numParams);
1823 
1824  for (int paramno = 0; paramno < numParams; paramno++)
1825  {
1826  Oid ptype = psrc->param_types[paramno];
1827  int32 plength;
1828  Datum pval;
1829  bool isNull;
1830  StringInfoData pbuf;
1831  char csave;
1832  int16 pformat;
1833 
1834  one_param_data.paramno = paramno;
1835  one_param_data.paramval = NULL;
1836 
1837  plength = pq_getmsgint(input_message, 4);
1838  isNull = (plength == -1);
1839 
1840  if (!isNull)
1841  {
1842  char *pvalue;
1843 
1844  /*
1845  * Rather than copying data around, we just initialize a
1846  * StringInfo pointing to the correct portion of the message
1847  * buffer. We assume we can scribble on the message buffer to
1848  * add a trailing NUL which is required for the input function
1849  * call.
1850  */
1851  pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
1852  csave = pvalue[plength];
1853  pvalue[plength] = '\0';
1854  initReadOnlyStringInfo(&pbuf, pvalue, plength);
1855  }
1856  else
1857  {
1858  pbuf.data = NULL; /* keep compiler quiet */
1859  csave = 0;
1860  }
1861 
1862  if (numPFormats > 1)
1863  pformat = pformats[paramno];
1864  else if (numPFormats > 0)
1865  pformat = pformats[0];
1866  else
1867  pformat = 0; /* default = text */
1868 
1869  if (pformat == 0) /* text mode */
1870  {
1871  Oid typinput;
1872  Oid typioparam;
1873  char *pstring;
1874 
1875  getTypeInputInfo(ptype, &typinput, &typioparam);
1876 
1877  /*
1878  * We have to do encoding conversion before calling the
1879  * typinput routine.
1880  */
1881  if (isNull)
1882  pstring = NULL;
1883  else
1884  pstring = pg_client_to_server(pbuf.data, plength);
1885 
1886  /* Now we can log the input string in case of error */
1887  one_param_data.paramval = pstring;
1888 
1889  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1890 
1891  one_param_data.paramval = NULL;
1892 
1893  /*
1894  * If we might need to log parameters later, save a copy of
1895  * the converted string in MessageContext; then free the
1896  * result of encoding conversion, if any was done.
1897  */
1898  if (pstring)
1899  {
1901  {
1902  MemoryContext oldcxt;
1903 
1905 
1906  if (knownTextValues == NULL)
1907  knownTextValues = palloc0_array(char *, numParams);
1908 
1910  knownTextValues[paramno] = pstrdup(pstring);
1911  else
1912  {
1913  /*
1914  * We can trim the saved string, knowing that we
1915  * won't print all of it. But we must copy at
1916  * least two more full characters than
1917  * BuildParamLogString wants to use; otherwise it
1918  * might fail to include the trailing ellipsis.
1919  */
1920  knownTextValues[paramno] =
1921  pnstrdup(pstring,
1923  + 2 * MAX_MULTIBYTE_CHAR_LEN);
1924  }
1925 
1926  MemoryContextSwitchTo(oldcxt);
1927  }
1928  if (pstring != pbuf.data)
1929  pfree(pstring);
1930  }
1931  }
1932  else if (pformat == 1) /* binary mode */
1933  {
1934  Oid typreceive;
1935  Oid typioparam;
1936  StringInfo bufptr;
1937 
1938  /*
1939  * Call the parameter type's binary input converter
1940  */
1941  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1942 
1943  if (isNull)
1944  bufptr = NULL;
1945  else
1946  bufptr = &pbuf;
1947 
1948  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1949 
1950  /* Trouble if it didn't eat the whole buffer */
1951  if (!isNull && pbuf.cursor != pbuf.len)
1952  ereport(ERROR,
1953  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1954  errmsg("incorrect binary data format in bind parameter %d",
1955  paramno + 1)));
1956  }
1957  else
1958  {
1959  ereport(ERROR,
1960  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1961  errmsg("unsupported format code: %d",
1962  pformat)));
1963  pval = 0; /* keep compiler quiet */
1964  }
1965 
1966  /* Restore message buffer contents */
1967  if (!isNull)
1968  pbuf.data[plength] = csave;
1969 
1970  params->params[paramno].value = pval;
1971  params->params[paramno].isnull = isNull;
1972 
1973  /*
1974  * We mark the params as CONST. This ensures that any custom plan
1975  * makes full use of the parameter values.
1976  */
1977  params->params[paramno].pflags = PARAM_FLAG_CONST;
1978  params->params[paramno].ptype = ptype;
1979  }
1980 
1981  /* Pop the per-parameter error callback */
1983 
1984  /*
1985  * Once all parameters have been received, prepare for printing them
1986  * in future errors, if configured to do so. (This is saved in the
1987  * portal, so that they'll appear when the query is executed later.)
1988  */
1990  params->paramValuesStr =
1991  BuildParamLogString(params,
1992  knownTextValues,
1994  }
1995  else
1996  params = NULL;
1997 
1998  /* Done storing stuff in portal's context */
1999  MemoryContextSwitchTo(oldContext);
2000 
2001  /*
2002  * Set up another error callback so that all the parameters are logged if
2003  * we get an error during the rest of the BIND processing.
2004  */
2005  params_data.portalName = portal->name;
2006  params_data.params = params;
2007  params_errcxt.previous = error_context_stack;
2008  params_errcxt.callback = ParamsErrorCallback;
2009  params_errcxt.arg = (void *) &params_data;
2010  error_context_stack = &params_errcxt;
2011 
2012  /* Get the result format codes */
2013  numRFormats = pq_getmsgint(input_message, 2);
2014  if (numRFormats > 0)
2015  {
2016  rformats = palloc_array(int16, numRFormats);
2017  for (int i = 0; i < numRFormats; i++)
2018  rformats[i] = pq_getmsgint(input_message, 2);
2019  }
2020 
2021  pq_getmsgend(input_message);
2022 
2023  /*
2024  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2025  * will be generated in MessageContext. The plan refcount will be
2026  * assigned to the Portal, so it will be released at portal destruction.
2027  */
2028  cplan = GetCachedPlan(psrc, params, NULL, NULL);
2029 
2030  /*
2031  * Now we can define the portal.
2032  *
2033  * DO NOT put any code that could possibly throw an error between the
2034  * above GetCachedPlan call and here.
2035  */
2036  PortalDefineQuery(portal,
2037  saved_stmt_name,
2038  query_string,
2039  psrc->commandTag,
2040  cplan->stmt_list,
2041  cplan);
2042 
2043  /* Done with the snapshot used for parameter I/O and parsing/planning */
2044  if (snapshot_set)
2046 
2047  /*
2048  * And we're ready to start portal execution.
2049  */
2050  PortalStart(portal, params, 0, InvalidSnapshot);
2051 
2052  /*
2053  * Apply the result format requests to the portal.
2054  */
2055  PortalSetResultFormat(portal, numRFormats, rformats);
2056 
2057  /*
2058  * Done binding; remove the parameters error callback. Entries emitted
2059  * later determine independently whether to log the parameters or not.
2060  */
2062 
2063  /*
2064  * Send BindComplete.
2065  */
2068 
2069  /*
2070  * Emit duration logging if appropriate.
2071  */
2072  switch (check_log_duration(msec_str, false))
2073  {
2074  case 1:
2075  ereport(LOG,
2076  (errmsg("duration: %s ms", msec_str),
2077  errhidestmt(true)));
2078  break;
2079  case 2:
2080  ereport(LOG,
2081  (errmsg("duration: %s ms bind %s%s%s: %s",
2082  msec_str,
2083  *stmt_name ? stmt_name : "<unnamed>",
2084  *portal_name ? "/" : "",
2085  *portal_name ? portal_name : "",
2086  psrc->query_string),
2087  errhidestmt(true),
2088  errdetail_params(params)));
2089  break;
2090  }
2091 
2092  if (save_log_statement_stats)
2093  ShowUsage("BIND MESSAGE STATISTICS");
2094 
2096 
2097  debug_query_string = NULL;
2098 }
void pgstat_report_query_id(uint64 query_id, bool force)
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
#define unconstify(underlying_type, expr)
Definition: c.h:1248
signed short int16
Definition: c.h:507
signed int int32
Definition: c.h:508
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errhidestmt(bool hide_stmt)
Definition: elog.c:1411
ErrorContextCallback * error_context_stack
Definition: elog.c:94
#define LOG
Definition: elog.h:31
#define DEBUG2
Definition: elog.h:29
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1772
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1754
int i
Definition: isn.c:72
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2874
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2940
char * pg_client_to_server(const char *s, int len)
Definition: mbutils.c:660
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1707
MemoryContext MessageContext
Definition: mcxt.c:153
ParamListInfo makeParamList(int numParams)
Definition: params.c:44
void ParamsErrorCallback(void *arg)
Definition: params.c:407
#define PARAM_FLAG_CONST
Definition: params.h:88
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:576
#define MAX_MULTIBYTE_CHAR_LEN
Definition: pg_wchar.h:33
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, ResourceOwner owner, QueryEnvironment *queryEnv)
Definition: plancache.c:1168
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, CommandTag commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:282
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
static int errdetail_abort(void)
Definition: postgres.c:2528
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2412
const char * debug_query_string
Definition: postgres.c:87
void ShowUsage(const char *title)
Definition: postgres.c:5118
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2508
static void bind_param_error_callback(void *arg)
Definition: postgres.c:2581
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2835
void ResetUsage(void)
Definition: postgres.c:5111
static void start_xact_command(void)
Definition: postgres.c:2775
#define valgrind_report_error_query(query)
Definition: postgres.c:227
uintptr_t Datum
Definition: postgres.h:64
unsigned int Oid
Definition: postgres_ext.h:31
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:415
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:579
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:635
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:508
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:388
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:623
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:433
#define PqMsg_BindComplete
Definition: protocol.h:39
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
MemoryContextSwitchTo(old_ctx)
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:648
void PopActiveSnapshot(void)
Definition: snapmgr.c:743
#define InvalidSnapshot
Definition: snapshot.h:123
static void initReadOnlyStringInfo(StringInfo str, char *data, int len)
Definition: stringinfo.h:130
const char * portalName
Definition: postgres.c:117
const char * paramval
Definition: postgres.c:119
CommandTag commandTag
Definition: plancache.h:101
const char * query_string
Definition: plancache.h:100
struct RawStmt * raw_parse_tree
Definition: plancache.h:99
List * query_list
Definition: plancache.h:111
List * stmt_list
Definition: plancache.h:150
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
bool isnull
Definition: params.h:93
uint16 pflags
Definition: params.h:94
Datum value
Definition: params.h:92
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
char * paramValuesStr
Definition: params.h:118
ParamListInfo params
Definition: params.h:157
const char * portalName
Definition: params.h:156
MemoryContext portalContext
Definition: portal.h:120
const char * name
Definition: portal.h:118
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:406

References analyze_requires_snapshot(), ErrorContextCallback::arg, bind_param_error_callback(), 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(), errmsg_internal(), ERROR, error_context_stack, FetchPreparedStatement(), GetCachedPlan(), GetTransactionSnapshot(), getTypeBinaryInputInfo(), getTypeInputInfo(), i, initReadOnlyStringInfo(), InvalidSnapshot, IsAbortedTransactionBlockState(), ParamExternData::isnull, IsTransactionExitStmt(), StringInfoData::len, lfirst_node, LOG, log_parameter_max_length_on_error, log_statement_stats, makeParamList(), MAX_MULTIBYTE_CHAR_LEN, MemoryContextSwitchTo(), MessageContext, PortalData::name, CachedPlanSource::num_params, OidInputFunctionCall(), OidReceiveFunctionCall(), palloc0_array, palloc_array, PARAM_FLAG_CONST, CachedPlanSource::param_types, BindParamCbData::paramno, ParamListInfoData::params, ParamsErrorCbData::params, ParamsErrorCallback(), BindParamCbData::paramval, ParamListInfoData::paramValuesStr, ParamExternData::pflags, pfree(), pg_client_to_server(), pgstat_report_activity(), pgstat_report_query_id(), PreparedStatement::plansource, pnstrdup(), PopActiveSnapshot(), PortalData::portalContext, PortalDefineQuery(), BindParamCbData::portalName, ParamsErrorCbData::portalName, PortalSetResultFormat(), PortalStart(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_putemptymessage(), PqMsg_BindComplete, ErrorContextCallback::previous, pstrdup(), ParamExternData::ptype, PushActiveSnapshot(), CachedPlanSource::query_list, 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, valgrind_report_error_query, ParamExternData::value, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

Definition at line 2723 of file postgres.c.

2724 {
2725  Portal portal;
2726 
2727  /*
2728  * Start up a transaction command. (Note that this will normally change
2729  * current memory context.) Nothing happens if we are already in one.
2730  */
2732 
2733  /* Switch back to message context */
2735 
2736  portal = GetPortalByName(portal_name);
2737  if (!PortalIsValid(portal))
2738  ereport(ERROR,
2739  (errcode(ERRCODE_UNDEFINED_CURSOR),
2740  errmsg("portal \"%s\" does not exist", portal_name)));
2741 
2742  /*
2743  * If we are in aborted transaction state, we can't run
2744  * SendRowDescriptionMessage(), because that needs catalog accesses.
2745  * Hence, refuse to Describe portals that return data. (We shouldn't just
2746  * refuse all Describes, since that might break the ability of some
2747  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2748  * blindly Describes whatever it does.)
2749  */
2751  portal->tupDesc)
2752  ereport(ERROR,
2753  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2754  errmsg("current transaction is aborted, "
2755  "commands ignored until end of transaction block"),
2756  errdetail_abort()));
2757 
2759  return; /* can't actually do anything... */
2760 
2761  if (portal->tupDesc)
2763  portal->tupDesc,
2764  FetchPortalTargetList(portal),
2765  portal->formats);
2766  else
2768 }
#define PortalIsValid(p)
Definition: portal.h:212
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
static StringInfoData row_description_buf
Definition: postgres.c:174
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:326
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:166
#define PqMsg_NoData
Definition: protocol.h:56
int16 * formats
Definition: portal.h:162
TupleDesc tupDesc
Definition: portal.h:160

References DestRemote, ereport, errcode(), errdetail_abort(), errmsg(), ERROR, FetchPortalTargetList(), PortalData::formats, GetPortalByName(), IsAbortedTransactionBlockState(), MemoryContextSwitchTo(), MessageContext, PortalIsValid, pq_putemptymessage(), PqMsg_NoData, row_description_buf, SendRowDescriptionMessage(), start_xact_command(), PortalData::tupDesc, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2630 of file postgres.c.

2631 {
2632  CachedPlanSource *psrc;
2633 
2634  /*
2635  * Start up a transaction command. (Note that this will normally change
2636  * current memory context.) Nothing happens if we are already in one.
2637  */
2639 
2640  /* Switch back to message context */
2642 
2643  /* Find prepared statement */
2644  if (stmt_name[0] != '\0')
2645  {
2646  PreparedStatement *pstmt;
2647 
2648  pstmt = FetchPreparedStatement(stmt_name, true);
2649  psrc = pstmt->plansource;
2650  }
2651  else
2652  {
2653  /* special-case the unnamed statement */
2654  psrc = unnamed_stmt_psrc;
2655  if (!psrc)
2656  ereport(ERROR,
2657  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2658  errmsg("unnamed prepared statement does not exist")));
2659  }
2660 
2661  /* Prepared statements shouldn't have changeable result descs */
2662  Assert(psrc->fixed_result);
2663 
2664  /*
2665  * If we are in aborted transaction state, we can't run
2666  * SendRowDescriptionMessage(), because that needs catalog accesses.
2667  * Hence, refuse to Describe statements that return data. (We shouldn't
2668  * just refuse all Describes, since that might break the ability of some
2669  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2670  * blindly Describes whatever it does.) We can Describe parameters
2671  * without doing anything dangerous, so we don't restrict that.
2672  */
2674  psrc->resultDesc)
2675  ereport(ERROR,
2676  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2677  errmsg("current transaction is aborted, "
2678  "commands ignored until end of transaction block"),
2679  errdetail_abort()));
2680 
2682  return; /* can't actually do anything... */
2683 
2684  /*
2685  * First describe the parameters...
2686  */
2689 
2690  for (int i = 0; i < psrc->num_params; i++)
2691  {
2692  Oid ptype = psrc->param_types[i];
2693 
2694  pq_sendint32(&row_description_buf, (int) ptype);
2695  }
2697 
2698  /*
2699  * Next send RowDescription or NoData to describe the result...
2700  */
2701  if (psrc->resultDesc)
2702  {
2703  List *tlist;
2704 
2705  /* Get the plan's primary targetlist */
2706  tlist = CachedPlanGetTargetList(psrc, NULL);
2707 
2709  psrc->resultDesc,
2710  tlist,
2711  NULL);
2712  }
2713  else
2715 }
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1640
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition: pqformat.c:109
void pq_endmessage_reuse(StringInfo buf)
Definition: pqformat.c:314
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:144
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:136
#define PqMsg_ParameterDescription
Definition: protocol.h:58
TupleDesc resultDesc
Definition: plancache.h:108

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(), PqMsg_NoData, PqMsg_ParameterDescription, CachedPlanSource::resultDesc, row_description_buf, SendRowDescriptionMessage(), start_xact_command(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_execute_message()

static void exec_execute_message ( const char *  portal_name,
long  max_rows 
)
static

Definition at line 2106 of file postgres.c.

2107 {
2108  CommandDest dest;
2109  DestReceiver *receiver;
2110  Portal portal;
2111  bool completed;
2112  QueryCompletion qc;
2113  const char *sourceText;
2114  const char *prepStmtName;
2115  ParamListInfo portalParams;
2116  bool save_log_statement_stats = log_statement_stats;
2117  bool is_xact_command;
2118  bool execute_is_fetch;
2119  bool was_logged = false;
2120  char msec_str[32];
2121  ParamsErrorCbData params_data;
2122  ErrorContextCallback params_errcxt;
2123  const char *cmdtagname;
2124  size_t cmdtaglen;
2125  ListCell *lc;
2126 
2127  /* Adjust destination to tell printtup.c what to do */
2129  if (dest == DestRemote)
2131 
2132  portal = GetPortalByName(portal_name);
2133  if (!PortalIsValid(portal))
2134  ereport(ERROR,
2135  (errcode(ERRCODE_UNDEFINED_CURSOR),
2136  errmsg("portal \"%s\" does not exist", portal_name)));
2137 
2138  /*
2139  * If the original query was a null string, just return
2140  * EmptyQueryResponse.
2141  */
2142  if (portal->commandTag == CMDTAG_UNKNOWN)
2143  {
2144  Assert(portal->stmts == NIL);
2145  NullCommand(dest);
2146  return;
2147  }
2148 
2149  /* Does the portal contain a transaction command? */
2150  is_xact_command = IsTransactionStmtList(portal->stmts);
2151 
2152  /*
2153  * We must copy the sourceText and prepStmtName into MessageContext in
2154  * case the portal is destroyed during finish_xact_command. We do not
2155  * make a copy of the portalParams though, preferring to just not print
2156  * them in that case.
2157  */
2158  sourceText = pstrdup(portal->sourceText);
2159  if (portal->prepStmtName)
2160  prepStmtName = pstrdup(portal->prepStmtName);
2161  else
2162  prepStmtName = "<unnamed>";
2163  portalParams = portal->portalParams;
2164 
2165  /*
2166  * Report query to various monitoring facilities.
2167  */
2168  debug_query_string = sourceText;
2169 
2171 
2172  foreach(lc, portal->stmts)
2173  {
2175 
2176  if (stmt->queryId != UINT64CONST(0))
2177  {
2178  pgstat_report_query_id(stmt->queryId, false);
2179  break;
2180  }
2181  }
2182 
2183  cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
2184 
2185  set_ps_display_with_len(cmdtagname, cmdtaglen);
2186 
2187  if (save_log_statement_stats)
2188  ResetUsage();
2189 
2190  BeginCommand(portal->commandTag, dest);
2191 
2192  /*
2193  * Create dest receiver in MessageContext (we don't want it in transaction
2194  * context, because that may get deleted if portal contains VACUUM).
2195  */
2196  receiver = CreateDestReceiver(dest);
2197  if (dest == DestRemoteExecute)
2198  SetRemoteDestReceiverParams(receiver, portal);
2199 
2200  /*
2201  * Ensure we are in a transaction command (this should normally be the
2202  * case already due to prior BIND).
2203  */
2205 
2206  /*
2207  * If we re-issue an Execute protocol request against an existing portal,
2208  * then we are only fetching more rows rather than completely re-executing
2209  * the query from the start. atStart is never reset for a v3 portal, so we
2210  * are safe to use this check.
2211  */
2212  execute_is_fetch = !portal->atStart;
2213 
2214  /* Log immediately if dictated by log_statement */
2215  if (check_log_statement(portal->stmts))
2216  {
2217  ereport(LOG,
2218  (errmsg("%s %s%s%s: %s",
2219  execute_is_fetch ?
2220  _("execute fetch from") :
2221  _("execute"),
2222  prepStmtName,
2223  *portal_name ? "/" : "",
2224  *portal_name ? portal_name : "",
2225  sourceText),
2226  errhidestmt(true),
2227  errdetail_params(portalParams)));
2228  was_logged = true;
2229  }
2230 
2231  /*
2232  * If we are in aborted transaction state, the only portals we can
2233  * actually run are those containing COMMIT or ROLLBACK commands.
2234  */
2236  !IsTransactionExitStmtList(portal->stmts))
2237  ereport(ERROR,
2238  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2239  errmsg("current transaction is aborted, "
2240  "commands ignored until end of transaction block"),
2241  errdetail_abort()));
2242 
2243  /* Check for cancel signal before we start execution */
2245 
2246  /*
2247  * Okay to run the portal. Set the error callback so that parameters are
2248  * logged. The parameters must have been saved during the bind phase.
2249  */
2250  params_data.portalName = portal->name;
2251  params_data.params = portalParams;
2252  params_errcxt.previous = error_context_stack;
2253  params_errcxt.callback = ParamsErrorCallback;
2254  params_errcxt.arg = (void *) &params_data;
2255  error_context_stack = &params_errcxt;
2256 
2257  if (max_rows <= 0)
2258  max_rows = FETCH_ALL;
2259 
2260  completed = PortalRun(portal,
2261  max_rows,
2262  true, /* always top level */
2263  !execute_is_fetch && max_rows == FETCH_ALL,
2264  receiver,
2265  receiver,
2266  &qc);
2267 
2268  receiver->rDestroy(receiver);
2269 
2270  /* Done executing; remove the params error callback */
2272 
2273  if (completed)
2274  {
2275  if (is_xact_command || (MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT))
2276  {
2277  /*
2278  * If this was a transaction control statement, commit it. We
2279  * will start a new xact command for the next command (if any).
2280  * Likewise if the statement required immediate commit. Without
2281  * this provision, we wouldn't force commit until Sync is
2282  * received, which creates a hazard if the client tries to
2283  * pipeline immediate-commit statements.
2284  */
2286 
2287  /*
2288  * These commands typically don't have any parameters, and even if
2289  * one did we couldn't print them now because the storage went
2290  * away during finish_xact_command. So pretend there were none.
2291  */
2292  portalParams = NULL;
2293  }
2294  else
2295  {
2296  /*
2297  * We need a CommandCounterIncrement after every query, except
2298  * those that start or end a transaction block.
2299  */
2301 
2302  /*
2303  * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2304  * message without immediately committing the transaction.
2305  */
2307 
2308  /*
2309  * Disable statement timeout whenever we complete an Execute
2310  * message. The next protocol message will start a fresh timeout.
2311  */
2313  }
2314 
2315  /* Send appropriate CommandComplete to client */
2316  EndCommand(&qc, dest, false);
2317  }
2318  else
2319  {
2320  /* Portal run not complete, so send PortalSuspended */
2323 
2324  /*
2325  * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2326  * too.
2327  */
2329  }
2330 
2331  /*
2332  * Emit duration logging if appropriate.
2333  */
2334  switch (check_log_duration(msec_str, was_logged))
2335  {
2336  case 1:
2337  ereport(LOG,
2338  (errmsg("duration: %s ms", msec_str),
2339  errhidestmt(true)));
2340  break;
2341  case 2:
2342  ereport(LOG,
2343  (errmsg("duration: %s ms %s %s%s%s: %s",
2344  msec_str,
2345  execute_is_fetch ?
2346  _("execute fetch from") :
2347  _("execute"),
2348  prepStmtName,
2349  *portal_name ? "/" : "",
2350  *portal_name ? portal_name : "",
2351  sourceText),
2352  errhidestmt(true),
2353  errdetail_params(portalParams)));
2354  break;
2355  }
2356 
2357  if (save_log_statement_stats)
2358  ShowUsage("EXECUTE MESSAGE STATISTICS");
2359 
2361 
2362  debug_query_string = NULL;
2363 }
const char * GetCommandTagNameAndLen(CommandTag commandTag, Size *len)
Definition: cmdtag.c:53
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:169
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:103
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
void NullCommand(CommandDest dest)
Definition: dest.c:218
CommandDest
Definition: dest.h:86
@ DestRemoteExecute
Definition: dest.h:90
#define _(x)
Definition: elog.c:90
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define FETCH_ALL
Definition: parsenodes.h:3352
#define NIL
Definition: pg_list.h:68
static void disable_statement_timeout(void)
Definition: postgres.c:5285
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2867
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2373
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2852
static void finish_xact_command(void)
Definition: postgres.c:2803
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:684
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:100
#define PqMsg_PortalSuspended
Definition: protocol.h:57
void set_ps_display_with_len(const char *activity, size_t len)
Definition: ps_status.c:451
CommandTag commandTag
Definition: portal.h:137
const char * sourceText
Definition: portal.h:136
bool atStart
Definition: portal.h:199
List * stmts
Definition: portal.h:139
ParamListInfo portalParams
Definition: portal.h:142
const char * prepStmtName
Definition: portal.h:119
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
void CommandCounterIncrement(void)
Definition: xact.c:1099
int MyXactFlags
Definition: xact.c:135
#define XACT_FLAGS_PIPELINING
Definition: xact.h:121
#define XACT_FLAGS_NEEDIMMEDIATECOMMIT
Definition: xact.h:114

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(), GetCommandTagNameAndLen(), GetPortalByName(), IsAbortedTransactionBlockState(), IsTransactionExitStmtList(), IsTransactionStmtList(), lfirst_node, LOG, log_statement_stats, MyXactFlags, PortalData::name, NIL, NullCommand(), ParamsErrorCbData::params, ParamsErrorCallback(), pgstat_report_activity(), pgstat_report_query_id(), PortalIsValid, ParamsErrorCbData::portalName, PortalData::portalParams, PortalRun(), pq_putemptymessage(), PqMsg_PortalSuspended, PortalData::prepStmtName, ErrorContextCallback::previous, pstrdup(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display_with_len(), SetRemoteDestReceiverParams(), ShowUsage(), PortalData::sourceText, start_xact_command(), STATE_RUNNING, stmt, PortalData::stmts, valgrind_report_error_query, whereToSendOutput, XACT_FLAGS_NEEDIMMEDIATECOMMIT, and XACT_FLAGS_PIPELINING.

Referenced by PostgresMain().

◆ exec_parse_message()

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

Definition at line 1400 of file postgres.c.

1404 {
1405  MemoryContext unnamed_stmt_context = NULL;
1406  MemoryContext oldcontext;
1407  List *parsetree_list;
1408  RawStmt *raw_parse_tree;
1409  List *querytree_list;
1410  CachedPlanSource *psrc;
1411  bool is_named;
1412  bool save_log_statement_stats = log_statement_stats;
1413  char msec_str[32];
1414 
1415  /*
1416  * Report query to various monitoring facilities.
1417  */
1418  debug_query_string = query_string;
1419 
1420  pgstat_report_activity(STATE_RUNNING, query_string);
1421 
1422  set_ps_display("PARSE");
1423 
1424  if (save_log_statement_stats)
1425  ResetUsage();
1426 
1427  ereport(DEBUG2,
1428  (errmsg_internal("parse %s: %s",
1429  *stmt_name ? stmt_name : "<unnamed>",
1430  query_string)));
1431 
1432  /*
1433  * Start up a transaction command so we can run parse analysis etc. (Note
1434  * that this will normally change current memory context.) Nothing happens
1435  * if we are already in one. This also arms the statement timeout if
1436  * necessary.
1437  */
1439 
1440  /*
1441  * Switch to appropriate context for constructing parsetrees.
1442  *
1443  * We have two strategies depending on whether the prepared statement is
1444  * named or not. For a named prepared statement, we do parsing in
1445  * MessageContext and copy the finished trees into the prepared
1446  * statement's plancache entry; then the reset of MessageContext releases
1447  * temporary space used by parsing and rewriting. For an unnamed prepared
1448  * statement, we assume the statement isn't going to hang around long, so
1449  * getting rid of temp space quickly is probably not worth the costs of
1450  * copying parse trees. So in this case, we create the plancache entry's
1451  * query_context here, and do all the parsing work therein.
1452  */
1453  is_named = (stmt_name[0] != '\0');
1454  if (is_named)
1455  {
1456  /* Named prepared statement --- parse in MessageContext */
1457  oldcontext = MemoryContextSwitchTo(MessageContext);
1458  }
1459  else
1460  {
1461  /* Unnamed prepared statement --- release any prior unnamed stmt */
1463  /* Create context for parsing */
1464  unnamed_stmt_context =
1466  "unnamed prepared statement",
1468  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1469  }
1470 
1471  /*
1472  * Do basic parsing of the query or queries (this should be safe even if
1473  * we are in aborted transaction state!)
1474  */
1475  parsetree_list = pg_parse_query(query_string);
1476 
1477  /*
1478  * We only allow a single user statement in a prepared statement. This is
1479  * mainly to keep the protocol simple --- otherwise we'd need to worry
1480  * about multiple result tupdescs and things like that.
1481  */
1482  if (list_length(parsetree_list) > 1)
1483  ereport(ERROR,
1484  (errcode(ERRCODE_SYNTAX_ERROR),
1485  errmsg("cannot insert multiple commands into a prepared statement")));
1486 
1487  if (parsetree_list != NIL)
1488  {
1489  bool snapshot_set = false;
1490 
1491  raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1492 
1493  /*
1494  * If we are in an aborted transaction, reject all commands except
1495  * COMMIT/ROLLBACK. It is important that this test occur before we
1496  * try to do parse analysis, rewrite, or planning, since all those
1497  * phases try to do database accesses, which may fail in abort state.
1498  * (It might be safe to allow some additional utility commands in this
1499  * state, but not many...)
1500  */
1502  !IsTransactionExitStmt(raw_parse_tree->stmt))
1503  ereport(ERROR,
1504  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1505  errmsg("current transaction is aborted, "
1506  "commands ignored until end of transaction block"),
1507  errdetail_abort()));
1508 
1509  /*
1510  * Create the CachedPlanSource before we do parse analysis, since it
1511  * needs to see the unmodified raw parse tree.
1512  */
1513  psrc = CreateCachedPlan(raw_parse_tree, query_string,
1514  CreateCommandTag(raw_parse_tree->stmt));
1515 
1516  /*
1517  * Set up a snapshot if parse analysis will need one.
1518  */
1519  if (analyze_requires_snapshot(raw_parse_tree))
1520  {
1522  snapshot_set = true;
1523  }
1524 
1525  /*
1526  * Analyze and rewrite the query. Note that the originally specified
1527  * parameter set is not required to be complete, so we have to use
1528  * pg_analyze_and_rewrite_varparams().
1529  */
1530  querytree_list = pg_analyze_and_rewrite_varparams(raw_parse_tree,
1531  query_string,
1532  &paramTypes,
1533  &numParams,
1534  NULL);
1535 
1536  /* Done with the snapshot used for parsing */
1537  if (snapshot_set)
1539  }
1540  else
1541  {
1542  /* Empty input string. This is legal. */
1543  raw_parse_tree = NULL;
1544  psrc = CreateCachedPlan(raw_parse_tree, query_string,
1545  CMDTAG_UNKNOWN);
1546  querytree_list = NIL;
1547  }
1548 
1549  /*
1550  * CachedPlanSource must be a direct child of MessageContext before we
1551  * reparent unnamed_stmt_context under it, else we have a disconnected
1552  * circular subgraph. Klugy, but less so than flipping contexts even more
1553  * above.
1554  */
1555  if (unnamed_stmt_context)
1557 
1558  /* Finish filling in the CachedPlanSource */
1559  CompleteCachedPlan(psrc,
1560  querytree_list,
1561  unnamed_stmt_context,
1562  paramTypes,
1563  numParams,
1564  NULL,
1565  NULL,
1566  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1567  true); /* fixed result */
1568 
1569  /* If we got a cancel signal during analysis, quit */
1571 
1572  if (is_named)
1573  {
1574  /*
1575  * Store the query as a prepared statement.
1576  */
1577  StorePreparedStatement(stmt_name, psrc, false);
1578  }
1579  else
1580  {
1581  /*
1582  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1583  */
1584  SaveCachedPlan(psrc);
1585  unnamed_stmt_psrc = psrc;
1586  }
1587 
1588  MemoryContextSwitchTo(oldcontext);
1589 
1590  /*
1591  * We do NOT close the open transaction command here; that only happens
1592  * when the client sends Sync. Instead, do CommandCounterIncrement just
1593  * in case something happened during parse/plan.
1594  */
1596 
1597  /*
1598  * Send ParseComplete.
1599  */
1602 
1603  /*
1604  * Emit duration logging if appropriate.
1605  */
1606  switch (check_log_duration(msec_str, false))
1607  {
1608  case 1:
1609  ereport(LOG,
1610  (errmsg("duration: %s ms", msec_str),
1611  errhidestmt(true)));
1612  break;
1613  case 2:
1614  ereport(LOG,
1615  (errmsg("duration: %s ms parse %s: %s",
1616  msec_str,
1617  *stmt_name ? stmt_name : "<unnamed>",
1618  query_string),
1619  errhidestmt(true)));
1620  break;
1621  }
1622 
1623  if (save_log_statement_stats)
1624  ShowUsage("PARSE MESSAGE STATISTICS");
1625 
1626  debug_query_string = NULL;
1627 }
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:389
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:637
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3317
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:482
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:366
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:192
List * pg_parse_query(const char *query_string)
Definition: postgres.c:614
List * pg_analyze_and_rewrite_varparams(RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:715
static void drop_unnamed_stmt(void)
Definition: postgres.c:2882
#define PqMsg_ParseComplete
Definition: protocol.h:38
MemoryContext context
Definition: plancache.h:109
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2362

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(), errmsg_internal(), ERROR, GetTransactionSnapshot(), IsAbortedTransactionBlockState(), IsTransactionExitStmt(), linitial_node, list_length(), LOG, log_statement_stats, MemoryContextSetParent(), MemoryContextSwitchTo(), MessageContext, NIL, pg_analyze_and_rewrite_varparams(), pg_parse_query(), pgstat_report_activity(), PopActiveSnapshot(), pq_putemptymessage(), PqMsg_ParseComplete, PushActiveSnapshot(), ResetUsage(), SaveCachedPlan(), set_ps_display(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, StorePreparedStatement(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 1022 of file postgres.c.

1023 {
1025  MemoryContext oldcontext;
1026  List *parsetree_list;
1027  ListCell *parsetree_item;
1028  bool save_log_statement_stats = log_statement_stats;
1029  bool was_logged = false;
1030  bool use_implicit_block;
1031  char msec_str[32];
1032 
1033  /*
1034  * Report query to various monitoring facilities.
1035  */
1036  debug_query_string = query_string;
1037 
1038  pgstat_report_activity(STATE_RUNNING, query_string);
1039 
1040  TRACE_POSTGRESQL_QUERY_START(query_string);
1041 
1042  /*
1043  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1044  * results because ResetUsage wasn't called.
1045  */
1046  if (save_log_statement_stats)
1047  ResetUsage();
1048 
1049  /*
1050  * Start up a transaction command. All queries generated by the
1051  * query_string will be in this same command block, *unless* we find a
1052  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1053  * one of those, else bad things will happen in xact.c. (Note that this
1054  * will normally change current memory context.)
1055  */
1057 
1058  /*
1059  * Zap any pre-existing unnamed statement. (While not strictly necessary,
1060  * it seems best to define simple-Query mode as if it used the unnamed
1061  * statement and portal; this ensures we recover any storage used by prior
1062  * unnamed operations.)
1063  */
1065 
1066  /*
1067  * Switch to appropriate context for constructing parsetrees.
1068  */
1069  oldcontext = MemoryContextSwitchTo(MessageContext);
1070 
1071  /*
1072  * Do basic parsing of the query or queries (this should be safe even if
1073  * we are in aborted transaction state!)
1074  */
1075  parsetree_list = pg_parse_query(query_string);
1076 
1077  /* Log immediately if dictated by log_statement */
1078  if (check_log_statement(parsetree_list))
1079  {
1080  ereport(LOG,
1081  (errmsg("statement: %s", query_string),
1082  errhidestmt(true),
1083  errdetail_execute(parsetree_list)));
1084  was_logged = true;
1085  }
1086 
1087  /*
1088  * Switch back to transaction context to enter the loop.
1089  */
1090  MemoryContextSwitchTo(oldcontext);
1091 
1092  /*
1093  * For historical reasons, if multiple SQL statements are given in a
1094  * single "simple Query" message, we execute them as a single transaction,
1095  * unless explicit transaction control commands are included to make
1096  * portions of the list be separate transactions. To represent this
1097  * behavior properly in the transaction machinery, we use an "implicit"
1098  * transaction block.
1099  */
1100  use_implicit_block = (list_length(parsetree_list) > 1);
1101 
1102  /*
1103  * Run through the raw parsetree(s) and process each one.
1104  */
1105  foreach(parsetree_item, parsetree_list)
1106  {
1107  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1108  bool snapshot_set = false;
1109  CommandTag commandTag;
1110  QueryCompletion qc;
1111  MemoryContext per_parsetree_context = NULL;
1112  List *querytree_list,
1113  *plantree_list;
1114  Portal portal;
1115  DestReceiver *receiver;
1116  int16 format;
1117  const char *cmdtagname;
1118  size_t cmdtaglen;
1119 
1120  pgstat_report_query_id(0, true);
1121 
1122  /*
1123  * Get the command name for use in status display (it also becomes the
1124  * default completion tag, down inside PortalRun). Set ps_status and
1125  * do any special start-of-SQL-command processing needed by the
1126  * destination.
1127  */
1128  commandTag = CreateCommandTag(parsetree->stmt);
1129  cmdtagname = GetCommandTagNameAndLen(commandTag, &cmdtaglen);
1130 
1131  set_ps_display_with_len(cmdtagname, cmdtaglen);
1132 
1133  BeginCommand(commandTag, dest);
1134 
1135  /*
1136  * If we are in an aborted transaction, reject all commands except
1137  * COMMIT/ABORT. It is important that this test occur before we try
1138  * to do parse analysis, rewrite, or planning, since all those phases
1139  * try to do database accesses, which may fail in abort state. (It
1140  * might be safe to allow some additional utility commands in this
1141  * state, but not many...)
1142  */
1144  !IsTransactionExitStmt(parsetree->stmt))
1145  ereport(ERROR,
1146  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1147  errmsg("current transaction is aborted, "
1148  "commands ignored until end of transaction block"),
1149  errdetail_abort()));
1150 
1151  /* Make sure we are in a transaction command */
1153 
1154  /*
1155  * If using an implicit transaction block, and we're not already in a
1156  * transaction block, start an implicit block to force this statement
1157  * to be grouped together with any following ones. (We must do this
1158  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1159  * list would cause later statements to not be grouped.)
1160  */
1161  if (use_implicit_block)
1163 
1164  /* If we got a cancel signal in parsing or prior command, quit */
1166 
1167  /*
1168  * Set up a snapshot if parse analysis/planning will need one.
1169  */
1170  if (analyze_requires_snapshot(parsetree))
1171  {
1173  snapshot_set = true;
1174  }
1175 
1176  /*
1177  * OK to analyze, rewrite, and plan this query.
1178  *
1179  * Switch to appropriate context for constructing query and plan trees
1180  * (these can't be in the transaction context, as that will get reset
1181  * when the command is COMMIT/ROLLBACK). If we have multiple
1182  * parsetrees, we use a separate context for each one, so that we can
1183  * free that memory before moving on to the next one. But for the
1184  * last (or only) parsetree, just use MessageContext, which will be
1185  * reset shortly after completion anyway. In event of an error, the
1186  * per_parsetree_context will be deleted when MessageContext is reset.
1187  */
1188  if (lnext(parsetree_list, parsetree_item) != NULL)
1189  {
1190  per_parsetree_context =
1192  "per-parsetree message context",
1194  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1195  }
1196  else
1197  oldcontext = MemoryContextSwitchTo(MessageContext);
1198 
1199  querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1200  NULL, 0, NULL);
1201 
1202  plantree_list = pg_plan_queries(querytree_list, query_string,
1203  CURSOR_OPT_PARALLEL_OK, NULL);
1204 
1205  /*
1206  * Done with the snapshot used for parsing/planning.
1207  *
1208  * While it looks promising to reuse the same snapshot for query
1209  * execution (at least for simple protocol), unfortunately it causes
1210  * execution to use a snapshot that has been acquired before locking
1211  * any of the tables mentioned in the query. This creates user-
1212  * visible anomalies, so refrain. Refer to
1213  * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1214  */
1215  if (snapshot_set)
1217 
1218  /* If we got a cancel signal in analysis or planning, quit */
1220 
1221  /*
1222  * Create unnamed portal to run the query or queries in. If there
1223  * already is one, silently drop it.
1224  */
1225  portal = CreatePortal("", true, true);
1226  /* Don't display the portal in pg_cursors */
1227  portal->visible = false;
1228 
1229  /*
1230  * We don't have to copy anything into the portal, because everything
1231  * we are passing here is in MessageContext or the
1232  * per_parsetree_context, and so will outlive the portal anyway.
1233  */
1234  PortalDefineQuery(portal,
1235  NULL,
1236  query_string,
1237  commandTag,
1238  plantree_list,
1239  NULL);
1240 
1241  /*
1242  * Start the portal. No parameters here.
1243  */
1244  PortalStart(portal, NULL, 0, InvalidSnapshot);
1245 
1246  /*
1247  * Select the appropriate output format: text unless we are doing a
1248  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1249  * --- but it avoids grottiness in other places. Ah, the joys of
1250  * backward compatibility...)
1251  */
1252  format = 0; /* TEXT is default */
1253  if (IsA(parsetree->stmt, FetchStmt))
1254  {
1255  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1256 
1257  if (!stmt->ismove)
1258  {
1259  Portal fportal = GetPortalByName(stmt->portalname);
1260 
1261  if (PortalIsValid(fportal) &&
1262  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1263  format = 1; /* BINARY */
1264  }
1265  }
1266  PortalSetResultFormat(portal, 1, &format);
1267 
1268  /*
1269  * Now we can create the destination receiver object.
1270  */
1271  receiver = CreateDestReceiver(dest);
1272  if (dest == DestRemote)
1273  SetRemoteDestReceiverParams(receiver, portal);
1274 
1275  /*
1276  * Switch back to transaction context for execution.
1277  */
1278  MemoryContextSwitchTo(oldcontext);
1279 
1280  /*
1281  * Run the portal to completion, and then drop it (and the receiver).
1282  */
1283  (void) PortalRun(portal,
1284  FETCH_ALL,
1285  true, /* always top level */
1286  true,
1287  receiver,
1288  receiver,
1289  &qc);
1290 
1291  receiver->rDestroy(receiver);
1292 
1293  PortalDrop(portal, false);
1294 
1295  if (lnext(parsetree_list, parsetree_item) == NULL)
1296  {
1297  /*
1298  * If this is the last parsetree of the query string, close down
1299  * transaction statement before reporting command-complete. This
1300  * is so that any end-of-transaction errors are reported before
1301  * the command-complete message is issued, to avoid confusing
1302  * clients who will expect either a command-complete message or an
1303  * error, not one and then the other. Also, if we're using an
1304  * implicit transaction block, we must close that out first.
1305  */
1306  if (use_implicit_block)
1309  }
1310  else if (IsA(parsetree->stmt, TransactionStmt))
1311  {
1312  /*
1313  * If this was a transaction control statement, commit it. We will
1314  * start a new xact command for the next command.
1315  */
1317  }
1318  else
1319  {
1320  /*
1321  * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1322  * we're not calling finish_xact_command(). (The implicit
1323  * transaction block should have prevented it from getting set.)
1324  */
1326 
1327  /*
1328  * We need a CommandCounterIncrement after every query, except
1329  * those that start or end a transaction block.
1330  */
1332 
1333  /*
1334  * Disable statement timeout between queries of a multi-query
1335  * string, so that the timeout applies separately to each query.
1336  * (Our next loop iteration will start a fresh timeout.)
1337  */
1339  }
1340 
1341  /*
1342  * Tell client that we're done with this query. Note we emit exactly
1343  * one EndCommand report for each raw parsetree, thus one for each SQL
1344  * command the client sent, regardless of rewriting. (But a command
1345  * aborted by error will not send an EndCommand report at all.)
1346  */
1347  EndCommand(&qc, dest, false);
1348 
1349  /* Now we may drop the per-parsetree context, if one was created. */
1350  if (per_parsetree_context)
1351  MemoryContextDelete(per_parsetree_context);
1352  } /* end loop over parsetrees */
1353 
1354  /*
1355  * Close down transaction statement, if one is open. (This will only do
1356  * something if the parsetree list was empty; otherwise the last loop
1357  * iteration already did it.)
1358  */
1360 
1361  /*
1362  * If there were no parsetrees, return EmptyQueryResponse message.
1363  */
1364  if (!parsetree_list)
1365  NullCommand(dest);
1366 
1367  /*
1368  * Emit duration logging if appropriate.
1369  */
1370  switch (check_log_duration(msec_str, was_logged))
1371  {
1372  case 1:
1373  ereport(LOG,
1374  (errmsg("duration: %s ms", msec_str),
1375  errhidestmt(true)));
1376  break;
1377  case 2:
1378  ereport(LOG,
1379  (errmsg("duration: %s ms statement: %s",
1380  msec_str, query_string),
1381  errhidestmt(true),
1382  errdetail_execute(parsetree_list)));
1383  break;
1384  }
1385 
1386  if (save_log_statement_stats)
1387  ShowUsage("QUERY STATISTICS");
1388 
1389  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1390 
1391  debug_query_string = NULL;
1392 }
CommandTag
Definition: cmdtag.h:23
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:3307
static char format
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:468
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2475
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:676
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:981
bool visible
Definition: portal.h:205
int cursorOptions
Definition: portal.h:147
void BeginImplicitTransactionBlock(void)
Definition: xact.c:4331
void EndImplicitTransactionBlock(void)
Definition: xact.c:4356

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_requires_snapshot(), Assert, 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, GetCommandTagNameAndLen(), GetPortalByName(), GetTransactionSnapshot(), if(), InvalidSnapshot, IsA, IsAbortedTransactionBlockState(), IsTransactionExitStmt(), lfirst_node, list_length(), lnext(), LOG, log_statement_stats, MemoryContextDelete(), MemoryContextSwitchTo(), MessageContext, MyXactFlags, NullCommand(), pg_analyze_and_rewrite_fixedparams(), pg_parse_query(), pg_plan_queries(), pgstat_report_activity(), pgstat_report_query_id(), PopActiveSnapshot(), PortalDefineQuery(), PortalDrop(), PortalIsValid, PortalRun(), PortalSetResultFormat(), PortalStart(), PushActiveSnapshot(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display_with_len(), SetRemoteDestReceiverParams(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, stmt, PortalData::visible, whereToSendOutput, and XACT_FLAGS_NEEDIMMEDIATECOMMIT.

Referenced by PostgresMain().

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2803 of file postgres.c.

2804 {
2805  /* cancel active statement timeout after each command */
2807 
2808  if (xact_started)
2809  {
2811 
2812 #ifdef MEMORY_CONTEXT_CHECKING
2813  /* Check all memory contexts that weren't freed during commit */
2814  /* (those that were, were checked before being deleted) */
2815  MemoryContextCheck(TopMemoryContext);
2816 #endif
2817 
2818 #ifdef SHOW_MEMORY_STATS
2819  /* Print mem stats after each commit for leak tracking */
2821 #endif
2822 
2823  xact_started = false;
2824  }
2825 }
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:814
void CommitTransactionCommand(void)
Definition: xact.c:3149

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

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

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 3051 of file postgres.c.

3052 {
3053  /* We're not returning, so no need to save errno */
3054  ereport(ERROR,
3055  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3056  errmsg("floating-point exception"),
3057  errdetail("An invalid floating-point operation was signaled. "
3058  "This probably means an out-of-range result or an "
3059  "invalid operation, such as division by zero.")));
3060 }

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

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), plperl_init_interp(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 5057 of file postgres.c.

5058 {
5059  if (am_walsender)
5060  {
5061  if (firstchar == PqMsg_FunctionCall)
5062  ereport(ERROR,
5063  (errcode(ERRCODE_PROTOCOL_VIOLATION),
5064  errmsg("fastpath function calls not supported in a replication connection")));
5065  else
5066  ereport(ERROR,
5067  (errcode(ERRCODE_PROTOCOL_VIOLATION),
5068  errmsg("extended query protocol not supported in a replication connection")));
5069  }
5070 }
#define PqMsg_FunctionCall
Definition: protocol.h:23
bool am_walsender
Definition: walsender.c:115

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

Referenced by PostgresMain().

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 5079 of file postgres.c.

5080 {
5081 #if defined(HAVE_GETRLIMIT)
5082  static long val = 0;
5083 
5084  /* This won't change after process launch, so check just once */
5085  if (val == 0)
5086  {
5087  struct rlimit rlim;
5088 
5089  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
5090  val = -1;
5091  else if (rlim.rlim_cur == RLIM_INFINITY)
5092  val = LONG_MAX;
5093  /* rlim_cur is probably of an unsigned type, so check for overflow */
5094  else if (rlim.rlim_cur >= LONG_MAX)
5095  val = LONG_MAX;
5096  else
5097  val = rlim.rlim_cur;
5098  }
5099  return val;
5100 #else
5101  /* On Windows we set the backend stack size in src/backend/Makefile */
5102  return WIN32_STACK_RLIMIT;
5103 #endif
5104 }
long val
Definition: informix.c:689

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3842 of file postgres.c.

3843 {
3844  switch (arg[0])
3845  {
3846  case 'p':
3847  if (optarg[1] == 'a') /* "parser" */
3848  return "log_parser_stats";
3849  else if (optarg[1] == 'l') /* "planner" */
3850  return "log_planner_stats";
3851  break;
3852 
3853  case 'e': /* "executor" */
3854  return "log_executor_stats";
3855  break;
3856  }
3857 
3858  return NULL;
3859 }
PGDLLIMPORT char * optarg
Definition: getopt.c:53

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3067 of file postgres.c.

3068 {
3069  RecoveryConflictPendingReasons[reason] = true;
3070  RecoveryConflictPending = true;
3071  InterruptPending = true;
3072  /* latch will be set by procsignal_sigusr1_handler */
3073 }
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:170
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:169

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 335 of file postgres.c.

336 {
337  int c;
338 
339  /*
340  * This will not process catchup interrupts or notifications while
341  * reading. But those can't really be relevant for a standalone backend
342  * anyway. To properly handle SIGTERM there's a hack in die() that
343  * directly processes interrupts at this stage...
344  */
346 
347  c = getc(stdin);
348 
350 
351  return c;
352 }
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:512
char * c

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 247 of file postgres.c.

248 {
249  int c; /* character read from getc() */
250 
251  /*
252  * display a prompt and obtain input from the user
253  */
254  printf("backend> ");
255  fflush(stdout);
256 
257  resetStringInfo(inBuf);
258 
259  /*
260  * Read characters until EOF or the appropriate delimiter is seen.
261  */
262  while ((c = interactive_getc()) != EOF)
263  {
264  if (c == '\n')
265  {
267  {
268  /*
269  * In -j mode, semicolon followed by two newlines ends the
270  * command; otherwise treat newline as regular character.
271  */
272  if (inBuf->len > 1 &&
273  inBuf->data[inBuf->len - 1] == '\n' &&
274  inBuf->data[inBuf->len - 2] == ';')
275  {
276  /* might as well drop the second newline */
277  break;
278  }
279  }
280  else
281  {
282  /*
283  * In plain mode, newline ends the command unless preceded by
284  * backslash.
285  */
286  if (inBuf->len > 0 &&
287  inBuf->data[inBuf->len - 1] == '\\')
288  {
289  /* discard backslash from inBuf */
290  inBuf->data[--inBuf->len] = '\0';
291  /* discard newline too */
292  continue;
293  }
294  else
295  {
296  /* keep the newline character, but end the command */
297  appendStringInfoChar(inBuf, '\n');
298  break;
299  }
300  }
301  }
302 
303  /* Not newline, or newline treated as regular character */
304  appendStringInfoChar(inBuf, (char) c);
305  }
306 
307  /* No input before EOF signal means time to quit. */
308  if (c == EOF && inBuf->len == 0)
309  return EOF;
310 
311  /*
312  * otherwise we have a user query so process it.
313  */
314 
315  /* Add '\0' to make it look the same as message case. */
316  appendStringInfoChar(inBuf, (char) '\0');
317 
318  /*
319  * if the query echo flag was given, print the query..
320  */
321  if (EchoQuery)
322  printf("statement: %s\n", inBuf->data);
323  fflush(stdout);
324 
325  return 'Q';
326 }
static void const char fflush(stdout)
#define printf(...)
Definition: port.h:244
static bool UseSemiNewlineNewline
Definition: postgres.c:166
static bool EchoQuery
Definition: postgres.c:165
static int interactive_getc(void)
Definition: postgres.c:335
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:191

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

Referenced by ReadCommand().

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2835 of file postgres.c.

2836 {
2837  if (parsetree && IsA(parsetree, TransactionStmt))
2838  {
2839  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2840 
2841  if (stmt->kind == TRANS_STMT_COMMIT ||
2842  stmt->kind == TRANS_STMT_PREPARE ||
2843  stmt->kind == TRANS_STMT_ROLLBACK ||
2844  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2845  return true;
2846  }
2847  return false;
2848 }
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3689
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3686
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3685
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3690

References IsA, stmt, 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().

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2852 of file postgres.c.

2853 {
2854  if (list_length(pstmts) == 1)
2855  {
2856  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2857 
2858  if (pstmt->commandType == CMD_UTILITY &&
2860  return true;
2861  }
2862  return false;
2863 }
@ CMD_UTILITY
Definition: nodes.h:270
CmdType commandType
Definition: plannodes.h:52
Node * utilityStmt
Definition: plannodes.h:95

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

Referenced by exec_execute_message().

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2867 of file postgres.c.

2868 {
2869  if (list_length(pstmts) == 1)
2870  {
2871  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2872 
2873  if (pstmt->commandType == CMD_UTILITY &&
2874  IsA(pstmt->utilityStmt, TransactionStmt))
2875  return true;
2876  }
2877  return false;
2878 }

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

Referenced by exec_execute_message().

◆ log_disconnections()

static void log_disconnections ( int  code,
Datum  arg 
)
static

Definition at line 5227 of file postgres.c.

5228 {
5229  Port *port = MyProcPort;
5230  long secs;
5231  int usecs;
5232  int msecs;
5233  int hours,
5234  minutes,
5235  seconds;
5236 
5239  &secs, &usecs);
5240  msecs = usecs / 1000;
5241 
5242  hours = secs / SECS_PER_HOUR;
5243  secs %= SECS_PER_HOUR;
5244  minutes = secs / SECS_PER_MINUTE;
5245  seconds = secs % SECS_PER_MINUTE;
5246 
5247  ereport(LOG,
5248  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5249  "user=%s database=%s host=%s%s%s",
5250  hours, minutes, seconds, msecs,
5251  port->user_name, port->database_name, port->remote_host,
5252  port->remote_port[0] ? " port=" : "", port->remote_port)));
5253 }
#define SECS_PER_HOUR
Definition: timestamp.h:127
#define SECS_PER_MINUTE
Definition: timestamp.h:128
TimestampTz MyStartTimestamp
Definition: globals.c:48
struct Port * MyProcPort
Definition: globals.c:50
static int port
Definition: pg_regress.c:115
Definition: libpq-be.h:133

References ereport, errmsg(), GetCurrentTimestamp(), LOG, MyProcPort, MyStartTimestamp, port, SECS_PER_HOUR, SECS_PER_MINUTE, and TimestampDifference().

Referenced by PostgresMain().

◆ pg_analyze_and_rewrite_fixedparams()

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

Definition at line 676 of file postgres.c.

681 {
682  Query *query;
683  List *querytree_list;
684 
685  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
686 
687  /*
688  * (1) Perform parse analysis.
689  */
690  if (log_parser_stats)
691  ResetUsage();
692 
693  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
694  queryEnv);
695 
696  if (log_parser_stats)
697  ShowUsage("PARSE ANALYSIS STATISTICS");
698 
699  /*
700  * (2) Rewrite the queries, as necessary
701  */
702  querytree_list = pg_rewrite_query(query);
703 
704  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
705 
706  return querytree_list;
707 }
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:105
List * pg_rewrite_query(Query *query)
Definition: postgres.c:809

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

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

◆ pg_analyze_and_rewrite_varparams()

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

Definition at line 715 of file postgres.c.

720 {
721  Query *query;
722  List *querytree_list;
723 
724  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
725 
726  /*
727  * (1) Perform parse analysis.
728  */
729  if (log_parser_stats)
730  ResetUsage();
731 
732  query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
733  queryEnv);
734 
735  /*
736  * Check all parameter types got determined.
737  */
738  for (int i = 0; i < *numParams; i++)
739  {
740  Oid ptype = (*paramTypes)[i];
741 
742  if (ptype == InvalidOid || ptype == UNKNOWNOID)
743  ereport(ERROR,
744  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
745  errmsg("could not determine data type of parameter $%d",
746  i + 1)));
747  }
748 
749  if (log_parser_stats)
750  ShowUsage("PARSE ANALYSIS STATISTICS");
751 
752  /*
753  * (2) Rewrite the queries, as necessary
754  */
755  querytree_list = pg_rewrite_query(query);
756 
757  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
758 
759  return querytree_list;
760 }
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:145
#define InvalidOid
Definition: postgres_ext.h:36

References ereport, errcode(), errmsg(), ERROR, i, InvalidOid, log_parser_stats, parse_analyze_varparams(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by exec_parse_message(), and PrepareQuery().

◆ pg_analyze_and_rewrite_withcb()

List* pg_analyze_and_rewrite_withcb ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 769 of file postgres.c.

774 {
775  Query *query;
776  List *querytree_list;
777 
778  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
779 
780  /*
781  * (1) Perform parse analysis.
782  */
783  if (log_parser_stats)
784  ResetUsage();
785 
786  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
787  queryEnv);
788 
789  if (log_parser_stats)
790  ShowUsage("PARSE ANALYSIS STATISTICS");
791 
792  /*
793  * (2) Rewrite the queries, as necessary
794  */
795  querytree_list = pg_rewrite_query(query);
796 
797  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
798 
799  return querytree_list;
800 }
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:186

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

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 614 of file postgres.c.

615 {
616  List *raw_parsetree_list;
617 
618  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
619 
620  if (log_parser_stats)
621  ResetUsage();
622 
623  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
624 
625  if (log_parser_stats)
626  ShowUsage("PARSER STATISTICS");
627 
628 #ifdef DEBUG_NODE_TESTS_ENABLED
629 
630  /* Optional debugging check: pass raw parsetrees through copyObject() */
631  if (Debug_copy_parse_plan_trees)
632  {
633  List *new_list = copyObject(raw_parsetree_list);
634 
635  /* This checks both copyObject() and the equal() routines... */
636  if (!equal(new_list, raw_parsetree_list))
637  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
638  else
639  raw_parsetree_list = new_list;
640  }
641 
642  /*
643  * Optional debugging check: pass raw parsetrees through
644  * outfuncs/readfuncs
645  */
646  if (Debug_write_read_parse_plan_trees)
647  {
648  char *str = nodeToStringWithLocations(raw_parsetree_list);
649  List *new_list = stringToNodeWithLocations(str);
650 
651  pfree(str);
652  /* This checks both outfuncs/readfuncs and the equal() routines... */
653  if (!equal(new_list, raw_parsetree_list))
654  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
655  else
656  raw_parsetree_list = new_list;
657  }
658 
659 #endif /* DEBUG_NODE_TESTS_ENABLED */
660 
661  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
662 
663  return raw_parsetree_list;
664 }
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:225
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static List * new_list(NodeTag type, int min_size)
Definition: list.c:91
#define copyObject(obj)
Definition: nodes.h:224
char * nodeToStringWithLocations(const void *obj)
Definition: outfuncs.c:800
@ RAW_PARSE_DEFAULT
Definition: parser.h:39

References copyObject, elog, equal(), log_parser_stats, new_list(), nodeToStringWithLocations(), pfree(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), str, 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().

◆ pg_plan_queries()

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

Definition at line 981 of file postgres.c.

983 {
984  List *stmt_list = NIL;
985  ListCell *query_list;
986 
987  foreach(query_list, querytrees)
988  {
989  Query *query = lfirst_node(Query, query_list);
990  PlannedStmt *stmt;
991 
992  if (query->commandType == CMD_UTILITY)
993  {
994  /* Utility commands require no planning. */
996  stmt->commandType = CMD_UTILITY;
997  stmt->canSetTag = query->canSetTag;
998  stmt->utilityStmt = query->utilityStmt;
999  stmt->stmt_location = query->stmt_location;
1000  stmt->stmt_len = query->stmt_len;
1001  stmt->queryId = query->queryId;
1002  }
1003  else
1004  {
1005  stmt = pg_plan_query(query, query_string, cursorOptions,
1006  boundParams);
1007  }
1008 
1009  stmt_list = lappend(stmt_list, stmt);
1010  }
1011 
1012  return stmt_list;
1013 }
List * lappend(List *list, void *datum)
Definition: list.c:339
#define makeNode(_type_)
Definition: nodes.h:155
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:893
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
ParseLoc stmt_location
Definition: parsenodes.h:240

References CMD_UTILITY, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), stmt, Query::stmt_location, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

◆ pg_plan_query()

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

Definition at line 893 of file postgres.c.

895 {
896  PlannedStmt *plan;
897 
898  /* Utility commands have no plans. */
899  if (querytree->commandType == CMD_UTILITY)
900  return NULL;
901 
902  /* Planner must have a snapshot in case it calls user-defined functions. */
904 
905  TRACE_POSTGRESQL_QUERY_PLAN_START();
906 
907  if (log_planner_stats)
908  ResetUsage();
909 
910  /* call the optimizer */
911  plan = planner(querytree, query_string, cursorOptions, boundParams);
912 
913  if (log_planner_stats)
914  ShowUsage("PLANNER STATISTICS");
915 
916 #ifdef DEBUG_NODE_TESTS_ENABLED
917 
918  /* Optional debugging check: pass plan tree through copyObject() */
919  if (Debug_copy_parse_plan_trees)
920  {
921  PlannedStmt *new_plan = copyObject(plan);
922 
923  /*
924  * equal() currently does not have routines to compare Plan nodes, so
925  * don't try to test equality here. Perhaps fix someday?
926  */
927 #ifdef NOT_USED
928  /* This checks both copyObject() and the equal() routines... */
929  if (!equal(new_plan, plan))
930  elog(WARNING, "copyObject() failed to produce an equal plan tree");
931  else
932 #endif
933  plan = new_plan;
934  }
935 
936  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
937  if (Debug_write_read_parse_plan_trees)
938  {
939  char *str;
940  PlannedStmt *new_plan;
941 
943  new_plan = stringToNodeWithLocations(str);
944  pfree(str);
945 
946  /*
947  * equal() currently does not have routines to compare Plan nodes, so
948  * don't try to test equality here. Perhaps fix someday?
949  */
950 #ifdef NOT_USED
951  /* This checks both outfuncs/readfuncs and the equal() routines... */
952  if (!equal(new_plan, plan))
953  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
954  else
955 #endif
956  plan = new_plan;
957  }
958 
959 #endif /* DEBUG_NODE_TESTS_ENABLED */
960 
961  /*
962  * Print plan if debugging.
963  */
964  if (Debug_print_plan)
966 
967  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
968 
969  return plan;
970 }
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:665
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool Debug_print_plan
Definition: guc_tables.c:491
bool Debug_pretty_print
Definition: guc_tables.c:494
#define plan(x)
Definition: pg_regress.c:161
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:276
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:782

References ActiveSnapshotSet(), Assert, CMD_UTILITY, copyObject, Debug_pretty_print, Debug_print_plan, elog, elog_node_display(), equal(), LOG, log_planner_stats, nodeToStringWithLocations(), pfree(), plan, planner(), querytree(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by BeginCopyTo(), ExecCreateTableAs(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), refresh_matview_datafill(), and standard_ExplainOneQuery().

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 809 of file postgres.c.

810 {
811  List *querytree_list;
812 
813  if (Debug_print_parse)
814  elog_node_display(LOG, "parse tree", query,
816 
817  if (log_parser_stats)
818  ResetUsage();
819 
820  if (query->commandType == CMD_UTILITY)
821  {
822  /* don't rewrite utilities, just dump 'em into result list */
823  querytree_list = list_make1(query);
824  }
825  else
826  {
827  /* rewrite regular queries */
828  querytree_list = QueryRewrite(query);
829  }
830 
831  if (log_parser_stats)
832  ShowUsage("REWRITER STATISTICS");
833 
834 #ifdef DEBUG_NODE_TESTS_ENABLED
835 
836  /* Optional debugging check: pass querytree through copyObject() */
837  if (Debug_copy_parse_plan_trees)
838  {
839  List *new_list;
840 
841  new_list = copyObject(querytree_list);
842  /* This checks both copyObject() and the equal() routines... */
843  if (!equal(new_list, querytree_list))
844  elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
845  else
846  querytree_list = new_list;
847  }
848 
849  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
850  if (Debug_write_read_parse_plan_trees)
851  {
852  List *new_list = NIL;
853  ListCell *lc;
854 
855  foreach(lc, querytree_list)
856  {
857  Query *curr_query = lfirst_node(Query, lc);
858  char *str = nodeToStringWithLocations(curr_query);
859  Query *new_query = stringToNodeWithLocations(str);
860 
861  /*
862  * queryId is not saved in stored rules, but we must preserve it
863  * here to avoid breaking pg_stat_statements.
864  */
865  new_query->queryId = curr_query->queryId;
866 
867  new_list = lappend(new_list, new_query);
868  pfree(str);
869  }
870 
871  /* This checks both outfuncs/readfuncs and the equal() routines... */
872  if (!equal(new_list, querytree_list))
873  elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
874  else
875  querytree_list = new_list;
876  }
877 
878 #endif /* DEBUG_NODE_TESTS_ENABLED */
879 
881  elog_node_display(LOG, "rewritten parse tree", querytree_list,
883 
884  return querytree_list;
885 }
bool Debug_print_rewritten
Definition: guc_tables.c:493
bool Debug_print_parse
Definition: guc_tables.c:492
#define list_make1(x1)
Definition: pg_list.h:212
List * QueryRewrite(Query *parsetree)

References CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), lappend(), lfirst_node, list_make1, LOG, log_parser_stats, new_list(), NIL, nodeToStringWithLocations(), pfree(), QueryRewrite(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), and pg_analyze_and_rewrite_withcb().

◆ PostgresMain()

void PostgresMain ( const char *  dbname,
const char *  username 
)

Definition at line 4253 of file postgres.c.

4254 {
4255  sigjmp_buf local_sigjmp_buf;
4256 
4257  /* these must be volatile to ensure state is preserved across longjmp: */
4258  volatile bool send_ready_for_query = true;
4259  volatile bool idle_in_transaction_timeout_enabled = false;
4260  volatile bool idle_session_timeout_enabled = false;
4261 
4262  Assert(dbname != NULL);
4263  Assert(username != NULL);
4264 
4266 
4267  /*
4268  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4269  * has already set up BlockSig and made that the active signal mask.)
4270  *
4271  * Note that postmaster blocked all signals before forking child process,
4272  * so there is no race condition whereby we might receive a signal before
4273  * we have set up the handler.
4274  *
4275  * Also note: it's best not to use any signals that are SIG_IGNored in the
4276  * postmaster. If such a signal arrives before we are able to change the
4277  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4278  * handler in the postmaster to reserve the signal. (Of course, this isn't
4279  * an issue for signals that are locally generated, such as SIGALRM and
4280  * SIGPIPE.)
4281  */
4282  if (am_walsender)
4283  WalSndSignals();
4284  else
4285  {
4287  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4288  pqsignal(SIGTERM, die); /* cancel current query and exit */
4289 
4290  /*
4291  * In a postmaster child backend, replace SignalHandlerForCrashExit
4292  * with quickdie, so we can tell the client we're dying.
4293  *
4294  * In a standalone backend, SIGQUIT can be generated from the keyboard
4295  * easily, while SIGTERM cannot, so we make both signals do die()
4296  * rather than quickdie().
4297  */
4298  if (IsUnderPostmaster)
4299  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4300  else
4301  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4302  InitializeTimeouts(); /* establishes SIGALRM handler */
4303 
4304  /*
4305  * Ignore failure to write to frontend. Note: if frontend closes
4306  * connection, we will notice it and exit cleanly when control next
4307  * returns to outer loop. This seems safer than forcing exit in the
4308  * midst of output during who-knows-what operation...
4309  */
4314 
4315  /*
4316  * Reset some signals that are accepted by postmaster but not by
4317  * backend
4318  */
4319  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4320  * platforms */
4321  }
4322 
4323  /* Early initialization */
4324  BaseInit();
4325 
4326  /* We need to allow SIGINT, etc during the initial transaction */
4327  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4328 
4329  /*
4330  * Generate a random cancel key, if this is a backend serving a
4331  * connection. InitPostgres() will advertise it in shared memory.
4332  */
4335  {
4336  if (!pg_strong_random(&MyCancelKey, sizeof(int32)))
4337  {
4338  ereport(ERROR,
4339  (errcode(ERRCODE_INTERNAL_ERROR),
4340  errmsg("could not generate random cancel key")));
4341  }
4342  MyCancelKeyValid = true;
4343  }
4344 
4345  /*
4346  * General initialization.
4347  *
4348  * NOTE: if you are tempted to add code in this vicinity, consider putting
4349  * it inside InitPostgres() instead. In particular, anything that
4350  * involves database access should be there, not here.
4351  *
4352  * Honor session_preload_libraries if not dealing with a WAL sender.
4353  */
4354  InitPostgres(dbname, InvalidOid, /* database to connect to */
4355  username, InvalidOid, /* role to connect as */
4357  NULL); /* no out_dbname */
4358 
4359  /*
4360  * If the PostmasterContext is still around, recycle the space; we don't
4361  * need it anymore after InitPostgres completes.
4362  */
4363  if (PostmasterContext)
4364  {
4366  PostmasterContext = NULL;
4367  }
4368 
4370 
4371  /*
4372  * Now all GUC states are fully set up. Report them to client if
4373  * appropriate.
4374  */
4376 
4377  /*
4378  * Also set up handler to log session end; we have to wait till now to be
4379  * sure Log_disconnections has its final value.
4380  */
4383 
4385 
4386  /* Perform initialization specific to a WAL sender process. */
4387  if (am_walsender)
4388  InitWalSender();
4389 
4390  /*
4391  * Send this backend's cancellation info to the frontend.
4392  */
4394  {
4396 
4401  pq_endmessage(&buf);
4402  /* Need not flush since ReadyForQuery will do it. */
4403  }
4404 
4405  /* Welcome banner for standalone case */
4407  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4408 
4409  /*
4410  * Create the memory context we will use in the main loop.
4411  *
4412  * MessageContext is reset once per iteration of the main loop, ie, upon
4413  * completion of processing of each command message from the client.
4414  */
4416  "MessageContext",
4418 
4419  /*
4420  * Create memory context and buffer used for RowDescription messages. As
4421  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4422  * frequently executed for ever single statement, we don't want to
4423  * allocate a separate buffer every time.
4424  */
4426  "RowDescriptionContext",
4431 
4432  /* Fire any defined login event triggers, if appropriate */
4434 
4435  /*
4436  * POSTGRES main processing loop begins here
4437  *
4438  * If an exception is encountered, processing resumes here so we abort the
4439  * current transaction and start a new one.
4440  *
4441  * You might wonder why this isn't coded as an infinite loop around a
4442  * PG_TRY construct. The reason is that this is the bottom of the
4443  * exception stack, and so with PG_TRY there would be no exception handler
4444  * in force at all during the CATCH part. By leaving the outermost setjmp
4445  * always active, we have at least some chance of recovering from an error
4446  * during error recovery. (If we get into an infinite loop thereby, it
4447  * will soon be stopped by overflow of elog.c's internal state stack.)
4448  *
4449  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4450  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4451  * is essential in case we longjmp'd out of a signal handler on a platform
4452  * where that leaves the signal blocked. It's not redundant with the
4453  * unblock in AbortTransaction() because the latter is only called if we
4454  * were inside a transaction.
4455  */
4456 
4457  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4458  {
4459  /*
4460  * NOTE: if you are tempted to add more code in this if-block,
4461  * consider the high probability that it should be in
4462  * AbortTransaction() instead. The only stuff done directly here
4463  * should be stuff that is guaranteed to apply *only* for outer-level
4464  * error recovery, such as adjusting the FE/BE protocol status.
4465  */
4466 
4467  /* Since not using PG_TRY, must reset error stack by hand */
4468  error_context_stack = NULL;
4469 
4470  /* Prevent interrupts while cleaning up */
4471  HOLD_INTERRUPTS();
4472 
4473  /*
4474  * Forget any pending QueryCancel request, since we're returning to
4475  * the idle loop anyway, and cancel any active timeout requests. (In
4476  * future we might want to allow some timeout requests to survive, but
4477  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4478  * we got here because of a query cancel interrupting the SIGALRM
4479  * interrupt handler.) Note in particular that we must clear the
4480  * statement and lock timeout indicators, to prevent any future plain
4481  * query cancels from being misreported as timeouts in case we're
4482  * forgetting a timeout cancel.
4483  */
4484  disable_all_timeouts(false); /* do first to avoid race condition */
4485  QueryCancelPending = false;
4486  idle_in_transaction_timeout_enabled = false;
4487  idle_session_timeout_enabled = false;
4488 
4489  /* Not reading from the client anymore. */
4490  DoingCommandRead = false;
4491 
4492  /* Make sure libpq is in a good state */
4493  pq_comm_reset();
4494 
4495  /* Report the error to the client and/or server log */
4496  EmitErrorReport();
4497 
4498  /*
4499  * If Valgrind noticed something during the erroneous query, print the
4500  * query string, assuming we have one.
4501  */
4503 
4504  /*
4505  * Make sure debug_query_string gets reset before we possibly clobber
4506  * the storage it points at.
4507  */
4508  debug_query_string = NULL;
4509 
4510  /*
4511  * Abort the current transaction in order to recover.
4512  */
4514 
4515  if (am_walsender)
4517 
4519 
4520  /*
4521  * We can't release replication slots inside AbortTransaction() as we
4522  * need to be able to start and abort transactions while having a slot
4523  * acquired. But we never need to hold them across top level errors,
4524  * so releasing here is fine. There also is a before_shmem_exit()
4525  * callback ensuring correct cleanup on FATAL errors.
4526  */
4527  if (MyReplicationSlot != NULL)
4529 
4530  /* We also want to cleanup temporary slots on error. */
4531  ReplicationSlotCleanup(false);
4532 
4534 
4535  /*
4536  * Now return to normal top-level context and clear ErrorContext for
4537  * next time.
4538  */
4540  FlushErrorState();
4541 
4542  /*
4543  * If we were handling an extended-query-protocol message, initiate
4544  * skip till next Sync. This also causes us not to issue
4545  * ReadyForQuery (until we get Sync).
4546  */
4548  ignore_till_sync = true;
4549 
4550  /* We don't have a transaction command open anymore */
4551  xact_started = false;
4552 
4553  /*
4554  * If an error occurred while we were reading a message from the
4555  * client, we have potentially lost track of where the previous
4556  * message ends and the next one begins. Even though we have
4557  * otherwise recovered from the error, we cannot safely read any more
4558  * messages from the client, so there isn't much we can do with the
4559  * connection anymore.
4560  */
4561  if (pq_is_reading_msg())
4562  ereport(FATAL,
4563  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4564  errmsg("terminating connection because protocol synchronization was lost")));
4565 
4566  /* Now we can allow interrupts again */
4568  }
4569 
4570  /* We can now handle ereport(ERROR) */
4571  PG_exception_stack = &local_sigjmp_buf;
4572 
4573  if (!ignore_till_sync)
4574  send_ready_for_query = true; /* initially, or after error */
4575 
4576  /*
4577  * Non-error queries loop here.
4578  */
4579 
4580  for (;;)
4581  {
4582  int firstchar;
4583  StringInfoData input_message;
4584 
4585  /*
4586  * At top of loop, reset extended-query-message flag, so that any
4587  * errors encountered in "idle" state don't provoke skip.
4588  */
4590 
4591  /*
4592  * For valgrind reporting purposes, the "current query" begins here.
4593  */
4594 #ifdef USE_VALGRIND
4595  old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4596 #endif
4597 
4598  /*
4599  * Release storage left over from prior query cycle, and create a new
4600  * query input buffer in the cleared MessageContext.
4601  */
4604 
4605  initStringInfo(&input_message);
4606 
4607  /*
4608  * Also consider releasing our catalog snapshot if any, so that it's
4609  * not preventing advance of global xmin while we wait for the client.
4610  */
4612 
4613  /*
4614  * (1) If we've reached idle state, tell the frontend we're ready for
4615  * a new query.
4616  *
4617  * Note: this includes fflush()'ing the last of the prior output.
4618  *
4619  * This is also a good time to flush out collected statistics to the
4620  * cumulative stats system, and to update the PS stats display. We
4621  * avoid doing those every time through the message loop because it'd
4622  * slow down processing of batched messages, and because we don't want
4623  * to report uncommitted updates (that confuses autovacuum). The
4624  * notification processor wants a call too, if we are not in a
4625  * transaction block.
4626  *
4627  * Also, if an idle timeout is enabled, start the timer for that.
4628  */
4629  if (send_ready_for_query)
4630  {
4632  {
4633  set_ps_display("idle in transaction (aborted)");
4635 
4636  /* Start the idle-in-transaction timer */
4639  {
4640  idle_in_transaction_timeout_enabled = true;
4643  }
4644  }
4646  {
4647  set_ps_display("idle in transaction");
4649 
4650  /* Start the idle-in-transaction timer */
4653  {
4654  idle_in_transaction_timeout_enabled = true;
4657  }
4658  }
4659  else
4660  {
4661  long stats_timeout;
4662 
4663  /*
4664  * Process incoming notifies (including self-notifies), if
4665  * any, and send relevant messages to the client. Doing it
4666  * here helps ensure stable behavior in tests: if any notifies
4667  * were received during the just-finished transaction, they'll
4668  * be seen by the client before ReadyForQuery is.
4669  */
4671  ProcessNotifyInterrupt(false);
4672 
4673  /*
4674  * Check if we need to report stats. If pgstat_report_stat()
4675  * decides it's too soon to flush out pending stats / lock
4676  * contention prevented reporting, it'll tell us when we
4677  * should try to report stats again (so that stats updates
4678  * aren't unduly delayed if the connection goes idle for a
4679  * long time). We only enable the timeout if we don't already
4680  * have a timeout in progress, because we don't disable the
4681  * timeout below. enable_timeout_after() needs to determine
4682  * the current timestamp, which can have a negative
4683  * performance impact. That's OK because pgstat_report_stat()
4684  * won't have us wake up sooner than a prior call.
4685  */
4686  stats_timeout = pgstat_report_stat(false);
4687  if (stats_timeout > 0)
4688  {
4691  stats_timeout);
4692  }
4693  else
4694  {
4695  /* all stats flushed, no need for the timeout */
4698  }
4699 
4700  set_ps_display("idle");
4702 
4703  /* Start the idle-session timer */
4704  if (IdleSessionTimeout > 0)
4705  {
4706  idle_session_timeout_enabled = true;
4709  }
4710  }
4711 
4712  /* Report any recently-changed GUC options */
4714 
4716  send_ready_for_query = false;
4717  }
4718 
4719  /*
4720  * (2) Allow asynchronous signals to be executed immediately if they
4721  * come in while we are waiting for client input. (This must be
4722  * conditional since we don't want, say, reads on behalf of COPY FROM
4723  * STDIN doing the same thing.)
4724  */
4725  DoingCommandRead = true;
4726 
4727  /*
4728  * (3) read a command (loop blocks here)
4729  */
4730  firstchar = ReadCommand(&input_message);
4731 
4732  /*
4733  * (4) turn off the idle-in-transaction and idle-session timeouts if
4734  * active. We do this before step (5) so that any last-moment timeout
4735  * is certain to be detected in step (5).
4736  *
4737  * At most one of these timeouts will be active, so there's no need to
4738  * worry about combining the timeout.c calls into one.
4739  */
4740  if (idle_in_transaction_timeout_enabled)
4741  {
4743  idle_in_transaction_timeout_enabled = false;
4744  }
4745  if (idle_session_timeout_enabled)
4746  {
4748  idle_session_timeout_enabled = false;
4749  }
4750 
4751  /*
4752  * (5) disable async signal conditions again.
4753  *
4754  * Query cancel is supposed to be a no-op when there is no query in
4755  * progress, so if a query cancel arrived while we were idle, just
4756  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4757  * it's called when DoingCommandRead is set, so check for interrupts
4758  * before resetting DoingCommandRead.
4759  */
4761  DoingCommandRead = false;
4762 
4763  /*
4764  * (6) check for any other interesting events that happened while we
4765  * slept.
4766  */
4767  if (ConfigReloadPending)
4768  {
4769  ConfigReloadPending = false;
4771  }
4772 
4773  /*
4774  * (7) process the command. But ignore it if we're skipping till
4775  * Sync.
4776  */
4777  if (ignore_till_sync && firstchar != EOF)
4778  continue;
4779 
4780  switch (firstchar)
4781  {
4782  case PqMsg_Query:
4783  {
4784  const char *query_string;
4785 
4786  /* Set statement_timestamp() */
4788 
4789  query_string = pq_getmsgstring(&input_message);
4790  pq_getmsgend(&input_message);
4791 
4792  if (am_walsender)
4793  {
4794  if (!exec_replication_command(query_string))
4795  exec_simple_query(query_string);
4796  }
4797  else
4798  exec_simple_query(query_string);
4799 
4800  valgrind_report_error_query(query_string);
4801 
4802  send_ready_for_query = true;
4803  }
4804  break;
4805 
4806  case PqMsg_Parse:
4807  {
4808  const char *stmt_name;
4809  const char *query_string;
4810  int numParams;
4811  Oid *paramTypes = NULL;
4812 
4813  forbidden_in_wal_sender(firstchar);
4814 
4815  /* Set statement_timestamp() */
4817 
4818  stmt_name = pq_getmsgstring(&input_message);
4819  query_string = pq_getmsgstring(&input_message);
4820  numParams = pq_getmsgint(&input_message, 2);
4821  if (numParams > 0)
4822  {
4823  paramTypes = palloc_array(Oid, numParams);
4824  for (int i = 0; i < numParams; i++)
4825  paramTypes[i] = pq_getmsgint(&input_message, 4);
4826  }
4827  pq_getmsgend(&input_message);
4828 
4829  exec_parse_message(query_string, stmt_name,
4830  paramTypes, numParams);
4831 
4832  valgrind_report_error_query(query_string);
4833  }
4834  break;
4835 
4836  case PqMsg_Bind:
4837  forbidden_in_wal_sender(firstchar);
4838 
4839  /* Set statement_timestamp() */
4841 
4842  /*
4843  * this message is complex enough that it seems best to put
4844  * the field extraction out-of-line
4845  */
4846  exec_bind_message(&input_message);
4847 
4848  /* exec_bind_message does valgrind_report_error_query */
4849  break;
4850 
4851  case PqMsg_Execute:
4852  {
4853  const char *portal_name;
4854  int max_rows;
4855 
4856  forbidden_in_wal_sender(firstchar);
4857 
4858  /* Set statement_timestamp() */
4860 
4861  portal_name = pq_getmsgstring(&input_message);
4862  max_rows = pq_getmsgint(&input_message, 4);
4863  pq_getmsgend(&input_message);
4864 
4865  exec_execute_message(portal_name, max_rows);
4866 
4867  /* exec_execute_message does valgrind_report_error_query */
4868  }
4869  break;
4870 
4871  case PqMsg_FunctionCall:
4872  forbidden_in_wal_sender(firstchar);
4873 
4874  /* Set statement_timestamp() */
4876 
4877  /* Report query to various monitoring facilities. */
4879  set_ps_display("<FASTPATH>");
4880 
4881  /* start an xact for this function invocation */
4883 
4884  /*
4885  * Note: we may at this point be inside an aborted
4886  * transaction. We can't throw error for that until we've
4887  * finished reading the function-call message, so
4888  * HandleFunctionRequest() must check for it after doing so.
4889  * Be careful not to do anything that assumes we're inside a
4890  * valid transaction here.
4891  */
4892 
4893  /* switch back to message context */
4895 
4896  HandleFunctionRequest(&input_message);
4897 
4898  /* commit the function-invocation transaction */
4900 
4901  valgrind_report_error_query("fastpath function call");
4902 
4903  send_ready_for_query = true;
4904  break;
4905 
4906  case PqMsg_Close:
4907  {
4908  int close_type;
4909  const char *close_target;
4910 
4911  forbidden_in_wal_sender(firstchar);
4912 
4913  close_type = pq_getmsgbyte(&input_message);
4914  close_target = pq_getmsgstring(&input_message);
4915  pq_getmsgend(&input_message);
4916 
4917  switch (close_type)
4918  {
4919  case 'S':
4920  if (close_target[0] != '\0')
4921  DropPreparedStatement(close_target, false);
4922  else
4923  {
4924  /* special-case the unnamed statement */
4926  }
4927  break;
4928  case 'P':
4929  {
4930  Portal portal;
4931 
4932  portal = GetPortalByName(close_target);
4933  if (PortalIsValid(portal))
4934  PortalDrop(portal, false);
4935  }
4936  break;
4937  default:
4938  ereport(ERROR,
4939  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4940  errmsg("invalid CLOSE message subtype %d",
4941  close_type)));
4942  break;
4943  }
4944 
4947 
4948  valgrind_report_error_query("CLOSE message");
4949  }
4950  break;
4951 
4952  case PqMsg_Describe:
4953  {
4954  int describe_type;
4955  const char *describe_target;
4956 
4957  forbidden_in_wal_sender(firstchar);
4958 
4959  /* Set statement_timestamp() (needed for xact) */
4961 
4962  describe_type = pq_getmsgbyte(&input_message);
4963  describe_target = pq_getmsgstring(&input_message);
4964  pq_getmsgend(&input_message);
4965 
4966  switch (describe_type)
4967  {
4968  case 'S':
4969  exec_describe_statement_message(describe_target);
4970  break;
4971  case 'P':
4972  exec_describe_portal_message(describe_target);
4973  break;
4974  default:
4975  ereport(ERROR,
4976  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4977  errmsg("invalid DESCRIBE message subtype %d",
4978  describe_type)));
4979  break;
4980  }
4981 
4982  valgrind_report_error_query("DESCRIBE message");
4983  }
4984  break;
4985 
4986  case PqMsg_Flush:
4987  pq_getmsgend(&input_message);
4989  pq_flush();
4990  break;
4991 
4992  case PqMsg_Sync:
4993  pq_getmsgend(&input_message);
4995  valgrind_report_error_query("SYNC message");
4996  send_ready_for_query = true;
4997  break;
4998 
4999  /*
5000  * 'X' means that the frontend is closing down the socket. EOF
5001  * means unexpected loss of frontend connection. Either way,
5002  * perform normal shutdown.
5003  */
5004  case EOF:
5005 
5006  /* for the cumulative statistics system */
5008 
5009  /* FALLTHROUGH */
5010 
5011  case PqMsg_Terminate:
5012 
5013  /*
5014  * Reset whereToSendOutput to prevent ereport from attempting
5015  * to send any more messages to client.
5016  */
5019 
5020  /*
5021  * NOTE: if you are tempted to add more code here, DON'T!
5022  * Whatever you had in mind to do should be set up as an
5023  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5024  * it will fail to be called during other backend-shutdown
5025  * scenarios.
5026  */
5027  proc_exit(0);
5028 
5029  case PqMsg_CopyData:
5030  case PqMsg_CopyDone:
5031  case PqMsg_CopyFail:
5032 
5033  /*
5034  * Accept but ignore these messages, per protocol spec; we
5035  * probably got here because a COPY failed, and the frontend
5036  * is still sending data.
5037  */
5038  break;
5039 
5040  default:
5041  ereport(FATAL,
5042  (errcode(ERRCODE_PROTOCOL_VIOLATION),
5043  errmsg("invalid frontend message type %d",
5044  firstchar)));
5045  }
5046  } /* end of input-reading loop */
5047 }
void ProcessNotifyInterrupt(bool flush)
Definition: async.c:1834
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:413
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:516
sigset_t UnBlockSig
Definition: pqsignal.c:22
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
void ReadyForQuery(CommandDest dest)
Definition: dest.c:256
@ DestDebug
Definition: dest.h:88
@ DestNone
Definition: dest.h:87
void EmitErrorReport(void)
Definition: elog.c:1687
void FlushErrorState(void)
Definition: elog.c:1867
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
#define FATAL
Definition: elog.h:41
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:188
int32 MyCancelKey
Definition: globals.c:52
int MyProcPid
Definition: globals.c:46
bool IsUnderPostmaster
Definition: globals.c:119
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:32
bool MyCancelKeyValid
Definition: globals.c:51
Oid MyDatabaseId
Definition: globals.c:93
void BeginReportingGUCOptions(void)
Definition: guc.c:2546
void ReportChangedGUCOptions(void)
Definition: guc.c:2596
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
static char * username
Definition: initdb.c:153
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void proc_exit(int code)
Definition: ipc.c:104
void jit_reset_after_error(void)
Definition: jit.c:127
#define pq_flush()
Definition: libpq.h:46
#define pq_comm_reset()
Definition: libpq.h:45
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
MemoryContext PostmasterContext
Definition: mcxt.c:151
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:449
@ InitProcessing
Definition: miscadmin.h:448
#define GetProcessingMode()
Definition: miscadmin.h:458
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:476
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
long pgstat_report_stat(bool force)
Definition: pgstat.c:659
@ DISCONNECT_CLIENT_EOF
Definition: pgstat.h:111
void pgstat_report_connect(Oid dboid)
bool pg_strong_random(void *buf, size_t len)
pqsigfunc pqsignal(int signo, pqsigfunc func)
void PortalErrorCleanup(void)
Definition: portalmem.c:917
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2630
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2907
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5227
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:5057
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2106
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3051
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3034
static bool ignore_till_sync
Definition: postgres.c:154
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1022
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1400
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1635
void die(SIGNAL_ARGS)
Definition: postgres.c:3004
static MemoryContext row_description_context
Definition: postgres.c:173
static bool doing_extended_query_message
Definition: postgres.c:153
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2723
bool Log_disconnections
Definition: postgres.c:93
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:491
void BaseInit(void)
Definition: postinit.c:604
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:698
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1181
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:399
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:671
#define PqMsg_CloseComplete
Definition: protocol.h:40
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_Describe
Definition: protocol.h:21
#define PqMsg_Parse
Definition: protocol.h:25
#define PqMsg_Bind
Definition: protocol.h:19
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_CopyFail
Definition: protocol.h:29
#define PqMsg_Flush
Definition: protocol.h:24
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_Query
Definition: protocol.h:26
#define PqMsg_Terminate
Definition: protocol.h:28
#define PqMsg_Execute
Definition: protocol.h:22
#define PqMsg_Close
Definition: protocol.h:20
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotRelease(void)
Definition: slot.c:652
void ReplicationSlotCleanup(bool synced_only)
Definition: slot.c:745
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:443
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:60
char * dbname
Definition: streamutil.c:50
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:751
void InitializeTimeouts(void)
Definition: timeout.c:470
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
void WalSndErrorCleanup(void)
Definition: walsender.c:325
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1952
void WalSndSignals(void)
Definition: walsender.c:3562
void InitWalSender(void)
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define SIGPIPE
Definition: win32_port.h:173
#define SIGQUIT
Definition: win32_port.h:169
#define SIGUSR1
Definition: win32_port.h:180
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4994
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:913
void AbortCurrentTransaction(void)
Definition: xact.c:3443

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, dbname, 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, EventTriggerOnLogin(), 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(), get_timeout_active(), GetPortalByName(), GetProcessingMode, HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeout, IdleSessionTimeout, ignore_till_sync, INIT_PG_LOAD_SESSION_LIBS, InitializeTimeouts(), InitPostgres(), InitProcessing, initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyCancelKeyValid, MyDatabaseId, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc_array, PG_exception_stack, pg_strong_random(), PGC_SIGHUP, pgstat_report_activity(), pgstat_report_connect(), 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(), PqMsg_BackendKeyData, PqMsg_Bind, PqMsg_Close, PqMsg_CloseComplete, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Describe, PqMsg_Execute, PqMsg_Flush, PqMsg_FunctionCall, PqMsg_Parse, PqMsg_Query, PqMsg_Sync, PqMsg_Terminate, pqsignal(), printf, proc_exit(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, row_description_buf, row_description_context, set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, TransactionTimeout, UnBlockSig, username, valgrind_report_error_query, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendMain(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4134 of file postgres.c.

4136 {
4137  const char *dbname = NULL;
4138 
4140 
4141  /* Initialize startup process environment. */
4142  InitStandaloneProcess(argv[0]);
4143 
4144  /*
4145  * Set default values for command-line options.
4146  */
4148 
4149  /*
4150  * Parse command-line options.
4151  */
4153 
4154  /* Must have gotten a database name, or have a default (the username) */
4155  if (dbname == NULL)
4156  {
4157  dbname = username;
4158  if (dbname == NULL)
4159  ereport(FATAL,
4160  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4161  errmsg("%s: no database nor user name specified",
4162  progname)));
4163  }
4164 
4165  /* Acquire configuration parameters */
4167  proc_exit(1);
4168 
4169  /*
4170  * Validate we have been given a reasonable-looking DataDir and change
4171  * into it.
4172  */
4173  checkDataDir();
4174  ChangeToDataDir();
4175 
4176  /*
4177  * Create lockfile for data directory.
4178  */
4179  CreateDataDirLockFile(false);
4180 
4181  /* read control file (error checking and contains config ) */
4182  LocalProcessControlFile(false);
4183 
4184  /*
4185  * process any libraries that should be preloaded at postmaster start
4186  */
4188 
4189  /* Initialize MaxBackends */
4191 
4192  /*
4193  * We don't need postmaster child slots in single-user mode, but
4194  * initialize them anyway to avoid having special handling.
4195  */
4197 
4198  /* Initialize size of fast-path lock cache. */
4200 
4201  /*
4202  * Give preloaded libraries a chance to request additional shared memory.
4203  */
4205 
4206  /*
4207  * Now that loadable modules have had their chance to request additional
4208  * shared memory, determine the value of any runtime-computed GUCs that
4209  * depend on the amount of shared memory required.
4210  */
4212 
4213  /*
4214  * Now that modules have been loaded, we can process any custom resource
4215  * managers specified in the wal_consistency_checking GUC.
4216  */
4218 
4220 
4221  /*
4222  * Remember stand-alone backend startup time,roughly at the same point
4223  * during startup that postmaster does so.
4224  */
4226 
4227  /*
4228  * Create a per-backend PGPROC struct in shared memory. We must do this
4229  * before we can use LWLocks.
4230  */
4231  InitProcess();
4232 
4233  /*
4234  * Now that sufficient infrastructure has been initialized, PostgresMain()
4235  * can do the rest.
4236  */
4238 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1784
void InitializeGUCOptions(void)
Definition: guc.c:1530
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:352
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:198
const char * progname
Definition: main.c:43
void ChangeToDataDir(void)
Definition: miscinit.c:464
void process_shmem_requests(void)
Definition: miscinit.c:1932
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void process_shared_preload_libraries(void)
Definition: miscinit.c:1904
void checkDataDir(void)
Definition: miscinit.c:351
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1516
void InitPostmasterChildSlots(void)
Definition: pmchild.c:86
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3882
static const char * userDoption
Definition: postgres.c:164
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4253
void InitializeMaxBackends(void)
Definition: postinit.c:543
void InitializeFastPathLocks(void)
Definition: postinit.c:575
void InitProcess(void)
Definition: proc.c:339
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4784
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4846

References Assert, ChangeToDataDir(), checkDataDir(), CreateDataDirLockFile(), CreateSharedMemoryAndSemaphores(), dbname, ereport, errcode(), errmsg(), FATAL, GetCurrentTimestamp(), InitializeFastPathLocks(), InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterChildSlots(), InitProcess(), InitStandaloneProcess(), IsUnderPostmaster, LocalProcessControlFile(), PGC_POSTMASTER, PgStartTime, PostgresMain(), proc_exit(), process_postgres_switches(), process_shared_preload_libraries(), process_shmem_requests(), progname, SelectConfigFiles(), userDoption, and username.

Referenced by main().

◆ process_postgres_switches()

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

Definition at line 3882 of file postgres.c.

3884 {
3885  bool secure = (ctx == PGC_POSTMASTER);
3886  int errs = 0;
3887  GucSource gucsource;
3888  int flag;
3889 
3890  if (secure)
3891  {
3892  gucsource = PGC_S_ARGV; /* switches came from command line */
3893 
3894  /* Ignore the initial --single argument, if present */
3895  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3896  {
3897  argv++;
3898  argc--;
3899  }
3900  }
3901  else
3902  {
3903  gucsource = PGC_S_CLIENT; /* switches came from client */
3904  }
3905 
3906 #ifdef HAVE_INT_OPTERR
3907 
3908  /*
3909  * Turn this off because it's either printed to stderr and not the log
3910  * where we'd want it, or argv[0] is now "--single", which would make for
3911  * a weird error message. We print our own error message below.
3912  */
3913  opterr = 0;
3914 #endif
3915 
3916  /*
3917  * Parse command-line options. CAUTION: keep this in sync with
3918  * postmaster/postmaster.c (the option sets should not conflict) and with
3919  * the common help() function in main/main.c.
3920  */
3921  while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3922  {
3923  switch (flag)
3924  {
3925  case 'B':
3926  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3927  break;
3928 
3929  case 'b':
3930  /* Undocumented flag used for binary upgrades */
3931  if (secure)
3932  IsBinaryUpgrade = true;
3933  break;
3934 
3935  case 'C':
3936  /* ignored for consistency with the postmaster */
3937  break;
3938 
3939  case 'c':
3940  case '-':
3941  {
3942  char *name,
3943  *value;
3944 
3946  if (!value)
3947  {
3948  if (flag == '-')
3949  ereport(ERROR,
3950  (errcode(ERRCODE_SYNTAX_ERROR),
3951  errmsg("--%s requires a value",
3952  optarg)));
3953  else
3954  ereport(ERROR,
3955  (errcode(ERRCODE_SYNTAX_ERROR),
3956  errmsg("-c %s requires a value",
3957  optarg)));
3958  }
3959  SetConfigOption(name, value, ctx, gucsource);
3960  pfree(name);
3961  pfree(value);
3962  break;
3963  }
3964 
3965  case 'D':
3966  if (secure)
3967  userDoption = strdup(optarg);
3968  break;
3969 
3970  case 'd':
3971  set_debug_options(atoi(optarg), ctx, gucsource);
3972  break;
3973 
3974  case 'E':
3975  if (secure)
3976  EchoQuery = true;
3977  break;
3978 
3979  case 'e':
3980  SetConfigOption("datestyle", "euro", ctx, gucsource);
3981  break;
3982 
3983  case 'F':
3984  SetConfigOption("fsync", "false", ctx, gucsource);
3985  break;
3986 
3987  case 'f':
3988  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3989  errs++;
3990  break;
3991 
3992  case 'h':
3993  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3994  break;
3995 
3996  case 'i':
3997  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3998  break;
3999 
4000  case 'j':
4001  if (secure)
4002  UseSemiNewlineNewline = true;
4003  break;
4004 
4005  case 'k':
4006  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
4007  break;
4008 
4009  case 'l':
4010  SetConfigOption("ssl", "true", ctx, gucsource);
4011  break;
4012 
4013  case 'N':
4014  SetConfigOption("max_connections", optarg, ctx, gucsource);
4015  break;
4016 
4017  case 'n':
4018  /* ignored for consistency with postmaster */
4019  break;
4020 
4021  case 'O':
4022  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4023  break;
4024 
4025  case 'P':
4026  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4027  break;
4028 
4029  case 'p':
4030  SetConfigOption("port", optarg, ctx, gucsource);
4031  break;
4032 
4033  case 'r':
4034  /* send output (stdout and stderr) to the given file */
4035  if (secure)
4037  break;
4038 
4039  case 'S':
4040  SetConfigOption("work_mem", optarg, ctx, gucsource);
4041  break;
4042 
4043  case 's':
4044  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4045  break;
4046 
4047  case 'T':
4048  /* ignored for consistency with the postmaster */
4049  break;
4050 
4051  case 't':
4052  {
4053  const char *tmp = get_stats_option_name(optarg);
4054 
4055  if (tmp)
4056  SetConfigOption(tmp, "true", ctx, gucsource);
4057  else
4058  errs++;
4059  break;
4060  }
4061 
4062  case 'v':
4063 
4064  /*
4065  * -v is no longer used in normal operation, since
4066  * FrontendProtocol is already set before we get here. We keep
4067  * the switch only for possible use in standalone operation,
4068  * in case we ever support using normal FE/BE protocol with a
4069  * standalone backend.
4070  */
4071  if (secure)
4073  break;
4074 
4075  case 'W':
4076  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
4077  break;
4078 
4079  default:
4080  errs++;
4081  break;
4082  }
4083 
4084  if (errs)
4085  break;
4086  }
4087 
4088  /*
4089  * Optional database name should be there only if *dbname is NULL.
4090  */
4091  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
4092  *dbname = strdup(argv[optind++]);
4093 
4094  if (errs || argc != optind)
4095  {
4096  if (errs)
4097  optind--; /* complain about the previous argument */
4098 
4099  /* spell the error message a bit differently depending on context */
4100  if (IsUnderPostmaster)
4101  ereport(FATAL,
4102  errcode(ERRCODE_SYNTAX_ERROR),
4103  errmsg("invalid command-line argument for server process: %s", argv[optind]),
4104  errhint("Try \"%s --help\" for more information.", progname));
4105  else
4106  ereport(FATAL,
4107  errcode(ERRCODE_SYNTAX_ERROR),
4108  errmsg("%s: invalid command-line argument: %s",
4109  progname, argv[optind]),
4110  errhint("Try \"%s --help\" for more information.", progname));
4111  }
4112 
4113  /*
4114  * Reset getopt(3) library so that it will work correctly in subprocesses
4115  * or when this function is called a second time with another array.
4116  */
4117  optind = 1;
4118 #ifdef HAVE_INT_OPTRESET
4119  optreset = 1; /* some systems need this too */
4120 #endif
4121 }
bool IsBinaryUpgrade
Definition: globals.c:120
ProtocolVersion FrontendProtocol
Definition: globals.c:29
char OutputFileName[MAXPGPATH]
Definition: globals.c:78
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6362
GucSource
Definition: guc.h:108
@ PGC_S_ARGV
Definition: guc.h:113
@ PGC_S_CLIENT
Definition: guc.h:118
static struct @160 value
#define MAXPGPATH
PGDLLIMPORT int optind
Definition: getopt.c:51
PGDLLIMPORT int opterr
Definition: getopt.c:50
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3771
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3800
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3842
uint32 ProtocolVersion
Definition: pqcomm.h:100
char * flag(int b)
Definition: test-ctype.c:33
const char * name

References dbname, EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, optarg, opterr, optind, OutputFileName, ParseLongOption(), pfree(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 512 of file postgres.c.

513 {
514  int save_errno = errno;
515 
516  if (DoingCommandRead)
517  {
518  /* Check for general interrupts that arrived before/while reading */
520 
521  /* Process sinval catchup interrupts, if any */
524 
525  /* Process notify interrupts, if any */
528  }
529  else if (ProcDiePending)
530  {
531  /*
532  * We're dying. If there is no data available to read, then it's safe
533  * (and sane) to handle that now. If we haven't tried to read yet,
534  * make sure the process latch is set, so that if there is no data
535  * then we'll come back here and die. If we're done reading, also
536  * make sure the process latch is set, as we might've undesirably
537  * cleared it while reading.
538  */
539  if (blocked)
541  else
542  SetLatch(MyLatch);
543  }
544 
545  errno = save_errno;
546 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:174
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:39

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 558 of file postgres.c.

559 {
560  int save_errno = errno;
561 
562  if (ProcDiePending)
563  {
564  /*
565  * We're dying. If it's not possible to write, then we should handle
566  * that immediately, else a stuck client could indefinitely delay our
567  * response to the signal. If we haven't tried to write yet, make
568  * sure the process latch is set, so that if the write would block
569  * then we'll come back here and die. If we're done writing, also
570  * make sure the process latch is set, as we might've undesirably
571  * cleared it while writing.
572  */
573  if (blocked)
574  {
575  /*
576  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
577  * service ProcDiePending.
578  */
579  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
580  {
581  /*
582  * We don't want to send the client the error message, as a)
583  * that would possibly block again, and b) it would likely
584  * lead to loss of protocol sync because we may have already
585  * sent a partial protocol message.
586  */
589 
591  }
592  }
593  else
594  SetLatch(MyLatch);
595  }
596 
597  errno = save_errno;
598 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:42
volatile uint32 CritSectionCount
Definition: globals.c:44

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

Referenced by secure_write().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3276 of file postgres.c.

3277 {
3278  /* OK to accept any interrupts now? */
3279  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3280  return;
3281  InterruptPending = false;
3282 
3283  if (ProcDiePending)
3284  {
3285  ProcDiePending = false;
3286  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3287  LockErrorCleanup();
3288  /* As in quickdie, don't risk sending to client during auth */
3292  ereport(FATAL,
3293  (errcode(ERRCODE_QUERY_CANCELED),
3294  errmsg("canceling authentication due to timeout")));
3295  else if (AmAutoVacuumWorkerProcess())
3296  ereport(FATAL,
3297  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3298  errmsg("terminating autovacuum process due to administrator command")));
3299  else if (IsLogicalWorker())
3300  ereport(FATAL,
3301  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3302  errmsg("terminating logical replication worker due to administrator command")));
3303  else if (IsLogicalLauncher())
3304  {
3305  ereport(DEBUG1,
3306  (errmsg_internal("logical replication launcher shutting down")));
3307 
3308  /*
3309  * The logical replication launcher can be stopped at any time.
3310  * Use exit status 1 so the background worker is restarted.
3311  */
3312  proc_exit(1);
3313  }
3314  else if (AmBackgroundWorkerProcess())
3315  ereport(FATAL,
3316  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3317  errmsg("terminating background worker \"%s\" due to administrator command",
3319  else
3320  ereport(FATAL,
3321  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3322  errmsg("terminating connection due to administrator command")));
3323  }
3324 
3326  {
3328 
3329  /*
3330  * Check for lost connection and re-arm, if still configured, but not
3331  * if we've arrived back at DoingCommandRead state. We don't want to
3332  * wake up idle sessions, and they already know how to detect lost
3333  * connections.
3334  */
3336  {
3337  if (!pq_check_connection())
3338  ClientConnectionLost = true;
3339  else
3342  }
3343  }
3344 
3346  {
3347  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3348  LockErrorCleanup();
3349  /* don't send to client, we already know the connection to be dead. */
3351  ereport(FATAL,
3352  (errcode(ERRCODE_CONNECTION_FAILURE),
3353  errmsg("connection to client lost")));
3354  }
3355 
3356  /*
3357  * Don't allow query cancel interrupts while reading input from the
3358  * client, because we might lose sync in the FE/BE protocol. (Die
3359  * interrupts are OK, because we won't read any further messages from the
3360  * client in that case.)
3361  *
3362  * See similar logic in ProcessRecoveryConflictInterrupts().
3363  */
3365  {
3366  /*
3367  * Re-arm InterruptPending so that we process the cancel request as
3368  * soon as we're done reading the message. (XXX this is seriously
3369  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3370  * can't use that macro directly as the initial test in this function,
3371  * meaning that this code also creates opportunities for other bugs to
3372  * appear.)
3373  */
3374  InterruptPending = true;
3375  }
3376  else if (QueryCancelPending)
3377  {
3378  bool lock_timeout_occurred;
3379  bool stmt_timeout_occurred;
3380 
3381  QueryCancelPending = false;
3382 
3383  /*
3384  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3385  * need to clear both, so always fetch both.
3386  */
3387  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3388  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3389 
3390  /*
3391  * If both were set, we want to report whichever timeout completed
3392  * earlier; this ensures consistent behavior if the machine is slow
3393  * enough that the second timeout triggers before we get here. A tie
3394  * is arbitrarily broken in favor of reporting a lock timeout.
3395  */
3396  if (lock_timeout_occurred && stmt_timeout_occurred &&
3398  lock_timeout_occurred = false; /* report stmt timeout */
3399 
3400  if (lock_timeout_occurred)
3401  {
3402  LockErrorCleanup();
3403  ereport(ERROR,
3404  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3405  errmsg("canceling statement due to lock timeout")));
3406  }
3407  if (stmt_timeout_occurred)
3408  {
3409  LockErrorCleanup();
3410  ereport(ERROR,
3411  (errcode(ERRCODE_QUERY_CANCELED),
3412  errmsg("canceling statement due to statement timeout")));
3413  }
3415  {
3416  LockErrorCleanup();
3417  ereport(ERROR,
3418  (errcode(ERRCODE_QUERY_CANCELED),
3419  errmsg("canceling autovacuum task")));
3420  }
3421 
3422  /*
3423  * If we are reading a command from the client, just ignore the cancel
3424  * request --- sending an extra error message won't accomplish
3425  * anything. Otherwise, go ahead and throw the error.
3426  */
3427  if (!DoingCommandRead)
3428  {
3429  LockErrorCleanup();
3430  ereport(ERROR,
3431  (errcode(ERRCODE_QUERY_CANCELED),
3432  errmsg("canceling statement due to user request")));
3433  }
3434  }
3435 
3438 
3440  {
3441  /*
3442  * If the GUC has been reset to zero, ignore the signal. This is
3443  * important because the GUC update itself won't disable any pending
3444  * interrupt. We need to unset the flag before the injection point,
3445  * otherwise we could loop in interrupts checking.
3446  */
3449  {
3450  INJECTION_POINT("idle-in-transaction-session-timeout");
3451  ereport(FATAL,
3452  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3453  errmsg("terminating connection due to idle-in-transaction timeout")));
3454  }
3455  }
3456 
3458  {
3459  /* As above, ignore the signal if the GUC has been reset to zero. */
3460  TransactionTimeoutPending = false;
3461  if (TransactionTimeout > 0)
3462  {
3463  INJECTION_POINT("transaction-timeout");
3464  ereport(FATAL,
3465  (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3466  errmsg("terminating connection due to transaction timeout")));
3467  }
3468  }
3469 
3471  {
3472  /* As above, ignore the signal if the GUC has been reset to zero. */
3473  IdleSessionTimeoutPending = false;
3474  if (IdleSessionTimeout > 0)
3475  {
3476  INJECTION_POINT("idle-session-timeout");
3477  ereport(FATAL,
3478  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3479  errmsg("terminating connection due to idle-session timeout")));
3480  }
3481  }
3482 
3483  /*
3484  * If there are pending stats updates and we currently are truly idle
3485  * (matching the conditions in PostgresMain(), report stats now.
3486  */
3489  {
3491  pgstat_report_stat(true);
3492  }
3493 
3496 
3499 
3502 
3505 }
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
void HandleParallelMessages(void)
Definition: parallel.c:1044
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:117
bool IsLogicalWorker(void)
Definition: worker.c:4843
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:41
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:40
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:39
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:38
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:43
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:36
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:37
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:35
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:34
#define INJECTION_POINT(name)
bool IsLogicalLauncher(void)
Definition: launcher.c:1249
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1289
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:373
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:374
int client_connection_check_interval
Definition: postgres.c:104
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3237
bool ClientAuthInProgress
Definition: postmaster.c:355
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
bool pq_check_connection(void)
Definition: pqcomm.c:2054
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:496
void LockErrorCleanup(void)
Definition: proc.c:759
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:827
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:793
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, BackgroundWorker::bgw_type, CheckClientConnectionPending, client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, enable_timeout_after(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelApplyMessages(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, IdleStatsUpdateTimeoutPending, INJECTION_POINT, InterruptHoldoffCount, InterruptPending, IsLogicalLauncher(), IsLogicalWorker(), IsTransactionOrTransactionBlock(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, ParallelApplyMessagePending, ParallelMessagePending, pgstat_report_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), ProcessRecoveryConflictInterrupts(), ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, STATEMENT_TIMEOUT, TransactionTimeout, TransactionTimeoutPending, and whereToSendOutput.

Referenced by die().

◆ ProcessRecoveryConflictInterrupt()

static void ProcessRecoveryConflictInterrupt ( ProcSignalReason  reason)
static

Definition at line 3079 of file postgres.c.

3080 {
3081  switch (reason)
3082  {
3084 
3085  /*
3086  * If we aren't waiting for a lock we can never deadlock.
3087  */
3088  if (GetAwaitedLock() == NULL)
3089  return;
3090 
3091  /* Intentional fall through to check wait for pin */
3092  /* FALLTHROUGH */
3093 
3095 
3096  /*
3097  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3098  * aren't blocking the Startup process there is nothing more to
3099  * do.
3100  *
3101  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3102  * if we're waiting for locks and the startup process is not
3103  * waiting for buffer pin (i.e., also waiting for locks), we set
3104  * the flag so that ProcSleep() will check for deadlocks.
3105  */
3107  {
3111  return;
3112  }
3113 
3115 
3116  /* Intentional fall through to error handling */
3117  /* FALLTHROUGH */
3118 
3122 
3123  /*
3124  * If we aren't in a transaction any longer then ignore.
3125  */
3127  return;
3128 
3129  /* FALLTHROUGH */
3130 
3132 
3133  /*
3134  * If we're not in a subtransaction then we are OK to throw an
3135  * ERROR to resolve the conflict. Otherwise drop through to the
3136  * FATAL case.
3137  *
3138  * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3139  * always throws an ERROR (ie never promotes to FATAL), though it
3140  * still has to respect QueryCancelHoldoffCount, so it shares this
3141  * code path. Logical decoding slots are only acquired while
3142  * performing logical decoding. During logical decoding no user
3143  * controlled code is run. During [sub]transaction abort, the
3144  * slot is released. Therefore user controlled code cannot
3145  * intercept an error before the replication slot is released.
3146  *
3147  * XXX other times that we can throw just an ERROR *may* be
3148  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3149  * transactions
3150  *
3151  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3152  * parent transactions and the transaction is not
3153  * transaction-snapshot mode
3154  *
3155  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3156  * cursors open in parent transactions
3157  */
3158  if (reason == PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT ||
3159  !IsSubTransaction())
3160  {
3161  /*
3162  * If we already aborted then we no longer need to cancel. We
3163  * do this here since we do not wish to ignore aborted
3164  * subtransactions, which must cause FATAL, currently.
3165  */
3167  return;
3168 
3169  /*
3170  * If a recovery conflict happens while we are waiting for
3171  * input from the client, the client is presumably just
3172  * sitting idle in a transaction, preventing recovery from
3173  * making progress. We'll drop through to the FATAL case
3174  * below to dislodge it, in that case.
3175  */
3176  if (!DoingCommandRead)
3177  {
3178  /* Avoid losing sync in the FE/BE protocol. */
3179  if (QueryCancelHoldoffCount != 0)
3180  {
3181  /*
3182  * Re-arm and defer this interrupt until later. See
3183  * similar code in ProcessInterrupts().
3184  */
3185  RecoveryConflictPendingReasons[reason] = true;
3186  RecoveryConflictPending = true;
3187  InterruptPending = true;
3188  return;
3189  }
3190 
3191  /*
3192  * We are cleared to throw an ERROR. Either it's the
3193  * logical slot case, or we have a top-level transaction
3194  * that we can abort and a conflict that isn't inherently
3195  * non-retryable.
3196  */
3197  LockErrorCleanup();
3199  ereport(ERROR,
3201  errmsg("canceling statement due to conflict with recovery"),
3202  errdetail_recovery_conflict(reason)));
3203  break;
3204  }
3205  }
3206 
3207  /* Intentional fall through to session cancel */
3208  /* FALLTHROUGH */
3209 
3211 
3212  /*
3213  * Retrying is not possible because the database is dropped, or we
3214  * decided above that we couldn't resolve the conflict with an
3215  * ERROR and fell through. Terminate the session.
3216  */
3218  ereport(FATAL,
3220  ERRCODE_DATABASE_DROPPED :
3222  errmsg("terminating connection due to conflict with recovery"),
3224  errhint("In a moment you should be able to reconnect to the"
3225  " database and repeat your command.")));
3226  break;
3227 
3228  default:
3229  elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3230  }
3231 }
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:5373
LOCALLOCK * GetAwaitedLock(void)
Definition: lock.c:1847
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
void pgstat_report_recovery_conflict(int reason)
static int errdetail_recovery_conflict(ProcSignalReason reason)
Definition: postgres.c:2542
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:712
void CheckDeadLockAlert(void)
Definition: proc.c:1865
bool IsSubTransaction(void)
Definition: xact.c:5049

References CheckDeadLockAlert(), DoingCommandRead, elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_recovery_conflict(), errhint(), errmsg(), ERROR, FATAL, GetAwaitedLock(), GetStartupBufferPinWaitBufId(), HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), LockErrorCleanup(), MyProc, pgstat_report_recovery_conflict(), PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelHoldoffCount, RecoveryConflictPending, PGPROC::recoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by ProcessRecoveryConflictInterrupts().

◆ ProcessRecoveryConflictInterrupts()

static void ProcessRecoveryConflictInterrupts ( void  )
static

Definition at line 3237 of file postgres.c.

3238 {
3239  /*
3240  * We don't need to worry about joggling the elbow of proc_exit, because
3241  * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3242  * us.
3243  */
3247 
3248  RecoveryConflictPending = false;
3249 
3252  reason++)
3253  {
3254  if (RecoveryConflictPendingReasons[reason])
3255  {
3256  RecoveryConflictPendingReasons[reason] = false;
3258  }
3259  }
3260 }
static void ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:3079
ProcSignalReason
Definition: procsignal.h:31
@ PROCSIG_RECOVERY_CONFLICT_LAST
Definition: procsignal.h:49
@ PROCSIG_RECOVERY_CONFLICT_FIRST
Definition: procsignal.h:41

References Assert, InterruptHoldoffCount, proc_exit_inprogress, ProcessRecoveryConflictInterrupt(), PROCSIG_RECOVERY_CONFLICT_FIRST, PROCSIG_RECOVERY_CONFLICT_LAST, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by ProcessInterrupts().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2907 of file postgres.c.

2908 {
2909  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2910  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
2911 
2912  /*
2913  * Prevent interrupts while exiting; though we just blocked signals that
2914  * would queue new interrupts, one may have been pending. We don't want a
2915  * quickdie() downgraded to a mere query cancel.
2916  */
2917  HOLD_INTERRUPTS();
2918 
2919  /*
2920  * If we're aborting out of client auth, don't risk trying to send
2921  * anything to the client; we will likely violate the protocol, not to
2922  * mention that we may have interrupted the guts of OpenSSL or some
2923  * authentication library.
2924  */
2927 
2928  /*
2929  * Notify the client before exiting, to give a clue on what happened.
2930  *
2931  * It's dubious to call ereport() from a signal handler. It is certainly
2932  * not async-signal safe. But it seems better to try, than to disconnect
2933  * abruptly and leave the client wondering what happened. It's remotely
2934  * possible that we crash or hang while trying to send the message, but
2935  * receiving a SIGQUIT is a sign that something has already gone badly
2936  * wrong, so there's not much to lose. Assuming the postmaster is still
2937  * running, it will SIGKILL us soon if we get stuck for some reason.
2938  *
2939  * One thing we can do to make this a tad safer is to clear the error
2940  * context stack, so that context callbacks are not called. That's a lot
2941  * less code that could be reached here, and the context info is unlikely
2942  * to be very relevant to a SIGQUIT report anyway.
2943  */
2944  error_context_stack = NULL;
2945 
2946  /*
2947  * When responding to a postmaster-issued signal, we send the message only
2948  * to the client; sending to the server log just creates log spam, plus
2949  * it's more code that we need to hope will work in a signal handler.
2950  *
2951  * Ideally these should be ereport(FATAL), but then we'd not get control
2952  * back to force the correct type of process exit.
2953  */
2954  switch (GetQuitSignalReason())
2955  {
2956  case PMQUIT_NOT_SENT:
2957  /* Hmm, SIGQUIT arrived out of the blue */
2958  ereport(WARNING,
2959  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2960  errmsg("terminating connection because of unexpected SIGQUIT signal")));
2961  break;
2962  case PMQUIT_FOR_CRASH:
2963  /* A crash-and-restart cycle is in progress */
2965  (errcode(ERRCODE_CRASH_SHUTDOWN),
2966  errmsg("terminating connection because of crash of another server process"),
2967  errdetail("The postmaster has commanded this server process to roll back"
2968  " the current transaction and exit, because another"
2969  " server process exited abnormally and possibly corrupted"
2970  " shared memory."),
2971  errhint("In a moment you should be able to reconnect to the"
2972  " database and repeat your command.")));
2973  break;
2974  case PMQUIT_FOR_STOP:
2975  /* Immediate-mode stop */
2977  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2978  errmsg("terminating connection due to immediate shutdown command")));
2979  break;
2980  }
2981 
2982  /*
2983  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2984  * because shared memory may be corrupted, so we don't want to try to
2985  * clean up our transaction. Just nail the windows shut and get out of
2986  * town. The callbacks wouldn't be safe to run from a signal handler,
2987  * anyway.
2988  *
2989  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2990  * a system reset cycle if someone sends a manual SIGQUIT to a random
2991  * backend. This is necessary precisely because we don't clean up our
2992  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2993  * should ensure the postmaster sees this as a crash, too, but no harm in
2994  * being doubly sure.)
2995  */
2996  _exit(2);
2997 }
sigset_t BlockSig
Definition: pqsignal.c:23
#define WARNING_CLIENT_ONLY
Definition: elog.h:38
QuitSignalReason GetQuitSignalReason(void)
Definition: pmsignal.c:213
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
@ PMQUIT_NOT_SENT
Definition: pmsignal.h:52

References BlockSig, ClientAuthInProgress, DestNone, DestRemote, ereport, errcode(), errdetail(), errhint(), errmsg(), error_context_stack, GetQuitSignalReason(), HOLD_INTERRUPTS, PMQUIT_FOR_CRASH, PMQUIT_FOR_STOP, PMQUIT_NOT_SENT, SIGQUIT, WARNING, WARNING_CLIENT_ONLY, and whereToSendOutput.

Referenced by PostgresMain().

◆ ReadCommand()

static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 491 of file postgres.c.

492 {
493  int result;
494 
496  result = SocketBackend(inBuf);
497  else
498  result = InteractiveBackend(inBuf);
499  return result;
500 }
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:363
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:247

References DestRemote, InteractiveBackend(), SocketBackend(), and whereToSendOutput.

Referenced by PostgresMain().

◆ ResetUsage()

void ResetUsage ( void  )

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3546 of file postgres.c.

3547 {
3548  stack_base_ptr = base;
3549 }
static char * stack_base_ptr
Definition: postgres.c:134

References stack_base_ptr.

◆ set_debug_options()

void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3771 of file postgres.c.

3772 {
3773  if (debug_flag > 0)
3774  {
3775  char debugstr[64];
3776 
3777  sprintf(debugstr, "debug%d", debug_flag);
3778  SetConfigOption("log_min_messages", debugstr, context, source);
3779  }
3780  else
3781  SetConfigOption("log_min_messages", "notice", context, source);
3782 
3783  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3784  {
3785  SetConfigOption("log_connections", "true", context, source);
3786  SetConfigOption("log_disconnections", "true", context, source);
3787  }
3788  if (debug_flag >= 2)
3789  SetConfigOption("log_statement", "all", context, source);
3790  if (debug_flag >= 3)
3791  SetConfigOption("debug_print_parse", "true", context, source);
3792  if (debug_flag >= 4)
3793  SetConfigOption("debug_print_plan", "true", context, source);
3794  if (debug_flag >= 5)
3795  SetConfigOption("debug_print_rewritten", "true", context, source);
3796 }
static rewind_source * source
Definition: pg_rewind.c:89
#define sprintf
Definition: port.h:240
tree context
Definition: radixtree.h:1835

References context, PGC_POSTMASTER, SetConfigOption(), source, and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_plan_disabling_options()

bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3800 of file postgres.c.

3801 {
3802  const char *tmp = NULL;
3803 
3804  switch (arg[0])
3805  {
3806  case 's': /* seqscan */
3807  tmp = "enable_seqscan";
3808  break;
3809  case 'i': /* indexscan */
3810  tmp = "enable_indexscan";
3811  break;
3812  case 'o': /* indexonlyscan */
3813  tmp = "enable_indexonlyscan";
3814  break;
3815  case 'b': /* bitmapscan */
3816  tmp = "enable_bitmapscan";
3817  break;
3818  case 't': /* tidscan */
3819  tmp = "enable_tidscan";
3820  break;
3821  case 'n': /* nestloop */
3822  tmp = "enable_nestloop";
3823  break;
3824  case 'm': /* mergejoin */
3825  tmp = "enable_mergejoin";
3826  break;
3827  case 'h': /* hashjoin */
3828  tmp = "enable_hashjoin";
3829  break;
3830  }
3831  if (tmp)
3832  {
3833  SetConfigOption(tmp, "false", context, source);
3834  return true;
3835  }
3836  else
3837  return false;
3838 }

References arg, context, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )

Definition at line 3513 of file postgres.c.

3514 {
3515 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3516  char stack_base;
3517 #endif
3518  pg_stack_base_t old;
3519 
3520  old = stack_base_ptr;
3521 
3522  /*
3523  * Set up reference point for stack depth checking. On recent gcc we use
3524  * __builtin_frame_address() to avoid a warning about storing a local
3525  * variable's address in a long-lived variable.
3526  */
3527 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3528  stack_base_ptr = __builtin_frame_address(0);
3529 #else
3530  stack_base_ptr = &stack_base;
3531 #endif
3532 
3533  return old;
3534 }
char * pg_stack_base_t
Definition: miscadmin.h:293

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 5118 of file postgres.c.

5119 {
5121  struct timeval user,
5122  sys;
5123  struct timeval elapse_t;
5124  struct rusage r;
5125 
5126  getrusage(RUSAGE_SELF, &r);
5127  gettimeofday(&elapse_t, NULL);
5128  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
5129  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
5130  if (elapse_t.tv_usec < Save_t.tv_usec)
5131  {
5132  elapse_t.tv_sec--;
5133  elapse_t.tv_usec += 1000000;
5134  }
5135  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5136  {
5137  r.ru_utime.tv_sec--;
5138  r.ru_utime.tv_usec += 1000000;
5139  }
5140  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5141  {
5142  r.ru_stime.tv_sec--;
5143  r.ru_stime.tv_usec += 1000000;
5144  }
5145 
5146  /*
5147  * The only stats we don't show here are ixrss, idrss, isrss. It takes
5148  * some work to interpret them, and most platforms don't fill them in.
5149  */
5150  initStringInfo(&str);
5151 
5152  appendStringInfoString(&str, "! system usage stats:\n");
5154  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5155  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5156  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5157  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5158  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5159  (long) (elapse_t.tv_sec - Save_t.tv_sec),
5160  (long) (elapse_t.tv_usec - Save_t.tv_usec));
5162  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5163  (long) user.tv_sec,
5164  (long) user.tv_usec,
5165  (long) sys.tv_sec,
5166  (long) sys.tv_usec);
5167 #ifndef WIN32
5168 
5169  /*
5170  * The following rusage fields are not defined by POSIX, but they're
5171  * present on all current Unix-like systems so we use them without any
5172  * special checks. Some of these could be provided in our Windows
5173  * emulation in src/port/win32getrusage.c with more work.
5174  */
5176  "!\t%ld kB max resident size\n",
5177 #if defined(__darwin__)
5178  /* in bytes on macOS */
5179  r.ru_maxrss / 1024
5180 #else
5181  /* in kilobytes on most other platforms */
5182  r.ru_maxrss
5183 #endif
5184  );
5186  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5187  r.ru_inblock - Save_r.ru_inblock,
5188  /* they only drink coffee at dec */
5189  r.ru_oublock - Save_r.ru_oublock,
5190  r.ru_inblock, r.ru_oublock);
5192  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5193  r.ru_majflt - Save_r.ru_majflt,
5194  r.ru_minflt - Save_r.ru_minflt,
5195  r.ru_majflt, r.ru_minflt,
5196  r.ru_nswap - Save_r.ru_nswap,
5197  r.ru_nswap);
5199  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5200  r.ru_nsignals - Save_r.ru_nsignals,
5201  r.ru_nsignals,
5202  r.ru_msgrcv - Save_r.ru_msgrcv,
5203  r.ru_msgsnd - Save_r.ru_msgsnd,
5204  r.ru_msgrcv, r.ru_msgsnd);
5206  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5207  r.ru_nvcsw - Save_r.ru_nvcsw,
5208  r.ru_nivcsw - Save_r.ru_nivcsw,
5209  r.ru_nvcsw, r.ru_nivcsw);
5210 #endif /* !WIN32 */
5211 
5212  /* remove trailing newline */
5213  if (str.data[str.len - 1] == '\n')
5214  str.data[--str.len] = '\0';
5215 
5216  ereport(LOG,
5217  (errmsg_internal("%s", title),
5218  errdetail_internal("%s", str.data)));
5219 
5220  pfree(str.data);
5221 }
#define __darwin__
Definition: darwin.h:3
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
static char * user
Definition: pg_regress.c:119
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:94
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:179
struct timeval ru_utime
Definition: resource.h:14
struct timeval ru_stime
Definition: resource.h:15

References __darwin__, appendStringInfo(), appendStringInfoString(), ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), LOG, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, Save_t, str, and user.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

◆ SocketBackend()

static int SocketBackend ( StringInfo  inBuf)
static

Definition at line 363 of file postgres.c.

364 {
365  int qtype;
366  int maxmsglen;
367 
368  /*
369  * Get message type code from the frontend.
370  */
372  pq_startmsgread();
373  qtype = pq_getbyte();
374 
375  if (qtype == EOF) /* frontend disconnected */
376  {
377  if (IsTransactionState())
379  (errcode(ERRCODE_CONNECTION_FAILURE),
380  errmsg("unexpected EOF on client connection with an open transaction")));
381  else
382  {
383  /*
384  * Can't send DEBUG log messages to client at this point. Since
385  * we're disconnecting right away, we don't need to restore
386  * whereToSendOutput.
387  */
389  ereport(DEBUG1,
390  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
391  errmsg_internal("unexpected EOF on client connection")));
392  }
393  return qtype;
394  }
395 
396  /*
397  * Validate message type code before trying to read body; if we have lost
398  * sync, better to say "command unknown" than to run out of memory because
399  * we used garbage as a length word. We can also select a type-dependent
400  * limit on what a sane length word could be. (The limit could be chosen
401  * more granularly, but it's not clear it's worth fussing over.)
402  *
403  * This also gives us a place to set the doing_extended_query_message flag
404  * as soon as possible.
405  */
406  switch (qtype)
407  {
408  case PqMsg_Query:
409  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
411  break;
412 
413  case PqMsg_FunctionCall:
414  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
416  break;
417 
418  case PqMsg_Terminate:
419  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
421  ignore_till_sync = false;
422  break;
423 
424  case PqMsg_Bind:
425  case PqMsg_Parse:
426  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
428  break;
429 
430  case PqMsg_Close:
431  case PqMsg_Describe:
432  case PqMsg_Execute:
433  case PqMsg_Flush:
434  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
436  break;
437 
438  case PqMsg_Sync:
439  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
440  /* stop any active skip-till-Sync */
441  ignore_till_sync = false;
442  /* mark not-extended, so that a new error doesn't begin skip */
444  break;
445 
446  case PqMsg_CopyData:
447  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
449  break;
450 
451  case PqMsg_CopyDone:
452  case PqMsg_CopyFail:
453  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
455  break;
456 
457  default:
458 
459  /*
460  * Otherwise we got garbage from the frontend. We treat this as
461  * fatal because we have probably lost message boundary sync, and
462  * there's no good way to recover.
463  */
464  ereport(FATAL,
465  (errcode(ERRCODE_PROTOCOL_VIOLATION),
466  errmsg("invalid frontend message type %d", qtype)));
467  maxmsglen = 0; /* keep compiler quiet */
468  break;
469  }
470 
471  /*
472  * In protocol version 3, all frontend messages have a length word next
473  * after the type code; we can read the message contents independently of
474  * the type.
475  */
476  if (pq_getmessage(inBuf, maxmsglen))
477  return EOF; /* suitable message already logged */
479 
480  return qtype;
481 }
#define COMMERROR
Definition: elog.h:33
#define PQ_SMALL_MESSAGE_LIMIT
Definition: libpq.h:30
#define PQ_LARGE_MESSAGE_LIMIT
Definition: libpq.h:31
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:141
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:143
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1203
int pq_getbyte(void)
Definition: pqcomm.c:964
void pq_startmsgread(void)
Definition: pqcomm.c:1141

References COMMERROR, DEBUG1, DestNone, doing_extended_query_message, ereport, errcode(), errmsg(), errmsg_internal(), FATAL, HOLD_CANCEL_INTERRUPTS, ignore_till_sync, IsTransactionState(), pq_getbyte(), pq_getmessage(), PQ_LARGE_MESSAGE_LIMIT, PQ_SMALL_MESSAGE_LIMIT, pq_startmsgread(), PqMsg_Bind, PqMsg_Close, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Describe, PqMsg_Execute, PqMsg_Flush, PqMsg_FunctionCall, PqMsg_Parse, PqMsg_Query, PqMsg_Sync, PqMsg_Terminate, RESUME_CANCEL_INTERRUPTS, and whereToSendOutput.

Referenced by ReadCommand().

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )

Definition at line 3577 of file postgres.c.

3578 {
3579  char stack_top_loc;
3580  long stack_depth;
3581 
3582  /*
3583  * Compute distance from reference point to my local variables
3584  */
3585  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3586 
3587  /*
3588  * Take abs value, since stacks grow up on some machines, down on others
3589  */
3590  if (stack_depth < 0)
3591  stack_depth = -stack_depth;
3592 
3593  /*
3594  * Trouble?
3595  *
3596  * The test on stack_base_ptr prevents us from erroring out if called
3597  * during process setup or in a non-backend process. Logically it should
3598  * be done first, but putting it here avoids wasting cycles during normal
3599  * cases.
3600  */
3601  if (stack_depth > max_stack_depth_bytes &&
3602  stack_base_ptr != NULL)
3603  return true;
3604 
3605  return false;
3606 }

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), MemoryContextStatsInternal(), rstacktoodeep(), and ShowTransactionStateRec().

◆ start_xact_command()

static void start_xact_command ( void  )
static

Definition at line 2775 of file postgres.c.

2776 {
2777  if (!xact_started)
2778  {
2780 
2781  xact_started = true;
2782  }
2783 
2784  /*
2785  * Start statement timeout if necessary. Note that this'll intentionally
2786  * not reset the clock on an already started timeout, to avoid the timing
2787  * overhead when start_xact_command() is invoked repeatedly, without an
2788  * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2789  * not desired, the timeout has to be disabled explicitly.
2790  */
2792 
2793  /* Start timeout for checking if the client has gone away if necessary. */
2796  MyProcPort &&
2800 }
static void enable_statement_timeout(void)
Definition: postgres.c:5263
void StartTransactionCommand(void)
Definition: xact.c:3051

References client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, enable_statement_timeout(), enable_timeout_after(), get_timeout_active(), IsUnderPostmaster, MyProcPort, StartTransactionCommand(), and xact_started.

Referenced by exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and PostgresMain().

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 3034 of file postgres.c.

3035 {
3036  /*
3037  * Don't joggle the elbow of proc_exit
3038  */
3039  if (!proc_exit_inprogress)
3040  {
3041  InterruptPending = true;
3042  QueryCancelPending = true;
3043  }
3044 
3045  /* If we're still here, waken anything waiting on the process latch */
3046  SetLatch(MyLatch);
3047 }

References InterruptPending, MyLatch, proc_exit_inprogress, QueryCancelPending, and SetLatch().

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), PostgresMain(), and WalSndSignals().

Variable Documentation

◆ client_connection_check_interval

int client_connection_check_interval = 0

Definition at line 104 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ doing_extended_query_message

bool doing_extended_query_message = false
static

Definition at line 153 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ DoingCommandRead

bool DoingCommandRead = false
static

◆ EchoQuery

bool EchoQuery = false
static

Definition at line 165 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ ignore_till_sync

bool ignore_till_sync = false
static

Definition at line 154 of file postgres.c.

Referenced by PostgresMain(), and SocketBackend().

◆ Log_disconnections

bool Log_disconnections = false

Definition at line 93 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

int log_statement = LOGSTMT_NONE

Definition at line 95 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

int max_stack_depth = 100

Definition at line 98 of file postgres.c.

Referenced by check_stack_depth().

◆ max_stack_depth_bytes

long max_stack_depth_bytes = 100 * 1024L
static

Definition at line 128 of file postgres.c.

Referenced by assign_max_stack_depth(), and stack_is_too_deep().

◆ PostAuthDelay

int PostAuthDelay = 0

Definition at line 101 of file postgres.c.

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), and InitPostgres().

◆ RecoveryConflictPending

volatile sig_atomic_t RecoveryConflictPending = false
static

◆ RecoveryConflictPendingReasons

volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
static

◆ restrict_nonsystem_relation_kind

int restrict_nonsystem_relation_kind

◆ row_description_buf

StringInfoData row_description_buf
static

◆ row_description_context

MemoryContext row_description_context = NULL
static

Definition at line 173 of file postgres.c.

Referenced by PostgresMain().

◆ Save_r

struct rusage Save_r
static

Definition at line 5079 of file postgres.c.

Referenced by ResetUsage(), and ShowUsage().

◆ Save_t

struct timeval Save_t
static

Definition at line 5079 of file postgres.c.

Referenced by ResetUsage(), and ShowUsage().

◆ stack_base_ptr

char* stack_base_ptr = NULL
static

Definition at line 134 of file postgres.c.

Referenced by restore_stack_base(), set_stack_base(), and stack_is_too_deep().

◆ unnamed_stmt_psrc

CachedPlanSource* unnamed_stmt_psrc = NULL
static

◆ userDoption

const char* userDoption = NULL
static

◆ UseSemiNewlineNewline

bool UseSemiNewlineNewline = false
static

Definition at line 166 of file postgres.c.

Referenced by InteractiveBackend(), and process_postgres_switches().

◆ whereToSendOutput

◆ xact_started

bool xact_started = false
static