PostgreSQL Source Code  git master
postgres.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <sys/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/autovacuum.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "replication/slot.h"
#include "replication/walsender.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/sinval.h"
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/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 228 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 3604 of file postgres.c.

3605 {
3606  long newval_bytes = newval * 1024L;
3607 
3608  max_stack_depth_bytes = newval_bytes;
3609 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:129

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 3734 of file postgres.c.

3735 {
3736  int *flags = (int *) extra;
3737 
3739 }
int restrict_nonsystem_relation_kind
Definition: postgres.c:108

References restrict_nonsystem_relation_kind.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3665 of file postgres.c.

3666 {
3667  if (IsTransactionState())
3668  {
3669  /*
3670  * If transaction_timeout GUC has changed within the transaction block
3671  * enable or disable the timer correspondingly.
3672  */
3675  else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3677  }
3678 }
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 2558 of file postgres.c.

2559 {
2562  char *quotedval;
2563 
2564  if (data->paramno < 0)
2565  return;
2566 
2567  /* If we have a textual value, quote it, and trim if necessary */
2568  if (data->paramval)
2569  {
2570  initStringInfo(&buf);
2573  quotedval = buf.data;
2574  }
2575  else
2576  quotedval = NULL;
2577 
2578  if (data->portalName && data->portalName[0] != '\0')
2579  {
2580  if (quotedval)
2581  errcontext("portal \"%s\" parameter $%d = %s",
2582  data->portalName, data->paramno + 1, quotedval);
2583  else
2584  errcontext("portal \"%s\" parameter $%d",
2585  data->portalName, data->paramno + 1);
2586  }
2587  else
2588  {
2589  if (quotedval)
2590  errcontext("unnamed portal parameter $%d = %s",
2591  data->paramno + 1, quotedval);
2592  else
2593  errcontext("unnamed portal parameter $%d",
2594  data->paramno + 1);
2595  }
2596 
2597  if (quotedval)
2598  pfree(quotedval);
2599 }
#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:73
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
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 3615 of file postgres.c.

3616 {
3617  if (!WaitEventSetCanReportClosed() && *newval != 0)
3618  {
3619  GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3620  return false;
3621  }
3622  return true;
3623 }
#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 2389 of file postgres.c.

2390 {
2391  if (log_duration || log_min_duration_sample >= 0 ||
2393  {
2394  long secs;
2395  int usecs;
2396  int msecs;
2397  bool exceeded_duration;
2398  bool exceeded_sample_duration;
2399  bool in_sample = false;
2400 
2403  &secs, &usecs);
2404  msecs = usecs / 1000;
2405 
2406  /*
2407  * This odd-looking test for log_min_duration_* being exceeded is
2408  * designed to avoid integer overflow with very long durations: don't
2409  * compute secs * 1000 until we've verified it will fit in int.
2410  */
2411  exceeded_duration = (log_min_duration_statement == 0 ||
2413  (secs > log_min_duration_statement / 1000 ||
2414  secs * 1000 + msecs >= log_min_duration_statement)));
2415 
2416  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2417  (log_min_duration_sample > 0 &&
2418  (secs > log_min_duration_sample / 1000 ||
2419  secs * 1000 + msecs >= log_min_duration_sample)));
2420 
2421  /*
2422  * Do not log if log_statement_sample_rate = 0. Log a sample if
2423  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2424  * log_statement_sample_rate = 1.
2425  */
2426  if (exceeded_sample_duration)
2427  in_sample = log_statement_sample_rate != 0 &&
2428  (log_statement_sample_rate == 1 ||
2430 
2431  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2432  {
2433  snprintf(msec_str, 32, "%ld.%03d",
2434  secs * 1000 + msecs, usecs % 1000);
2435  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2436  return 2;
2437  else
2438  return 1;
2439  }
2440  }
2441 
2442  return 0;
2443 }
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 2350 of file postgres.c.

2351 {
2352  ListCell *stmt_item;
2353 
2354  if (log_statement == LOGSTMT_NONE)
2355  return false;
2356  if (log_statement == LOGSTMT_ALL)
2357  return true;
2358 
2359  /* Else we have to inspect the statement(s) to see whether to log */
2360  foreach(stmt_item, stmt_list)
2361  {
2362  Node *stmt = (Node *) lfirst(stmt_item);
2363 
2365  return true;
2366  }
2367 
2368  return false;
2369 }
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:96
Definition: nodes.h:129
@ LOGSTMT_NONE
Definition: tcopprot.h:37
@ LOGSTMT_ALL
Definition: tcopprot.h:40
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3246

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 3650 of file postgres.c.

3651 {
3652  if (*newval &&
3654  {
3655  GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3656  "\"log_parser_stats\", \"log_planner_stats\", "
3657  "or \"log_executor_stats\" is true.");
3658  return false;
3659  }
3660  return true;
3661 }
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 3587 of file postgres.c.

3588 {
3589  long newval_bytes = *newval * 1024L;
3590  long stack_rlimit = get_stack_depth_rlimit();
3591 
3592  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3593  {
3594  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3595  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3596  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3597  return false;
3598  }
3599  return true;
3600 }
#define GUC_check_errhint
Definition: guc.h:480
long get_stack_depth_rlimit(void)
Definition: postgres.c:5047
#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 3684 of file postgres.c.

3685 {
3686  char *rawstring;
3687  List *elemlist;
3688  ListCell *l;
3689  int flags = 0;
3690 
3691  /* Need a modifiable copy of string */
3692  rawstring = pstrdup(*newval);
3693 
3694  if (!SplitIdentifierString(rawstring, ',', &elemlist))
3695  {
3696  /* syntax error in list */
3697  GUC_check_errdetail("List syntax is invalid.");
3698  pfree(rawstring);
3699  list_free(elemlist);
3700  return false;
3701  }
3702 
3703  foreach(l, elemlist)
3704  {
3705  char *tok = (char *) lfirst(l);
3706 
3707  if (pg_strcasecmp(tok, "view") == 0)
3708  flags |= RESTRICT_RELKIND_VIEW;
3709  else if (pg_strcasecmp(tok, "foreign-table") == 0)
3711  else
3712  {
3713  GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3714  pfree(rawstring);
3715  list_free(elemlist);
3716  return false;
3717  }
3718  }
3719 
3720  pfree(rawstring);
3721  list_free(elemlist);
3722 
3723  /* Save the flags in *extra, for use by the assign function */
3724  *extra = guc_malloc(ERROR, sizeof(int));
3725  *((int *) *extra) = flags;
3726 
3727  return true;
3728 }
#define ERROR
Definition: elog.h:39
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:637
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:3437

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 3540 of file postgres.c.

3541 {
3542  if (stack_is_too_deep())
3543  {
3544  ereport(ERROR,
3545  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3546  errmsg("stack depth limit exceeded"),
3547  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3548  "after ensuring the platform's stack depth limit is adequate.",
3549  max_stack_depth)));
3550  }
3551 }
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:99
bool stack_is_too_deep(void)
Definition: postgres.c:3554

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

Referenced by _jumbleNode(), AlterTypeRecurse(), apply_scanjoin_target_to_paths(), ATExecAddColumn(), ATExecAlterConstrRecurse(), ATExecDropColumn(), 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(), 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 3636 of file postgres.c.

3637 {
3638  if (*newval && log_statement_stats)
3639  {
3640  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3641  return false;
3642  }
3643  return true;
3644 }
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 2981 of file postgres.c.

2982 {
2983  /* Don't joggle the elbow of proc_exit */
2984  if (!proc_exit_inprogress)
2985  {
2986  InterruptPending = true;
2987  ProcDiePending = true;
2988  }
2989 
2990  /* for the cumulative stats system */
2992 
2993  /* If we're still here, waken anything waiting on the process latch */
2994  SetLatch(MyLatch);
2995 
2996  /*
2997  * If we're in single user mode, we want to quit immediately - we can't
2998  * rely on latches as they wouldn't work when stdin/stdout is a file.
2999  * Rather ugly, but it's unlikely to be worthwhile to invest much more
3000  * effort just for the benefit of single user mode.
3001  */
3004 }
@ 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:91
static bool DoingCommandRead
Definition: postgres.c:148
void ProcessInterrupts(void)
Definition: postgres.c:3253

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 5253 of file postgres.c.

5254 {
5257 }
@ 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 2859 of file postgres.c.

