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
 

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 int errdetail_recovery_conflict (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 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 RecoveryConflictInterrupt (ProcSignalReason reason)
 
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 bool RecoveryConflictPending = false
 
static bool RecoveryConflictRetryable = true
 
static ProcSignalReason RecoveryConflictReason
 
static MemoryContext row_description_context = NULL
 
static StringInfoData row_description_buf
 
static struct rusage Save_r
 
static struct timeval Save_t
 

Typedef Documentation

◆ BindParamCbData

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3525 of file postgres.c.

3526 {
3527  long newval_bytes = newval * 1024L;
3528 
3529  max_stack_depth_bytes = newval_bytes;
3530 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:119

References max_stack_depth_bytes, and newval.

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2511 of file postgres.c.

2512 {
2515  char *quotedval;
2516 
2517  if (data->paramno < 0)
2518  return;
2519 
2520  /* If we have a textual value, quote it, and trim if necessary */
2521  if (data->paramval)
2522  {
2523  initStringInfo(&buf);
2526  quotedval = buf.data;
2527  }
2528  else
2529  quotedval = NULL;
2530 
2531  if (data->portalName && data->portalName[0] != '\0')
2532  {
2533  if (quotedval)
2534  errcontext("portal \"%s\" parameter $%d = %s",
2535  data->portalName, data->paramno + 1, quotedval);
2536  else
2537  errcontext("portal \"%s\" parameter $%d",
2538  data->portalName, data->paramno + 1);
2539  }
2540  else
2541  {
2542  if (quotedval)
2543  errcontext("unnamed portal parameter $%d = %s",
2544  data->paramno + 1, quotedval);
2545  else
2546  errcontext("unnamed portal parameter $%d",
2547  data->paramno + 1);
2548  }
2549 
2550  if (quotedval)
2551  pfree(quotedval);
2552 }
#define errcontext
Definition: elog.h:196
int log_parameter_max_length_on_error
Definition: guc_tables.c:498
void pfree(void *pointer)
Definition: mcxt.c:1436
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 3536 of file postgres.c.

3537 {
3538  if (!WaitEventSetCanReportClosed() && *newval != 0)
3539  {
3540  GUC_check_errdetail("client_connection_check_interval must be set to 0 on this platform.");
3541  return false;
3542  }
3543  return true;
3544 }
#define GUC_check_errdetail
Definition: guc.h:437
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2138

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2345 of file postgres.c.

2346 {
2347  if (log_duration || log_min_duration_sample >= 0 ||
2349  {
2350  long secs;
2351  int usecs;
2352  int msecs;
2353  bool exceeded_duration;
2354  bool exceeded_sample_duration;
2355  bool in_sample = false;
2356 
2359  &secs, &usecs);
2360  msecs = usecs / 1000;
2361 
2362  /*
2363  * This odd-looking test for log_min_duration_* being exceeded is
2364  * designed to avoid integer overflow with very long durations: don't
2365  * compute secs * 1000 until we've verified it will fit in int.
2366  */
2367  exceeded_duration = (log_min_duration_statement == 0 ||
2369  (secs > log_min_duration_statement / 1000 ||
2370  secs * 1000 + msecs >= log_min_duration_statement)));
2371 
2372  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2373  (log_min_duration_sample > 0 &&
2374  (secs > log_min_duration_sample / 1000 ||
2375  secs * 1000 + msecs >= log_min_duration_sample)));
2376 
2377  /*
2378  * Do not log if log_statement_sample_rate = 0. Log a sample if
2379  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2380  * log_statement_sample_rate = 1.
2381  */
2382  if (exceeded_sample_duration)
2383  in_sample = log_statement_sample_rate != 0 &&
2384  (log_statement_sample_rate == 1 ||
2386 
2387  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2388  {
2389  snprintf(msec_str, 32, "%ld.%03d",
2390  secs * 1000 + msecs, usecs % 1000);
2391  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2392  return 2;
2393  else
2394  return 1;
2395  }
2396  }
2397 
2398  return 0;
2399 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1667
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1582
int log_min_duration_statement
Definition: guc_tables.c:496
int log_min_duration_sample
Definition: guc_tables.c:495
double log_statement_sample_rate
Definition: guc_tables.c:500
bool log_duration
Definition: guc_tables.c:468
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 2306 of file postgres.c.

2307 {
2308  ListCell *stmt_item;
2309 
2310  if (log_statement == LOGSTMT_NONE)
2311  return false;
2312  if (log_statement == LOGSTMT_ALL)
2313  return true;
2314 
2315  /* Else we have to inspect the statement(s) to see whether to log */
2316  foreach(stmt_item, stmt_list)
2317  {
2318  Node *stmt = (Node *) lfirst(stmt_item);
2319 
2321  return true;
2322  }
2323 
2324  return false;
2325 }
#define stmt
Definition: indent_codes.h:59
#define lfirst(lc)
Definition: pg_list.h:172
int log_statement
Definition: postgres.c:89
Definition: nodes.h:129
@ LOGSTMT_NONE
Definition: tcopprot.h:38
@ LOGSTMT_ALL
Definition: tcopprot.h:41
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3243

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

3572 {
3573  if (*newval &&
3575  {
3576  GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3577  "\"log_parser_stats\", \"log_planner_stats\", "
3578  "or \"log_executor_stats\" is true.");
3579  return false;
3580  }
3581  return true;
3582 }
bool log_parser_stats
Definition: guc_tables.c:474
bool log_planner_stats
Definition: guc_tables.c:475
bool log_executor_stats
Definition: guc_tables.c:476

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

3509 {
3510  long newval_bytes = *newval * 1024L;
3511  long stack_rlimit = get_stack_depth_rlimit();
3512 
3513  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3514  {
3515  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3516  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3517  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3518  return false;
3519  }
3520  return true;
3521 }
#define GUC_check_errhint
Definition: guc.h:441
long get_stack_depth_rlimit(void)
Definition: postgres.c:4838
#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 3461 of file postgres.c.

3462 {
3463  if (stack_is_too_deep())
3464  {
3465  ereport(ERROR,
3466  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3467  errmsg("stack depth limit exceeded"),
3468  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3469  "after ensuring the platform's stack depth limit is adequate.",
3470  max_stack_depth)));
3471  }
3472 }
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:92
bool stack_is_too_deep(void)
Definition: postgres.c:3475

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(), datum_to_jsonb(), 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(), 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 3557 of file postgres.c.

3558 {
3559  if (*newval && log_statement_stats)
3560  {
3561  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3562  return false;
3563  }
3564  return true;
3565 }
bool log_statement_stats
Definition: guc_tables.c:477

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2935 of file postgres.c.

2936 {
2937  int save_errno = errno;
2938 
2939  /* Don't joggle the elbow of proc_exit */
2940  if (!proc_exit_inprogress)
2941  {
2942  InterruptPending = true;
2943  ProcDiePending = true;
2944  }
2945 
2946  /* for the cumulative stats system */
2948 
2949  /* If we're still here, waken anything waiting on the process latch */
2950  SetLatch(MyLatch);
2951 
2952  /*
2953  * If we're in single user mode, we want to quit immediately - we can't
2954  * rely on latches as they wouldn't work when stdin/stdout is a file.
2955  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2956  * effort just for the benefit of single user mode.
2957  */
2960 
2961  errno = save_errno;
2962 }
@ 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:607
@ DISCONNECT_KILLED
Definition: pgstat.h:82
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:84
static bool DoingCommandRead
Definition: postgres.c:138
void ProcessInterrupts(void)
Definition: postgres.c:3149

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

5044 {
5047 }
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 2813 of file postgres.c.

