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 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)
 
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
 
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 224 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 3595 of file postgres.c.

3596 {
3597  long newval_bytes = newval * 1024L;
3598 
3599  max_stack_depth_bytes = newval_bytes;
3600 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:125

References max_stack_depth_bytes, and newval.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3656 of file postgres.c.

3657 {
3658  if (IsTransactionState())
3659  {
3660  /*
3661  * If transaction_timeout GUC has changed within the transaction block
3662  * enable or disable the timer correspondingly.
3663  */
3666  else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3668  }
3669 }
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:384

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

2549 {
2552  char *quotedval;
2553 
2554  if (data->paramno < 0)
2555  return;
2556 
2557  /* If we have a textual value, quote it, and trim if necessary */
2558  if (data->paramval)
2559  {
2560  initStringInfo(&buf);
2563  quotedval = buf.data;
2564  }
2565  else
2566  quotedval = NULL;
2567 
2568  if (data->portalName && data->portalName[0] != '\0')
2569  {
2570  if (quotedval)
2571  errcontext("portal \"%s\" parameter $%d = %s",
2572  data->portalName, data->paramno + 1, quotedval);
2573  else
2574  errcontext("portal \"%s\" parameter $%d",
2575  data->portalName, data->paramno + 1);
2576  }
2577  else
2578  {
2579  if (quotedval)
2580  errcontext("unnamed portal parameter $%d = %s",
2581  data->paramno + 1, quotedval);
2582  else
2583  errcontext("unnamed portal parameter $%d",
2584  data->paramno + 1);
2585  }
2586 
2587  if (quotedval)
2588  pfree(quotedval);
2589 }
#define errcontext
Definition: elog.h:196
int log_parameter_max_length_on_error
Definition: guc_tables.c:529
void pfree(void *pointer)
Definition: mcxt.c:1520
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 3606 of file postgres.c.

3607 {
3608  if (!WaitEventSetCanReportClosed() && *newval != 0)
3609  {
3610  GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3611  return false;
3612  }
3613  return true;
3614 }
#define GUC_check_errdetail
Definition: guc.h:447
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2215

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2379 of file postgres.c.

2380 {
2381  if (log_duration || log_min_duration_sample >= 0 ||
2383  {
2384  long secs;
2385  int usecs;
2386  int msecs;
2387  bool exceeded_duration;
2388  bool exceeded_sample_duration;
2389  bool in_sample = false;
2390 
2393  &secs, &usecs);
2394  msecs = usecs / 1000;
2395 
2396  /*
2397  * This odd-looking test for log_min_duration_* being exceeded is
2398  * designed to avoid integer overflow with very long durations: don't
2399  * compute secs * 1000 until we've verified it will fit in int.
2400  */
2401  exceeded_duration = (log_min_duration_statement == 0 ||
2403  (secs > log_min_duration_statement / 1000 ||
2404  secs * 1000 + msecs >= log_min_duration_statement)));
2405 
2406  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2407  (log_min_duration_sample > 0 &&
2408  (secs > log_min_duration_sample / 1000 ||
2409  secs * 1000 + msecs >= log_min_duration_sample)));
2410 
2411  /*
2412  * Do not log if log_statement_sample_rate = 0. Log a sample if
2413  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2414  * log_statement_sample_rate = 1.
2415  */
2416  if (exceeded_sample_duration)
2417  in_sample = log_statement_sample_rate != 0 &&
2418  (log_statement_sample_rate == 1 ||
2420 
2421  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2422  {
2423  snprintf(msec_str, 32, "%ld.%03d",
2424  secs * 1000 + msecs, usecs % 1000);
2425  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2426  return 2;
2427  else
2428  return 1;
2429  }
2430  }
2431 
2432  return 0;
2433 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1730
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
int log_min_duration_statement
Definition: guc_tables.c:527
int log_min_duration_sample
Definition: guc_tables.c:526
double log_statement_sample_rate
Definition: guc_tables.c:531
bool log_duration
Definition: guc_tables.c:499
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:876
bool xact_is_sampled
Definition: xact.c:293

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

2341 {
2342  ListCell *stmt_item;
2343 
2344  if (log_statement == LOGSTMT_NONE)
2345  return false;
2346  if (log_statement == LOGSTMT_ALL)
2347  return true;
2348 
2349  /* Else we have to inspect the statement(s) to see whether to log */
2350  foreach(stmt_item, stmt_list)
2351  {
2352  Node *stmt = (Node *) lfirst(stmt_item);
2353 
2355  return true;
2356  }
2357 
2358  return false;
2359 }
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:95
Definition: nodes.h:129
@ LOGSTMT_NONE
Definition: tcopprot.h:37
@ LOGSTMT_ALL
Definition: tcopprot.h:40
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c: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 3641 of file postgres.c.

3642 {
3643  if (*newval &&
3645  {
3646  GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3647  "\"log_parser_stats\", \"log_planner_stats\", "
3648  "or \"log_executor_stats\" is true.");
3649  return false;
3650  }
3651  return true;
3652 }
bool log_parser_stats
Definition: guc_tables.c:505
bool log_planner_stats
Definition: guc_tables.c:506
bool log_executor_stats
Definition: guc_tables.c:507

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

3579 {
3580  long newval_bytes = *newval * 1024L;
3581  long stack_rlimit = get_stack_depth_rlimit();
3582 
3583  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3584  {
3585  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3586  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3587  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3588  return false;
3589  }
3590  return true;
3591 }
#define GUC_check_errhint
Definition: guc.h:451
long get_stack_depth_rlimit(void)
Definition: postgres.c:4961
#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_stack_depth()

void check_stack_depth ( void  )

Definition at line 3531 of file postgres.c.

3532 {
3533  if (stack_is_too_deep())
3534  {
3535  ereport(ERROR,
3536  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3537  errmsg("stack depth limit exceeded"),
3538  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3539  "after ensuring the platform's stack depth limit is adequate.",
3540  max_stack_depth)));
3541  }
3542 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int max_stack_depth
Definition: postgres.c:98
bool stack_is_too_deep(void)
Definition: postgres.c:3545

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

3628 {
3629  if (*newval && log_statement_stats)
3630  {
3631  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3632  return false;
3633  }
3634  return true;
3635 }
bool log_statement_stats
Definition: guc_tables.c:508

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2972 of file postgres.c.

2973 {
2974  /* Don't joggle the elbow of proc_exit */
2975  if (!proc_exit_inprogress)
2976  {
2977  InterruptPending = true;
2978  ProcDiePending = true;
2979  }
2980 
2981  /* for the cumulative stats system */
2983 
2984  /* If we're still here, waken anything waiting on the process latch */
2985  SetLatch(MyLatch);
2986 
2987  /*
2988  * If we're in single user mode, we want to quit immediately - we can't
2989  * rely on latches as they wouldn't work when stdin/stdout is a file.
2990  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2991  * effort just for the benefit of single user mode.
2992  */
2995 }
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:60
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:632
@ DISCONNECT_KILLED
Definition: pgstat.h:82
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool DoingCommandRead
Definition: postgres.c:144
void ProcessInterrupts(void)
Definition: postgres.c:3244

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

5168 {
5171 }
@ 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 2850 of file postgres.c.