2860 {
2861  /* paranoia to avoid a dangling pointer in case of error */
2862  if (unnamed_stmt_psrc)
2863  {
2865 
2866  unnamed_stmt_psrc = NULL;
2867  DropCachedPlan(psrc);
2868  }
2869 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:526
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:162

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 5231 of file postgres.c.

5232 {
5233  /* must be within an xact */
5235 
5236  if (StatementTimeout > 0
5238  {
5241  }
5242  else
5243  {
5246  }
5247 }
#define Assert(condition)
Definition: c.h:858
static bool xact_started
Definition: postgres.c:141
int StatementTimeout
Definition: proc.c:59
int TransactionTimeout
Definition: proc.c:62

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 2505 of file postgres.c.

2506 {
2508  errdetail("Abort reason: recovery conflict");
2509 
2510  return 0;
2511 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
PGPROC * MyProc
Definition: proc.c:67
bool recoveryConflictPending
Definition: proc.h:215

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 2452 of file postgres.c.

2453 {
2454  ListCell *parsetree_item;
2455 
2456  foreach(parsetree_item, raw_parsetree_list)
2457  {
2458  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2459 
2460  if (IsA(parsetree->stmt, ExecuteStmt))
2461  {
2462  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2463  PreparedStatement *pstmt;
2464 
2465  pstmt = FetchPreparedStatement(stmt->name, false);
2466  if (pstmt)
2467  {
2468  errdetail("prepare: %s", pstmt->plansource->query_string);
2469  return 0;
2470  }
2471  }
2472  }
2473 
2474  return 0;
2475 }
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:2012

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 2485 of file postgres.c.

2486 {
2487  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2488  {
2489  char *str;
2490 
2492  if (str && str[0] != '\0')
2493  errdetail("Parameters: %s", str);
2494  }
2495 
2496  return 0;
2497 }
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 2519 of file postgres.c.

2520 {
2521  switch (reason)
2522  {
2524  errdetail("User was holding shared buffer pin for too long.");
2525  break;
2527  errdetail("User was holding a relation lock for too long.");
2528  break;
2530  errdetail("User was or might have been using tablespace that must be dropped.");
2531  break;
2533  errdetail("User query might have needed to see row versions that must be removed.");
2534  break;
2536  errdetail("User was using a logical replication slot that must be invalidated.");
2537  break;
2539  errdetail("User transaction caused buffer deadlock with recovery.");
2540  break;
2542  errdetail("User was connected to a database that must be dropped.");
2543  break;
2544  default:
2545  break;
2546  /* no errdetail */
2547  }
2548 
2549  return 0;
2550 }
@ 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 1636 of file postgres.c.

1637 {
1638  const char *portal_name;
1639  const char *stmt_name;
1640  int numPFormats;
1641  int16 *pformats = NULL;
1642  int numParams;
1643  int numRFormats;
1644  int16 *rformats = NULL;
1645  CachedPlanSource *psrc;
1646  CachedPlan *cplan;
1647  Portal portal;
1648  char *query_string;
1649  char *saved_stmt_name;
1650  ParamListInfo params;
1651  MemoryContext oldContext;
1652  bool save_log_statement_stats = log_statement_stats;
1653  bool snapshot_set = false;
1654  char msec_str[32];
1655  ParamsErrorCbData params_data;
1656  ErrorContextCallback params_errcxt;
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  set_ps_display("BIND");
1693 
1694  if (save_log_statement_stats)
1695  ResetUsage();
1696 
1697  /*
1698  * Start up a transaction command so we can call functions etc. (Note that
1699  * this will normally change current memory context.) Nothing happens if
1700  * we are already in one. This also arms the statement timeout if
1701  * necessary.
1702  */
1704 
1705  /* Switch back to message context */
1707 
1708  /* Get the parameter format codes */
1709  numPFormats = pq_getmsgint(input_message, 2);
1710  if (numPFormats > 0)
1711  {
1712  pformats = palloc_array(int16, numPFormats);
1713  for (int i = 0; i < numPFormats; i++)
1714  pformats[i] = pq_getmsgint(input_message, 2);
1715  }
1716 
1717  /* Get the parameter value count */
1718  numParams = pq_getmsgint(input_message, 2);
1719 
1720  if (numPFormats > 1 && numPFormats != numParams)
1721  ereport(ERROR,
1722  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1723  errmsg("bind message has %d parameter formats but %d parameters",
1724  numPFormats, numParams)));
1725 
1726  if (numParams != psrc->num_params)
1727  ereport(ERROR,
1728  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1729  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1730  numParams, stmt_name, psrc->num_params)));
1731 
1732  /*
1733  * If we are in aborted transaction state, the only portals we can
1734  * actually run are those containing COMMIT or ROLLBACK commands. We
1735  * disallow binding anything else to avoid problems with infrastructure
1736  * that expects to run inside a valid transaction. We also disallow
1737  * binding any parameters, since we can't risk calling user-defined I/O
1738  * functions.
1739  */
1741  (!(psrc->raw_parse_tree &&
1743  numParams != 0))
1744  ereport(ERROR,
1745  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1746  errmsg("current transaction is aborted, "
1747  "commands ignored until end of transaction block"),
1748  errdetail_abort()));
1749 
1750  /*
1751  * Create the portal. Allow silent replacement of an existing portal only
1752  * if the unnamed portal is specified.
1753  */
1754  if (portal_name[0] == '\0')
1755  portal = CreatePortal(portal_name, true, true);
1756  else
1757  portal = CreatePortal(portal_name, false, false);
1758 
1759  /*
1760  * Prepare to copy stuff into the portal's memory context. We do all this
1761  * copying first, because it could possibly fail (out-of-memory) and we
1762  * don't want a failure to occur between GetCachedPlan and
1763  * PortalDefineQuery; that would result in leaking our plancache refcount.
1764  */
1765  oldContext = MemoryContextSwitchTo(portal->portalContext);
1766 
1767  /* Copy the plan's query string into the portal */
1768  query_string = pstrdup(psrc->query_string);
1769 
1770  /* Likewise make a copy of the statement name, unless it's unnamed */
1771  if (stmt_name[0])
1772  saved_stmt_name = pstrdup(stmt_name);
1773  else
1774  saved_stmt_name = NULL;
1775 
1776  /*
1777  * Set a snapshot if we have parameters to fetch (since the input
1778  * functions might need it) or the query isn't a utility command (and
1779  * hence could require redoing parse analysis and planning). We keep the
1780  * snapshot active till we're done, so that plancache.c doesn't have to
1781  * take new ones.
1782  */
1783  if (numParams > 0 ||
1784  (psrc->raw_parse_tree &&
1786  {
1788  snapshot_set = true;
1789  }
1790 
1791  /*
1792  * Fetch parameters, if any, and store in the portal's memory context.
1793  */
1794  if (numParams > 0)
1795  {
1796  char **knownTextValues = NULL; /* allocate on first use */
1797  BindParamCbData one_param_data;
1798 
1799  /*
1800  * Set up an error callback so that if there's an error in this phase,
1801  * we can report the specific parameter causing the problem.
1802  */
1803  one_param_data.portalName = portal->name;
1804  one_param_data.paramno = -1;
1805  one_param_data.paramval = NULL;
1806  params_errcxt.previous = error_context_stack;
1807  params_errcxt.callback = bind_param_error_callback;
1808  params_errcxt.arg = (void *) &one_param_data;
1809  error_context_stack = &params_errcxt;
1810 
1811  params = makeParamList(numParams);
1812 
1813  for (int paramno = 0; paramno < numParams; paramno++)
1814  {
1815  Oid ptype = psrc->param_types[paramno];
1816  int32 plength;
1817  Datum pval;
1818  bool isNull;
1819  StringInfoData pbuf;
1820  char csave;
1821  int16 pformat;
1822 
1823  one_param_data.paramno = paramno;
1824  one_param_data.paramval = NULL;
1825 
1826  plength = pq_getmsgint(input_message, 4);
1827  isNull = (plength == -1);
1828 
1829  if (!isNull)
1830  {
1831  char *pvalue;
1832 
1833  /*
1834  * Rather than copying data around, we just initialize a
1835  * StringInfo pointing to the correct portion of the message
1836  * buffer. We assume we can scribble on the message buffer to
1837  * add a trailing NUL which is required for the input function
1838  * call.
1839  */
1840  pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
1841  csave = pvalue[plength];
1842  pvalue[plength] = '\0';
1843  initReadOnlyStringInfo(&pbuf, pvalue, plength);
1844  }
1845  else
1846  {
1847  pbuf.data = NULL; /* keep compiler quiet */
1848  csave = 0;
1849  }
1850 
1851  if (numPFormats > 1)
1852  pformat = pformats[paramno];
1853  else if (numPFormats > 0)
1854  pformat = pformats[0];
1855  else
1856  pformat = 0; /* default = text */
1857 
1858  if (pformat == 0) /* text mode */
1859  {
1860  Oid typinput;
1861  Oid typioparam;
1862  char *pstring;
1863 
1864  getTypeInputInfo(ptype, &typinput, &typioparam);
1865 
1866  /*
1867  * We have to do encoding conversion before calling the
1868  * typinput routine.
1869  */
1870  if (isNull)
1871  pstring = NULL;
1872  else
1873  pstring = pg_client_to_server(pbuf.data, plength);
1874 
1875  /* Now we can log the input string in case of error */
1876  one_param_data.paramval = pstring;
1877 
1878  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1879 
1880  one_param_data.paramval = NULL;
1881 
1882  /*
1883  * If we might need to log parameters later, save a copy of
1884  * the converted string in MessageContext; then free the
1885  * result of encoding conversion, if any was done.
1886  */
1887  if (pstring)
1888  {
1890  {
1891  MemoryContext oldcxt;
1892 
1894 
1895  if (knownTextValues == NULL)
1896  knownTextValues = palloc0_array(char *, numParams);
1897 
1899  knownTextValues[paramno] = pstrdup(pstring);
1900  else
1901  {
1902  /*
1903  * We can trim the saved string, knowing that we
1904  * won't print all of it. But we must copy at
1905  * least two more full characters than
1906  * BuildParamLogString wants to use; otherwise it
1907  * might fail to include the trailing ellipsis.
1908  */
1909  knownTextValues[paramno] =
1910  pnstrdup(pstring,
1912  + 2 * MAX_MULTIBYTE_CHAR_LEN);
1913  }
1914 
1915  MemoryContextSwitchTo(oldcxt);
1916  }
1917  if (pstring != pbuf.data)
1918  pfree(pstring);
1919  }
1920  }
1921  else if (pformat == 1) /* binary mode */
1922  {
1923  Oid typreceive;
1924  Oid typioparam;
1925  StringInfo bufptr;
1926 
1927  /*
1928  * Call the parameter type's binary input converter
1929  */
1930  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1931 
1932  if (isNull)
1933  bufptr = NULL;
1934  else
1935  bufptr = &pbuf;
1936 
1937  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1938 
1939  /* Trouble if it didn't eat the whole buffer */
1940  if (!isNull && pbuf.cursor != pbuf.len)
1941  ereport(ERROR,
1942  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1943  errmsg("incorrect binary data format in bind parameter %d",
1944  paramno + 1)));
1945  }
1946  else
1947  {
1948  ereport(ERROR,
1949  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1950  errmsg("unsupported format code: %d",
1951  pformat)));
1952  pval = 0; /* keep compiler quiet */
1953  }
1954 
1955  /* Restore message buffer contents */
1956  if (!isNull)
1957  pbuf.data[plength] = csave;
1958 
1959  params->params[paramno].value = pval;
1960  params->params[paramno].isnull = isNull;
1961 
1962  /*
1963  * We mark the params as CONST. This ensures that any custom plan
1964  * makes full use of the parameter values.
1965  */
1966  params->params[paramno].pflags = PARAM_FLAG_CONST;
1967  params->params[paramno].ptype = ptype;
1968  }
1969 
1970  /* Pop the per-parameter error callback */
1972 
1973  /*
1974  * Once all parameters have been received, prepare for printing them
1975  * in future errors, if configured to do so. (This is saved in the
1976  * portal, so that they'll appear when the query is executed later.)
1977  */
1979  params->paramValuesStr =
1980  BuildParamLogString(params,
1981  knownTextValues,
1983  }
1984  else
1985  params = NULL;
1986 
1987  /* Done storing stuff in portal's context */
1988  MemoryContextSwitchTo(oldContext);
1989 
1990  /*
1991  * Set up another error callback so that all the parameters are logged if
1992  * we get an error during the rest of the BIND processing.
1993  */
1994  params_data.portalName = portal->name;
1995  params_data.params = params;
1996  params_errcxt.previous = error_context_stack;
1997  params_errcxt.callback = ParamsErrorCallback;
1998  params_errcxt.arg = (void *) &params_data;
1999  error_context_stack = &params_errcxt;
2000 
2001  /* Get the result format codes */
2002  numRFormats = pq_getmsgint(input_message, 2);
2003  if (numRFormats > 0)
2004  {
2005  rformats = palloc_array(int16, numRFormats);
2006  for (int i = 0; i < numRFormats; i++)
2007  rformats[i] = pq_getmsgint(input_message, 2);
2008  }
2009 
2010  pq_getmsgend(input_message);
2011 
2012  /*
2013  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2014  * will be generated in MessageContext. The plan refcount will be
2015  * assigned to the Portal, so it will be released at portal destruction.
2016  */
2017  cplan = GetCachedPlan(psrc, params, NULL, NULL);
2018 
2019  /*
2020  * Now we can define the portal.
2021  *
2022  * DO NOT put any code that could possibly throw an error between the
2023  * above GetCachedPlan call and here.
2024  */
2025  PortalDefineQuery(portal,
2026  saved_stmt_name,
2027  query_string,
2028  psrc->commandTag,
2029  cplan->stmt_list,
2030  cplan);
2031 
2032  /* Done with the snapshot used for parameter I/O and parsing/planning */
2033  if (snapshot_set)
2035 
2036  /*
2037  * And we're ready to start portal execution.
2038  */
2039  PortalStart(portal, params, 0, InvalidSnapshot);
2040 
2041  /*
2042  * Apply the result format requests to the portal.
2043  */
2044  PortalSetResultFormat(portal, numRFormats, rformats);
2045 
2046  /*
2047  * Done binding; remove the parameters error callback. Entries emitted
2048  * later determine independently whether to log the parameters or not.
2049  */
2051 
2052  /*
2053  * Send BindComplete.
2054  */
2057 
2058  /*
2059  * Emit duration logging if appropriate.
2060  */
2061  switch (check_log_duration(msec_str, false))
2062  {
2063  case 1:
2064  ereport(LOG,
2065  (errmsg("duration: %s ms", msec_str),
2066  errhidestmt(true)));
2067  break;
2068  case 2:
2069  ereport(LOG,
2070  (errmsg("duration: %s ms bind %s%s%s: %s",
2071  msec_str,
2072  *stmt_name ? stmt_name : "<unnamed>",
2073  *portal_name ? "/" : "",
2074  *portal_name ? portal_name : "",
2075  psrc->query_string),
2076  errhidestmt(true),
2077  errdetail_params(params)));
2078  break;
2079  }
2080 
2081  if (save_log_statement_stats)
2082  ShowUsage("BIND MESSAGE STATISTICS");
2083 
2085 
2086  debug_query_string = NULL;
2087 }
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
#define unconstify(underlying_type, expr)
Definition: c.h:1245
signed short int16
Definition: c.h:493
signed int int32
Definition: c.h:494
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:64
#define palloc0_array(type, count)
Definition: fe_memutils.h:65
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:73
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:491
#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:2505
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2389
const char * debug_query_string
Definition: postgres.c:88
void ShowUsage(const char *title)
Definition: postgres.c:5086
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2485
static void bind_param_error_callback(void *arg)
Definition: postgres.c:2558
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2812
void ResetUsage(void)
Definition: postgres.c:5079
static void start_xact_command(void)
Definition: postgres.c:2752
#define valgrind_report_error_query(query)
Definition: postgres.c:228
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:118
const char * paramval
Definition: postgres.c:120
CommandTag commandTag
Definition: plancache.h:101
const char * query_string
Definition: plancache.h:100
struct RawStmt * raw_parse_tree
Definition: plancache.h:99
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, 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(), 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_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 2700 of file postgres.c.