2814 {
2815  /* paranoia to avoid a dangling pointer in case of error */
2816  if (unnamed_stmt_psrc)
2817  {
2819 
2820  unnamed_stmt_psrc = NULL;
2821  DropCachedPlan(psrc);
2822  }
2823 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:498
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:152

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

5023 {
5024  /* must be within an xact */
5026 
5027  if (StatementTimeout > 0)
5028  {
5031  }
5032  else
5033  {
5036  }
5037 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool xact_started
Definition: postgres.c:131
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 2461 of file postgres.c.

2462 {
2464  errdetail("abort reason: recovery conflict");
2465 
2466  return 0;
2467 }
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 2408 of file postgres.c.

2409 {
2410  ListCell *parsetree_item;
2411 
2412  foreach(parsetree_item, raw_parsetree_list)
2413  {
2414  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2415 
2416  if (IsA(parsetree->stmt, ExecuteStmt))
2417  {
2418  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2419  PreparedStatement *pstmt;
2420 
2421  pstmt = FetchPreparedStatement(stmt->name, false);
2422  if (pstmt)
2423  {
2424  errdetail("prepare: %s", pstmt->plansource->query_string);
2425  return 0;
2426  }
2427  }
2428  }
2429 
2430  return 0;
2431 }
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:1740

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

2442 {
2443  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2444  {
2445  char *str;
2446 
2448  if (str && str[0] != '\0')
2449  errdetail("parameters: %s", str);
2450  }
2451 
2452  return 0;
2453 }
int log_parameter_max_length
Definition: guc_tables.c:497
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 ( void  )
static

Definition at line 2475 of file postgres.c.

2476 {
2477  switch (RecoveryConflictReason)
2478  {
2480  errdetail("User was holding shared buffer pin for too long.");
2481  break;
2483  errdetail("User was holding a relation lock for too long.");
2484  break;
2486  errdetail("User was or might have been using tablespace that must be dropped.");
2487  break;
2489  errdetail("User query might have needed to see row versions that must be removed.");
2490  break;
2492  errdetail("User transaction caused buffer deadlock with recovery.");
2493  break;
2495  errdetail("User was connected to a database that must be dropped.");
2496  break;
2497  default:
2498  break;
2499  /* no errdetail */
2500  }
2501 
2502  return 0;
2503 }
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:162
@ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
Definition: procsignal.h:45
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:43
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:41
@ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
Definition: procsignal.h:44
@ PROCSIG_RECOVERY_CONFLICT_TABLESPACE
Definition: procsignal.h:42
@ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition: procsignal.h:46

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

Referenced by ProcessInterrupts().

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1592 of file postgres.c.

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

2655 {
2656  Portal portal;
2657 
2658  /*
2659  * Start up a transaction command. (Note that this will normally change
2660  * current memory context.) Nothing happens if we are already in one.
2661  */
2663 
2664  /* Switch back to message context */
2666 
2667  portal = GetPortalByName(portal_name);
2668  if (!PortalIsValid(portal))
2669  ereport(ERROR,
2670  (errcode(ERRCODE_UNDEFINED_CURSOR),
2671  errmsg("portal \"%s\" does not exist", portal_name)));
2672 
2673  /*
2674  * If we are in aborted transaction state, we can't run
2675  * SendRowDescriptionMessage(), because that needs catalog accesses.
2676  * Hence, refuse to Describe portals that return data. (We shouldn't just
2677  * refuse all Describes, since that might break the ability of some
2678  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2679  * blindly Describes whatever it does.)
2680  */
2682  portal->tupDesc)
2683  ereport(ERROR,
2684  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2685  errmsg("current transaction is aborted, "
2686  "commands ignored until end of transaction block"),
2687  errdetail_abort()));
2688 
2690  return; /* can't actually do anything... */
2691 
2692  if (portal->tupDesc)
2694  portal->tupDesc,
2695  FetchPortalTargetList(portal),
2696  portal->formats);
2697  else
2698  pq_putemptymessage('n'); /* NoData */
2699 }
#define PortalIsValid(p)
Definition: portal.h:212
Portal GetPortalByName(const char *name)
Definition: portalmem.c:131
static StringInfoData row_description_buf
Definition: postgres.c:166
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:326
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:166
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(), 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 2560 of file postgres.c.

2561 {
2562  CachedPlanSource *psrc;
2563 
2564  /*
2565  * Start up a transaction command. (Note that this will normally change
2566  * current memory context.) Nothing happens if we are already in one.
2567  */
2569 
2570  /* Switch back to message context */
2572 
2573  /* Find prepared statement */
2574  if (stmt_name[0] != '\0')
2575  {
2576  PreparedStatement *pstmt;
2577 
2578  pstmt = FetchPreparedStatement(stmt_name, true);
2579  psrc = pstmt->plansource;
2580  }
2581  else
2582  {
2583  /* special-case the unnamed statement */
2584  psrc = unnamed_stmt_psrc;
2585  if (!psrc)
2586  ereport(ERROR,
2587  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2588  errmsg("unnamed prepared statement does not exist")));
2589  }
2590 
2591  /* Prepared statements shouldn't have changeable result descs */
2592  Assert(psrc->fixed_result);
2593 
2594  /*
2595  * If we are in aborted transaction state, we can't run
2596  * SendRowDescriptionMessage(), because that needs catalog accesses.
2597  * Hence, refuse to Describe statements that return data. (We shouldn't
2598  * just refuse all Describes, since that might break the ability of some
2599  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2600  * blindly Describes whatever it does.) We can Describe parameters
2601  * without doing anything dangerous, so we don't restrict that.
2602  */
2604  psrc->resultDesc)
2605  ereport(ERROR,
2606  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2607  errmsg("current transaction is aborted, "
2608  "commands ignored until end of transaction block"),
2609  errdetail_abort()));
2610 
2612  return; /* can't actually do anything... */
2613 
2614  /*
2615  * First describe the parameters...
2616  */
2617  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2618  * message type */
2620 
2621  for (int i = 0; i < psrc->num_params; i++)
2622  {
2623  Oid ptype = psrc->param_types[i];
2624 
2625  pq_sendint32(&row_description_buf, (int) ptype);
2626  }
2628 
2629  /*
2630  * Next send RowDescription or NoData to describe the result...
2631  */
2632  if (psrc->resultDesc)
2633  {
2634  List *tlist;
2635 
2636  /* Get the plan's primary targetlist */
2637  tlist = CachedPlanGetTargetList(psrc, NULL);
2638 
2640  psrc->resultDesc,
2641  tlist,
2642  NULL);
2643  }
2644  else
2645  pq_putemptymessage('n'); /* NoData */
2646 }
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1611
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(), 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 2053 of file postgres.c.

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

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

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(), 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 979 of file postgres.c.

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

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

2735 {
2736  /* cancel active statement timeout after each command */
2738 
2739  if (xact_started)
2740  {
2742 
2743 #ifdef MEMORY_CONTEXT_CHECKING
2744  /* Check all memory contexts that weren't freed during commit */
2745  /* (those that were, were checked before being deleted) */
2746  MemoryContextCheck(TopMemoryContext);
2747 #endif
2748 
2749 #ifdef SHOW_MEMORY_STATS
2750  /* Print mem stats after each commit for leak tracking */
2752 #endif
2753 
2754  xact_started = false;
2755  }
2756 }
MemoryContext TopMemoryContext
Definition: mcxt.c:141
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:683
void CommitTransactionCommand(void)
Definition: xact.c:3041

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

2991 {
2992  /* We're not returning, so no need to save errno */
2993  ereport(ERROR,
2994  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2995  errmsg("floating-point exception"),
2996  errdetail("An invalid floating-point operation was signaled. "
2997  "This probably means an out-of-range result or an "
2998  "invalid operation, such as division by zero.")));
2999 }

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

4817 {
4818  if (am_walsender)
4819  {
4820  if (firstchar == 'F')
4821  ereport(ERROR,
4822  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4823  errmsg("fastpath function calls not supported in a replication connection")));
4824  else
4825  ereport(ERROR,
4826  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4827  errmsg("extended query protocol not supported in a replication connection")));
4828  }
4829 }
bool am_walsender
Definition: walsender.c:116

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

Referenced by PostgresMain().

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4838 of file postgres.c.

4839 {
4840 #if defined(HAVE_GETRLIMIT)
4841  static long val = 0;
4842 
4843  /* This won't change after process launch, so check just once */
4844  if (val == 0)
4845  {
4846  struct rlimit rlim;
4847 
4848  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4849  val = -1;
4850  else if (rlim.rlim_cur == RLIM_INFINITY)
4851  val = LONG_MAX;
4852  /* rlim_cur is probably of an unsigned type, so check for overflow */
4853  else if (rlim.rlim_cur >= LONG_MAX)
4854  val = LONG_MAX;
4855  else
4856  val = rlim.rlim_cur;
4857  }
4858  return val;
4859 #else
4860  /* On Windows we set the backend stack size in src/backend/Makefile */
4861  return WIN32_STACK_RLIMIT;
4862 #endif
4863 }
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 3663 of file postgres.c.

3664 {
3665  switch (arg[0])
3666  {
3667  case 'p':
3668  if (optarg[1] == 'a') /* "parser" */
3669  return "log_parser_stats";
3670  else if (optarg[1] == 'l') /* "planner" */
3671  return "log_planner_stats";
3672  break;
3673 
3674  case 'e': /* "executor" */
3675  return "log_executor_stats";
3676  break;
3677  }
3678 
3679  return NULL;
3680 }
PGDLLIMPORT char * optarg
Definition: getopt.c:52

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 298 of file postgres.c.

299 {
300  int c;
301 
302  /*
303  * This will not process catchup interrupts or notifications while
304  * reading. But those can't really be relevant for a standalone backend
305  * anyway. To properly handle SIGTERM there's a hack in die() that
306  * directly processes interrupts at this stage...
307  */
309 
310  c = getc(stdin);
311 
313 
314  return c;
315 }
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:475
char * c

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 210 of file postgres.c.

211 {
212  int c; /* character read from getc() */
213 
214  /*
215  * display a prompt and obtain input from the user
216  */
217  printf("backend> ");
218  fflush(stdout);
219 
220  resetStringInfo(inBuf);
221 
222  /*
223  * Read characters until EOF or the appropriate delimiter is seen.
224  */
225  while ((c = interactive_getc()) != EOF)
226  {
227  if (c == '\n')
228  {
230  {
231  /*
232  * In -j mode, semicolon followed by two newlines ends the
233  * command; otherwise treat newline as regular character.
234  */
235  if (inBuf->len > 1 &&
236  inBuf->data[inBuf->len - 1] == '\n' &&
237  inBuf->data[inBuf->len - 2] == ';')
238  {
239  /* might as well drop the second newline */
240  break;
241  }
242  }
243  else
244  {
245  /*
246  * In plain mode, newline ends the command unless preceded by
247  * backslash.
248  */
249  if (inBuf->len > 0 &&
250  inBuf->data[inBuf->len - 1] == '\\')
251  {
252  /* discard backslash from inBuf */
253  inBuf->data[--inBuf->len] = '\0';
254  /* discard newline too */
255  continue;
256  }
257  else
258  {
259  /* keep the newline character, but end the command */
260  appendStringInfoChar(inBuf, '\n');
261  break;
262  }
263  }
264  }
265 
266  /* Not newline, or newline treated as regular character */
267  appendStringInfoChar(inBuf, (char) c);
268  }
269 
270  /* No input before EOF signal means time to quit. */
271  if (c == EOF && inBuf->len == 0)
272  return EOF;
273 
274  /*
275  * otherwise we have a user query so process it.
276  */
277 
278  /* Add '\0' to make it look the same as message case. */
279  appendStringInfoChar(inBuf, (char) '\0');
280 
281  /*
282  * if the query echo flag was given, print the query..
283  */
284  if (EchoQuery)
285  printf("statement: %s\n", inBuf->data);
286  fflush(stdout);
287 
288  return 'Q';
289 }
static void const char fflush(stdout)
#define printf(...)
Definition: port.h:244
static bool UseSemiNewlineNewline
Definition: postgres.c:157
static bool EchoQuery
Definition: postgres.c:156
static int interactive_getc(void)
Definition: postgres.c:298
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 2766 of file postgres.c.