2851 {
2852  /* paranoia to avoid a dangling pointer in case of error */
2853  if (unnamed_stmt_psrc)
2854  {
2856 
2857  unnamed_stmt_psrc = NULL;
2858  DropCachedPlan(psrc);
2859  }
2860 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:526
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:158

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

5146 {
5147  /* must be within an xact */
5149 
5150  if (StatementTimeout > 0
5152  {
5155  }
5156  else
5157  {
5160  }
5161 }
#define Assert(condition)
Definition: c.h:858
static bool xact_started
Definition: postgres.c:137
int StatementTimeout
Definition: proc.c:58
int TransactionTimeout
Definition: proc.c:61

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

Referenced by start_xact_command().

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2495 of file postgres.c.

2496 {
2498  errdetail("Abort reason: recovery conflict");
2499 
2500  return 0;
2501 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
PGPROC * MyProc
Definition: proc.c:66
bool recoveryConflictPending
Definition: proc.h:216

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

2443 {
2444  ListCell *parsetree_item;
2445 
2446  foreach(parsetree_item, raw_parsetree_list)
2447  {
2448  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2449 
2450  if (IsA(parsetree->stmt, ExecuteStmt))
2451  {
2452  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2453  PreparedStatement *pstmt;
2454 
2455  pstmt = FetchPreparedStatement(stmt->name, false);
2456  if (pstmt)
2457  {
2458  errdetail("prepare: %s", pstmt->plansource->query_string);
2459  return 0;
2460  }
2461  }
2462  }
2463 
2464  return 0;
2465 }
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:2025

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

2476 {
2477  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2478  {
2479  char *str;
2480 
2482  if (str && str[0] != '\0')
2483  errdetail("Parameters: %s", str);
2484  }
2485 
2486  return 0;
2487 }
int log_parameter_max_length
Definition: guc_tables.c:528
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 2509 of file postgres.c.

2510 {
2511  switch (reason)
2512  {
2514  errdetail("User was holding shared buffer pin for too long.");
2515  break;
2517  errdetail("User was holding a relation lock for too long.");
2518  break;
2520  errdetail("User was or might have been using tablespace that must be dropped.");
2521  break;
2523  errdetail("User query might have needed to see row versions that must be removed.");
2524  break;
2526  errdetail("User was using a logical replication slot that must be invalidated.");
2527  break;
2529  errdetail("User transaction caused buffer deadlock with recovery.");
2530  break;
2532  errdetail("User was connected to a database that must be dropped.");
2533  break;
2534  default:
2535  break;
2536  /* no errdetail */
2537  }
2538 
2539  return 0;
2540 }
@ 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 1626 of file postgres.c.

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

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

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

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

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

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

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

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

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

2772 {
2773  /* cancel active statement timeout after each command */
2775 
2776  if (xact_started)
2777  {
2779 
2780 #ifdef MEMORY_CONTEXT_CHECKING
2781  /* Check all memory contexts that weren't freed during commit */
2782  /* (those that were, were checked before being deleted) */
2783  MemoryContextCheck(TopMemoryContext);
2784 #endif
2785 
2786 #ifdef SHOW_MEMORY_STATS
2787  /* Print mem stats after each commit for leak tracking */
2789 #endif
2790 
2791  xact_started = false;
2792  }
2793 }
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:814
void CommitTransactionCommand(void)
Definition: xact.c:3093

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

3020 {
3021  /* We're not returning, so no need to save errno */
3022  ereport(ERROR,
3023  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3024  errmsg("floating-point exception"),
3025  errdetail("An invalid floating-point operation was signaled. "
3026  "This probably means an out-of-range result or an "
3027  "invalid operation, such as division by zero.")));
3028 }

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

4940 {
4941  if (am_walsender)
4942  {
4943  if (firstchar == PqMsg_FunctionCall)
4944  ereport(ERROR,
4945  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4946  errmsg("fastpath function calls not supported in a replication connection")));
4947  else
4948  ereport(ERROR,
4949  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4950  errmsg("extended query protocol not supported in a replication connection")));
4951  }
4952 }
#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 4961 of file postgres.c.

4962 {
4963 #if defined(HAVE_GETRLIMIT)
4964  static long val = 0;
4965 
4966  /* This won't change after process launch, so check just once */
4967  if (val == 0)
4968  {
4969  struct rlimit rlim;
4970 
4971  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4972  val = -1;
4973  else if (rlim.rlim_cur == RLIM_INFINITY)
4974  val = LONG_MAX;
4975  /* rlim_cur is probably of an unsigned type, so check for overflow */
4976  else if (rlim.rlim_cur >= LONG_MAX)
4977  val = LONG_MAX;
4978  else
4979  val = rlim.rlim_cur;
4980  }
4981  return val;
4982 #else
4983  /* On Windows we set the backend stack size in src/backend/Makefile */
4984  return WIN32_STACK_RLIMIT;
4985 #endif
4986 }
long val
Definition: informix.c:670

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

3751 {
3752  switch (arg[0])
3753  {
3754  case 'p':
3755  if (optarg[1] == 'a') /* "parser" */
3756  return "log_parser_stats";
3757  else if (optarg[1] == 'l') /* "planner" */
3758  return "log_planner_stats";
3759  break;
3760 
3761  case 'e': /* "executor" */
3762  return "log_executor_stats";
3763  break;
3764  }
3765 
3766  return NULL;
3767 }
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 3035 of file postgres.c.

3036 {
3037  RecoveryConflictPendingReasons[reason] = true;
3038  RecoveryConflictPending = true;
3039  InterruptPending = true;
3040  /* latch will be set by procsignal_sigusr1_handler */
3041 }
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:167
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:166

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 332 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 244 of file postgres.c.

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

2804 {
2805  if (parsetree && IsA(parsetree, TransactionStmt))
2806  {
2807  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2808 
2809  if (stmt->kind == TRANS_STMT_COMMIT ||
2810  stmt->kind == TRANS_STMT_PREPARE ||
2811  stmt->kind == TRANS_STMT_ROLLBACK ||
2812  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2813  return true;
2814  }
2815  return false;
2816 }
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3666
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3663
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3662
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3667

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

2821 {
2822  if (list_length(pstmts) == 1)
2823  {
2824  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2825 
2826  if (pstmt->commandType == CMD_UTILITY &&
2828  return true;
2829  }
2830  return false;
2831 }
@ 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 2835 of file postgres.c.

2836 {
2837  if (list_length(pstmts) == 1)
2838  {
2839  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2840 
2841  if (pstmt->commandType == CMD_UTILITY &&
2842  IsA(pstmt->utilityStmt, TransactionStmt))
2843  return true;
2844  }
2845  return false;
2846 }

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

5110 {
5111  Port *port = MyProcPort;
5112  long secs;
5113  int usecs;
5114  int msecs;
5115  int hours,
5116  minutes,
5117  seconds;
5118 
5121  &secs, &usecs);
5122  msecs = usecs / 1000;
5123 
5124  hours = secs / SECS_PER_HOUR;
5125  secs %= SECS_PER_HOUR;
5126  minutes = secs / SECS_PER_MINUTE;
5127  seconds = secs % SECS_PER_MINUTE;
5128 
5129  ereport(LOG,
5130  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5131  "user=%s database=%s host=%s%s%s",
5132  hours, minutes, seconds, msecs,
5133  port->user_name, port->database_name, port->remote_host,
5134  port->remote_port[0] ? " port=" : "", port->remote_port)));
5135 }
#define SECS_PER_HOUR
Definition: timestamp.h:127
#define SECS_PER_MINUTE
Definition: timestamp.h:128
TimestampTz MyStartTimestamp
Definition: globals.c:47
struct Port * MyProcPort
Definition: globals.c:49
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 671 of file postgres.c.

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

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

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

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

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