2701 {
2702  Portal portal;
2703 
2704  /*
2705  * Start up a transaction command. (Note that this will normally change
2706  * current memory context.) Nothing happens if we are already in one.
2707  */
2709 
2710  /* Switch back to message context */
2712 
2713  portal = GetPortalByName(portal_name);
2714  if (!PortalIsValid(portal))
2715  ereport(ERROR,
2716  (errcode(ERRCODE_UNDEFINED_CURSOR),
2717  errmsg("portal \"%s\" does not exist", portal_name)));
2718 
2719  /*
2720  * If we are in aborted transaction state, we can't run
2721  * SendRowDescriptionMessage(), because that needs catalog accesses.
2722  * Hence, refuse to Describe portals that return data. (We shouldn't just
2723  * refuse all Describes, since that might break the ability of some
2724  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2725  * blindly Describes whatever it does.)
2726  */
2728  portal->tupDesc)
2729  ereport(ERROR,
2730  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2731  errmsg("current transaction is aborted, "
2732  "commands ignored until end of transaction block"),
2733  errdetail_abort()));
2734 
2736  return; /* can't actually do anything... */
2737 
2738  if (portal->tupDesc)
2740  portal->tupDesc,
2741  FetchPortalTargetList(portal),
2742  portal->formats);
2743  else
2745 }
#define PortalIsValid(p)
Definition: portal.h:212
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
static StringInfoData row_description_buf
Definition: postgres.c:175
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 2607 of file postgres.c.