2767 {
2768  if (parsetree && IsA(parsetree, TransactionStmt))
2769  {
2770  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2771 
2772  if (stmt->kind == TRANS_STMT_COMMIT ||
2773  stmt->kind == TRANS_STMT_PREPARE ||
2774  stmt->kind == TRANS_STMT_ROLLBACK ||
2775  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2776  return true;
2777  }
2778  return false;
2779 }
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3386
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3383
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3382
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3387

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

2784 {
2785  if (list_length(pstmts) == 1)
2786  {
2787  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2788 
2789  if (pstmt->commandType == CMD_UTILITY &&
2791  return true;
2792  }
2793  return false;
2794 }
@ CMD_UTILITY
Definition: nodes.h:281
CmdType commandType
Definition: plannodes.h:53
Node * utilityStmt
Definition: plannodes.h:99

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

2799 {
2800  if (list_length(pstmts) == 1)
2801  {
2802  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2803 
2804  if (pstmt->commandType == CMD_UTILITY &&
2805  IsA(pstmt->utilityStmt, TransactionStmt))
2806  return true;
2807  }
2808  return false;
2809 }

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

4987 {
4988  Port *port = MyProcPort;
4989  long secs;
4990  int usecs;
4991  int msecs;
4992  int hours,
4993  minutes,
4994  seconds;
4995 
4998  &secs, &usecs);
4999  msecs = usecs / 1000;
5000 
5001  hours = secs / SECS_PER_HOUR;
5002  secs %= SECS_PER_HOUR;
5003  minutes = secs / SECS_PER_MINUTE;
5004  seconds = secs % SECS_PER_MINUTE;
5005 
5006  ereport(LOG,
5007  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5008  "user=%s database=%s host=%s%s%s",
5009  hours, minutes, seconds, msecs,
5010  port->user_name, port->database_name, port->remote_host,
5011  port->remote_port[0] ? " port=" : "", port->remote_port)));
5012 }
#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:90
Definition: libpq-be.h:146

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

642 {
643  Query *query;
644  List *querytree_list;
645 
646  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
647 
648  /*
649  * (1) Perform parse analysis.
650  */
651  if (log_parser_stats)
652  ResetUsage();
653 
654  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
655  queryEnv);
656 
657  if (log_parser_stats)
658  ShowUsage("PARSE ANALYSIS STATISTICS");
659 
660  /*
661  * (2) Rewrite the queries, as necessary
662  */
663  querytree_list = pg_rewrite_query(query);
664 
665  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
666 
667  return querytree_list;
668 }
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:770

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

681 {
682  Query *query;
683  List *querytree_list;
684 
685  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
686 
687  /*
688  * (1) Perform parse analysis.
689  */
690  if (log_parser_stats)
691  ResetUsage();
692 
693  query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
694  queryEnv);
695 
696  /*
697  * Check all parameter types got determined.
698  */
699  for (int i = 0; i < *numParams; i++)
700  {
701  Oid ptype = (*paramTypes)[i];
702 
703  if (ptype == InvalidOid || ptype == UNKNOWNOID)
704  ereport(ERROR,
705  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
706  errmsg("could not determine data type of parameter $%d",
707  i + 1)));
708  }
709 
710  if (log_parser_stats)
711  ShowUsage("PARSE ANALYSIS STATISTICS");
712 
713  /*
714  * (2) Rewrite the queries, as necessary
715  */
716  querytree_list = pg_rewrite_query(query);
717 
718  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
719 
720  return querytree_list;
721 }
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 730 of file postgres.c.

735 {
736  Query *query;
737  List *querytree_list;
738 
739  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
740 
741  /*
742  * (1) Perform parse analysis.
743  */
744  if (log_parser_stats)
745  ResetUsage();
746 
747  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
748  queryEnv);
749 
750  if (log_parser_stats)
751  ShowUsage("PARSE ANALYSIS STATISTICS");
752 
753  /*
754  * (2) Rewrite the queries, as necessary
755  */
756  querytree_list = pg_rewrite_query(query);
757 
758  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
759 
760  return querytree_list;
761 }
Query * parse_analyze_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 577 of file postgres.c.

578 {
579  List *raw_parsetree_list;
580 
581  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
582 
583  if (log_parser_stats)
584  ResetUsage();
585 
586  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
587 
588  if (log_parser_stats)
589  ShowUsage("PARSER STATISTICS");
590 
591 #ifdef COPY_PARSE_PLAN_TREES
592  /* Optional debugging check: pass raw parsetrees through copyObject() */
593  {
594  List *new_list = copyObject(raw_parsetree_list);
595 
596  /* This checks both copyObject() and the equal() routines... */
597  if (!equal(new_list, raw_parsetree_list))
598  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
599  else
600  raw_parsetree_list = new_list;
601  }
602 #endif
603 
604  /*
605  * Optional debugging check: pass raw parsetrees through
606  * outfuncs/readfuncs
607  */
608 #ifdef WRITE_READ_PARSE_PLAN_TREES
609  {
610  char *str = nodeToString(raw_parsetree_list);
611  List *new_list = stringToNodeWithLocations(str);
612 
613  pfree(str);
614  /* This checks both outfuncs/readfuncs and the equal() routines... */
615  if (!equal(new_list, raw_parsetree_list))
616  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
617  else
618  raw_parsetree_list = new_list;
619  }
620 #endif
621 
622  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
623 
624  return raw_parsetree_list;
625 }
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:877
@ 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 938 of file postgres.c.

940 {
941  List *stmt_list = NIL;
942  ListCell *query_list;
943 
944  foreach(query_list, querytrees)
945  {
946  Query *query = lfirst_node(Query, query_list);
947  PlannedStmt *stmt;
948 
949  if (query->commandType == CMD_UTILITY)
950  {
951  /* Utility commands require no planning. */
953  stmt->commandType = CMD_UTILITY;
954  stmt->canSetTag = query->canSetTag;
955  stmt->utilityStmt = query->utilityStmt;
956  stmt->stmt_location = query->stmt_location;
957  stmt->stmt_len = query->stmt_len;
958  stmt->queryId = query->queryId;
959  }
960  else
961  {
962  stmt = pg_plan_query(query, query_string, cursorOptions,
963  boundParams);
964  }
965 
966  stmt_list = lappend(stmt_list, stmt);
967  }
968 
969  return stmt_list;
970 }
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:852
int stmt_location
Definition: parsenodes.h:236
CmdType commandType
Definition: parsenodes.h:128
Node * utilityStmt
Definition: parsenodes.h:143

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

854 {
855  PlannedStmt *plan;
856 
857  /* Utility commands have no plans. */
858  if (querytree->commandType == CMD_UTILITY)
859  return NULL;
860 
861  /* Planner must have a snapshot in case it calls user-defined functions. */
863 
864  TRACE_POSTGRESQL_QUERY_PLAN_START();
865 
866  if (log_planner_stats)
867  ResetUsage();
868 
869  /* call the optimizer */
870  plan = planner(querytree, query_string, cursorOptions, boundParams);
871 
872  if (log_planner_stats)
873  ShowUsage("PLANNER STATISTICS");
874 
875 #ifdef COPY_PARSE_PLAN_TREES
876  /* Optional debugging check: pass plan tree through copyObject() */
877  {
878  PlannedStmt *new_plan = copyObject(plan);
879 
880  /*
881  * equal() currently does not have routines to compare Plan nodes, so
882  * don't try to test equality here. Perhaps fix someday?
883  */
884 #ifdef NOT_USED
885  /* This checks both copyObject() and the equal() routines... */
886  if (!equal(new_plan, plan))
887  elog(WARNING, "copyObject() failed to produce an equal plan tree");
888  else
889 #endif
890  plan = new_plan;
891  }
892 #endif
893 
894 #ifdef WRITE_READ_PARSE_PLAN_TREES
895  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
896  {
897  char *str;
898  PlannedStmt *new_plan;
899 
900  str = nodeToString(plan);
901  new_plan = stringToNodeWithLocations(str);
902  pfree(str);
903 
904  /*
905  * equal() currently does not have routines to compare Plan nodes, so
906  * don't try to test equality here. Perhaps fix someday?
907  */
908 #ifdef NOT_USED
909  /* This checks both outfuncs/readfuncs and the equal() routines... */
910  if (!equal(new_plan, plan))
911  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
912  else
913 #endif
914  plan = new_plan;
915  }
916 #endif
917 
918  /*
919  * Print plan if debugging.
920  */
921  if (Debug_print_plan)
922  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
923 
924  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
925 
926  return plan;
927 }
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:469
bool Debug_pretty_print
Definition: guc_tables.c:472
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:273
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:817

References ActiveSnapshotSet(), Assert(), CMD_UTILITY, copyObject, Debug_pretty_print, Debug_print_plan, elog(), elog_node_display(), equal(), LOG, log_planner_stats, nodeToString(), pfree(), 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 770 of file postgres.c.