612 {
613  List *raw_parsetree_list;
614 
615  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
616 
617  if (log_parser_stats)
618  ResetUsage();
619 
620  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
621 
622  if (log_parser_stats)
623  ShowUsage("PARSER STATISTICS");
624 
625 #ifdef COPY_PARSE_PLAN_TREES
626  /* Optional debugging check: pass raw parsetrees through copyObject() */
627  {
628  List *new_list = copyObject(raw_parsetree_list);
629 
630  /* This checks both copyObject() and the equal() routines... */
631  if (!equal(new_list, raw_parsetree_list))
632  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
633  else
634  raw_parsetree_list = new_list;
635  }
636 #endif
637 
638  /*
639  * Optional debugging check: pass raw parsetrees through
640  * outfuncs/readfuncs
641  */
642 #ifdef WRITE_READ_PARSE_PLAN_TREES
643  {
644  char *str = nodeToStringWithLocations(raw_parsetree_list);
645  List *new_list = stringToNodeWithLocations(str);
646 
647  pfree(str);
648  /* This checks both outfuncs/readfuncs and the equal() routines... */
649  if (!equal(new_list, raw_parsetree_list))
650  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
651  else
652  raw_parsetree_list = new_list;
653  }
654 #endif
655 
656  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
657 
658  return raw_parsetree_list;
659 }
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:224
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 972 of file postgres.c.

974 {
975  List *stmt_list = NIL;
976  ListCell *query_list;
977 
978  foreach(query_list, querytrees)
979  {
980  Query *query = lfirst_node(Query, query_list);
981  PlannedStmt *stmt;
982 
983  if (query->commandType == CMD_UTILITY)
984  {
985  /* Utility commands require no planning. */
987  stmt->commandType = CMD_UTILITY;
988  stmt->canSetTag = query->canSetTag;
989  stmt->utilityStmt = query->utilityStmt;
990  stmt->stmt_location = query->stmt_location;
991  stmt->stmt_len = query->stmt_len;
992  stmt->queryId = query->queryId;
993  }
994  else
995  {
996  stmt = pg_plan_query(query, query_string, cursorOptions,
997  boundParams);
998  }
999 
1000  stmt_list = lappend(stmt_list, stmt);
1001  }
1002 
1003  return stmt_list;
1004 }
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:886
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 886 of file postgres.c.

888 {
889  PlannedStmt *plan;
890 
891  /* Utility commands have no plans. */
892  if (querytree->commandType == CMD_UTILITY)
893  return NULL;
894 
895  /* Planner must have a snapshot in case it calls user-defined functions. */
897 
898  TRACE_POSTGRESQL_QUERY_PLAN_START();
899 
900  if (log_planner_stats)
901  ResetUsage();
902 
903  /* call the optimizer */
904  plan = planner(querytree, query_string, cursorOptions, boundParams);
905 
906  if (log_planner_stats)
907  ShowUsage("PLANNER STATISTICS");
908 
909 #ifdef COPY_PARSE_PLAN_TREES
910  /* Optional debugging check: pass plan tree through copyObject() */
911  {
912  PlannedStmt *new_plan = copyObject(plan);
913 
914  /*
915  * equal() currently does not have routines to compare Plan nodes, so
916  * don't try to test equality here. Perhaps fix someday?
917  */
918 #ifdef NOT_USED
919  /* This checks both copyObject() and the equal() routines... */
920  if (!equal(new_plan, plan))
921  elog(WARNING, "copyObject() failed to produce an equal plan tree");
922  else
923 #endif
924  plan = new_plan;
925  }
926 #endif
927 
928 #ifdef WRITE_READ_PARSE_PLAN_TREES
929  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
930  {
931  char *str;
932  PlannedStmt *new_plan;
933 
935  new_plan = stringToNodeWithLocations(str);
936  pfree(str);
937 
938  /*
939  * equal() currently does not have routines to compare Plan nodes, so
940  * don't try to test equality here. Perhaps fix someday?
941  */
942 #ifdef NOT_USED
943  /* This checks both outfuncs/readfuncs and the equal() routines... */
944  if (!equal(new_plan, plan))
945  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
946  else
947 #endif
948  plan = new_plan;
949  }
950 #endif
951 
952  /*
953  * Print plan if debugging.
954  */
955  if (Debug_print_plan)
957 
958  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
959 
960  return plan;
961 }
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:500
bool Debug_pretty_print
Definition: guc_tables.c:503
#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 804 of file postgres.c.

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