2608 {
2609  CachedPlanSource *psrc;
2610 
2611  /*
2612  * Start up a transaction command. (Note that this will normally change
2613  * current memory context.) Nothing happens if we are already in one.
2614  */
2616 
2617  /* Switch back to message context */
2619 
2620  /* Find prepared statement */
2621  if (stmt_name[0] != '\0')
2622  {
2623  PreparedStatement *pstmt;
2624 
2625  pstmt = FetchPreparedStatement(stmt_name, true);
2626  psrc = pstmt->plansource;
2627  }
2628  else
2629  {
2630  /* special-case the unnamed statement */
2631  psrc = unnamed_stmt_psrc;
2632  if (!psrc)
2633  ereport(ERROR,
2634  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2635  errmsg("unnamed prepared statement does not exist")));
2636  }
2637 
2638  /* Prepared statements shouldn't have changeable result descs */
2639  Assert(psrc->fixed_result);
2640 
2641  /*
2642  * If we are in aborted transaction state, we can't run
2643  * SendRowDescriptionMessage(), because that needs catalog accesses.
2644  * Hence, refuse to Describe statements that return data. (We shouldn't
2645  * just refuse all Describes, since that might break the ability of some
2646  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2647  * blindly Describes whatever it does.) We can Describe parameters
2648  * without doing anything dangerous, so we don't restrict that.
2649  */
2651  psrc->resultDesc)
2652  ereport(ERROR,
2653  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2654  errmsg("current transaction is aborted, "
2655  "commands ignored until end of transaction block"),
2656  errdetail_abort()));
2657 
2659  return; /* can't actually do anything... */
2660 
2661  /*
2662  * First describe the parameters...
2663  */
2666 
2667  for (int i = 0; i < psrc->num_params; i++)
2668  {
2669  Oid ptype = psrc->param_types[i];
2670 
2671  pq_sendint32(&row_description_buf, (int) ptype);
2672  }
2674 
2675  /*
2676  * Next send RowDescription or NoData to describe the result...
2677  */
2678  if (psrc->resultDesc)
2679  {
2680  List *tlist;
2681 
2682  /* Get the plan's primary targetlist */
2683  tlist = CachedPlanGetTargetList(psrc, NULL);
2684 
2686  psrc->resultDesc,
2687  tlist,
2688  NULL);
2689  }
2690  else
2692 }
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 2095 of file postgres.c.

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

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

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 1023 of file postgres.c.

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

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 2780 of file postgres.c.

2781 {
2782  /* cancel active statement timeout after each command */
2784 
2785  if (xact_started)
2786  {
2788 
2789 #ifdef MEMORY_CONTEXT_CHECKING
2790  /* Check all memory contexts that weren't freed during commit */
2791  /* (those that were, were checked before being deleted) */
2792  MemoryContextCheck(TopMemoryContext);
2793 #endif
2794 
2795 #ifdef SHOW_MEMORY_STATS
2796  /* Print mem stats after each commit for leak tracking */
2798 #endif
2799 
2800  xact_started = false;
2801  }
2802 }
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:814
void CommitTransactionCommand(void)
Definition: xact.c:3137

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 3028 of file postgres.c.

3029 {
3030  /* We're not returning, so no need to save errno */
3031  ereport(ERROR,
3032  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3033  errmsg("floating-point exception"),
3034  errdetail("An invalid floating-point operation was signaled. "
3035  "This probably means an out-of-range result or an "
3036  "invalid operation, such as division by zero.")));
3037 }

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 5025 of file postgres.c.

5026 {
5027  if (am_walsender)
5028  {
5029  if (firstchar == PqMsg_FunctionCall)
5030  ereport(ERROR,
5031  (errcode(ERRCODE_PROTOCOL_VIOLATION),
5032  errmsg("fastpath function calls not supported in a replication connection")));
5033  else
5034  ereport(ERROR,
5035  (errcode(ERRCODE_PROTOCOL_VIOLATION),
5036  errmsg("extended query protocol not supported in a replication connection")));
5037  }
5038 }
#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 5047 of file postgres.c.

5048 {
5049 #if defined(HAVE_GETRLIMIT)
5050  static long val = 0;
5051 
5052  /* This won't change after process launch, so check just once */
5053  if (val == 0)
5054  {
5055  struct rlimit rlim;
5056 
5057  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
5058  val = -1;
5059  else if (rlim.rlim_cur == RLIM_INFINITY)
5060  val = LONG_MAX;
5061  /* rlim_cur is probably of an unsigned type, so check for overflow */
5062  else if (rlim.rlim_cur >= LONG_MAX)
5063  val = LONG_MAX;
5064  else
5065  val = rlim.rlim_cur;
5066  }
5067  return val;
5068 #else
5069  /* On Windows we set the backend stack size in src/backend/Makefile */
5070  return WIN32_STACK_RLIMIT;
5071 #endif
5072 }
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 3819 of file postgres.c.

3820 {
3821  switch (arg[0])
3822  {
3823  case 'p':
3824  if (optarg[1] == 'a') /* "parser" */
3825  return "log_parser_stats";
3826  else if (optarg[1] == 'l') /* "planner" */
3827  return "log_planner_stats";
3828  break;
3829 
3830  case 'e': /* "executor" */
3831  return "log_executor_stats";
3832  break;
3833  }
3834 
3835  return NULL;
3836 }
PGDLLIMPORT char * optarg
Definition: getopt.c:52

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3044 of file postgres.c.

3045 {
3046  RecoveryConflictPendingReasons[reason] = true;
3047  RecoveryConflictPending = true;
3048  InterruptPending = true;
3049  /* latch will be set by procsignal_sigusr1_handler */
3050 }
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:171
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:170

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 336 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 248 of file postgres.c.

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

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 2812 of file postgres.c.

2813 {
2814  if (parsetree && IsA(parsetree, TransactionStmt))
2815  {
2816  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2817 
2818  if (stmt->kind == TRANS_STMT_COMMIT ||
2819  stmt->kind == TRANS_STMT_PREPARE ||
2820  stmt->kind == TRANS_STMT_ROLLBACK ||
2821  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2822  return true;
2823  }
2824  return false;
2825 }
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3651
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3648
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3647
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3652

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 2829 of file postgres.c.

2830 {
2831  if (list_length(pstmts) == 1)
2832  {
2833  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2834 
2835  if (pstmt->commandType == CMD_UTILITY &&
2837  return true;
2838  }
2839  return false;
2840 }
@ 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 2844 of file postgres.c.

2845 {
2846  if (list_length(pstmts) == 1)
2847  {
2848  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2849 
2850  if (pstmt->commandType == CMD_UTILITY &&
2851  IsA(pstmt->utilityStmt, TransactionStmt))
2852  return true;
2853  }
2854  return false;
2855 }

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 5195 of file postgres.c.

5196 {
5197  Port *port = MyProcPort;
5198  long secs;
5199  int usecs;
5200  int msecs;
5201  int hours,
5202  minutes,
5203  seconds;
5204 
5207  &secs, &usecs);
5208  msecs = usecs / 1000;
5209 
5210  hours = secs / SECS_PER_HOUR;
5211  secs %= SECS_PER_HOUR;
5212  minutes = secs / SECS_PER_MINUTE;
5213  seconds = secs % SECS_PER_MINUTE;
5214 
5215  ereport(LOG,
5216  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5217  "user=%s database=%s host=%s%s%s",
5218  hours, minutes, seconds, msecs,
5219  port->user_name, port->database_name, port->remote_host,
5220  port->remote_port[0] ? " port=" : "", port->remote_port)));
5221 }
#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:116
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 677 of file postgres.c.

682 {
683  Query *query;
684  List *querytree_list;
685 
686  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
687 
688  /*
689  * (1) Perform parse analysis.
690  */
691  if (log_parser_stats)
692  ResetUsage();
693 
694  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
695  queryEnv);
696 
697  if (log_parser_stats)
698  ShowUsage("PARSE ANALYSIS STATISTICS");
699 
700  /*
701  * (2) Rewrite the queries, as necessary
702  */
703  querytree_list = pg_rewrite_query(query);
704 
705  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
706 
707  return querytree_list;
708 }
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:810

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 716 of file postgres.c.

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

775 {
776  Query *query;
777  List *querytree_list;
778 
779  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
780 
781  /*
782  * (1) Perform parse analysis.
783  */
784  if (log_parser_stats)
785  ResetUsage();
786 
787  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
788  queryEnv);
789 
790  if (log_parser_stats)
791  ShowUsage("PARSE ANALYSIS STATISTICS");
792 
793  /*
794  * (2) Rewrite the queries, as necessary
795  */
796  querytree_list = pg_rewrite_query(query);
797 
798  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
799 
800  return querytree_list;
801 }
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 615 of file postgres.c.