771 {
772  List *querytree_list;
773 
774  if (Debug_print_parse)
775  elog_node_display(LOG, "parse tree", query,
777 
778  if (log_parser_stats)
779  ResetUsage();
780 
781  if (query->commandType == CMD_UTILITY)
782  {
783  /* don't rewrite utilities, just dump 'em into result list */
784  querytree_list = list_make1(query);
785  }
786  else
787  {
788  /* rewrite regular queries */
789  querytree_list = QueryRewrite(query);
790  }
791 
792  if (log_parser_stats)
793  ShowUsage("REWRITER STATISTICS");
794 
795 #ifdef COPY_PARSE_PLAN_TREES
796  /* Optional debugging check: pass querytree through copyObject() */
797  {
798  List *new_list;
799 
800  new_list = copyObject(querytree_list);
801  /* This checks both copyObject() and the equal() routines... */
802  if (!equal(new_list, querytree_list))
803  elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
804  else
805  querytree_list = new_list;
806  }
807 #endif
808 
809 #ifdef WRITE_READ_PARSE_PLAN_TREES
810  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
811  {
812  List *new_list = NIL;
813  ListCell *lc;
814 
815  foreach(lc, querytree_list)
816  {
817  Query *curr_query = lfirst_node(Query, lc);
818  char *str = nodeToString(curr_query);
819  Query *new_query = stringToNodeWithLocations(str);
820 
821  /*
822  * queryId is not saved in stored rules, but we must preserve it
823  * here to avoid breaking pg_stat_statements.
824  */
825  new_query->queryId = curr_query->queryId;
826 
827  new_list = lappend(new_list, new_query);
828  pfree(str);
829  }
830 
831  /* This checks both outfuncs/readfuncs and the equal() routines... */
832  if (!equal(new_list, querytree_list))
833  elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
834  else
835  querytree_list = new_list;
836  }
837 #endif
838 
840  elog_node_display(LOG, "rewritten parse tree", querytree_list,
842 
843  return querytree_list;
844 }
bool Debug_print_rewritten
Definition: guc_tables.c:471
bool Debug_print_parse
Definition: guc_tables.c:470
#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 4065 of file postgres.c.

4066 {
4067  int firstchar;
4068  StringInfoData input_message;
4069  sigjmp_buf local_sigjmp_buf;
4070  volatile bool send_ready_for_query = true;
4071  bool idle_in_transaction_timeout_enabled = false;
4072  bool idle_session_timeout_enabled = false;
4073 
4074  Assert(dbname != NULL);
4075  Assert(username != NULL);
4076 
4078 
4079  /*
4080  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4081  * has already set up BlockSig and made that the active signal mask.)
4082  *
4083  * Note that postmaster blocked all signals before forking child process,
4084  * so there is no race condition whereby we might receive a signal before
4085  * we have set up the handler.
4086  *
4087  * Also note: it's best not to use any signals that are SIG_IGNored in the
4088  * postmaster. If such a signal arrives before we are able to change the
4089  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4090  * handler in the postmaster to reserve the signal. (Of course, this isn't
4091  * an issue for signals that are locally generated, such as SIGALRM and
4092  * SIGPIPE.)
4093  */
4094  if (am_walsender)
4095  WalSndSignals();
4096  else
4097  {
4099  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4100  pqsignal(SIGTERM, die); /* cancel current query and exit */
4101 
4102  /*
4103  * In a postmaster child backend, replace SignalHandlerForCrashExit
4104  * with quickdie, so we can tell the client we're dying.
4105  *
4106  * In a standalone backend, SIGQUIT can be generated from the keyboard
4107  * easily, while SIGTERM cannot, so we make both signals do die()
4108  * rather than quickdie().
4109  */
4110  if (IsUnderPostmaster)
4111  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4112  else
4113  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4114  InitializeTimeouts(); /* establishes SIGALRM handler */
4115 
4116  /*
4117  * Ignore failure to write to frontend. Note: if frontend closes
4118  * connection, we will notice it and exit cleanly when control next
4119  * returns to outer loop. This seems safer than forcing exit in the
4120  * midst of output during who-knows-what operation...
4121  */
4126 
4127  /*
4128  * Reset some signals that are accepted by postmaster but not by
4129  * backend
4130  */
4131  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4132  * platforms */
4133  }
4134 
4135  /* Early initialization */
4136  BaseInit();
4137 
4138  /* We need to allow SIGINT, etc during the initial transaction */
4139  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4140 
4141  /*
4142  * General initialization.
4143  *
4144  * NOTE: if you are tempted to add code in this vicinity, consider putting
4145  * it inside InitPostgres() instead. In particular, anything that
4146  * involves database access should be there, not here.
4147  */
4148  InitPostgres(dbname, InvalidOid, /* database to connect to */
4149  username, InvalidOid, /* role to connect as */
4150  !am_walsender, /* honor session_preload_libraries? */
4151  false, /* don't ignore datallowconn */
4152  NULL); /* no out_dbname */
4153 
4154  /*
4155  * If the PostmasterContext is still around, recycle the space; we don't
4156  * need it anymore after InitPostgres completes. Note this does not trash
4157  * *MyProcPort, because ConnCreate() allocated that space with malloc()
4158  * ... else we'd need to copy the Port data first. Also, subsidiary data
4159  * such as the username isn't lost either; see ProcessStartupPacket().
4160  */
4161  if (PostmasterContext)
4162  {
4164  PostmasterContext = NULL;
4165  }
4166 
4168 
4169  /*
4170  * Now all GUC states are fully set up. Report them to client if
4171  * appropriate.
4172  */
4174 
4175  /*
4176  * Also set up handler to log session end; we have to wait till now to be
4177  * sure Log_disconnections has its final value.
4178  */
4181 
4183 
4184  /* Perform initialization specific to a WAL sender process. */
4185  if (am_walsender)
4186  InitWalSender();
4187 
4188  /*
4189  * Send this backend's cancellation info to the frontend.
4190  */
4192  {
4194 
4195  pq_beginmessage(&buf, 'K');
4198  pq_endmessage(&buf);
4199  /* Need not flush since ReadyForQuery will do it. */
4200  }
4201 
4202  /* Welcome banner for standalone case */
4204  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4205 
4206  /*
4207  * Create the memory context we will use in the main loop.
4208  *
4209  * MessageContext is reset once per iteration of the main loop, ie, upon
4210  * completion of processing of each command message from the client.
4211  */
4213  "MessageContext",
4215 
4216  /*
4217  * Create memory context and buffer used for RowDescription messages. As
4218  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4219  * frequently executed for ever single statement, we don't want to
4220  * allocate a separate buffer every time.
4221  */
4223  "RowDescriptionContext",
4228 
4229  /*
4230  * POSTGRES main processing loop begins here
4231  *
4232  * If an exception is encountered, processing resumes here so we abort the
4233  * current transaction and start a new one.
4234  *
4235  * You might wonder why this isn't coded as an infinite loop around a
4236  * PG_TRY construct. The reason is that this is the bottom of the
4237  * exception stack, and so with PG_TRY there would be no exception handler
4238  * in force at all during the CATCH part. By leaving the outermost setjmp
4239  * always active, we have at least some chance of recovering from an error
4240  * during error recovery. (If we get into an infinite loop thereby, it
4241  * will soon be stopped by overflow of elog.c's internal state stack.)
4242  *
4243  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4244  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4245  * is essential in case we longjmp'd out of a signal handler on a platform
4246  * where that leaves the signal blocked. It's not redundant with the
4247  * unblock in AbortTransaction() because the latter is only called if we
4248  * were inside a transaction.
4249  */
4250 
4251  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4252  {
4253  /*
4254  * NOTE: if you are tempted to add more code in this if-block,
4255  * consider the high probability that it should be in
4256  * AbortTransaction() instead. The only stuff done directly here
4257  * should be stuff that is guaranteed to apply *only* for outer-level
4258  * error recovery, such as adjusting the FE/BE protocol status.
4259  */
4260 
4261  /* Since not using PG_TRY, must reset error stack by hand */
4262  error_context_stack = NULL;
4263 
4264  /* Prevent interrupts while cleaning up */
4265  HOLD_INTERRUPTS();
4266 
4267  /*
4268  * Forget any pending QueryCancel request, since we're returning to
4269  * the idle loop anyway, and cancel any active timeout requests. (In
4270  * future we might want to allow some timeout requests to survive, but
4271  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4272  * we got here because of a query cancel interrupting the SIGALRM
4273  * interrupt handler.) Note in particular that we must clear the
4274  * statement and lock timeout indicators, to prevent any future plain
4275  * query cancels from being misreported as timeouts in case we're
4276  * forgetting a timeout cancel.
4277  */
4278  disable_all_timeouts(false);
4279  QueryCancelPending = false; /* second to avoid race condition */
4280 
4281  /* Not reading from the client anymore. */
4282  DoingCommandRead = false;
4283 
4284  /* Make sure libpq is in a good state */
4285  pq_comm_reset();
4286 
4287  /* Report the error to the client and/or server log */
4288  EmitErrorReport();
4289 
4290  /*
4291  * Make sure debug_query_string gets reset before we possibly clobber
4292  * the storage it points at.
4293  */
4294  debug_query_string = NULL;
4295 
4296  /*
4297  * Abort the current transaction in order to recover.
4298  */
4300 
4301  if (am_walsender)
4303 
4305 
4306  /*
4307  * We can't release replication slots inside AbortTransaction() as we
4308  * need to be able to start and abort transactions while having a slot
4309  * acquired. But we never need to hold them across top level errors,
4310  * so releasing here is fine. There also is a before_shmem_exit()
4311  * callback ensuring correct cleanup on FATAL errors.
4312  */
4313  if (MyReplicationSlot != NULL)
4315 
4316  /* We also want to cleanup temporary slots on error. */
4318 
4320 
4321  /*
4322  * Now return to normal top-level context and clear ErrorContext for
4323  * next time.
4324  */
4326  FlushErrorState();
4327 
4328  /*
4329  * If we were handling an extended-query-protocol message, initiate
4330  * skip till next Sync. This also causes us not to issue
4331  * ReadyForQuery (until we get Sync).
4332  */
4334  ignore_till_sync = true;
4335 
4336  /* We don't have a transaction command open anymore */
4337  xact_started = false;
4338 
4339  /*
4340  * If an error occurred while we were reading a message from the
4341  * client, we have potentially lost track of where the previous
4342  * message ends and the next one begins. Even though we have
4343  * otherwise recovered from the error, we cannot safely read any more
4344  * messages from the client, so there isn't much we can do with the
4345  * connection anymore.
4346  */
4347  if (pq_is_reading_msg())
4348  ereport(FATAL,
4349  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4350  errmsg("terminating connection because protocol synchronization was lost")));
4351 
4352  /* Now we can allow interrupts again */
4354  }
4355 
4356  /* We can now handle ereport(ERROR) */
4357  PG_exception_stack = &local_sigjmp_buf;
4358 
4359  if (!ignore_till_sync)
4360  send_ready_for_query = true; /* initially, or after error */
4361 
4362  /*
4363  * Non-error queries loop here.
4364  */
4365 
4366  for (;;)
4367  {
4368  /*
4369  * At top of loop, reset extended-query-message flag, so that any
4370  * errors encountered in "idle" state don't provoke skip.
4371  */
4373 
4374  /*
4375  * Release storage left over from prior query cycle, and create a new
4376  * query input buffer in the cleared MessageContext.
4377  */
4380 
4381  initStringInfo(&input_message);
4382 
4383  /*
4384  * Also consider releasing our catalog snapshot if any, so that it's
4385  * not preventing advance of global xmin while we wait for the client.
4386  */
4388 
4389  /*
4390  * (1) If we've reached idle state, tell the frontend we're ready for
4391  * a new query.
4392  *
4393  * Note: this includes fflush()'ing the last of the prior output.
4394  *
4395  * This is also a good time to flush out collected statistics to the
4396  * cumulative stats system, and to update the PS stats display. We
4397  * avoid doing those every time through the message loop because it'd
4398  * slow down processing of batched messages, and because we don't want
4399  * to report uncommitted updates (that confuses autovacuum). The
4400  * notification processor wants a call too, if we are not in a
4401  * transaction block.
4402  *
4403  * Also, if an idle timeout is enabled, start the timer for that.
4404  */
4405  if (send_ready_for_query)
4406  {
4408  {
4409  set_ps_display("idle in transaction (aborted)");
4411 
4412  /* Start the idle-in-transaction timer */
4414  {
4415  idle_in_transaction_timeout_enabled = true;
4418  }
4419  }
4421  {
4422  set_ps_display("idle in transaction");
4424 
4425  /* Start the idle-in-transaction timer */
4427  {
4428  idle_in_transaction_timeout_enabled = true;
4431  }
4432  }
4433  else
4434  {
4435  long stats_timeout;
4436 
4437  /*
4438  * Process incoming notifies (including self-notifies), if
4439  * any, and send relevant messages to the client. Doing it
4440  * here helps ensure stable behavior in tests: if any notifies
4441  * were received during the just-finished transaction, they'll
4442  * be seen by the client before ReadyForQuery is.
4443  */
4445  ProcessNotifyInterrupt(false);
4446 
4447  /*
4448  * Check if we need to report stats. If pgstat_report_stat()
4449  * decides it's too soon to flush out pending stats / lock
4450  * contention prevented reporting, it'll tell us when we
4451  * should try to report stats again (so that stats updates
4452  * aren't unduly delayed if the connection goes idle for a
4453  * long time). We only enable the timeout if we don't already
4454  * have a timeout in progress, because we don't disable the
4455  * timeout below. enable_timeout_after() needs to determine
4456  * the current timestamp, which can have a negative
4457  * performance impact. That's OK because pgstat_report_stat()
4458  * won't have us wake up sooner than a prior call.
4459  */
4460  stats_timeout = pgstat_report_stat(false);
4461  if (stats_timeout > 0)
4462  {
4465  stats_timeout);
4466  }
4467  else
4468  {
4469  /* all stats flushed, no need for the timeout */
4472  }
4473 
4474  set_ps_display("idle");
4476 
4477  /* Start the idle-session timer */
4478  if (IdleSessionTimeout > 0)
4479  {
4480  idle_session_timeout_enabled = true;
4483  }
4484  }
4485 
4486  /* Report any recently-changed GUC options */
4488 
4490  send_ready_for_query = false;
4491  }
4492 
4493  /*
4494  * (2) Allow asynchronous signals to be executed immediately if they
4495  * come in while we are waiting for client input. (This must be
4496  * conditional since we don't want, say, reads on behalf of COPY FROM
4497  * STDIN doing the same thing.)
4498  */
4499  DoingCommandRead = true;
4500 
4501  /*
4502  * (3) read a command (loop blocks here)
4503  */
4504  firstchar = ReadCommand(&input_message);
4505 
4506  /*
4507  * (4) turn off the idle-in-transaction and idle-session timeouts if
4508  * active. We do this before step (5) so that any last-moment timeout
4509  * is certain to be detected in step (5).
4510  *
4511  * At most one of these timeouts will be active, so there's no need to
4512  * worry about combining the timeout.c calls into one.
4513  */
4514  if (idle_in_transaction_timeout_enabled)
4515  {
4517  idle_in_transaction_timeout_enabled = false;
4518  }
4519  if (idle_session_timeout_enabled)
4520  {
4522  idle_session_timeout_enabled = false;
4523  }
4524 
4525  /*
4526  * (5) disable async signal conditions again.
4527  *
4528  * Query cancel is supposed to be a no-op when there is no query in
4529  * progress, so if a query cancel arrived while we were idle, just
4530  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4531  * it's called when DoingCommandRead is set, so check for interrupts
4532  * before resetting DoingCommandRead.
4533  */
4535  DoingCommandRead = false;
4536 
4537  /*
4538  * (6) check for any other interesting events that happened while we
4539  * slept.
4540  */
4541  if (ConfigReloadPending)
4542  {
4543  ConfigReloadPending = false;
4545  }
4546 
4547  /*
4548  * (7) process the command. But ignore it if we're skipping till
4549  * Sync.
4550  */
4551  if (ignore_till_sync && firstchar != EOF)
4552  continue;
4553 
4554  switch (firstchar)
4555  {
4556  case 'Q': /* simple query */
4557  {
4558  const char *query_string;
4559 
4560  /* Set statement_timestamp() */
4562 
4563  query_string = pq_getmsgstring(&input_message);
4564  pq_getmsgend(&input_message);
4565 
4566  if (am_walsender)
4567  {
4568  if (!exec_replication_command(query_string))
4569  exec_simple_query(query_string);
4570  }
4571  else
4572  exec_simple_query(query_string);
4573 
4574  send_ready_for_query = true;
4575  }
4576  break;
4577 
4578  case 'P': /* parse */
4579  {
4580  const char *stmt_name;
4581  const char *query_string;
4582  int numParams;
4583  Oid *paramTypes = NULL;
4584 
4585  forbidden_in_wal_sender(firstchar);
4586 
4587  /* Set statement_timestamp() */
4589 
4590  stmt_name = pq_getmsgstring(&input_message);
4591  query_string = pq_getmsgstring(&input_message);
4592  numParams = pq_getmsgint(&input_message, 2);
4593  if (numParams > 0)
4594  {
4595  paramTypes = palloc_array(Oid, numParams);
4596  for (int i = 0; i < numParams; i++)
4597  paramTypes[i] = pq_getmsgint(&input_message, 4);
4598  }
4599  pq_getmsgend(&input_message);
4600 
4601  exec_parse_message(query_string, stmt_name,
4602  paramTypes, numParams);
4603  }
4604  break;
4605 
4606  case 'B': /* bind */
4607  forbidden_in_wal_sender(firstchar);
4608 
4609  /* Set statement_timestamp() */
4611 
4612  /*
4613  * this message is complex enough that it seems best to put
4614  * the field extraction out-of-line
4615  */
4616  exec_bind_message(&input_message);
4617  break;
4618 
4619  case 'E': /* execute */
4620  {
4621  const char *portal_name;
4622  int max_rows;
4623 
4624  forbidden_in_wal_sender(firstchar);
4625 
4626  /* Set statement_timestamp() */
4628 
4629  portal_name = pq_getmsgstring(&input_message);
4630  max_rows = pq_getmsgint(&input_message, 4);
4631  pq_getmsgend(&input_message);
4632 
4633  exec_execute_message(portal_name, max_rows);
4634  }
4635  break;
4636 
4637  case 'F': /* fastpath function call */
4638  forbidden_in_wal_sender(firstchar);
4639 
4640  /* Set statement_timestamp() */
4642 
4643  /* Report query to various monitoring facilities. */
4645  set_ps_display("<FASTPATH>");
4646 
4647  /* start an xact for this function invocation */
4649 
4650  /*
4651  * Note: we may at this point be inside an aborted
4652  * transaction. We can't throw error for that until we've
4653  * finished reading the function-call message, so
4654  * HandleFunctionRequest() must check for it after doing so.
4655  * Be careful not to do anything that assumes we're inside a
4656  * valid transaction here.
4657  */
4658 
4659  /* switch back to message context */
4661 
4662  HandleFunctionRequest(&input_message);
4663 
4664  /* commit the function-invocation transaction */
4666 
4667  send_ready_for_query = true;
4668  break;
4669 
4670  case 'C': /* close */
4671  {
4672  int close_type;
4673  const char *close_target;
4674 
4675  forbidden_in_wal_sender(firstchar);
4676 
4677  close_type = pq_getmsgbyte(&input_message);
4678  close_target = pq_getmsgstring(&input_message);
4679  pq_getmsgend(&input_message);
4680 
4681  switch (close_type)
4682  {
4683  case 'S':
4684  if (close_target[0] != '\0')
4685  DropPreparedStatement(close_target, false);
4686  else
4687  {
4688  /* special-case the unnamed statement */
4690  }
4691  break;
4692  case 'P':
4693  {
4694  Portal portal;
4695 
4696  portal = GetPortalByName(close_target);
4697  if (PortalIsValid(portal))
4698  PortalDrop(portal, false);
4699  }
4700  break;
4701  default:
4702  ereport(ERROR,
4703  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4704  errmsg("invalid CLOSE message subtype %d",
4705  close_type)));
4706  break;
4707  }
4708 
4710  pq_putemptymessage('3'); /* CloseComplete */
4711  }
4712  break;
4713 
4714  case 'D': /* describe */
4715  {
4716  int describe_type;
4717  const char *describe_target;
4718 
4719  forbidden_in_wal_sender(firstchar);
4720 
4721  /* Set statement_timestamp() (needed for xact) */
4723 
4724  describe_type = pq_getmsgbyte(&input_message);
4725  describe_target = pq_getmsgstring(&input_message);
4726  pq_getmsgend(&input_message);
4727 
4728  switch (describe_type)
4729  {
4730  case 'S':
4731  exec_describe_statement_message(describe_target);
4732  break;
4733  case 'P':
4734  exec_describe_portal_message(describe_target);
4735  break;
4736  default:
4737  ereport(ERROR,
4738  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4739  errmsg("invalid DESCRIBE message subtype %d",
4740  describe_type)));
4741  break;
4742  }
4743  }
4744  break;
4745 
4746  case 'H': /* flush */
4747  pq_getmsgend(&input_message);
4749  pq_flush();
4750  break;
4751 
4752  case 'S': /* sync */
4753  pq_getmsgend(&input_message);
4755  send_ready_for_query = true;
4756  break;
4757 
4758  /*
4759  * 'X' means that the frontend is closing down the socket. EOF
4760  * means unexpected loss of frontend connection. Either way,
4761  * perform normal shutdown.
4762  */
4763  case EOF:
4764 
4765  /* for the cumulative statistics system */
4767 
4768  /* FALLTHROUGH */
4769 
4770  case 'X':
4771 
4772  /*
4773  * Reset whereToSendOutput to prevent ereport from attempting
4774  * to send any more messages to client.
4775  */
4778 
4779  /*
4780  * NOTE: if you are tempted to add more code here, DON'T!
4781  * Whatever you had in mind to do should be set up as an
4782  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4783  * it will fail to be called during other backend-shutdown
4784  * scenarios.
4785  */
4786  proc_exit(0);
4787 
4788  case 'd': /* copy data */
4789  case 'c': /* copy done */
4790  case 'f': /* copy fail */
4791 
4792  /*
4793  * Accept but ignore these messages, per protocol spec; we
4794  * probably got here because a COPY failed, and the frontend
4795  * is still sending data.
4796  */
4797  break;
4798 
4799  default:
4800  ereport(FATAL,
4801  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4802  errmsg("invalid frontend message type %d",
4803  firstchar)));
4804  }
4805  } /* end of input-reading loop */
4806 }
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:400
@ InitProcessing
Definition: miscadmin.h:399
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
#define SetProcessingMode(mode)
Definition: miscadmin.h:411
const char * username
Definition: pgbench.c:306
long pgstat_report_stat(bool force)
Definition: pgstat.c:575
@ 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:2560
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2838
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4986
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4816
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2053
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2990
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2969
static bool ignore_till_sync
Definition: postgres.c:145
static void exec_simple_query(const char *query_string)
Definition: postgres.c:979
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1357
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1592
void die(SIGNAL_ARGS)
Definition: postgres.c:2935
static MemoryContext row_description_context
Definition: postgres.c:165
static bool doing_extended_query_message
Definition: postgres.c:144
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2654
bool Log_disconnections
Definition: postgres.c:87
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:454
void BaseInit(void)
Definition: postinit.c:636
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:725
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1186
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
void ReplicationSlotCleanup(void)
Definition: slot.c:603
ReplicationSlot * MyReplicationSlot
Definition: slot.c:98
void ReplicationSlotRelease(void)
Definition: slot.c:547
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:478
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:1669
void WalSndSignals(void)
Definition: walsender.c:3233
void InitWalSender(void)
#define SIGCHLD
Definition: win32_port.h:186
#define SIGHUP
Definition: win32_port.h:176
#define SIG_DFL
Definition: win32_port.h:171
#define SIGPIPE
Definition: win32_port.h:181
#define SIGQUIT
Definition: win32_port.h:177
#define SIGUSR1
Definition: win32_port.h:188
#define SIGUSR2
Definition: win32_port.h:189
#define SIG_IGN
Definition: win32_port.h:173
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4841
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899
void AbortCurrentTransaction(void)
Definition: xact.c:3312

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(), 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, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 3955 of file postgres.c.

