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/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 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 222 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:123

References max_stack_depth_bytes, and newval.

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2550 of file postgres.c.

2551 {
2554  char *quotedval;
2555 
2556  if (data->paramno < 0)
2557  return;
2558 
2559  /* If we have a textual value, quote it, and trim if necessary */
2560  if (data->paramval)
2561  {
2562  initStringInfo(&buf);
2565  quotedval = buf.data;
2566  }
2567  else
2568  quotedval = NULL;
2569 
2570  if (data->portalName && data->portalName[0] != '\0')
2571  {
2572  if (quotedval)
2573  errcontext("portal \"%s\" parameter $%d = %s",
2574  data->portalName, data->paramno + 1, quotedval);
2575  else
2576  errcontext("portal \"%s\" parameter $%d",
2577  data->portalName, data->paramno + 1);
2578  }
2579  else
2580  {
2581  if (quotedval)
2582  errcontext("unnamed portal parameter $%d = %s",
2583  data->paramno + 1, quotedval);
2584  else
2585  errcontext("unnamed portal parameter $%d",
2586  data->paramno + 1);
2587  }
2588 
2589  if (quotedval)
2590  pfree(quotedval);
2591 }
#define errcontext
Definition: elog.h:196
int log_parameter_max_length_on_error
Definition: guc_tables.c:523
void pfree(void *pointer)
Definition: mcxt.c:1456
void * arg
const void * data
static char * buf
Definition: pg_test_fsync.c:67
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:436
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2172

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2381 of file postgres.c.

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

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

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:499
bool log_planner_stats
Definition: guc_tables.c:500
bool log_executor_stats
Definition: guc_tables.c:501

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:440
long get_stack_depth_rlimit(void)
Definition: postgres.c:4933
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

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:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int max_stack_depth
Definition: postgres.c:96
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(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json_internal(), datum_to_jsonb_internal(), dofindsubquery(), emit_jsp_gin_entries(), equal(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), 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(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), get_steps_using_prefix_recurse(), gistSplit(), hash_range(), hash_range_extended(), hash_record(), hash_record_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), is_simple_union_all_recurse(), JsonbDeepContains(), lseg_inside_poly(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), p_ishost(), p_isURLPath(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker_impl(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), pull_up_sublinks_jointree_recurse(), pull_up_subqueries_recurse(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker_impl(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), regex_selectivity_sub(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), setPath(), split_array(), SplitToVariants(), standard_ProcessUtility(), transformExprRecurse(), transformFromClauseItem(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute_locations_recurse(), TS_execute_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

◆ check_stage_log_stats()

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

Definition at line 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:502

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2974 of file postgres.c.

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

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

5139 {
5142 }
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:784
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:689
@ 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 2852 of file postgres.c.

2853 {
2854  /* paranoia to avoid a dangling pointer in case of error */
2855  if (unnamed_stmt_psrc)
2856  {
2858 
2859  unnamed_stmt_psrc = NULL;
2860  DropCachedPlan(psrc);
2861  }
2862 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:502
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156

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

5118 {
5119  /* must be within an xact */
5121 
5122  if (StatementTimeout > 0)
5123  {
5126  }
5127  else
5128  {
5131  }
5132 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool xact_started
Definition: postgres.c:135
int StatementTimeout
Definition: proc.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:564

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

Referenced by start_xact_command().

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2497 of file postgres.c.

2498 {
2500  errdetail("abort reason: recovery conflict");
2501 
2502  return 0;
2503 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
PGPROC * MyProc
Definition: proc.c:66
bool recoveryConflictPending
Definition: proc.h:211

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4911 of file postgres.c.

4912 {
4913  if (am_walsender)
4914  {
4915  if (firstchar == PqMsg_FunctionCall)
4916  ereport(ERROR,
4917  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4918  errmsg("fastpath function calls not supported in a replication connection")));
4919  else
4920  ereport(ERROR,
4921  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4922  errmsg("extended query protocol not supported in a replication connection")));
4923  }
4924 }
#define PqMsg_FunctionCall
Definition: protocol.h:23
bool am_walsender
Definition: walsender.c:116

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

4934 {
4935 #if defined(HAVE_GETRLIMIT)
4936  static long val = 0;
4937 
4938  /* This won't change after process launch, so check just once */
4939  if (val == 0)
4940  {
4941  struct rlimit rlim;
4942 
4943  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4944  val = -1;
4945  else if (rlim.rlim_cur == RLIM_INFINITY)
4946  val = LONG_MAX;
4947  /* rlim_cur is probably of an unsigned type, so check for overflow */
4948  else if (rlim.rlim_cur >= LONG_MAX)
4949  val = LONG_MAX;
4950  else
4951  val = rlim.rlim_cur;
4952  }
4953  return val;
4954 #else
4955  /* On Windows we set the backend stack size in src/backend/Makefile */
4956  return WIN32_STACK_RLIMIT;
4957 #endif
4958 }
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 3725 of file postgres.c.

3726 {
3727  switch (arg[0])
3728  {
3729  case 'p':
3730  if (optarg[1] == 'a') /* "parser" */
3731  return "log_parser_stats";
3732  else if (optarg[1] == 'l') /* "planner" */
3733  return "log_planner_stats";
3734  break;
3735 
3736  case 'e': /* "executor" */
3737  return "log_executor_stats";
3738  break;
3739  }
3740 
3741  return NULL;
3742 }
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 3045 of file postgres.c.

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

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 330 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 242 of file postgres.c.

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

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

2806 {
2807  if (parsetree && IsA(parsetree, TransactionStmt))
2808  {
2809  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2810 
2811  if (stmt->kind == TRANS_STMT_COMMIT ||
2812  stmt->kind == TRANS_STMT_PREPARE ||
2813  stmt->kind == TRANS_STMT_ROLLBACK ||
2814  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2815  return true;
2816  }
2817  return false;
2818 }
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3534
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3531
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3530
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3535

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

2823 {
2824  if (list_length(pstmts) == 1)
2825  {
2826  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2827 
2828  if (pstmt->commandType == CMD_UTILITY &&
2830  return true;
2831  }
2832  return false;
2833 }
@ CMD_UTILITY
Definition: nodes.h:281
CmdType commandType
Definition: plannodes.h:53
Node * utilityStmt
Definition: plannodes.h:96

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

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

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

5082 {
5083  Port *port = MyProcPort;
5084  long secs;
5085  int usecs;
5086  int msecs;
5087  int hours,
5088  minutes,
5089  seconds;
5090 
5093  &secs, &usecs);
5094  msecs = usecs / 1000;
5095 
5096  hours = secs / SECS_PER_HOUR;
5097  secs %= SECS_PER_HOUR;
5098  minutes = secs / SECS_PER_MINUTE;
5099  seconds = secs % SECS_PER_MINUTE;
5100 
5101  ereport(LOG,
5102  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5103  "user=%s database=%s host=%s%s%s",
5104  hours, minutes, seconds, msecs,
5105  port->user_name, port->database_name, port->remote_host,
5106  port->remote_port[0] ? " port=" : "", port->remote_port)));
5107 }
#define SECS_PER_HOUR
Definition: timestamp.h:126
#define SECS_PER_MINUTE
Definition: timestamp.h:127
TimestampTz MyStartTimestamp
Definition: globals.c:46
struct Port * MyProcPort
Definition: globals.c:47
static int port
Definition: pg_regress.c:109
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 669 of file postgres.c.

674 {
675  Query *query;
676  List *querytree_list;
677 
678  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
679 
680  /*
681  * (1) Perform parse analysis.
682  */
683  if (log_parser_stats)
684  ResetUsage();
685 
686  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
687  queryEnv);
688 
689  if (log_parser_stats)
690  ShowUsage("PARSE ANALYSIS STATISTICS");
691 
692  /*
693  * (2) Rewrite the queries, as necessary
694  */
695  querytree_list = pg_rewrite_query(query);
696 
697  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
698 
699  return querytree_list;
700 }
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:802

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

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

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

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

972 {
973  List *stmt_list = NIL;
974  ListCell *query_list;
975 
976  foreach(query_list, querytrees)
977  {
978  Query *query = lfirst_node(Query, query_list);
979  PlannedStmt *stmt;
980 
981  if (query->commandType == CMD_UTILITY)
982  {
983  /* Utility commands require no planning. */
985  stmt->commandType = CMD_UTILITY;
986  stmt->canSetTag = query->canSetTag;
987  stmt->utilityStmt = query->utilityStmt;
988  stmt->stmt_location = query->stmt_location;
989  stmt->stmt_len = query->stmt_len;
990  stmt->queryId = query->queryId;
991  }
992  else
993  {
994  stmt = pg_plan_query(query, query_string, cursorOptions,
995  boundParams);
996  }
997 
998  stmt_list = lappend(stmt_list, stmt);
999  }
1000 
1001  return stmt_list;
1002 }
List * lappend(List *list, void *datum)
Definition: list.c:338
#define makeNode(_type_)
Definition: nodes.h:176
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:884
int stmt_location
Definition: parsenodes.h:235
CmdType commandType
Definition: parsenodes.h:127
Node * utilityStmt
Definition: parsenodes.h:142

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

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

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

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

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

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, 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, InitializeTimeouts(), InitPostgres(), InitProcessing, initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, 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, 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 4017 of file postgres.c.

4019 {
4020  const char *dbname = NULL;
4021 
4023 
4024  /* Initialize startup process environment. */
4025  InitStandaloneProcess(argv[0]);
4026 
4027  /*
4028  * Set default values for command-line options.
4029  */
4031 
4032  /*
4033  * Parse command-line options.
4034  */
4036 
4037  /* Must have gotten a database name, or have a default (the username) */
4038  if (dbname == NULL)
4039  {
4040  dbname = username;
4041  if (dbname == NULL)
4042  ereport(FATAL,
4043  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4044  errmsg("%s: no database nor user name specified",
4045  progname)));
4046  }
4047 
4048  /* Acquire configuration parameters */
4050  proc_exit(1);
4051 
4052  /*
4053  * Validate we have been given a reasonable-looking DataDir and change
4054  * into it.
4055  */
4056  checkDataDir();
4057  ChangeToDataDir();
4058 
4059  /*
4060  * Create lockfile for data directory.
4061  */
4062  CreateDataDirLockFile(false);
4063 
4064  /* read control file (error checking and contains config ) */
4065  LocalProcessControlFile(false);
4066 
4067  /*
4068  * process any libraries that should be preloaded at postmaster start
4069  */
4071 
4072  /* Initialize MaxBackends */
4074 
4075  /*
4076  * Give preloaded libraries a chance to request additional shared memory.
4077  */
4079 
4080  /*
4081  * Now that loadable modules have had their chance to request additional
4082  * shared memory, determine the value of any runtime-computed GUCs that
4083  * depend on the amount of shared memory required.
4084  */
4086 
4087  /*
4088  * Now that modules have been loaded, we can process any custom resource
4089  * managers specified in the wal_consistency_checking GUC.
4090  */
4092 
4094 
4095  /*
4096  * Remember stand-alone backend startup time,roughly at the same point
4097  * during startup that postmaster does so.
4098  */
4100 
4101  /*
4102  * Create a per-backend PGPROC struct in shared memory. We must do this
4103  * before we can use LWLocks.
4104  */
4105  InitProcess();
4106 
4107  /*
4108  * Now that sufficient infrastructure has been initialized, PostgresMain()
4109  * can do the rest.
4110  */
4112 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1749
void InitializeGUCOptions(void)
Definition: guc.c:1495
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:333
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:175
const char * progname
Definition: main.c:45
void ChangeToDataDir(void)
Definition: miscinit.c:449
void process_shmem_requests(void)
Definition: miscinit.c:1857
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void process_shared_preload_libraries(void)
Definition: miscinit.c:1829
void checkDataDir(void)
Definition: miscinit.c:336
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1441
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3765
static const char * userDoption
Definition: postgres.c:159
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4127
void InitializeMaxBackends(void)
Definition: postinit.c:559
void InitProcess(void)
Definition: proc.c:297
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4426
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4488

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

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

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

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

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

Referenced by secure_write().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3254 of file postgres.c.

3255 {
3256  /* OK to accept any interrupts now? */
3257  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3258  return;
3259  InterruptPending = false;
3260 
3261  if (ProcDiePending)
3262  {
3263  ProcDiePending = false;
3264  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3265  LockErrorCleanup();
3266  /* As in quickdie, don't risk sending to client during auth */
3270  ereport(FATAL,
3271  (errcode(ERRCODE_QUERY_CANCELED),
3272  errmsg("canceling authentication due to timeout")));
3273  else if (IsAutoVacuumWorkerProcess())
3274  ereport(FATAL,
3275  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3276  errmsg("terminating autovacuum process due to administrator command")));
3277  else if (IsLogicalWorker())
3278  ereport(FATAL,
3279  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3280  errmsg("terminating logical replication worker due to administrator command")));
3281  else if (IsLogicalLauncher())
3282  {
3283  ereport(DEBUG1,
3284  (errmsg_internal("logical replication launcher shutting down")));
3285 
3286  /*
3287  * The logical replication launcher can be stopped at any time.
3288  * Use exit status 1 so the background worker is restarted.
3289  */
3290  proc_exit(1);
3291  }
3292  else if (IsBackgroundWorker)
3293  ereport(FATAL,
3294  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3295  errmsg("terminating background worker \"%s\" due to administrator command",
3297  else
3298  ereport(FATAL,
3299  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3300  errmsg("terminating connection due to administrator command")));
3301  }
3302 
3304  {
3306 
3307  /*
3308  * Check for lost connection and re-arm, if still configured, but not
3309  * if we've arrived back at DoingCommandRead state. We don't want to
3310  * wake up idle sessions, and they already know how to detect lost
3311  * connections.
3312  */
3314  {
3315  if (!pq_check_connection())
3316  ClientConnectionLost = true;
3317  else
3320  }
3321  }
3322 
3324  {
3325  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3326  LockErrorCleanup();
3327  /* don't send to client, we already know the connection to be dead. */
3329  ereport(FATAL,
3330  (errcode(ERRCODE_CONNECTION_FAILURE),
3331  errmsg("connection to client lost")));
3332  }
3333 
3334  /*
3335  * Don't allow query cancel interrupts while reading input from the
3336  * client, because we might lose sync in the FE/BE protocol. (Die
3337  * interrupts are OK, because we won't read any further messages from the
3338  * client in that case.)
3339  *
3340  * See similar logic in ProcessRecoveryConflictInterrupts().
3341  */
3343  {
3344  /*
3345  * Re-arm InterruptPending so that we process the cancel request as
3346  * soon as we're done reading the message. (XXX this is seriously
3347  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3348  * can't use that macro directly as the initial test in this function,
3349  * meaning that this code also creates opportunities for other bugs to
3350  * appear.)
3351  */
3352  InterruptPending = true;
3353  }
3354  else if (QueryCancelPending)
3355  {
3356  bool lock_timeout_occurred;
3357  bool stmt_timeout_occurred;
3358 
3359  QueryCancelPending = false;
3360 
3361  /*
3362  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3363  * need to clear both, so always fetch both.
3364  */
3365  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3366  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3367 
3368  /*
3369  * If both were set, we want to report whichever timeout completed
3370  * earlier; this ensures consistent behavior if the machine is slow
3371  * enough that the second timeout triggers before we get here. A tie
3372  * is arbitrarily broken in favor of reporting a lock timeout.
3373  */
3374  if (lock_timeout_occurred && stmt_timeout_occurred &&
3376  lock_timeout_occurred = false; /* report stmt timeout */
3377 
3378  if (lock_timeout_occurred)
3379  {
3380  LockErrorCleanup();
3381  ereport(ERROR,
3382  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3383  errmsg("canceling statement due to lock timeout")));
3384  }
3385  if (stmt_timeout_occurred)
3386  {
3387  LockErrorCleanup();
3388  ereport(ERROR,
3389  (errcode(ERRCODE_QUERY_CANCELED),
3390  errmsg("canceling statement due to statement timeout")));
3391  }
3393  {
3394  LockErrorCleanup();
3395  ereport(ERROR,
3396  (errcode(ERRCODE_QUERY_CANCELED),
3397  errmsg("canceling autovacuum task")));
3398  }
3399 
3400  /*
3401  * If we are reading a command from the client, just ignore the cancel
3402  * request --- sending an extra error message won't accomplish
3403  * anything. Otherwise, go ahead and throw the error.
3404  */
3405  if (!DoingCommandRead)
3406  {
3407  LockErrorCleanup();
3408  ereport(ERROR,
3409  (errcode(ERRCODE_QUERY_CANCELED),
3410  errmsg("canceling statement due to user request")));
3411  }
3412  }
3413 
3416 
3418  {
3419  /*
3420  * If the GUC has been reset to zero, ignore the signal. This is
3421  * important because the GUC update itself won't disable any pending
3422  * interrupt.
3423  */
3425  ereport(FATAL,
3426  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3427  errmsg("terminating connection due to idle-in-transaction timeout")));
3428  else
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:3397
void HandleParallelMessages(void)
Definition: parallel.c:1026
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:117
bool IsLogicalWorker(void)
Definition: worker.c:4744
#define DEBUG1
Definition: elog.h:30
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:39
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:36
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:41
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
bool IsBackgroundWorker
Definition: globals.c:115
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
bool IsLogicalLauncher(void)
Definition: launcher.c:1242
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1199
int client_connection_check_interval
Definition: postgres.c:102
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3215
bool ClientAuthInProgress
Definition: postmaster.c:356
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
bool pq_check_connection(void)
Definition: pqcomm.c:2033
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:468
void LockErrorCleanup(void)
Definition: proc.c:698
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:831
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:797
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:36

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, and whereToSendOutput.

Referenced by die().

◆ ProcessRecoveryConflictInterrupt()

static void ProcessRecoveryConflictInterrupt ( ProcSignalReason  reason)
static

Definition at line 3057 of file postgres.c.

3058 {
3059  switch (reason)
3060  {
3062 
3063  /*
3064  * If we aren't waiting for a lock we can never deadlock.
3065  */
3066  if (!IsWaitingForLock())
3067  return;
3068 
3069  /* Intentional fall through to check wait for pin */
3070  /* FALLTHROUGH */
3071 
3073 
3074  /*
3075  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3076  * aren't blocking the Startup process there is nothing more to
3077  * do.
3078  *
3079  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3080  * if we're waiting for locks and the startup process is not
3081  * waiting for buffer pin (i.e., also waiting for locks), we set
3082  * the flag so that ProcSleep() will check for deadlocks.
3083  */
3085  {
3089  return;
3090  }
3091 
3093 
3094  /* Intentional fall through to error handling */
3095  /* FALLTHROUGH */
3096 
3100 
3101  /*
3102  * If we aren't in a transaction any longer then ignore.
3103  */
3105  return;
3106 
3107  /* FALLTHROUGH */
3108 
3110 
3111  /*
3112  * If we're not in a subtransaction then we are OK to throw an
3113  * ERROR to resolve the conflict. Otherwise drop through to the
3114  * FATAL case.
3115  *
3116  * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3117  * always throws an ERROR (ie never promotes to FATAL), though it
3118  * still has to respect QueryCancelHoldoffCount, so it shares this
3119  * code path. Logical decoding slots are only acquired while
3120  * performing logical decoding. During logical decoding no user
3121  * controlled code is run. During [sub]transaction abort, the
3122  * slot is released. Therefore user controlled code cannot
3123  * intercept an error before the replication slot is released.
3124  *
3125  * XXX other times that we can throw just an ERROR *may* be
3126  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3127  * transactions
3128  *
3129  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3130  * parent transactions and the transaction is not
3131  * transaction-snapshot mode
3132  *
3133  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3134  * cursors open in parent transactions
3135  */
3136  if (reason == PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT ||
3137  !IsSubTransaction())
3138  {
3139  /*
3140  * If we already aborted then we no longer need to cancel. We
3141  * do this here since we do not wish to ignore aborted
3142  * subtransactions, which must cause FATAL, currently.
3143  */
3145  return;
3146 
3147  /*
3148  * If a recovery conflict happens while we are waiting for
3149  * input from the client, the client is presumably just
3150  * sitting idle in a transaction, preventing recovery from
3151  * making progress. We'll drop through to the FATAL case
3152  * below to dislodge it, in that case.
3153  */
3154  if (!DoingCommandRead)
3155  {
3156  /* Avoid losing sync in the FE/BE protocol. */
3157  if (QueryCancelHoldoffCount != 0)
3158  {
3159  /*
3160  * Re-arm and defer this interrupt until later. See
3161  * similar code in ProcessInterrupts().
3162  */
3163  RecoveryConflictPendingReasons[reason] = true;
3164  RecoveryConflictPending = true;
3165  InterruptPending = true;
3166  return;
3167  }
3168 
3169  /*
3170  * We are cleared to throw an ERROR. Either it's the
3171  * logical slot case, or we have a top-level transaction
3172  * that we can abort and a conflict that isn't inherently
3173  * non-retryable.
3174  */
3175  LockErrorCleanup();
3177  ereport(ERROR,
3179  errmsg("canceling statement due to conflict with recovery"),
3180  errdetail_recovery_conflict(reason)));
3181  break;
3182  }
3183  }
3184 
3185  /* Intentional fall through to session cancel */
3186  /* FALLTHROUGH */
3187 
3189 
3190  /*
3191  * Retrying is not possible because the database is dropped, or we
3192  * decided above that we couldn't resolve the conflict with an
3193  * ERROR and fell through. Terminate the session.
3194  */
3196  ereport(FATAL,
3198  ERRCODE_DATABASE_DROPPED :
3200  errmsg("terminating connection due to conflict with recovery"),
3201