616 {
617  List *raw_parsetree_list;
618 
619  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
620 
621  if (log_parser_stats)
622  ResetUsage();
623 
624  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
625 
626  if (log_parser_stats)
627  ShowUsage("PARSER STATISTICS");
628 
629 #ifdef DEBUG_NODE_TESTS_ENABLED
630 
631  /* Optional debugging check: pass raw parsetrees through copyObject() */
632  if (Debug_copy_parse_plan_trees)
633  {
634  List *new_list = copyObject(raw_parsetree_list);
635 
636  /* This checks both copyObject() and the equal() routines... */
637  if (!equal(new_list, raw_parsetree_list))
638  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
639  else
640  raw_parsetree_list = new_list;
641  }
642 
643  /*
644  * Optional debugging check: pass raw parsetrees through
645  * outfuncs/readfuncs
646  */
647  if (Debug_write_read_parse_plan_trees)
648  {
649  char *str = nodeToStringWithLocations(raw_parsetree_list);
650  List *new_list = stringToNodeWithLocations(str);
651 
652  pfree(str);
653  /* This checks both outfuncs/readfuncs and the equal() routines... */
654  if (!equal(new_list, raw_parsetree_list))
655  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
656  else
657  raw_parsetree_list = new_list;
658  }
659 
660 #endif /* DEBUG_NODE_TESTS_ENABLED */
661 
662  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
663 
664  return raw_parsetree_list;
665 }
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:797
@ 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 982 of file postgres.c.

984 {
985  List *stmt_list = NIL;
986  ListCell *query_list;
987 
988  foreach(query_list, querytrees)
989  {
990  Query *query = lfirst_node(Query, query_list);
991  PlannedStmt *stmt;
992 
993  if (query->commandType == CMD_UTILITY)
994  {
995  /* Utility commands require no planning. */
997  stmt->commandType = CMD_UTILITY;
998  stmt->canSetTag = query->canSetTag;
999  stmt->utilityStmt = query->utilityStmt;
1000  stmt->stmt_location = query->stmt_location;
1001  stmt->stmt_len = query->stmt_len;
1002  stmt->queryId = query->queryId;
1003  }
1004  else
1005  {
1006  stmt = pg_plan_query(query, query_string, cursorOptions,
1007  boundParams);
1008  }
1009 
1010  stmt_list = lappend(stmt_list, stmt);
1011  }
1012 
1013  return stmt_list;
1014 }
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:894
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
ParseLoc stmt_location
Definition: parsenodes.h:238

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 894 of file postgres.c.

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

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