3957 {
3958  const char *dbname = NULL;
3959 
3961 
3962  /* Initialize startup process environment. */
3963  InitStandaloneProcess(argv[0]);
3964 
3965  /*
3966  * Set default values for command-line options.
3967  */
3969 
3970  /*
3971  * Parse command-line options.
3972  */
3974 
3975  /* Must have gotten a database name, or have a default (the username) */
3976  if (dbname == NULL)
3977  {
3978  dbname = username;
3979  if (dbname == NULL)
3980  ereport(FATAL,
3981  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3982  errmsg("%s: no database nor user name specified",
3983  progname)));
3984  }
3985 
3986  /* Acquire configuration parameters */
3988  proc_exit(1);
3989 
3990  /*
3991  * Validate we have been given a reasonable-looking DataDir and change
3992  * into it.
3993  */
3994  checkDataDir();
3995  ChangeToDataDir();
3996 
3997  /*
3998  * Create lockfile for data directory.
3999  */
4000  CreateDataDirLockFile(false);
4001 
4002  /* read control file (error checking and contains config ) */
4003  LocalProcessControlFile(false);
4004 
4005  /*
4006  * process any libraries that should be preloaded at postmaster start
4007  */
4009 
4010  /* Initialize MaxBackends */
4012 
4013  /*
4014  * Give preloaded libraries a chance to request additional shared memory.
4015  */
4017 
4018  /*
4019  * Now that loadable modules have had their chance to request additional
4020  * shared memory, determine the value of any runtime-computed GUCs that
4021  * depend on the amount of shared memory required.
4022  */
4024 
4025  /*
4026  * Now that modules have been loaded, we can process any custom resource
4027  * managers specified in the wal_consistency_checking GUC.
4028  */
4030 
4032 
4033  /*
4034  * Remember stand-alone backend startup time,roughly at the same point
4035  * during startup that postmaster does so.
4036  */
4038 
4039  /*
4040  * Create a per-backend PGPROC struct in shared memory. We must do this
4041  * before we can use LWLocks.
4042  */
4043  InitProcess();
4044 
4045  /*
4046  * Now that sufficient infrastructure has been initialized, PostgresMain()
4047  * can do the rest.
4048  */
4050 }
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:325
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:174
const char * progname
Definition: main.c:45
void ChangeToDataDir(void)
Definition: miscinit.c:449
void process_shmem_requests(void)
Definition: miscinit.c:1875
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void process_shared_preload_libraries(void)
Definition: miscinit.c:1847
void checkDataDir(void)
Definition: miscinit.c:336
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1459
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3703
static const char * userDoption
Definition: postgres.c:155
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4065
void InitializeMaxBackends(void)
Definition: postinit.c:566
void InitProcess(void)
Definition: proc.c:297
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4400
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4463

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