4153 {
4154  sigjmp_buf local_sigjmp_buf;
4155 
4156  /* these must be volatile to ensure state is preserved across longjmp: */
4157  volatile bool send_ready_for_query = true;
4158  volatile bool idle_in_transaction_timeout_enabled = false;
4159  volatile bool idle_session_timeout_enabled = false;
4160 
4161  Assert(dbname != NULL);
4162  Assert(username != NULL);
4163 
4165 
4166  /*
4167  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4168  * has already set up BlockSig and made that the active signal mask.)
4169  *
4170  * Note that postmaster blocked all signals before forking child process,
4171  * so there is no race condition whereby we might receive a signal before
4172  * we have set up the handler.
4173  *
4174  * Also note: it's best not to use any signals that are SIG_IGNored in the
4175  * postmaster. If such a signal arrives before we are able to change the
4176  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4177  * handler in the postmaster to reserve the signal. (Of course, this isn't
4178  * an issue for signals that are locally generated, such as SIGALRM and
4179  * SIGPIPE.)
4180  */
4181  if (am_walsender)
4182  WalSndSignals();
4183  else
4184  {
4186  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4187  pqsignal(SIGTERM, die); /* cancel current query and exit */
4188 
4189  /*
4190  * In a postmaster child backend, replace SignalHandlerForCrashExit
4191  * with quickdie, so we can tell the client we're dying.
4192  *
4193  * In a standalone backend, SIGQUIT can be generated from the keyboard
4194  * easily, while SIGTERM cannot, so we make both signals do die()
4195  * rather than quickdie().
4196  */
4197  if (IsUnderPostmaster)
4198  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4199  else
4200  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4201  InitializeTimeouts(); /* establishes SIGALRM handler */
4202 
4203  /*
4204  * Ignore failure to write to frontend. Note: if frontend closes
4205  * connection, we will notice it and exit cleanly when control next
4206  * returns to outer loop. This seems safer than forcing exit in the
4207  * midst of output during who-knows-what operation...
4208  */
4213 
4214  /*
4215  * Reset some signals that are accepted by postmaster but not by
4216  * backend
4217  */
4218  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4219  * platforms */
4220  }
4221 
4222  /* Early initialization */
4223  BaseInit();
4224 
4225  /* We need to allow SIGINT, etc during the initial transaction */
4226  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4227 
4228  /*
4229  * General initialization.
4230  *
4231  * NOTE: if you are tempted to add code in this vicinity, consider putting
4232  * it inside InitPostgres() instead. In particular, anything that
4233  * involves database access should be there, not here.
4234  *
4235  * Honor session_preload_libraries if not dealing with a WAL sender.
4236  */
4237  InitPostgres(dbname, InvalidOid, /* database to connect to */
4238  username, InvalidOid, /* role to connect as */
4240  NULL); /* no out_dbname */
4241 
4242  /*
4243  * If the PostmasterContext is still around, recycle the space; we don't
4244  * need it anymore after InitPostgres completes.
4245  */
4246  if (PostmasterContext)
4247  {
4249  PostmasterContext = NULL;
4250  }
4251 
4253 
4254  /*
4255  * Now all GUC states are fully set up. Report them to client if
4256  * appropriate.
4257  */
4259 
4260  /*
4261  * Also set up handler to log session end; we have to wait till now to be
4262  * sure Log_disconnections has its final value.
4263  */
4266 
4268 
4269  /* Perform initialization specific to a WAL sender process. */
4270  if (am_walsender)
4271  InitWalSender();
4272 
4273  /*
4274  * Send this backend's cancellation info to the frontend.
4275  */
4277  {
4279 
4283  pq_endmessage(&buf);
4284  /* Need not flush since ReadyForQuery will do it. */
4285  }
4286 
4287  /* Welcome banner for standalone case */
4289  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4290 
4291  /*
4292  * Create the memory context we will use in the main loop.
4293  *
4294  * MessageContext is reset once per iteration of the main loop, ie, upon
4295  * completion of processing of each command message from the client.
4296  */
4298  "MessageContext",
4300 
4301  /*
4302  * Create memory context and buffer used for RowDescription messages. As
4303  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4304  * frequently executed for ever single statement, we don't want to
4305  * allocate a separate buffer every time.
4306  */
4308  "RowDescriptionContext",
4313 
4314  /* Fire any defined login event triggers, if appropriate */
4316 
4317  /*
4318  * POSTGRES main processing loop begins here
4319  *
4320  * If an exception is encountered, processing resumes here so we abort the
4321  * current transaction and start a new one.
4322  *
4323  * You might wonder why this isn't coded as an infinite loop around a
4324  * PG_TRY construct. The reason is that this is the bottom of the
4325  * exception stack, and so with PG_TRY there would be no exception handler
4326  * in force at all during the CATCH part. By leaving the outermost setjmp
4327  * always active, we have at least some chance of recovering from an error
4328  * during error recovery. (If we get into an infinite loop thereby, it
4329  * will soon be stopped by overflow of elog.c's internal state stack.)
4330  *
4331  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4332  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4333  * is essential in case we longjmp'd out of a signal handler on a platform
4334  * where that leaves the signal blocked. It's not redundant with the
4335  * unblock in AbortTransaction() because the latter is only called if we
4336  * were inside a transaction.
4337  */
4338 
4339  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4340  {
4341  /*
4342  * NOTE: if you are tempted to add more code in this if-block,
4343  * consider the high probability that it should be in
4344  * AbortTransaction() instead. The only stuff done directly here
4345  * should be stuff that is guaranteed to apply *only* for outer-level
4346  * error recovery, such as adjusting the FE/BE protocol status.
4347  */
4348 
4349  /* Since not using PG_TRY, must reset error stack by hand */
4350  error_context_stack = NULL;
4351 
4352  /* Prevent interrupts while cleaning up */
4353  HOLD_INTERRUPTS();
4354 
4355  /*
4356  * Forget any pending QueryCancel request, since we're returning to
4357  * the idle loop anyway, and cancel any active timeout requests. (In
4358  * future we might want to allow some timeout requests to survive, but
4359  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4360  * we got here because of a query cancel interrupting the SIGALRM
4361  * interrupt handler.) Note in particular that we must clear the
4362  * statement and lock timeout indicators, to prevent any future plain
4363  * query cancels from being misreported as timeouts in case we're
4364  * forgetting a timeout cancel.
4365  */
4366  disable_all_timeouts(false); /* do first to avoid race condition */
4367  QueryCancelPending = false;
4368  idle_in_transaction_timeout_enabled = false;
4369  idle_session_timeout_enabled = false;
4370 
4371  /* Not reading from the client anymore. */
4372  DoingCommandRead = false;
4373 
4374  /* Make sure libpq is in a good state */
4375  pq_comm_reset();
4376 
4377  /* Report the error to the client and/or server log */
4378  EmitErrorReport();
4379 
4380  /*
4381  * If Valgrind noticed something during the erroneous query, print the
4382  * query string, assuming we have one.
4383  */
4385 
4386  /*
4387  * Make sure debug_query_string gets reset before we possibly clobber
4388  * the storage it points at.
4389  */
4390  debug_query_string = NULL;
4391 
4392  /*
4393  * Abort the current transaction in order to recover.
4394  */
4396 
4397  if (am_walsender)
4399 
4401 
4402  /*
4403  * We can't release replication slots inside AbortTransaction() as we
4404  * need to be able to start and abort transactions while having a slot
4405  * acquired. But we never need to hold them across top level errors,
4406  * so releasing here is fine. There also is a before_shmem_exit()
4407  * callback ensuring correct cleanup on FATAL errors.
4408  */
4409  if (MyReplicationSlot != NULL)
4411 
4412  /* We also want to cleanup temporary slots on error. */
4413  ReplicationSlotCleanup(false);
4414 
4416 
4417  /*
4418  * Now return to normal top-level context and clear ErrorContext for
4419  * next time.
4420  */
4422  FlushErrorState();
4423 
4424  /*
4425  * If we were handling an extended-query-protocol message, initiate
4426  * skip till next Sync. This also causes us not to issue
4427  * ReadyForQuery (until we get Sync).
4428  */
4430  ignore_till_sync = true;
4431 
4432  /* We don't have a transaction command open anymore */
4433  xact_started = false;
4434 
4435  /*
4436  * If an error occurred while we were reading a message from the
4437  * client, we have potentially lost track of where the previous
4438  * message ends and the next one begins. Even though we have
4439  * otherwise recovered from the error, we cannot safely read any more
4440  * messages from the client, so there isn't much we can do with the
4441  * connection anymore.
4442  */
4443  if (pq_is_reading_msg())
4444  ereport(FATAL,
4445  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4446  errmsg("terminating connection because protocol synchronization was lost")));
4447 
4448  /* Now we can allow interrupts again */
4450  }
4451 
4452  /* We can now handle ereport(ERROR) */
4453  PG_exception_stack = &local_sigjmp_buf;
4454 
4455  if (!ignore_till_sync)
4456  send_ready_for_query = true; /* initially, or after error */
4457 
4458  /*
4459  * Non-error queries loop here.
4460  */
4461 
4462  for (;;)
4463  {
4464  int firstchar;
4465  StringInfoData input_message;
4466 
4467  /*
4468  * At top of loop, reset extended-query-message flag, so that any
4469  * errors encountered in "idle" state don't provoke skip.
4470  */
4472 
4473  /*
4474  * For valgrind reporting purposes, the "current query" begins here.
4475  */
4476 #ifdef USE_VALGRIND
4477  old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4478 #endif
4479 
4480  /*
4481  * Release storage left over from prior query cycle, and create a new
4482  * query input buffer in the cleared MessageContext.
4483  */
4486 
4487  initStringInfo(&input_message);
4488 
4489  /*
4490  * Also consider releasing our catalog snapshot if any, so that it's
4491  * not preventing advance of global xmin while we wait for the client.
4492  */
4494 
4495  /*
4496  * (1) If we've reached idle state, tell the frontend we're ready for
4497  * a new query.
4498  *
4499  * Note: this includes fflush()'ing the last of the prior output.
4500  *
4501  * This is also a good time to flush out collected statistics to the
4502  * cumulative stats system, and to update the PS stats display. We
4503  * avoid doing those every time through the message loop because it'd
4504  * slow down processing of batched messages, and because we don't want
4505  * to report uncommitted updates (that confuses autovacuum). The
4506  * notification processor wants a call too, if we are not in a
4507  * transaction block.
4508  *
4509  * Also, if an idle timeout is enabled, start the timer for that.
4510  */
4511  if (send_ready_for_query)
4512  {
4514  {
4515  set_ps_display("idle in transaction (aborted)");
4517 
4518  /* Start the idle-in-transaction timer */
4521  {
4522  idle_in_transaction_timeout_enabled = true;
4525  }
4526  }
4528  {
4529  set_ps_display("idle in transaction");
4531 
4532  /* Start the idle-in-transaction timer */
4535  {
4536  idle_in_transaction_timeout_enabled = true;
4539  }
4540  }
4541  else
4542  {
4543  long stats_timeout;
4544 
4545  /*
4546  * Process incoming notifies (including self-notifies), if
4547  * any, and send relevant messages to the client. Doing it
4548  * here helps ensure stable behavior in tests: if any notifies
4549  * were received during the just-finished transaction, they'll
4550  * be seen by the client before ReadyForQuery is.
4551  */
4553  ProcessNotifyInterrupt(false);
4554 
4555  /*
4556  * Check if we need to report stats. If pgstat_report_stat()
4557  * decides it's too soon to flush out pending stats / lock
4558  * contention prevented reporting, it'll tell us when we
4559  * should try to report stats again (so that stats updates
4560  * aren't unduly delayed if the connection goes idle for a
4561  * long time). We only enable the timeout if we don't already
4562  * have a timeout in progress, because we don't disable the
4563  * timeout below. enable_timeout_after() needs to determine
4564  * the current timestamp, which can have a negative
4565  * performance impact. That's OK because pgstat_report_stat()
4566  * won't have us wake up sooner than a prior call.
4567  */
4568  stats_timeout = pgstat_report_stat(false);
4569  if (stats_timeout > 0)
4570  {
4573  stats_timeout);
4574  }
4575  else
4576  {
4577  /* all stats flushed, no need for the timeout */
4580  }
4581 
4582  set_ps_display("idle");
4584 
4585  /* Start the idle-session timer */
4586  if (IdleSessionTimeout > 0)
4587  {
4588  idle_session_timeout_enabled = true;
4591  }
4592  }
4593 
4594  /* Report any recently-changed GUC options */
4596 
4598  send_ready_for_query = false;
4599  }
4600 
4601  /*
4602  * (2) Allow asynchronous signals to be executed immediately if they
4603  * come in while we are waiting for client input. (This must be
4604  * conditional since we don't want, say, reads on behalf of COPY FROM
4605  * STDIN doing the same thing.)
4606  */
4607  DoingCommandRead = true;
4608 
4609  /*
4610  * (3) read a command (loop blocks here)
4611  */
4612  firstchar = ReadCommand(&input_message);
4613 
4614  /*
4615  * (4) turn off the idle-in-transaction and idle-session timeouts if
4616  * active. We do this before step (5) so that any last-moment timeout
4617  * is certain to be detected in step (5).
4618  *
4619  * At most one of these timeouts will be active, so there's no need to
4620  * worry about combining the timeout.c calls into one.
4621  */
4622  if (idle_in_transaction_timeout_enabled)
4623  {
4625  idle_in_transaction_timeout_enabled = false;
4626  }
4627  if (idle_session_timeout_enabled)
4628  {
4630  idle_session_timeout_enabled = false;
4631  }
4632 
4633  /*
4634  * (5) disable async signal conditions again.
4635  *
4636  * Query cancel is supposed to be a no-op when there is no query in
4637  * progress, so if a query cancel arrived while we were idle, just
4638  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4639  * it's called when DoingCommandRead is set, so check for interrupts
4640  * before resetting DoingCommandRead.
4641  */
4643  DoingCommandRead = false;
4644 
4645  /*
4646  * (6) check for any other interesting events that happened while we
4647  * slept.
4648  */
4649  if (ConfigReloadPending)
4650  {
4651  ConfigReloadPending = false;
4653  }
4654 
4655  /*
4656  * (7) process the command. But ignore it if we're skipping till
4657  * Sync.
4658  */
4659  if (ignore_till_sync && firstchar != EOF)
4660  continue;
4661 
4662  switch (firstchar)
4663  {
4664  case PqMsg_Query:
4665  {
4666  const char *query_string;
4667 
4668  /* Set statement_timestamp() */
4670 
4671  query_string = pq_getmsgstring(&input_message);
4672  pq_getmsgend(&input_message);
4673 
4674  if (am_walsender)
4675  {
4676  if (!exec_replication_command(query_string))
4677  exec_simple_query(query_string);
4678  }
4679  else
4680  exec_simple_query(query_string);
4681 
4682  valgrind_report_error_query(query_string);
4683 
4684  send_ready_for_query = true;
4685  }
4686  break;
4687 
4688  case PqMsg_Parse:
4689  {
4690  const char *stmt_name;
4691  const char *query_string;
4692  int numParams;
4693  Oid *paramTypes = NULL;
4694 
4695  forbidden_in_wal_sender(firstchar);
4696 
4697  /* Set statement_timestamp() */
4699 
4700  stmt_name = pq_getmsgstring(&input_message);
4701  query_string = pq_getmsgstring(&input_message);
4702  numParams = pq_getmsgint(&input_message, 2);
4703  if (numParams > 0)
4704  {
4705  paramTypes = palloc_array(Oid, numParams);
4706  for (int i = 0; i < numParams; i++)
4707  paramTypes[i] = pq_getmsgint(&input_message, 4);
4708  }
4709  pq_getmsgend(&input_message);
4710 
4711  exec_parse_message(query_string, stmt_name,
4712  paramTypes, numParams);
4713 
4714  valgrind_report_error_query(query_string);
4715  }
4716  break;
4717 
4718  case PqMsg_Bind:
4719  forbidden_in_wal_sender(firstchar);
4720 
4721  /* Set statement_timestamp() */
4723 
4724  /*
4725  * this message is complex enough that it seems best to put
4726  * the field extraction out-of-line
4727  */
4728  exec_bind_message(&input_message);
4729 
4730  /* exec_bind_message does valgrind_report_error_query */
4731  break;
4732 
4733  case PqMsg_Execute:
4734  {
4735  const char *portal_name;
4736  int max_rows;
4737 
4738  forbidden_in_wal_sender(firstchar);
4739 
4740  /* Set statement_timestamp() */
4742 
4743  portal_name = pq_getmsgstring(&input_message);
4744  max_rows = pq_getmsgint(&input_message, 4);
4745  pq_getmsgend(&input_message);
4746 
4747  exec_execute_message(portal_name, max_rows);
4748 
4749  /* exec_execute_message does valgrind_report_error_query */
4750  }
4751  break;
4752 
4753  case PqMsg_FunctionCall:
4754  forbidden_in_wal_sender(firstchar);
4755 
4756  /* Set statement_timestamp() */
4758 
4759  /* Report query to various monitoring facilities. */
4761  set_ps_display("<FASTPATH>");
4762 
4763  /* start an xact for this function invocation */
4765 
4766  /*
4767  * Note: we may at this point be inside an aborted
4768  * transaction. We can't throw error for that until we've
4769  * finished reading the function-call message, so
4770  * HandleFunctionRequest() must check for it after doing so.
4771  * Be careful not to do anything that assumes we're inside a
4772  * valid transaction here.
4773  */
4774 
4775  /* switch back to message context */
4777 
4778  HandleFunctionRequest(&input_message);
4779 
4780  /* commit the function-invocation transaction */
4782 
4783  valgrind_report_error_query("fastpath function call");
4784 
4785  send_ready_for_query = true;
4786  break;
4787 
4788  case PqMsg_Close:
4789  {
4790  int close_type;
4791  const char *close_target;
4792 
4793  forbidden_in_wal_sender(firstchar);
4794 
4795  close_type = pq_getmsgbyte(&input_message);
4796  close_target = pq_getmsgstring(&input_message);
4797  pq_getmsgend(&input_message);
4798 
4799  switch (close_type)
4800  {
4801  case 'S':
4802  if (close_target[0] != '\0')
4803  DropPreparedStatement(close_target, false);
4804  else
4805  {
4806  /* special-case the unnamed statement */
4808  }
4809  break;
4810  case 'P':
4811  {
4812  Portal portal;
4813 
4814  portal = GetPortalByName(close_target);
4815  if (PortalIsValid(portal))
4816  PortalDrop(portal, false);
4817  }
4818  break;
4819  default:
4820  ereport(ERROR,
4821  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4822  errmsg("invalid CLOSE message subtype %d",
4823  close_type)));
4824  break;
4825  }
4826 
4829 
4830  valgrind_report_error_query("CLOSE message");
4831  }
4832  break;
4833 
4834  case PqMsg_Describe:
4835  {
4836  int describe_type;
4837  const char *describe_target;
4838 
4839  forbidden_in_wal_sender(firstchar);
4840 
4841  /* Set statement_timestamp() (needed for xact) */
4843 
4844  describe_type = pq_getmsgbyte(&input_message);
4845  describe_target = pq_getmsgstring(&input_message);
4846  pq_getmsgend(&input_message);
4847 
4848  switch (describe_type)
4849  {
4850  case 'S':
4851  exec_describe_statement_message(describe_target);
4852  break;
4853  case 'P':
4854  exec_describe_portal_message(describe_target);
4855  break;
4856  default:
4857  ereport(ERROR,
4858  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4859  errmsg("invalid DESCRIBE message subtype %d",
4860  describe_type)));
4861  break;
4862  }
4863 
4864  valgrind_report_error_query("DESCRIBE message");
4865  }
4866  break;
4867 
4868  case PqMsg_Flush:
4869  pq_getmsgend(&input_message);
4871  pq_flush();
4872  break;
4873 
4874  case PqMsg_Sync:
4875  pq_getmsgend(&input_message);
4877  valgrind_report_error_query("SYNC message");
4878  send_ready_for_query = true;
4879  break;
4880 
4881  /*
4882  * 'X' means that the frontend is closing down the socket. EOF
4883  * means unexpected loss of frontend connection. Either way,
4884  * perform normal shutdown.
4885  */
4886  case EOF:
4887 
4888  /* for the cumulative statistics system */
4890 
4891  /* FALLTHROUGH */
4892 
4893  case PqMsg_Terminate:
4894 
4895  /*
4896  * Reset whereToSendOutput to prevent ereport from attempting
4897  * to send any more messages to client.
4898  */
4901 
4902  /*
4903  * NOTE: if you are tempted to add more code here, DON'T!
4904  * Whatever you had in mind to do should be set up as an
4905  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4906  * it will fail to be called during other backend-shutdown
4907  * scenarios.
4908  */
4909  proc_exit(0);
4910 
4911  case PqMsg_CopyData:
4912  case PqMsg_CopyDone:
4913  case PqMsg_CopyFail:
4914 
4915  /*
4916  * Accept but ignore these messages, per protocol spec; we
4917  * probably got here because a COPY failed, and the frontend
4918  * is still sending data.
4919  */
4920  break;
4921 
4922  default:
4923  ereport(FATAL,
4924  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4925  errmsg("invalid frontend message type %d",
4926  firstchar)));
4927  }
4928  } /* end of input-reading loop */
4929 }
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:1670
void FlushErrorState(void)
Definition: elog.c:1834
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:50
int MyProcPid
Definition: globals.c:45
bool IsUnderPostmaster
Definition: globals.c:117
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
Oid MyDatabaseId
Definition: globals.c:91
void BeginReportingGUCOptions(void)
Definition: guc.c:2548
void ReportChangedGUCOptions(void)
Definition: guc.c:2598
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void proc_exit(int code)
Definition: ipc.c:104
void jit_reset_after_error(void)
Definition: jit.c:127
#define pq_flush()
Definition: libpq.h:46
#define pq_comm_reset()
Definition: libpq.h:45
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
MemoryContext PostmasterContext
Definition: mcxt.c:151
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:449
@ InitProcessing
Definition: miscadmin.h:448
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:476
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
const char * username
Definition: pgbench.c:296
long pgstat_report_stat(bool force)
Definition: pgstat.c:579
@ DISCONNECT_CLIENT_EOF
Definition: pgstat.h:80
void pgstat_report_connect(Oid dboid)
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:2597
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2875
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5109
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4939
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2085
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3019
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3002
static bool ignore_till_sync
Definition: postgres.c:151
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1013
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1391
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1626
void die(SIGNAL_ARGS)
Definition: postgres.c:2972
static MemoryContext row_description_context
Definition: postgres.c:170
static bool doing_extended_query_message
Definition: postgres.c:150
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2691
bool Log_disconnections
Definition: postgres.c:93
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:488
void BaseInit(void)
Definition: postinit.c:645
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:736
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1180
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:635
#define PqMsg_CloseComplete
Definition: protocol.h:40
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_Describe
Definition: protocol.h:21
#define PqMsg_Parse
Definition: protocol.h:25
#define PqMsg_Bind
Definition: protocol.h:19
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_CopyFail
Definition: protocol.h:29
#define PqMsg_Flush
Definition: protocol.h:24
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_Query
Definition: protocol.h:26
#define PqMsg_Terminate
Definition: protocol.h:28
#define PqMsg_Execute
Definition: protocol.h:22
#define PqMsg_Close
Definition: protocol.h:20
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotRelease(void)
Definition: slot.c:652
void ReplicationSlotCleanup(bool synced_only)
Definition: slot.c:745
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:443
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:60
char * dbname
Definition: streamutil.c: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:1977
void WalSndSignals(void)
Definition: walsender.c:3590
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:4933
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:911
void AbortCurrentTransaction(void)
Definition: xact.c:3387

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(), 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, MyDatabaseId, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc_array, PG_exception_stack, 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 4042 of file postgres.c.