4222 {
4223  sigjmp_buf local_sigjmp_buf;
4224 
4225  /* these must be volatile to ensure state is preserved across longjmp: */
4226  volatile bool send_ready_for_query = true;
4227  volatile bool idle_in_transaction_timeout_enabled = false;
4228  volatile bool idle_session_timeout_enabled = false;
4229 
4230  Assert(dbname != NULL);
4231  Assert(username != NULL);
4232 
4234 
4235  /*
4236  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4237  * has already set up BlockSig and made that the active signal mask.)
4238  *
4239  * Note that postmaster blocked all signals before forking child process,
4240  * so there is no race condition whereby we might receive a signal before
4241  * we have set up the handler.
4242  *
4243  * Also note: it's best not to use any signals that are SIG_IGNored in the
4244  * postmaster. If such a signal arrives before we are able to change the
4245  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4246  * handler in the postmaster to reserve the signal. (Of course, this isn't
4247  * an issue for signals that are locally generated, such as SIGALRM and
4248  * SIGPIPE.)
4249  */
4250  if (am_walsender)
4251  WalSndSignals();
4252  else
4253  {
4255  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4256  pqsignal(SIGTERM, die); /* cancel current query and exit */
4257 
4258  /*
4259  * In a postmaster child backend, replace SignalHandlerForCrashExit
4260  * with quickdie, so we can tell the client we're dying.
4261  *
4262  * In a standalone backend, SIGQUIT can be generated from the keyboard
4263  * easily, while SIGTERM cannot, so we make both signals do die()
4264  * rather than quickdie().
4265  */
4266  if (IsUnderPostmaster)
4267  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4268  else
4269  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4270  InitializeTimeouts(); /* establishes SIGALRM handler */
4271 
4272  /*
4273  * Ignore failure to write to frontend. Note: if frontend closes
4274  * connection, we will notice it and exit cleanly when control next
4275  * returns to outer loop. This seems safer than forcing exit in the
4276  * midst of output during who-knows-what operation...
4277  */
4282 
4283  /*
4284  * Reset some signals that are accepted by postmaster but not by
4285  * backend
4286  */
4287  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4288  * platforms */
4289  }
4290 
4291  /* Early initialization */
4292  BaseInit();
4293 
4294  /* We need to allow SIGINT, etc during the initial transaction */
4295  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4296 
4297  /*
4298  * Generate a random cancel key, if this is a backend serving a
4299  * connection. InitPostgres() will advertise it in shared memory.
4300  */
4303  {
4304  if (!pg_strong_random(&MyCancelKey, sizeof(int32)))
4305  {
4306  ereport(ERROR,
4307  (errcode(ERRCODE_INTERNAL_ERROR),
4308  errmsg("could not generate random cancel key")));
4309  }
4310  MyCancelKeyValid = true;
4311  }
4312 
4313  /*
4314  * General initialization.
4315  *
4316  * NOTE: if you are tempted to add code in this vicinity, consider putting
4317  * it inside InitPostgres() instead. In particular, anything that
4318  * involves database access should be there, not here.
4319  *
4320  * Honor session_preload_libraries if not dealing with a WAL sender.
4321  */
4322  InitPostgres(dbname, InvalidOid, /* database to connect to */
4323  username, InvalidOid, /* role to connect as */
4325  NULL); /* no out_dbname */
4326 
4327  /*
4328  * If the PostmasterContext is still around, recycle the space; we don't
4329  * need it anymore after InitPostgres completes.
4330  */
4331  if (PostmasterContext)
4332  {
4334  PostmasterContext = NULL;
4335  }
4336 
4338 
4339  /*
4340  * Now all GUC states are fully set up. Report them to client if
4341  * appropriate.
4342  */
4344 
4345  /*
4346  * Also set up handler to log session end; we have to wait till now to be
4347  * sure Log_disconnections has its final value.
4348  */
4351 
4353 
4354  /* Perform initialization specific to a WAL sender process. */
4355  if (am_walsender)
4356  InitWalSender();
4357 
4358  /*
4359  * Send this backend's cancellation info to the frontend.
4360  */
4362  {
4364 
4369  pq_endmessage(&buf);
4370  /* Need not flush since ReadyForQuery will do it. */
4371  }
4372 
4373  /* Welcome banner for standalone case */
4375  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4376 
4377  /*
4378  * Create the memory context we will use in the main loop.
4379  *
4380  * MessageContext is reset once per iteration of the main loop, ie, upon
4381  * completion of processing of each command message from the client.
4382  */
4384  "MessageContext",
4386 
4387  /*
4388  * Create memory context and buffer used for RowDescription messages. As
4389  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4390  * frequently executed for ever single statement, we don't want to
4391  * allocate a separate buffer every time.
4392  */
4394  "RowDescriptionContext",
4399 
4400  /* Fire any defined login event triggers, if appropriate */
4402 
4403  /*
4404  * POSTGRES main processing loop begins here
4405  *
4406  * If an exception is encountered, processing resumes here so we abort the
4407  * current transaction and start a new one.
4408  *
4409  * You might wonder why this isn't coded as an infinite loop around a
4410  * PG_TRY construct. The reason is that this is the bottom of the
4411  * exception stack, and so with PG_TRY there would be no exception handler
4412  * in force at all during the CATCH part. By leaving the outermost setjmp
4413  * always active, we have at least some chance of recovering from an error
4414  * during error recovery. (If we get into an infinite loop thereby, it
4415  * will soon be stopped by overflow of elog.c's internal state stack.)
4416  *
4417  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4418  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4419  * is essential in case we longjmp'd out of a signal handler on a platform
4420  * where that leaves the signal blocked. It's not redundant with the
4421  * unblock in AbortTransaction() because the latter is only called if we
4422  * were inside a transaction.
4423  */
4424 
4425  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4426  {
4427  /*
4428  * NOTE: if you are tempted to add more code in this if-block,
4429  * consider the high probability that it should be in
4430  * AbortTransaction() instead. The only stuff done directly here
4431  * should be stuff that is guaranteed to apply *only* for outer-level
4432  * error recovery, such as adjusting the FE/BE protocol status.
4433  */
4434 
4435  /* Since not using PG_TRY, must reset error stack by hand */
4436  error_context_stack = NULL;
4437 
4438  /* Prevent interrupts while cleaning up */
4439  HOLD_INTERRUPTS();
4440 
4441  /*
4442  * Forget any pending QueryCancel request, since we're returning to
4443  * the idle loop anyway, and cancel any active timeout requests. (In
4444  * future we might want to allow some timeout requests to survive, but
4445  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4446  * we got here because of a query cancel interrupting the SIGALRM
4447  * interrupt handler.) Note in particular that we must clear the
4448  * statement and lock timeout indicators, to prevent any future plain
4449  * query cancels from being misreported as timeouts in case we're
4450  * forgetting a timeout cancel.
4451  */
4452  disable_all_timeouts(false); /* do first to avoid race condition */
4453  QueryCancelPending = false;
4454  idle_in_transaction_timeout_enabled = false;
4455  idle_session_timeout_enabled = false;
4456 
4457  /* Not reading from the client anymore. */
4458  DoingCommandRead = false;
4459 
4460  /* Make sure libpq is in a good state */
4461  pq_comm_reset();
4462 
4463  /* Report the error to the client and/or server log */
4464  EmitErrorReport();
4465 
4466  /*
4467  * If Valgrind noticed something during the erroneous query, print the
4468  * query string, assuming we have one.
4469  */
4471 
4472  /*
4473  * Make sure debug_query_string gets reset before we possibly clobber
4474  * the storage it points at.
4475  */
4476  debug_query_string = NULL;
4477 
4478  /*
4479  * Abort the current transaction in order to recover.
4480  */
4482 
4483  if (am_walsender)
4485 
4487 
4488  /*
4489  * We can't release replication slots inside AbortTransaction() as we
4490  * need to be able to start and abort transactions while having a slot
4491  * acquired. But we never need to hold them across top level errors,
4492  * so releasing here is fine. There also is a before_shmem_exit()
4493  * callback ensuring correct cleanup on FATAL errors.
4494  */
4495  if (MyReplicationSlot != NULL)
4497 
4498  /* We also want to cleanup temporary slots on error. */
4499  ReplicationSlotCleanup(false);
4500 
4502 
4503  /*
4504  * Now return to normal top-level context and clear ErrorContext for
4505  * next time.
4506  */
4508  FlushErrorState();
4509 
4510  /*
4511  * If we were handling an extended-query-protocol message, initiate
4512  * skip till next Sync. This also causes us not to issue
4513  * ReadyForQuery (until we get Sync).
4514  */
4516  ignore_till_sync = true;
4517 
4518  /* We don't have a transaction command open anymore */
4519  xact_started = false;
4520 
4521  /*
4522  * If an error occurred while we were reading a message from the
4523  * client, we have potentially lost track of where the previous
4524  * message ends and the next one begins. Even though we have
4525  * otherwise recovered from the error, we cannot safely read any more
4526  * messages from the client, so there isn't much we can do with the
4527  * connection anymore.
4528  */
4529  if (pq_is_reading_msg())
4530  ereport(FATAL,
4531  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4532  errmsg("terminating connection because protocol synchronization was lost")));
4533 
4534  /* Now we can allow interrupts again */
4536  }
4537 
4538  /* We can now handle ereport(ERROR) */
4539  PG_exception_stack = &local_sigjmp_buf;
4540 
4541  if (!ignore_till_sync)
4542  send_ready_for_query = true; /* initially, or after error */
4543 
4544  /*
4545  * Non-error queries loop here.
4546  */
4547 
4548  for (;;)
4549  {
4550  int firstchar;
4551  StringInfoData input_message;
4552 
4553  /*
4554  * At top of loop, reset extended-query-message flag, so that any
4555  * errors encountered in "idle" state don't provoke skip.
4556  */
4558 
4559  /*
4560  * For valgrind reporting purposes, the "current query" begins here.
4561  */
4562 #ifdef USE_VALGRIND
4563  old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4564 #endif
4565 
4566  /*
4567  * Release storage left over from prior query cycle, and create a new
4568  * query input buffer in the cleared MessageContext.
4569  */
4572 
4573  initStringInfo(&input_message);
4574 
4575  /*
4576  * Also consider releasing our catalog snapshot if any, so that it's
4577  * not preventing advance of global xmin while we wait for the client.
4578  */
4580 
4581  /*
4582  * (1) If we've reached idle state, tell the frontend we're ready for
4583  * a new query.
4584  *
4585  * Note: this includes fflush()'ing the last of the prior output.
4586  *
4587  * This is also a good time to flush out collected statistics to the
4588  * cumulative stats system, and to update the PS stats display. We
4589  * avoid doing those every time through the message loop because it'd
4590  * slow down processing of batched messages, and because we don't want
4591  * to report uncommitted updates (that confuses autovacuum). The
4592  * notification processor wants a call too, if we are not in a
4593  * transaction block.
4594  *
4595  * Also, if an idle timeout is enabled, start the timer for that.
4596  */
4597  if (send_ready_for_query)
4598  {
4600  {
4601  set_ps_display("idle in transaction (aborted)");
4603 
4604  /* Start the idle-in-transaction timer */
4607  {
4608  idle_in_transaction_timeout_enabled = true;
4611  }
4612  }
4614  {
4615  set_ps_display("idle in transaction");
4617 
4618  /* Start the idle-in-transaction timer */
4621  {
4622  idle_in_transaction_timeout_enabled = true;
4625  }
4626  }
4627  else
4628  {
4629  long stats_timeout;
4630 
4631  /*
4632  * Process incoming notifies (including self-notifies), if
4633  * any, and send relevant messages to the client. Doing it
4634  * here helps ensure stable behavior in tests: if any notifies
4635  * were received during the just-finished transaction, they'll
4636  * be seen by the client before ReadyForQuery is.
4637  */
4639  ProcessNotifyInterrupt(false);
4640 
4641  /*
4642  * Check if we need to report stats. If pgstat_report_stat()
4643  * decides it's too soon to flush out pending stats / lock
4644  * contention prevented reporting, it'll tell us when we
4645  * should try to report stats again (so that stats updates
4646  * aren't unduly delayed if the connection goes idle for a
4647  * long time). We only enable the timeout if we don't already
4648  * have a timeout in progress, because we don't disable the
4649  * timeout below. enable_timeout_after() needs to determine
4650  * the current timestamp, which can have a negative
4651  * performance impact. That's OK because pgstat_report_stat()
4652  * won't have us wake up sooner than a prior call.
4653  */
4654  stats_timeout = pgstat_report_stat(false);
4655  if (stats_timeout > 0)
4656  {
4659  stats_timeout);
4660  }
4661  else
4662  {
4663  /* all stats flushed, no need for the timeout */
4666  }
4667 
4668  set_ps_display("idle");
4670 
4671  /* Start the idle-session timer */
4672  if (IdleSessionTimeout > 0)
4673  {
4674  idle_session_timeout_enabled = true;
4677  }
4678  }
4679 
4680  /* Report any recently-changed GUC options */
4682 
4684  send_ready_for_query = false;
4685  }
4686 
4687  /*
4688  * (2) Allow asynchronous signals to be executed immediately if they
4689  * come in while we are waiting for client input. (This must be
4690  * conditional since we don't want, say, reads on behalf of COPY FROM
4691  * STDIN doing the same thing.)
4692  */
4693  DoingCommandRead = true;
4694 
4695  /*
4696  * (3) read a command (loop blocks here)
4697  */
4698  firstchar = ReadCommand(&input_message);
4699 
4700  /*
4701  * (4) turn off the idle-in-transaction and idle-session timeouts if
4702  * active. We do this before step (5) so that any last-moment timeout
4703  * is certain to be detected in step (5).
4704  *
4705  * At most one of these timeouts will be active, so there's no need to
4706  * worry about combining the timeout.c calls into one.
4707  */
4708  if (idle_in_transaction_timeout_enabled)
4709  {
4711  idle_in_transaction_timeout_enabled = false;
4712  }
4713  if (idle_session_timeout_enabled)
4714  {
4716  idle_session_timeout_enabled = false;
4717  }
4718 
4719  /*
4720  * (5) disable async signal conditions again.
4721  *
4722  * Query cancel is supposed to be a no-op when there is no query in
4723  * progress, so if a query cancel arrived while we were idle, just
4724  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4725  * it's called when DoingCommandRead is set, so check for interrupts
4726  * before resetting DoingCommandRead.
4727  */
4729  DoingCommandRead = false;
4730 
4731  /*
4732  * (6) check for any other interesting events that happened while we
4733  * slept.
4734  */
4735  if (ConfigReloadPending)
4736  {
4737  ConfigReloadPending = false;
4739  }
4740 
4741  /*
4742  * (7) process the command. But ignore it if we're skipping till
4743  * Sync.
4744  */
4745  if (ignore_till_sync && firstchar != EOF)
4746  continue;
4747 
4748  switch (firstchar)
4749  {
4750  case PqMsg_Query:
4751  {
4752  const char *query_string;
4753 
4754  /* Set statement_timestamp() */
4756 
4757  query_string = pq_getmsgstring(&input_message);
4758  pq_getmsgend(&input_message);
4759 
4760  if (am_walsender)
4761  {
4762  if (!exec_replication_command(query_string))
4763  exec_simple_query(query_string);
4764  }
4765  else
4766  exec_simple_query(query_string);
4767 
4768  valgrind_report_error_query(query_string);
4769 
4770  send_ready_for_query = true;
4771  }
4772  break;
4773 
4774  case PqMsg_Parse:
4775  {
4776  const char *stmt_name;
4777  const char *query_string;
4778  int numParams;
4779  Oid *paramTypes = NULL;
4780 
4781  forbidden_in_wal_sender(firstchar);
4782 
4783  /* Set statement_timestamp() */
4785 
4786  stmt_name = pq_getmsgstring(&input_message);
4787  query_string = pq_getmsgstring(&input_message);
4788  numParams = pq_getmsgint(&input_message, 2);
4789  if (numParams > 0)
4790  {
4791  paramTypes = palloc_array(Oid, numParams);
4792  for (int i = 0; i < numParams; i++)
4793  paramTypes[i] = pq_getmsgint(&input_message, 4);
4794  }
4795  pq_getmsgend(&input_message);
4796 
4797  exec_parse_message(query_string, stmt_name,
4798  paramTypes, numParams);
4799 
4800  valgrind_report_error_query(query_string);
4801  }
4802  break;
4803 
4804  case PqMsg_Bind:
4805  forbidden_in_wal_sender(firstchar);
4806 
4807  /* Set statement_timestamp() */
4809 
4810  /*
4811  * this message is complex enough that it seems best to put
4812  * the field extraction out-of-line
4813  */
4814  exec_bind_message(&input_message);
4815 
4816  /* exec_bind_message does valgrind_report_error_query */
4817  break;
4818 
4819  case PqMsg_Execute:
4820  {
4821  const char *portal_name;
4822  int max_rows;
4823 
4824  forbidden_in_wal_sender(firstchar);
4825 
4826  /* Set statement_timestamp() */
4828 
4829  portal_name = pq_getmsgstring(&input_message);
4830  max_rows = pq_getmsgint(&input_message, 4);
4831  pq_getmsgend(&input_message);
4832 
4833  exec_execute_message(portal_name, max_rows);
4834 
4835  /* exec_execute_message does valgrind_report_error_query */
4836  }
4837  break;
4838 
4839  case PqMsg_FunctionCall:
4840  forbidden_in_wal_sender(firstchar);
4841 
4842  /* Set statement_timestamp() */
4844 
4845  /* Report query to various monitoring facilities. */
4847  set_ps_display("<FASTPATH>");
4848 
4849  /* start an xact for this function invocation */
4851 
4852  /*
4853  * Note: we may at this point be inside an aborted
4854  * transaction. We can't throw error for that until we've
4855  * finished reading the function-call message, so
4856  * HandleFunctionRequest() must check for it after doing so.
4857  * Be careful not to do anything that assumes we're inside a
4858  * valid transaction here.
4859  */
4860 
4861  /* switch back to message context */
4863 
4864  HandleFunctionRequest(&input_message);
4865 
4866  /* commit the function-invocation transaction */
4868 
4869  valgrind_report_error_query("fastpath function call");
4870 
4871  send_ready_for_query = true;
4872  break;
4873 
4874  case PqMsg_Close:
4875  {
4876  int close_type;
4877  const char *close_target;
4878 
4879  forbidden_in_wal_sender(firstchar);
4880 
4881  close_type = pq_getmsgbyte(&input_message);
4882  close_target = pq_getmsgstring(&input_message);
4883  pq_getmsgend(&input_message);
4884 
4885  switch (close_type)
4886  {
4887  case 'S':
4888  if (close_target[0] != '\0')
4889  DropPreparedStatement(close_target, false);
4890  else
4891  {
4892  /* special-case the unnamed statement */
4894  }
4895  break;
4896  case 'P':
4897  {
4898  Portal portal;
4899 
4900  portal = GetPortalByName(close_target);
4901  if (PortalIsValid(portal))
4902  PortalDrop(portal, false);
4903  }
4904  break;
4905  default:
4906  ereport(ERROR,
4907  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4908  errmsg("invalid CLOSE message subtype %d",
4909  close_type)));
4910  break;
4911  }
4912 
4915 
4916  valgrind_report_error_query("CLOSE message");
4917  }
4918  break;
4919 
4920  case PqMsg_Describe:
4921  {
4922  int describe_type;
4923  const char *describe_target;
4924 
4925  forbidden_in_wal_sender(firstchar);
4926 
4927  /* Set statement_timestamp() (needed for xact) */
4929 
4930  describe_type = pq_getmsgbyte(&input_message);
4931  describe_target = pq_getmsgstring(&input_message);
4932  pq_getmsgend(&input_message);
4933 
4934  switch (describe_type)
4935  {
4936  case 'S':
4937  exec_describe_statement_message(describe_target);
4938  break;
4939  case 'P':
4940  exec_describe_portal_message(describe_target);
4941  break;
4942  default:
4943  ereport(ERROR,
4944  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4945  errmsg("invalid DESCRIBE message subtype %d",
4946  describe_type)));
4947  break;
4948  }
4949 
4950  valgrind_report_error_query("DESCRIBE message");
4951  }
4952  break;
4953 
4954  case PqMsg_Flush:
4955  pq_getmsgend(&input_message);
4957  pq_flush();
4958  break;
4959 
4960  case PqMsg_Sync:
4961  pq_getmsgend(&input_message);
4963  valgrind_report_error_query("SYNC message");
4964  send_ready_for_query = true;
4965  break;
4966 
4967  /*
4968  * 'X' means that the frontend is closing down the socket. EOF
4969  * means unexpected loss of frontend connection. Either way,
4970  * perform normal shutdown.
4971  */
4972  case EOF:
4973 
4974  /* for the cumulative statistics system */
4976 
4977  /* FALLTHROUGH */
4978 
4979  case PqMsg_Terminate:
4980 
4981  /*
4982  * Reset whereToSendOutput to prevent ereport from attempting
4983  * to send any more messages to client.
4984  */
4987 
4988  /*
4989  * NOTE: if you are tempted to add more code here, DON'T!
4990  * Whatever you had in mind to do should be set up as an
4991  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4992  * it will fail to be called during other backend-shutdown
4993  * scenarios.
4994  */
4995  proc_exit(0);
4996 
4997  case PqMsg_CopyData:
4998  case PqMsg_CopyDone:
4999  case PqMsg_CopyFail:
5000 
5001  /*
5002  * Accept but ignore these messages, per protocol spec; we
5003  * probably got here because a COPY failed, and the frontend
5004  * is still sending data.
5005  */
5006  break;
5007 
5008  default:
5009  ereport(FATAL,
5010  (errcode(ERRCODE_PROTOCOL_VIOLATION),
5011  errmsg("invalid frontend message type %d",
5012  firstchar)));
5013  }
5014  } /* end of input-reading loop */
5015 }
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:189
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:2545
void ReportChangedGUCOptions(void)
Definition: guc.c:2595
@ 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:446
@ InitProcessing
Definition: miscadmin.h:445
#define GetProcessingMode()
Definition: miscadmin.h:455
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:473
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:457
long pgstat_report_stat(bool force)
Definition: pgstat.c:660
@ 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:2607
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2884
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5195
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:5025
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2095
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3028
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3011
static bool ignore_till_sync
Definition: postgres.c:155
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1023
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1401
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1636
void die(SIGNAL_ARGS)
Definition: postgres.c:2981
static MemoryContext row_description_context
Definition: postgres.c:174
static bool doing_extended_query_message
Definition: postgres.c:154
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2700
bool Log_disconnections
Definition: postgres.c:94
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:492
void BaseInit(void)
Definition: postinit.c:569
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:663
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:63
int IdleInTransactionSessionTimeout
Definition: proc.c:61
char * dbname
Definition: streamutil.c:52
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:327
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1980
void WalSndSignals(void)
Definition: walsender.c:3593
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:4982
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:913
void AbortCurrentTransaction(void)
Definition: xact.c:3431

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 4111 of file postgres.c.