3705 {
3706  bool secure = (ctx == PGC_POSTMASTER);
3707  int errs = 0;
3708  GucSource gucsource;
3709  int flag;
3710 
3711  if (secure)
3712  {
3713  gucsource = PGC_S_ARGV; /* switches came from command line */
3714 
3715  /* Ignore the initial --single argument, if present */
3716  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3717  {
3718  argv++;
3719  argc--;
3720  }
3721  }
3722  else
3723  {
3724  gucsource = PGC_S_CLIENT; /* switches came from client */
3725  }
3726 
3727 #ifdef HAVE_INT_OPTERR
3728 
3729  /*
3730  * Turn this off because it's either printed to stderr and not the log
3731  * where we'd want it, or argv[0] is now "--single", which would make for
3732  * a weird error message. We print our own error message below.
3733  */
3734  opterr = 0;
3735 #endif
3736 
3737  /*
3738  * Parse command-line options. CAUTION: keep this in sync with
3739  * postmaster/postmaster.c (the option sets should not conflict) and with
3740  * the common help() function in main/main.c.
3741  */
3742  while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3743  {
3744  switch (flag)
3745  {
3746  case 'B':
3747  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3748  break;
3749 
3750  case 'b':
3751  /* Undocumented flag used for binary upgrades */
3752  if (secure)
3753  IsBinaryUpgrade = true;
3754  break;
3755 
3756  case 'C':
3757  /* ignored for consistency with the postmaster */
3758  break;
3759 
3760  case 'c':
3761  case '-':
3762  {
3763  char *name,
3764  *value;
3765 
3767  if (!value)
3768  {
3769  if (flag == '-')
3770  ereport(ERROR,
3771  (errcode(ERRCODE_SYNTAX_ERROR),
3772  errmsg("--%s requires a value",
3773  optarg)));
3774  else
3775  ereport(ERROR,
3776  (errcode(ERRCODE_SYNTAX_ERROR),
3777  errmsg("-c %s requires a value",
3778  optarg)));
3779  }
3780  SetConfigOption(name, value, ctx, gucsource);
3781  pfree(name);
3782  pfree(value);
3783  break;
3784  }
3785 
3786  case 'D':
3787  if (secure)
3788  userDoption = strdup(optarg);
3789  break;
3790 
3791  case 'd':
3792  set_debug_options(atoi(optarg), ctx, gucsource);
3793  break;
3794 
3795  case 'E':
3796  if (secure)
3797  EchoQuery = true;
3798  break;
3799 
3800  case 'e':
3801  SetConfigOption("datestyle", "euro", ctx, gucsource);
3802  break;
3803 
3804  case 'F':
3805  SetConfigOption("fsync", "false", ctx, gucsource);
3806  break;
3807 
3808  case 'f':
3809  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3810  errs++;
3811  break;
3812 
3813  case 'h':
3814  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3815  break;
3816 
3817  case 'i':
3818  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3819  break;
3820 
3821  case 'j':
3822  if (secure)
3823  UseSemiNewlineNewline = true;
3824  break;
3825 
3826  case 'k':
3827  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3828  break;
3829 
3830  case 'l':
3831  SetConfigOption("ssl", "true", ctx, gucsource);
3832  break;
3833 
3834  case 'N':
3835  SetConfigOption("max_connections", optarg, ctx, gucsource);
3836  break;
3837 
3838  case 'n':
3839  /* ignored for consistency with postmaster */
3840  break;
3841 
3842  case 'O':
3843  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3844  break;
3845 
3846  case 'P':
3847  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3848  break;
3849 
3850  case 'p':
3851  SetConfigOption("port", optarg, ctx, gucsource);
3852  break;
3853 
3854  case 'r':
3855  /* send output (stdout and stderr) to the given file */
3856  if (secure)
3858  break;
3859 
3860  case 'S':
3861  SetConfigOption("work_mem", optarg, ctx, gucsource);
3862  break;
3863 
3864  case 's':
3865  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3866  break;
3867 
3868  case 'T':
3869  /* ignored for consistency with the postmaster */
3870  break;
3871 
3872  case 't':
3873  {
3874  const char *tmp = get_stats_option_name(optarg);
3875 
3876  if (tmp)
3877  SetConfigOption(tmp, "true", ctx, gucsource);
3878  else
3879  errs++;
3880  break;
3881  }
3882 
3883  case 'v':
3884 
3885  /*
3886  * -v is no longer used in normal operation, since
3887  * FrontendProtocol is already set before we get here. We keep
3888  * the switch only for possible use in standalone operation,
3889  * in case we ever support using normal FE/BE protocol with a
3890  * standalone backend.
3891  */
3892  if (secure)
3894  break;
3895 
3896  case 'W':
3897  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3898  break;
3899 
3900  default:
3901  errs++;
3902  break;
3903  }
3904 
3905  if (errs)
3906  break;
3907  }
3908 
3909  /*
3910  * Optional database name should be there only if *dbname is NULL.
3911  */
3912  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3913  *dbname = strdup(argv[optind++]);
3914 
3915  if (errs || argc != optind)
3916  {
3917  if (errs)
3918  optind--; /* complain about the previous argument */
3919 
3920  /* spell the error message a bit differently depending on context */
3921  if (IsUnderPostmaster)
3922  ereport(FATAL,
3923  errcode(ERRCODE_SYNTAX_ERROR),
3924  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3925  errhint("Try \"%s --help\" for more information.", progname));
3926  else
3927  ereport(FATAL,
3928  errcode(ERRCODE_SYNTAX_ERROR),
3929  errmsg("%s: invalid command-line argument: %s",
3930  progname, argv[optind]),
3931  errhint("Try \"%s --help\" for more information.", progname));
3932  }
3933 
3934  /*
3935  * Reset getopt(3) library so that it will work correctly in subprocesses
3936  * or when this function is called a second time with another array.
3937  */
3938  optind = 1;
3939 #ifdef HAVE_INT_OPTRESET
3940  optreset = 1; /* some systems need this too */
3941 #endif
3942 }
const char * name
Definition: encode.c:571
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 @143 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:3592
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3621
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3663
uint32 ProtocolVersion
Definition: pqcomm.h:87
char * flag(int b)
Definition: test-ctype.c:33

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