4044 {
4045  const char *dbname = NULL;
4046 
4048 
4049  /* Initialize startup process environment. */
4050  InitStandaloneProcess(argv[0]);
4051 
4052  /*
4053  * Set default values for command-line options.
4054  */
4056 
4057  /*
4058  * Parse command-line options.
4059  */
4061 
4062  /* Must have gotten a database name, or have a default (the username) */
4063  if (dbname == NULL)
4064  {
4065  dbname = username;
4066  if (dbname == NULL)
4067  ereport(FATAL,
4068  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4069  errmsg("%s: no database nor user name specified",
4070  progname)));
4071  }
4072 
4073  /* Acquire configuration parameters */
4075  proc_exit(1);
4076 
4077  /*
4078  * Validate we have been given a reasonable-looking DataDir and change
4079  * into it.
4080  */
4081  checkDataDir();
4082  ChangeToDataDir();
4083 
4084  /*
4085  * Create lockfile for data directory.
4086  */
4087  CreateDataDirLockFile(false);
4088 
4089  /* read control file (error checking and contains config ) */
4090  LocalProcessControlFile(false);
4091 
4092  /*
4093  * process any libraries that should be preloaded at postmaster start
4094  */
4096 
4097  /* Initialize MaxBackends */
4099 
4100  /*
4101  * Give preloaded libraries a chance to request additional shared memory.
4102  */
4104 
4105  /*
4106  * Now that loadable modules have had their chance to request additional
4107  * shared memory, determine the value of any runtime-computed GUCs that
4108  * depend on the amount of shared memory required.
4109  */
4111 
4112  /*
4113  * Now that modules have been loaded, we can process any custom resource
4114  * managers specified in the wal_consistency_checking GUC.
4115  */
4117 
4119 
4120  /*
4121  * Remember stand-alone backend startup time,roughly at the same point
4122  * during startup that postmaster does so.
4123  */
4125 
4126  /*
4127  * Create a per-backend PGPROC struct in shared memory. We must do this
4128  * before we can use LWLocks.
4129  */
4130  InitProcess();
4131 
4132  /*
4133  * Now that sufficient infrastructure has been initialized, PostgresMain()
4134  * can do the rest.
4135  */
4137 }
TimestampTz PgStartTime
Definition: timestamp.c:52
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1786
void InitializeGUCOptions(void)
Definition: guc.c:1532
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:369
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:199
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:3790
static const char * userDoption
Definition: postgres.c:161
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4152
void InitializeMaxBackends(void)
Definition: postinit.c:575
void InitProcess(void)
Definition: proc.c:296
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4751
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4813

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