4113 {
4114  const char *dbname = NULL;
4115 
4117 
4118  /* Initialize startup process environment. */
4119  InitStandaloneProcess(argv[0]);
4120 
4121  /*
4122  * Set default values for command-line options.
4123  */
4125 
4126  /*
4127  * Parse command-line options.
4128  */
4130 
4131  /* Must have gotten a database name, or have a default (the username) */
4132  if (dbname == NULL)
4133  {
4134  dbname = username;
4135  if (dbname == NULL)
4136  ereport(FATAL,
4137  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4138  errmsg("%s: no database nor user name specified",
4139  progname)));
4140  }
4141 
4142  /* Acquire configuration parameters */
4144  proc_exit(1);
4145 
4146  /*
4147  * Validate we have been given a reasonable-looking DataDir and change
4148  * into it.
4149  */
4150  checkDataDir();
4151  ChangeToDataDir();
4152 
4153  /*
4154  * Create lockfile for data directory.
4155  */
4156  CreateDataDirLockFile(false);
4157 
4158  /* read control file (error checking and contains config ) */
4159  LocalProcessControlFile(false);
4160 
4161  /*
4162  * process any libraries that should be preloaded at postmaster start
4163  */
4165 
4166  /* Initialize MaxBackends */
4168 
4169  /*
4170  * Give preloaded libraries a chance to request additional shared memory.
4171  */
4173 
4174  /*
4175  * Now that loadable modules have had their chance to request additional
4176  * shared memory, determine the value of any runtime-computed GUCs that
4177  * depend on the amount of shared memory required.
4178  */
4180 
4181  /*
4182  * Now that modules have been loaded, we can process any custom resource
4183  * managers specified in the wal_consistency_checking GUC.
4184  */
4186 
4188 
4189  /*
4190  * Remember stand-alone backend startup time,roughly at the same point
4191  * during startup that postmaster does so.
4192  */
4194 
4195  /*
4196  * Create a per-backend PGPROC struct in shared memory. We must do this
4197  * before we can use LWLocks.
4198  */
4199  InitProcess();
4200 
4201  /*
4202  * Now that sufficient infrastructure has been initialized, PostgresMain()
4203  * can do the rest.
4204  */
4206 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1783
void InitializeGUCOptions(void)
Definition: guc.c:1529
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:351
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:196
const char * progname
Definition: main.c:44
void ChangeToDataDir(void)
Definition: miscinit.c:454
void process_shmem_requests(void)
Definition: miscinit.c:1871
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:181
void process_shared_preload_libraries(void)
Definition: miscinit.c:1843
void checkDataDir(void)
Definition: miscinit.c:341
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1455
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3859
static const char * userDoption
Definition: postgres.c:165
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4221
void InitializeMaxBackends(void)
Definition: postinit.c:542
void InitProcess(void)
Definition: proc.c:297
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4777
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4839

