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/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 223 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 3587 of file postgres.c.

3588 {
3589  long newval_bytes = newval * 1024L;
3590 
3591  max_stack_depth_bytes = newval_bytes;
3592 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:124

References max_stack_depth_bytes, and newval.

◆ assign_transaction_timeout()

void assign_transaction_timeout ( int  newval,
void *  extra 
)

Definition at line 3648 of file postgres.c.

3649 {
3650  if (IsTransactionState())
3651  {
3652  /*
3653  * If transaction_timeout GUC has changed within the transaction block
3654  * enable or disable the timer correspondingly.
3655  */
3658  else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3660  }
3661 }
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:378

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

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

3599 {
3600  if (!WaitEventSetCanReportClosed() && *newval != 0)
3601  {
3602  GUC_check_errdetail("client_connection_check_interval must be set to 0 on this platform.");
3603  return false;
3604  }
3605  return true;
3606 }
#define GUC_check_errdetail
Definition: guc.h:446
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2216

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2378 of file postgres.c.

2379 {
2380  if (log_duration || log_min_duration_sample >= 0 ||
2382  {
2383  long secs;
2384  int usecs;
2385  int msecs;
2386  bool exceeded_duration;
2387  bool exceeded_sample_duration;
2388  bool in_sample = false;
2389 
2392  &secs, &usecs);
2393  msecs = usecs / 1000;
2394 
2395  /*
2396  * This odd-looking test for log_min_duration_* being exceeded is
2397  * designed to avoid integer overflow with very long durations: don't
2398  * compute secs * 1000 until we've verified it will fit in int.
2399  */
2400  exceeded_duration = (log_min_duration_statement == 0 ||
2402  (secs > log_min_duration_statement / 1000 ||
2403  secs * 1000 + msecs >= log_min_duration_statement)));
2404 
2405  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2406  (log_min_duration_sample > 0 &&
2407  (secs > log_min_duration_sample / 1000 ||
2408  secs * 1000 + msecs >= log_min_duration_sample)));
2409 
2410  /*
2411  * Do not log if log_statement_sample_rate = 0. Log a sample if
2412  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2413  * log_statement_sample_rate = 1.
2414  */
2415  if (exceeded_sample_duration)
2416  in_sample = log_statement_sample_rate != 0 &&
2417  (log_statement_sample_rate == 1 ||
2419 
2420  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2421  {
2422  snprintf(msec_str, 32, "%ld.%03d",
2423  secs * 1000 + msecs, usecs % 1000);
2424  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2425  return 2;
2426  else
2427  return 1;
2428  }
2429  }
2430 
2431  return 0;
2432 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1731
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1655
int log_min_duration_statement
Definition: guc_tables.c:524
int log_min_duration_sample
Definition: guc_tables.c:523
double log_statement_sample_rate
Definition: guc_tables.c:528
bool log_duration
Definition: guc_tables.c:496
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:232
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define snprintf
Definition: port.h:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:864
bool xact_is_sampled
Definition: xact.c:290

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

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

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

3634 {
3635  if (*newval &&
3637  {
3638  GUC_check_errdetail("Cannot enable log_statement_stats when "
3639  "log_parser_stats, log_planner_stats, "
3640  "or log_executor_stats is true.");
3641  return false;
3642  }
3643  return true;
3644 }
bool log_parser_stats
Definition: guc_tables.c:502
bool log_planner_stats
Definition: guc_tables.c:503
bool log_executor_stats
Definition: guc_tables.c:504

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

◆ check_max_stack_depth()

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

Definition at line 3570 of file postgres.c.

3571 {
3572  long newval_bytes = *newval * 1024L;
3573  long stack_rlimit = get_stack_depth_rlimit();
3574 
3575  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3576  {
3577  GUC_check_errdetail("max_stack_depth must not exceed %ldkB.",
3578  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3579  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3580  return false;
3581  }
3582  return true;
3583 }
#define GUC_check_errhint
Definition: guc.h:450
long get_stack_depth_rlimit(void)
Definition: postgres.c:4956
#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 3523 of file postgres.c.

3524 {
3525  if (stack_is_too_deep())
3526  {
3527  ereport(ERROR,
3528  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3529  errmsg("stack depth limit exceeded"),
3530  errhint("Increase the configuration parameter max_stack_depth (currently %dkB), "
3531  "after ensuring the platform's stack depth limit is adequate.",
3532  max_stack_depth)));
3533  }
3534 }
int errhint(const char *fmt,...)
Definition: elog.c:1322
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int max_stack_depth
Definition: postgres.c:97
bool stack_is_too_deep(void)
Definition: postgres.c:3537

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

Referenced by _jumbleNode(), AlterTypeRecurse(), apply_scanjoin_target_to_paths(), ATAddCheckNNConstraint(), ATExecAddColumn(), ATExecAlterConstrRecurse(), ATExecDropColumn(), ATExecSetNotNull(), CheckAttributeType(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json_internal(), datum_to_jsonb_internal(), dofindsubquery(), dropconstraint_internal(), emit_jsp_gin_entries(), equal(), eval_const_expressions_mutator(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), executeBoolItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator_impl(), expression_tree_walker_impl(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findDependentObjects(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), get_steps_using_prefix_recurse(), gistSplit(), hash_range(), hash_range_extended(), hash_record(), hash_record_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), is_simple_union_all_recurse(), JsonbDeepContains(), lseg_inside_poly(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), p_ishost(), p_isURLPath(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker_impl(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), pull_up_sublinks_jointree_recurse(), pull_up_subqueries_recurse(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker_impl(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), regex_selectivity_sub(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), set_attnotnull(), 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 3619 of file postgres.c.

3620 {
3621  if (*newval && log_statement_stats)
3622  {
3623  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3624  return false;
3625  }
3626  return true;
3627 }
bool log_statement_stats
Definition: guc_tables.c:505

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2971 of file postgres.c.

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

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

5163 {
5166 }
@ 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 2849 of file postgres.c.

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

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

5141 {
5142  /* must be within an xact */
5144 
5145  if (StatementTimeout > 0
5147  {
5150  }
5151  else
5152  {
5155  }
5156 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool xact_started
Definition: postgres.c:136
int StatementTimeout
Definition: proc.c:60
int TransactionTimeout
Definition: proc.c:63

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

2495 {
2497  errdetail("Abort reason: recovery conflict");
2498 
2499  return 0;
2500 }
int errdetail(const char *fmt,...)
Definition: elog.c:1208
PGPROC * MyProc
Definition: proc.c:68
bool recoveryConflictPending
Definition: proc.h:206

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

2442 {
2443  ListCell *parsetree_item;
2444 
2445  foreach(parsetree_item, raw_parsetree_list)
2446  {
2447  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2448 
2449  if (IsA(parsetree->stmt, ExecuteStmt))
2450  {
2451  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2452  PreparedStatement *pstmt;
2453 
2454  pstmt = FetchPreparedStatement(stmt->name, false);
2455  if (pstmt)
2456  {
2457  errdetail("prepare: %s", pstmt->plansource->query_string);
2458  return 0;
2459  }
2460  }
2461  }
2462 
2463  return 0;
2464 }
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:434
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define lfirst_node(type, lc)
Definition: pg_list.h:176
Node * stmt
Definition: parsenodes.h:1861

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

2475 {
2476  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2477  {
2478  char *str;
2479 
2481  if (str && str[0] != '\0')
2482  errdetail("Parameters: %s", str);
2483  }
2484 
2485  return 0;
2486 }
int log_parameter_max_length
Definition: guc_tables.c:525
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335

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

Referenced by exec_bind_message(), and exec_execute_message().

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( ProcSignalReason  reason)
static

Definition at line 2508 of file postgres.c.

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

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

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

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

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

Referenced by PostgresMain().

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2596 of file postgres.c.

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

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

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

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

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

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

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

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

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

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

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

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4934 of file postgres.c.

4935 {
4936  if (am_walsender)
4937  {
4938  if (firstchar == PqMsg_FunctionCall)
4939  ereport(ERROR,
4940  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4941  errmsg("fastpath function calls not supported in a replication connection")));
4942  else
4943  ereport(ERROR,
4944  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4945  errmsg("extended query protocol not supported in a replication connection")));
4946  }
4947 }
#define PqMsg_FunctionCall
Definition: protocol.h:23
bool am_walsender
Definition: walsender.c:118

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

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

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

3743 {
3744  switch (arg[0])
3745  {
3746  case 'p':
3747  if (optarg[1] == 'a') /* "parser" */
3748  return "log_parser_stats";
3749  else if (optarg[1] == 'l') /* "planner" */
3750  return "log_planner_stats";
3751  break;
3752 
3753  case 'e': /* "executor" */
3754  return "log_executor_stats";
3755  break;
3756  }
3757 
3758  return NULL;
3759 }
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 3034 of file postgres.c.

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

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 331 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 243 of file postgres.c.

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

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

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

2820 {
2821  if (list_length(pstmts) == 1)
2822  {
2823  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2824 
2825  if (pstmt->commandType == CMD_UTILITY &&
2827  return true;
2828  }
2829  return false;
2830 }
@ CMD_UTILITY
Definition: nodes.h:260
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 2834 of file postgres.c.

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

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

5105 {
5106  Port *port = MyProcPort;
5107  long secs;
5108  int usecs;
5109  int msecs;
5110  int hours,
5111  minutes,
5112  seconds;
5113 
5116  &secs, &usecs);
5117  msecs = usecs / 1000;
5118 
5119  hours = secs / SECS_PER_HOUR;
5120  secs %= SECS_PER_HOUR;
5121  minutes = secs / SECS_PER_MINUTE;
5122  seconds = secs % SECS_PER_MINUTE;
5123 
5124  ereport(LOG,
5125  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5126  "user=%s database=%s host=%s%s%s",
5127  hours, minutes, seconds, msecs,
5128  port->user_name, port->database_name, port->remote_host,
5129  port->remote_port[0] ? " port=" : "", port->remote_port)));
5130 }
#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:48
static int port
Definition: pg_regress.c:116
Definition: libpq-be.h:147

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

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

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

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

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

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

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

References copyObject, elog(), equal(), log_parser_stats, new_list(), nodeToString(), pfree(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), generate_unaccent_rules::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 971 of file postgres.c.

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

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

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

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

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

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 803 of file postgres.c.

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

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

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 BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4034 of file postgres.c.

4036 {
4037  const char *dbname = NULL;
4038 
4040 
4041  /* Initialize startup process environment. */
4042  InitStandaloneProcess(argv[0]);
4043 
4044  /*
4045  * Set default values for command-line options.
4046  */
4048 
4049  /*
4050  * Parse command-line options.
4051  */
4053 
4054  /* Must have gotten a database name, or have a default (the username) */
4055  if (dbname == NULL)
4056  {
4057  dbname = username;
4058  if (dbname == NULL)
4059  ereport(FATAL,
4060  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4061  errmsg("%s: no database nor user name specified",
4062  progname)));
4063  }
4064 
4065  /* Acquire configuration parameters */
4067  proc_exit(1);
4068 
4069  /*
4070  * Validate we have been given a reasonable-looking DataDir and change
4071  * into it.
4072  */
4073  checkDataDir();
4074  ChangeToDataDir();
4075 
4076  /*
4077  * Create lockfile for data directory.
4078  */
4079  CreateDataDirLockFile(false);
4080 
4081  /* read control file (error checking and contains config ) */
4082  LocalProcessControlFile(false);
4083 
4084  /*
4085  * process any libraries that should be preloaded at postmaster start
4086  */
4088 
4089  /* Initialize MaxBackends */
4091 
4092  /*
4093  * Give preloaded libraries a chance to request additional shared memory.
4094  */
4096 
4097  /*
4098  * Now that loadable modules have had their chance to request additional
4099  * shared memory, determine the value of any runtime-computed GUCs that
4100  * depend on the amount of shared memory required.
4101  */
4103 
4104  /*
4105  * Now that modules have been loaded, we can process any custom resource
4106  * managers specified in the wal_consistency_checking GUC.
4107  */
4109 
4111 
4112  /*
4113  * Remember stand-alone backend startup time,roughly at the same point
4114  * during startup that postmaster does so.
4115  */
4117 
4118  /*
4119  * Create a per-backend PGPROC struct in shared memory. We must do this
4120  * before we can use LWLocks.
4121  */
4122  InitProcess();
4123 
4124  /*
4125  * Now that sufficient infrastructure has been initialized, PostgresMain()
4126  * can do the rest.
4127  */
4129 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1779
void InitializeGUCOptions(void)
Definition: guc.c:1525
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:372
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:202
const char * progname
Definition: main.c:45
void ChangeToDataDir(void)
Definition: miscinit.c:455
void process_shmem_requests(void)
Definition: miscinit.c:1872
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void process_shared_preload_libraries(void)
Definition: miscinit.c:1844
void checkDataDir(void)
Definition: miscinit.c:342
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1456
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3782
static const char * userDoption
Definition: postgres.c:160
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4144
void InitializeMaxBackends(void)
Definition: postinit.c:561
void InitProcess(void)
Definition: proc.c:299
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4686
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4748

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

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

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

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

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

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

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