3792 {
3793  bool secure = (ctx == PGC_POSTMASTER);
3794  int errs = 0;
3795  GucSource gucsource;
3796  int flag;
3797 
3798  if (secure)
3799  {
3800  gucsource = PGC_S_ARGV; /* switches came from command line */
3801 
3802  /* Ignore the initial --single argument, if present */
3803  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3804  {
3805  argv++;
3806  argc--;
3807  }
3808  }
3809  else
3810  {
3811  gucsource = PGC_S_CLIENT; /* switches came from client */
3812  }
3813 
3814 #ifdef HAVE_INT_OPTERR
3815 
3816  /*
3817  * Turn this off because it's either printed to stderr and not the log
3818  * where we'd want it, or argv[0] is now "--single", which would make for
3819  * a weird error message. We print our own error message below.
3820  */
3821  opterr = 0;
3822 #endif
3823 
3824  /*
3825  * Parse command-line options. CAUTION: keep this in sync with
3826  * postmaster/postmaster.c (the option sets should not conflict) and with
3827  * the common help() function in main/main.c.
3828  */
3829  while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3830  {
3831  switch (flag)
3832  {
3833  case 'B':
3834  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3835  break;
3836 
3837  case 'b':
3838  /* Undocumented flag used for binary upgrades */
3839  if (secure)
3840  IsBinaryUpgrade = true;
3841  break;
3842 
3843  case 'C':
3844  /* ignored for consistency with the postmaster */
3845  break;
3846 
3847  case 'c':
3848  case '-':
3849  {
3850  char *name,
3851  *value;
3852 
3854  if (!value)
3855  {
3856  if (flag == '-')
3857  ereport(ERROR,
3858  (errcode(ERRCODE_SYNTAX_ERROR),
3859  errmsg("--%s requires a value",
3860  optarg)));
3861  else
3862  ereport(ERROR,
3863  (errcode(ERRCODE_SYNTAX_ERROR),
3864  errmsg("-c %s requires a value",
3865  optarg)));
3866  }
3867  SetConfigOption(name, value, ctx, gucsource);
3868  pfree(name);
3869  pfree(value);
3870  break;
3871  }
3872 
3873  case 'D':
3874  if (secure)
3875  userDoption = strdup(optarg);
3876  break;
3877 
3878  case 'd':
3879  set_debug_options(atoi(optarg), ctx, gucsource);
3880  break;
3881 
3882  case 'E':
3883  if (secure)
3884  EchoQuery = true;
3885  break;
3886 
3887  case 'e':
3888  SetConfigOption("datestyle", "euro", ctx, gucsource);
3889  break;
3890 
3891  case 'F':
3892  SetConfigOption("fsync", "false", ctx, gucsource);
3893  break;
3894 
3895  case 'f':
3896  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3897  errs++;
3898  break;
3899 
3900  case 'h':
3901  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3902  break;
3903 
3904  case 'i':
3905  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3906  break;
3907 
3908  case 'j':
3909  if (secure)
3910  UseSemiNewlineNewline = true;
3911  break;
3912 
3913  case 'k':
3914  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3915  break;
3916 
3917  case 'l':
3918  SetConfigOption("ssl", "true", ctx, gucsource);
3919  break;
3920 
3921  case 'N':
3922  SetConfigOption("max_connections", optarg, ctx, gucsource);
3923  break;
3924 
3925  case 'n':
3926  /* ignored for consistency with postmaster */
3927  break;
3928 
3929  case 'O':
3930  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3931  break;
3932 
3933  case 'P':
3934  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3935  break;
3936 
3937  case 'p':
3938  SetConfigOption("port", optarg, ctx, gucsource);
3939  break;
3940 
3941  case 'r':
3942  /* send output (stdout and stderr) to the given file */
3943  if (secure)
3945  break;
3946 
3947  case 'S':
3948  SetConfigOption("work_mem", optarg, ctx, gucsource);
3949  break;
3950 
3951  case 's':
3952  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3953  break;
3954 
3955  case 'T':
3956  /* ignored for consistency with the postmaster */
3957  break;
3958 
3959  case 't':
3960  {
3961  const char *tmp = get_stats_option_name(optarg);
3962 
3963  if (tmp)
3964  SetConfigOption(tmp, "true", ctx, gucsource);
3965  else
3966  errs++;
3967  break;
3968  }
3969 
3970  case 'v':
3971 
3972  /*
3973  * -v is no longer used in normal operation, since
3974  * FrontendProtocol is already set before we get here. We keep
3975  * the switch only for possible use in standalone operation,
3976  * in case we ever support using normal FE/BE protocol with a
3977  * standalone backend.
3978  */
3979  if (secure)
3981  break;
3982 
3983  case 'W':
3984  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3985  break;
3986 
3987  default:
3988  errs++;
3989  break;
3990  }
3991 
3992  if (errs)
3993  break;
3994  }
3995 
3996  /*
3997  * Optional database name should be there only if *dbname is NULL.
3998  */
3999  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
4000  *dbname = strdup(argv[optind++]);
4001 
4002  if (errs || argc != optind)
4003  {
4004  if (errs)
4005  optind--; /* complain about the previous argument */
4006 
4007  /* spell the error message a bit differently depending on context */
4008  if (IsUnderPostmaster)
4009  ereport(FATAL,
4010  errcode(ERRCODE_SYNTAX_ERROR),
4011  errmsg("invalid command-line argument for server process: %s", argv[optind]),
4012  errhint("Try \"%s --help\" for more information.", progname));
4013  else
4014  ereport(FATAL,
4015  errcode(ERRCODE_SYNTAX_ERROR),
4016  errmsg("%s: invalid command-line argument: %s",
4017  progname, argv[optind]),
4018  errhint("Try \"%s --help\" for more information.", progname));
4019  }
4020 
4021  /*
4022  * Reset getopt(3) library so that it will work correctly in subprocesses
4023  * or when this function is called a second time with another array.
4024  */
4025  optind = 1;
4026 #ifdef HAVE_INT_OPTRESET
4027  optreset = 1; /* some systems need this too */
4028 #endif
4029 }
bool IsBinaryUpgrade
Definition: globals.c:118
ProtocolVersion FrontendProtocol
Definition: globals.c:28
char OutputFileName[MAXPGPATH]
Definition: globals.c:76
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4285
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6321
GucSource
Definition: guc.h:108
@ PGC_S_ARGV
Definition: guc.h:113
@ PGC_S_CLIENT
Definition: guc.h:118
static struct @155 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:3679
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3708
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3750
uint32 ProtocolVersion
Definition: pqcomm.h:99
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 509 of file postgres.c.

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

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

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