476 {
477  int save_errno = errno;
478 
479  if (DoingCommandRead)
480  {
481  /* Check for general interrupts that arrived before/while reading */
483 
484  /* Process sinval catchup interrupts, if any */
487 
488  /* Process notify interrupts, if any */
491  }
492  else if (ProcDiePending)
493  {
494  /*
495  * We're dying. If there is no data available to read, then it's safe
496  * (and sane) to handle that now. If we haven't tried to read yet,
497  * make sure the process latch is set, so that if there is no data
498  * then we'll come back here and die. If we're done reading, also
499  * make sure the process latch is set, as we might've undesirably
500  * cleared it while reading.
501  */
502  if (blocked)
504  else
505  SetLatch(MyLatch);
506  }
507 
508  errno = save_errno;
509 }
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 521 of file postgres.c.

522 {
523  int save_errno = errno;
524 
525  if (ProcDiePending)
526  {
527  /*
528  * We're dying. If it's not possible to write, then we should handle
529  * that immediately, else a stuck client could indefinitely delay our
530  * response to the signal. If we haven't tried to write yet, make
531  * sure the process latch is set, so that if the write would block
532  * then we'll come back here and die. If we're done writing, also
533  * make sure the process latch is set, as we might've undesirably
534  * cleared it while writing.
535  */
536  if (blocked)
537  {
538  /*
539  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
540  * service ProcDiePending.
541  */
542  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
543  {
544  /*
545  * We don't want to send the client the error message, as a)
546  * that would possibly block again, and b) it would likely
547  * lead to loss of protocol sync because we may have already
548  * sent a partial protocol message.
549  */
552 
554  }
555  }
556  else
557  SetLatch(MyLatch);
558  }
559 
560  errno = save_errno;
561 }
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 3149 of file postgres.c.