References Assert, ChangeToDataDir(), checkDataDir(), CreateDataDirLockFile(), CreateSharedMemoryAndSemaphores(), dbname, ereport, errcode(), errmsg(), FATAL, GetCurrentTimestamp(), InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), 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 3859 of file postgres.c.

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

514 {
515  int save_errno = errno;
516 
517  if (DoingCommandRead)
518  {
519  /* Check for general interrupts that arrived before/while reading */
521 
522  /* Process sinval catchup interrupts, if any */
525 
526  /* Process notify interrupts, if any */
529  }
530  else if (ProcDiePending)
531  {
532  /*
533  * We're dying. If there is no data available to read, then it's safe
534  * (and sane) to handle that now. If we haven't tried to read yet,
535  * make sure the process latch is set, so that if there is no data
536  * then we'll come back here and die. If we're done reading, also
537  * make sure the process latch is set, as we might've undesirably
538  * cleared it while reading.
539  */
540  if (blocked)
542  else
543  SetLatch(MyLatch);
544  }
545 
546  errno = save_errno;
547 }
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 559 of file postgres.c.

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

3254 {
3255  /* OK to accept any interrupts now? */
3256  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3257  return;
3258  InterruptPending = false;
3259 
3260  if (ProcDiePending)
3261  {
3262  ProcDiePending = false;
3263  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3264  LockErrorCleanup();
3265  /* As in quickdie, don't risk sending to client during auth */
3269  ereport(FATAL,
3270  (errcode(ERRCODE_QUERY_CANCELED),
3271  errmsg("canceling authentication due to timeout")));
3272  else if (AmAutoVacuumWorkerProcess())
3273  ereport(FATAL,
3274  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3275  errmsg("terminating autovacuum process due to administrator command")));
3276  else if (IsLogicalWorker())
3277  ereport(FATAL,
3278  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3279  errmsg("terminating logical replication worker due to administrator command")));
3280  else if (IsLogicalLauncher())
3281  {
3282  ereport(DEBUG1,
3283  (errmsg_internal("logical replication launcher shutting down")));
3284 
3285  /*
3286  * The logical replication launcher can be stopped at any time.
3287  * Use exit status 1 so the background worker is restarted.
3288  */
3289  proc_exit(1);
3290  }
3291  else if (AmBackgroundWorkerProcess())
3292  ereport(FATAL,
3293  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3294  errmsg("terminating background worker \"%s\" due to administrator command",
3296  else
3297  ereport(FATAL,
3298  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3299  errmsg("terminating connection due to administrator command")));
3300  }
3301 
3303  {
3305 
3306  /*
3307  * Check for lost connection and re-arm, if still configured, but not
3308  * if we've arrived back at DoingCommandRead state. We don't want to
3309  * wake up idle sessions, and they already know how to detect lost
3310  * connections.
3311  */
3313  {
3314  if (!pq_check_connection())
3315  ClientConnectionLost = true;
3316  else
3319  }
3320  }
3321 
3323  {
3324  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3325  LockErrorCleanup();
3326  /* don't send to client, we already know the connection to be dead. */
3328  ereport(FATAL,
3329  (errcode(ERRCODE_CONNECTION_FAILURE),
3330  errmsg("connection to client lost")));
3331  }
3332 
3333  /*
3334  * Don't allow query cancel interrupts while reading input from the
3335  * client, because we might lose sync in the FE/BE protocol. (Die
3336  * interrupts are OK, because we won't read any further messages from the
3337  * client in that case.)
3338  *
3339  * See similar logic in ProcessRecoveryConflictInterrupts().
3340  */
3342  {
3343  /*
3344  * Re-arm InterruptPending so that we process the cancel request as
3345  * soon as we're done reading the message. (XXX this is seriously
3346  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3347  * can't use that macro directly as the initial test in this function,
3348  * meaning that this code also creates opportunities for other bugs to
3349  * appear.)
3350  */
3351  InterruptPending = true;
3352  }
3353  else if (QueryCancelPending)
3354  {
3355  bool lock_timeout_occurred;
3356  bool stmt_timeout_occurred;
3357 
3358  QueryCancelPending = false;
3359 
3360  /*
3361  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3362  * need to clear both, so always fetch both.
3363  */
3364  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3365  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3366 
3367  /*
3368  * If both were set, we want to report whichever timeout completed
3369  * earlier; this ensures consistent behavior if the machine is slow
3370  * enough that the second timeout triggers before we get here. A tie
3371  * is arbitrarily broken in favor of reporting a lock timeout.
3372  */
3373  if (lock_timeout_occurred && stmt_timeout_occurred &&
3375  lock_timeout_occurred = false; /* report stmt timeout */
3376 
3377  if (lock_timeout_occurred)
3378  {
3379  LockErrorCleanup();
3380  ereport(ERROR,
3381  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3382  errmsg("canceling statement due to lock timeout")));
3383  }
3384  if (stmt_timeout_occurred)
3385  {
3386  LockErrorCleanup();
3387  ereport(ERROR,
3388  (errcode(ERRCODE_QUERY_CANCELED),
3389  errmsg("canceling statement due to statement timeout")));
3390  }
3392  {
3393  LockErrorCleanup();
3394  ereport(ERROR,
3395  (errcode(ERRCODE_QUERY_CANCELED),
3396  errmsg("canceling autovacuum task")));
3397  }
3398 
3399  /*
3400  * If we are reading a command from the client, just ignore the cancel
3401  * request --- sending an extra error message won't accomplish
3402  * anything. Otherwise, go ahead and throw the error.
3403  */
3404  if (!DoingCommandRead)
3405  {
3406  LockErrorCleanup();
3407  ereport(ERROR,
3408  (errcode(ERRCODE_QUERY_CANCELED),
3409  errmsg("canceling statement due to user request")));
3410  }
3411  }
3412 
3415 
3417  {
3418  /*
3419  * If the GUC has been reset to zero, ignore the signal. This is
3420  * important because the GUC update itself won't disable any pending
3421  * interrupt. We need to unset the flag before the injection point,
3422  * otherwise we could loop in interrupts checking.
3423  */
3426  {
3427  INJECTION_POINT("idle-in-transaction-session-timeout");
3428  ereport(FATAL,
3429  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3430  errmsg("terminating connection due to idle-in-transaction timeout")));
3431  }
3432  }
3433 
3435  {
3436  /* As above, ignore the signal if the GUC has been reset to zero. */
3437  TransactionTimeoutPending = false;
3438  if (TransactionTimeout > 0)
3439  {
3440  INJECTION_POINT("transaction-timeout");
3441  ereport(FATAL,
3442  (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3443  errmsg("terminating connection due to transaction timeout")));
3444  }
3445  }
3446 
3448  {
3449  /* As above, ignore the signal if the GUC has been reset to zero. */
3450  IdleSessionTimeoutPending = false;
3451  if (IdleSessionTimeout > 0)
3452  {
3453  INJECTION_POINT("idle-session-timeout");
3454  ereport(FATAL,
3455  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3456  errmsg("terminating connection due to idle-session timeout")));
3457  }
3458  }
3459 
3460  /*
3461  * If there are pending stats updates and we currently are truly idle
3462  * (matching the conditions in PostgresMain(), report stats now.
3463  */
3466  {
3468  pgstat_report_stat(true);
3469  }
3470 
3473 
3476 
3479 
3482 }
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
void HandleParallelMessages(void)
Definition: parallel.c:1027
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:115
bool IsLogicalWorker(void)
Definition: worker.c:4842
#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:372
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:373
int client_connection_check_interval
Definition: postgres.c:105