Referenced by secure_write().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3244 of file postgres.c.

3245 {
3246  /* OK to accept any interrupts now? */
3247  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3248  return;
3249  InterruptPending = false;
3250 
3251  if (ProcDiePending)
3252  {
3253  ProcDiePending = false;
3254  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3255  LockErrorCleanup();
3256  /* As in quickdie, don't risk sending to client during auth */
3260  ereport(FATAL,
3261  (errcode(ERRCODE_QUERY_CANCELED),
3262  errmsg("canceling authentication due to timeout")));
3263  else if (AmAutoVacuumWorkerProcess())
3264  ereport(FATAL,
3265  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3266  errmsg("terminating autovacuum process due to administrator command")));
3267  else if (IsLogicalWorker())
3268  ereport(FATAL,
3269  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3270  errmsg("terminating logical replication worker due to administrator command")));
3271  else if (IsLogicalLauncher())
3272  {
3273  ereport(DEBUG1,
3274  (errmsg_internal("logical replication launcher shutting down")));
3275 
3276  /*
3277  * The logical replication launcher can be stopped at any time.
3278  * Use exit status 1 so the background worker is restarted.
3279  */
3280  proc_exit(1);
3281  }
3282  else if (AmBackgroundWorkerProcess())
3283  ereport(FATAL,
3284  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3285  errmsg("terminating background worker \"%s\" due to administrator command",
3287  else
3288  ereport(FATAL,
3289  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3290  errmsg("terminating connection due to administrator command")));
3291  }
3292 
3294  {
3296 
3297  /*
3298  * Check for lost connection and re-arm, if still configured, but not
3299  * if we've arrived back at DoingCommandRead state. We don't want to
3300  * wake up idle sessions, and they already know how to detect lost
3301  * connections.
3302  */
3304  {
3305  if (!pq_check_connection())
3306  ClientConnectionLost = true;
3307  else
3310  }
3311  }
3312 
3314  {
3315  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3316  LockErrorCleanup();
3317  /* don't send to client, we already know the connection to be dead. */
3319  ereport(FATAL,
3320  (errcode(ERRCODE_CONNECTION_FAILURE),
3321  errmsg("connection to client lost")));
3322  }
3323 
3324  /*
3325  * Don't allow query cancel interrupts while reading input from the
3326  * client, because we might lose sync in the FE/BE protocol. (Die
3327  * interrupts are OK, because we won't read any further messages from the
3328  * client in that case.)
3329  *
3330  * See similar logic in ProcessRecoveryConflictInterrupts().
3331  */
3333  {
3334  /*
3335  * Re-arm InterruptPending so that we process the cancel request as
3336  * soon as we're done reading the message. (XXX this is seriously
3337  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3338  * can't use that macro directly as the initial test in this function,
3339  * meaning that this code also creates opportunities for other bugs to
3340  * appear.)
3341  */
3342  InterruptPending = true;
3343  }
3344  else if (QueryCancelPending)
3345  {
3346  bool lock_timeout_occurred;
3347  bool stmt_timeout_occurred;
3348 
3349  QueryCancelPending = false;
3350 
3351  /*
3352  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3353  * need to clear both, so always fetch both.
3354  */
3355  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3356  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3357 
3358  /*
3359  * If both were set, we want to report whichever timeout completed
3360  * earlier; this ensures consistent behavior if the machine is slow
3361  * enough that the second timeout triggers before we get here. A tie
3362  * is arbitrarily broken in favor of reporting a lock timeout.
3363  */
3364  if (lock_timeout_occurred && stmt_timeout_occurred &&
3366  lock_timeout_occurred = false; /* report stmt timeout */
3367 
3368  if (lock_timeout_occurred)
3369  {
3370  LockErrorCleanup();
3371  ereport(ERROR,
3372  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3373  errmsg("canceling statement due to lock timeout")));
3374  }
3375  if (stmt_timeout_occurred)
3376  {
3377  LockErrorCleanup();
3378  ereport(ERROR,
3379  (errcode(ERRCODE_QUERY_CANCELED),
3380  errmsg("canceling statement due to statement timeout")));
3381  }
3383  {
3384  LockErrorCleanup();
3385  ereport(ERROR,
3386  (errcode(ERRCODE_QUERY_CANCELED),
3387  errmsg("canceling autovacuum task")));
3388  }
3389 
3390  /*
3391  * If we are reading a command from the client, just ignore the cancel
3392  * request --- sending an extra error message won't accomplish
3393  * anything. Otherwise, go ahead and throw the error.
3394  */
3395  if (!DoingCommandRead)
3396  {
3397  LockErrorCleanup();
3398  ereport(ERROR,
3399  (errcode(ERRCODE_QUERY_CANCELED),
3400  errmsg("canceling statement due to user request")));
3401  }
3402  }
3403 
3406 
3408  {
3409  /*
3410  * If the GUC has been reset to zero, ignore the signal. This is
3411  * important because the GUC update itself won't disable any pending
3412  * interrupt. We need to unset the flag before the injection point,
3413  * otherwise we could loop in interrupts checking.
3414  */
3417  {
3418  INJECTION_POINT("idle-in-transaction-session-timeout");
3419  ereport(FATAL,
3420  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3421  errmsg("terminating connection due to idle-in-transaction timeout")));
3422  }
3423  }
3424 
3426  {
3427  /* As above, ignore the signal if the GUC has been reset to zero. */
3428  TransactionTimeoutPending = false;
3429  if (TransactionTimeout > 0)
3430  {
3431  INJECTION_POINT("transaction-timeout");
3432  ereport(FATAL,
3433  (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3434  errmsg("terminating connection due to transaction timeout")));
3435  }
3436  }
3437 
3439  {
3440  /* As above, ignore the signal if the GUC has been reset to zero. */
3441  IdleSessionTimeoutPending = false;
3442  if (IdleSessionTimeout > 0)
3443  {
3444  INJECTION_POINT("idle-session-timeout");
3445  ereport(FATAL,
3446  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3447  errmsg("terminating connection due to idle-session timeout")));
3448  }
3449  }
3450 
3451  /*
3452  * If there are pending stats updates and we currently are truly idle
3453  * (matching the conditions in PostgresMain(), report stats now.
3454  */
3457  {
3459  pgstat_report_stat(true);
3460  }
3461 
3464 
3467 
3470 
3473 }
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:4744
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:40
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:39
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:38
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:37
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:42
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:36
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
#define INJECTION_POINT(name)
bool IsLogicalLauncher(void)
Definition: launcher.c:1243
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1288
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:375
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:376
int client_connection_check_interval
Definition: postgres.c:104
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3205
bool ClientAuthInProgress
Definition: postmaster.c:350
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:185
bool pq_check_connection(void)
Definition: pqcomm.c:2053
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:464
void LockErrorCleanup(void)
Definition: proc.c:730
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:827
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:793
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:37

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