3150 {
3151  /* OK to accept any interrupts now? */
3152  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3153  return;
3154  InterruptPending = false;
3155 
3156  if (ProcDiePending)
3157  {
3158  ProcDiePending = false;
3159  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3160  LockErrorCleanup();
3161  /* As in quickdie, don't risk sending to client during auth */
3165  ereport(FATAL,
3166  (errcode(ERRCODE_QUERY_CANCELED),
3167  errmsg("canceling authentication due to timeout")));
3168  else if (IsAutoVacuumWorkerProcess())
3169  ereport(FATAL,
3170  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3171  errmsg("terminating autovacuum process due to administrator command")));
3172  else if (IsLogicalWorker())
3173  ereport(FATAL,
3174  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3175  errmsg("terminating logical replication worker due to administrator command")));
3176  else if (IsLogicalLauncher())
3177  {
3178  ereport(DEBUG1,
3179  (errmsg_internal("logical replication launcher shutting down")));
3180 
3181  /*
3182  * The logical replication launcher can be stopped at any time.
3183  * Use exit status 1 so the background worker is restarted.
3184  */
3185  proc_exit(1);
3186  }
3188  {
3190  ereport(FATAL,
3192  errmsg("terminating connection due to conflict with recovery"),
3194  }
3195  else if (RecoveryConflictPending)
3196  {
3197  /* Currently there is only one non-retryable recovery conflict */
3200  ereport(FATAL,
3201  (errcode(ERRCODE_DATABASE_DROPPED),
3202  errmsg("terminating connection due to conflict with recovery"),
3204  }
3205  else if (IsBackgroundWorker)
3206  ereport(FATAL,
3207  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3208  errmsg("terminating background worker \"%s\" due to administrator command",
3210  else
3211  ereport(FATAL,
3212  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3213  errmsg("terminating connection due to administrator command")));
3214  }
3215 
3217  {
3219 
3220  /*
3221  * Check for lost connection and re-arm, if still configured, but not
3222  * if we've arrived back at DoingCommandRead state. We don't want to
3223  * wake up idle sessions, and they already know how to detect lost
3224  * connections.
3225  */
3227  {
3228  if (!pq_check_connection())
3229  ClientConnectionLost = true;
3230  else
3233  }
3234  }
3235 
3237  {
3238  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3239  LockErrorCleanup();
3240  /* don't send to client, we already know the connection to be dead. */
3242  ereport(FATAL,
3243  (errcode(ERRCODE_CONNECTION_FAILURE),
3244  errmsg("connection to client lost")));
3245  }
3246 
3247  /*
3248  * If a recovery conflict happens while we are waiting for input from the
3249  * client, the client is presumably just sitting idle in a transaction,
3250  * preventing recovery from making progress. Terminate the connection to
3251  * dislodge it.
3252  */
3254  {
3255  QueryCancelPending = false; /* this trumps QueryCancel */
3256  RecoveryConflictPending = false;
3257  LockErrorCleanup();
3259  ereport(FATAL,
3261  errmsg("terminating connection due to conflict with recovery"),
3263  errhint("In a moment you should be able to reconnect to the"
3264  " database and repeat your command.")));
3265  }
3266 
3267  /*
3268  * Don't allow query cancel interrupts while reading input from the
3269  * client, because we might lose sync in the FE/BE protocol. (Die
3270  * interrupts are OK, because we won't read any further messages from the
3271  * client in that case.)
3272  */
3274  {
3275  /*
3276  * Re-arm InterruptPending so that we process the cancel request as
3277  * soon as we're done reading the message. (XXX this is seriously
3278  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3279  * can't use that macro directly as the initial test in this function,
3280  * meaning that this code also creates opportunities for other bugs to
3281  * appear.)
3282  */
3283  InterruptPending = true;
3284  }
3285  else if (QueryCancelPending)
3286  {
3287  bool lock_timeout_occurred;
3288  bool stmt_timeout_occurred;
3289 
3290  QueryCancelPending = false;
3291 
3292  /*
3293  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3294  * need to clear both, so always fetch both.
3295  */
3296  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3297  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3298 
3299  /*
3300  * If both were set, we want to report whichever timeout completed
3301  * earlier; this ensures consistent behavior if the machine is slow
3302  * enough that the second timeout triggers before we get here. A tie
3303  * is arbitrarily broken in favor of reporting a lock timeout.
3304  */
3305  if (lock_timeout_occurred && stmt_timeout_occurred &&
3307  lock_timeout_occurred = false; /* report stmt timeout */
3308 
3309  if (lock_timeout_occurred)
3310  {
3311  LockErrorCleanup();
3312  ereport(ERROR,
3313  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3314  errmsg("canceling statement due to lock timeout")));
3315  }
3316  if (stmt_timeout_occurred)
3317  {
3318  LockErrorCleanup();
3319  ereport(ERROR,
3320  (errcode(ERRCODE_QUERY_CANCELED),
3321  errmsg("canceling statement due to statement timeout")));
3322  }
3324  {
3325  LockErrorCleanup();
3326  ereport(ERROR,
3327  (errcode(ERRCODE_QUERY_CANCELED),
3328  errmsg("canceling autovacuum task")));
3329  }
3331  {
3332  RecoveryConflictPending = false;
3333  LockErrorCleanup();
3335  ereport(ERROR,
3337  errmsg("canceling statement due to conflict with recovery"),
3339  }
3340 
3341  /*
3342  * If we are reading a command from the client, just ignore the cancel
3343  * request --- sending an extra error message won't accomplish
3344  * anything. Otherwise, go ahead and throw the error.
3345  */
3346  if (!DoingCommandRead)
3347  {
3348  LockErrorCleanup();
3349  ereport(ERROR,
3350  (errcode(ERRCODE_QUERY_CANCELED),
3351  errmsg("canceling statement due to user request")));
3352  }
3353  }
3354 
3356  {
3357  /*
3358  * If the GUC has been reset to zero, ignore the signal. This is
3359  * important because the GUC update itself won't disable any pending
3360  * interrupt.
3361  */
3363  ereport(FATAL,
3364  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3365  errmsg("terminating connection due to idle-in-transaction timeout")));
3366  else
3368  }
3369 
3371  {
3372  /* As above, ignore the signal if the GUC has been reset to zero. */
3373  if (IdleSessionTimeout > 0)
3374  ereport(FATAL,
3375  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3376  errmsg("terminating connection due to idle-session timeout")));
3377  else
3378  IdleSessionTimeoutPending = false;
3379  }
3380 
3381  /*
3382  * If there are pending stats updates and we currently are truly idle
3383  * (matching the conditions in PostgresMain(), report stats now.
3384  */
3387  {
3389  pgstat_report_stat(true);
3390  }
3391 
3394 
3397 
3400 
3403 }
volatile sig_atomic_t ParallelApplyMessagePending
void HandleParallelApplyMessages(void)
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3321
void HandleParallelMessages(void)
Definition: parallel.c:1025
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:116
bool IsLogicalWorker(void)
Definition: worker.c:4705
#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:1198
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1183
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
void pgstat_report_recovery_conflict(int reason)
int client_connection_check_interval
Definition: postgres.c:98
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2475
static bool RecoveryConflictRetryable
Definition: postgres.c:161
static bool RecoveryConflictPending
Definition: postgres.c:160
bool ClientAuthInProgress
Definition: postmaster.c:356
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:193
bool pq_check_connection(void)
Definition: pqcomm.c:2029
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 Assert(), BackgroundWorker::bgw_type, CheckClientConnectionPending, client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, enable_timeout_after(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_recovery_conflict(), errhint(), 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_recovery_conflict(), pgstat_report_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), PROCSIG_RECOVERY_CONFLICT_DATABASE, ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2838 of file postgres.c.

2839 {
2840  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2841  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
2842 
2843  /*
2844  * Prevent interrupts while exiting; though we just blocked signals that
2845  * would queue new interrupts, one may have been pending. We don't want a
2846  * quickdie() downgraded to a mere query cancel.
2847  */
2848  HOLD_INTERRUPTS();
2849 
2850  /*
2851  * If we're aborting out of client auth, don't risk trying to send
2852  * anything to the client; we will likely violate the protocol, not to
2853  * mention that we may have interrupted the guts of OpenSSL or some
2854  * authentication library.
2855  */
2858 
2859  /*
2860  * Notify the client before exiting, to give a clue on what happened.
2861  *
2862  * It's dubious to call ereport() from a signal handler. It is certainly
2863  * not async-signal safe. But it seems better to try, than to disconnect
2864  * abruptly and leave the client wondering what happened. It's remotely
2865  * possible that we crash or hang while trying to send the message, but
2866  * receiving a SIGQUIT is a sign that something has already gone badly
2867  * wrong, so there's not much to lose. Assuming the postmaster is still
2868  * running, it will SIGKILL us soon if we get stuck for some reason.
2869  *
2870  * One thing we can do to make this a tad safer is to clear the error
2871  * context stack, so that context callbacks are not called. That's a lot
2872  * less code that could be reached here, and the context info is unlikely
2873  * to be very relevant to a SIGQUIT report anyway.
2874  */
2875  error_context_stack = NULL;
2876 
2877  /*
2878  * When responding to a postmaster-issued signal, we send the message only
2879  * to the client; sending to the server log just creates log spam, plus
2880  * it's more code that we need to hope will work in a signal handler.
2881  *
2882  * Ideally these should be ereport(FATAL), but then we'd not get control
2883  * back to force the correct type of process exit.
2884  */
2885  switch (GetQuitSignalReason())
2886  {
2887  case PMQUIT_NOT_SENT:
2888  /* Hmm, SIGQUIT arrived out of the blue */
2889  ereport(WARNING,
2890  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2891  errmsg("terminating connection because of unexpected SIGQUIT signal")));
2892  break;
2893  case PMQUIT_FOR_CRASH:
2894  /* A crash-and-restart cycle is in progress */
2896  (errcode(ERRCODE_CRASH_SHUTDOWN),
2897  errmsg("terminating connection because of crash of another server process"),
2898  errdetail("The postmaster has commanded this server process to roll back"
2899  " the current transaction and exit, because another"
2900  " server process exited abnormally and possibly corrupted"
2901  " shared memory."),
2902  errhint("In a moment you should be able to reconnect to the"
2903  " database and repeat your command.")));
2904  break;
2905  case PMQUIT_FOR_STOP:
2906  /* Immediate-mode stop */
2908  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2909  errmsg("terminating connection due to immediate shutdown command")));
2910  break;
2911  }
2912 
2913  /*
2914  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2915  * because shared memory may be corrupted, so we don't want to try to
2916  * clean up our transaction. Just nail the windows shut and get out of
2917  * town. The callbacks wouldn't be safe to run from a signal handler,
2918  * anyway.
2919  *
2920  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2921  * a system reset cycle if someone sends a manual SIGQUIT to a random
2922  * backend. This is necessary precisely because we don't clean up our
2923  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2924  * should ensure the postmaster sees this as a crash, too, but no harm in
2925  * being doubly sure.)
2926  */
2927  _exit(2);
2928 }
sigset_t BlockSig
Definition: pqsignal.c:23
#define WARNING_CLIENT_ONLY
Definition: elog.h:38
QuitSignalReason GetQuitSignalReason(void)
Definition: pmsignal.c:229
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
@ PMQUIT_NOT_SENT
Definition: pmsignal.h:52

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

Referenced by PostgresMain().

◆ ReadCommand()

static int ReadCommand ( StringInfo  inBuf)
static

Definition at line 454 of file postgres.c.

455 {
456  int result;
457 
459  result = SocketBackend(inBuf);
460  else
461  result = InteractiveBackend(inBuf);
462  return result;
463 }
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:326
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:210

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

Referenced by PostgresMain().

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3008 of file postgres.c.

3009 {
3010  int save_errno = errno;
3011 
3012  /*
3013  * Don't joggle the elbow of proc_exit
3014  */
3015  if (!proc_exit_inprogress)
3016  {
3017  RecoveryConflictReason = reason;
3018  switch (reason)
3019  {
3021 
3022  /*
3023  * If we aren't waiting for a lock we can never deadlock.
3024  */
3025  if (!IsWaitingForLock())
3026  return;
3027 
3028  /* Intentional fall through to check wait for pin */
3029  /* FALLTHROUGH */
3030 
3032 
3033  /*
3034  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3035  * aren't blocking the Startup process there is nothing more
3036  * to do.
3037  *
3038  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is
3039  * requested, if we're waiting for locks and the startup
3040  * process is not waiting for buffer pin (i.e., also waiting
3041  * for locks), we set the flag so that ProcSleep() will check
3042  * for deadlocks.
3043  */
3045  {
3049  return;
3050  }
3051 
3053 
3054  /* Intentional fall through to error handling */
3055  /* FALLTHROUGH */
3056 
3060 
3061  /*
3062  * If we aren't in a transaction any longer then ignore.
3063  */
3065  return;
3066 
3067  /*
3068  * If we can abort just the current subtransaction then we are
3069  * OK to throw an ERROR to resolve the conflict. Otherwise
3070  * drop through to the FATAL case.
3071  *
3072  * XXX other times that we can throw just an ERROR *may* be
3073