Referenced by die().

◆ ProcessRecoveryConflictInterrupt()

static void ProcessRecoveryConflictInterrupt ( ProcSignalReason  reason)
static

Definition at line 3047 of file postgres.c.

3048 {
3049  switch (reason)
3050  {
3052 
3053  /*
3054  * If we aren't waiting for a lock we can never deadlock.
3055  */
3056  if (!IsWaitingForLock())
3057  return;
3058 
3059  /* Intentional fall through to check wait for pin */
3060  /* FALLTHROUGH */
3061 
3063 
3064  /*
3065  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3066  * aren't blocking the Startup process there is nothing more to
3067  * do.
3068  *
3069  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3070  * if we're waiting for locks and the startup process is not
3071  * waiting for buffer pin (i.e., also waiting for locks), we set
3072  * the flag so that ProcSleep() will check for deadlocks.
3073  */
3075  {
3079  return;
3080  }
3081 
3083 
3084  /* Intentional fall through to error handling */
3085  /* FALLTHROUGH */
3086 
3090 
3091  /*
3092  * If we aren't in a transaction any longer then ignore.
3093  */
3095  return;
3096 
3097  /* FALLTHROUGH */
3098 
3100 
3101  /*
3102  * If we're not in a subtransaction then we are OK to throw an
3103  * ERROR to resolve the conflict. Otherwise drop through to the
3104  * FATAL case.
3105  *
3106  * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3107  * always throws an ERROR (ie never promotes to FATAL), though it
3108  * still has to respect QueryCancelHoldoffCount, so it shares this
3109  * code path. Logical decoding slots are only acquired while
3110  * performing logical decoding. During logical decoding no user
3111  * controlled code is run. During [sub]transaction abort, the
3112  * slot is released. Therefore user controlled code cannot
3113  * intercept an error before the replication slot is released.
3114  *
3115  * XXX other times that we can throw just an ERROR *may* be
3116  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3117  * transactions
3118  *
3119  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3120  * p