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/select.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 3504 of file postgres.c.

3505 {
3506  long newval_bytes = newval * 1024L;
3507 
3508  max_stack_depth_bytes = newval_bytes;
3509 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:120

References max_stack_depth_bytes, and newval.

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2493 of file postgres.c.

2494 {
2497  char *quotedval;
2498 
2499  if (data->paramno < 0)
2500  return;
2501 
2502  /* If we have a textual value, quote it, and trim if necessary */
2503  if (data->paramval)
2504  {
2505  initStringInfo(&buf);
2508  quotedval = buf.data;
2509  }
2510  else
2511  quotedval = NULL;
2512 
2513  if (data->portalName && data->portalName[0] != '\0')
2514  {
2515  if (quotedval)
2516  errcontext("portal \"%s\" parameter $%d = %s",
2517  data->portalName, data->paramno + 1, quotedval);
2518  else
2519  errcontext("portal \"%s\" parameter $%d",
2520  data->portalName, data->paramno + 1);
2521  }
2522  else
2523  {
2524  if (quotedval)
2525  errcontext("unnamed portal parameter $%d = %s",
2526  data->paramno + 1, quotedval);
2527  else
2528  errcontext("unnamed portal parameter $%d",
2529  data->paramno + 1);
2530  }
2531 
2532  if (quotedval)
2533  pfree(quotedval);
2534 }
#define errcontext
Definition: elog.h:192
int log_parameter_max_length_on_error
Definition: guc_tables.c:491
void pfree(void *pointer)
Definition: mcxt.c:1306
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 3515 of file postgres.c.

3516 {
3517  if (!WaitEventSetCanReportClosed() && *newval != 0)
3518  {
3519  GUC_check_errdetail("client_connection_check_interval must be set to 0 on this platform.");
3520  return false;
3521  }
3522  return true;
3523 }
#define GUC_check_errdetail
Definition: guc.h:434
bool WaitEventSetCanReportClosed(void)
Definition: latch.c:2091

References GUC_check_errdetail, newval, and WaitEventSetCanReportClosed().

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2327 of file postgres.c.

2328 {
2329  if (log_duration || log_min_duration_sample >= 0 ||
2331  {
2332  long secs;
2333  int usecs;
2334  int msecs;
2335  bool exceeded_duration;
2336  bool exceeded_sample_duration;
2337  bool in_sample = false;
2338 
2341  &secs, &usecs);
2342  msecs = usecs / 1000;
2343 
2344  /*
2345  * This odd-looking test for log_min_duration_* being exceeded is
2346  * designed to avoid integer overflow with very long durations: don't
2347  * compute secs * 1000 until we've verified it will fit in int.
2348  */
2349  exceeded_duration = (log_min_duration_statement == 0 ||
2351  (secs > log_min_duration_statement / 1000 ||
2352  secs * 1000 + msecs >= log_min_duration_statement)));
2353 
2354  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2355  (log_min_duration_sample > 0 &&
2356  (secs > log_min_duration_sample / 1000 ||
2357  secs * 1000 + msecs >= log_min_duration_sample)));
2358 
2359  /*
2360  * Do not log if log_statement_sample_rate = 0. Log a sample if
2361  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2362  * log_statement_sample_rate = 1.
2363  */
2364  if (exceeded_sample_duration)
2365  in_sample = log_statement_sample_rate != 0 &&
2366  (log_statement_sample_rate == 1 ||
2368 
2369  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2370  {
2371  snprintf(msec_str, 32, "%ld.%03d",
2372  secs * 1000 + msecs, usecs % 1000);
2373  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2374  return 2;
2375  else
2376  return 1;
2377  }
2378  }
2379 
2380  return 0;
2381 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1664
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1573
int log_min_duration_statement
Definition: guc_tables.c:489
int log_min_duration_sample
Definition: guc_tables.c:488
double log_statement_sample_rate
Definition: guc_tables.c:493
bool log_duration
Definition: guc_tables.c:461
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:226
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:28
#define snprintf
Definition: port.h:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:863
bool xact_is_sampled
Definition: xact.c:289

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

2289 {
2290  ListCell *stmt_item;
2291 
2292  if (log_statement == LOGSTMT_NONE)
2293  return false;
2294  if (log_statement == LOGSTMT_ALL)
2295  return true;
2296 
2297  /* Else we have to inspect the statement(s) to see whether to log */
2298  foreach(stmt_item, stmt_list)
2299  {
2300  Node *stmt = (Node *) lfirst(stmt_item);
2301 
2302  if (GetCommandLogLevel(stmt) <= log_statement)
2303  return true;
2304  }
2305 
2306  return false;
2307 }
#define lfirst(lc)
Definition: pg_list.h:170
int log_statement
Definition: postgres.c:90
Definition: nodes.h:118
@ LOGSTMT_NONE
Definition: tcopprot.h:38
@ LOGSTMT_ALL
Definition: tcopprot.h:41
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3240

References GetCommandLogLevel(), lfirst, log_statement, LOGSTMT_ALL, and LOGSTMT_NONE.

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

3551 {
3552  if (*newval &&
3554  {
3555  GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3556  "\"log_parser_stats\", \"log_planner_stats\", "
3557  "or \"log_executor_stats\" is true.");
3558  return false;
3559  }
3560  return true;
3561 }
bool log_parser_stats
Definition: guc_tables.c:467
bool log_planner_stats
Definition: guc_tables.c:468
bool log_executor_stats
Definition: guc_tables.c:469

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

3488 {
3489  long newval_bytes = *newval * 1024L;
3490  long stack_rlimit = get_stack_depth_rlimit();
3491 
3492  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3493  {
3494  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3495  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3496  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3497  return false;
3498  }
3499  return true;
3500 }
#define GUC_check_errhint
Definition: guc.h:438
long get_stack_depth_rlimit(void)
Definition: postgres.c:4817
#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 3440 of file postgres.c.

3441 {
3442  if (stack_is_too_deep())
3443  {
3444  ereport(ERROR,
3445  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3446  errmsg("stack depth limit exceeded"),
3447  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3448  "after ensuring the platform's stack depth limit is adequate.",
3449  max_stack_depth)));
3450  }
3451 }
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
int max_stack_depth
Definition: postgres.c:93
bool stack_is_too_deep(void)
Definition: postgres.c:3454

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

Referenced by 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(), JsonbDeepContains(), JumbleExpr(), 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(), 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_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 3536 of file postgres.c.

3537 {
3538  if (*newval && log_statement_stats)
3539  {
3540  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3541  return false;
3542  }
3543  return true;
3544 }
bool log_statement_stats
Definition: guc_tables.c:470

References GUC_check_errdetail, log_statement_stats, and newval.

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2917 of file postgres.c.

2918 {
2919  int save_errno = errno;
2920 
2921  /* Don't joggle the elbow of proc_exit */
2922  if (!proc_exit_inprogress)
2923  {
2924  InterruptPending = true;
2925  ProcDiePending = true;
2926  }
2927 
2928  /* for the cumulative stats system */
2930 
2931  /* If we're still here, waken anything waiting on the process latch */
2932  SetLatch(MyLatch);
2933 
2934  /*
2935  * If we're in single user mode, we want to quit immediately - we can't
2936  * rely on latches as they wouldn't work when stdin/stdout is a file.
2937  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2938  * effort just for the benefit of single user mode.
2939  */
2942 
2943  errno = save_errno;
2944 }
@ DestRemote
Definition: dest.h:91
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:591
@ DISCONNECT_KILLED
Definition: pgstat.h:81
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:85
static bool DoingCommandRead
Definition: postgres.c:139
void ProcessInterrupts(void)
Definition: postgres.c:3131

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

5023 {
5026 }
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 2795 of file postgres.c.

2796 {
2797  /* paranoia to avoid a dangling pointer in case of error */
2798  if (unnamed_stmt_psrc)
2799  {
2801 
2802  unnamed_stmt_psrc = NULL;
2803  DropCachedPlan(psrc);
2804  }
2805 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:498
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:153

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

5002 {
5003  /* must be within an xact */
5005 
5006  if (StatementTimeout > 0)
5007  {
5010  }
5011  else
5012  {
5015  }
5016 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool xact_started
Definition: postgres.c:132
int StatementTimeout
Definition: proc.c:61
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 2443 of file postgres.c.

2444 {
2446  errdetail("abort reason: recovery conflict");
2447 
2448  return 0;
2449 }
int errdetail(const char *fmt,...)
Definition: elog.c:1039
PGPROC * MyProc
Definition: proc.c:68
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 2390 of file postgres.c.

2391 {
2392  ListCell *parsetree_item;
2393 
2394  foreach(parsetree_item, raw_parsetree_list)
2395  {
2396  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2397 
2398  if (IsA(parsetree->stmt, ExecuteStmt))
2399  {
2400  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2401  PreparedStatement *pstmt;
2402 
2403  pstmt = FetchPreparedStatement(stmt->name, false);
2404  if (pstmt)
2405  {
2406  errdetail("prepare: %s", pstmt->plansource->query_string);
2407  return 0;
2408  }
2409  }
2410  }
2411 
2412  return 0;
2413 }
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:434
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define lfirst_node(type, lc)
Definition: pg_list.h:174
char * name
Definition: parsenodes.h:3681
Node * stmt
Definition: parsenodes.h:1657

References errdetail(), FetchPreparedStatement(), IsA, lfirst_node, ExecuteStmt::name, and RawStmt::stmt.

Referenced by exec_simple_query().

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2423 of file postgres.c.

2424 {
2425  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2426  {
2427  char *str;
2428 
2430  if (str && str[0] != '\0')
2431  errdetail("parameters: %s", str);
2432  }
2433 
2434  return 0;
2435 }
int log_parameter_max_length
Definition: guc_tables.c:490
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 2457 of file postgres.c.

2458 {
2459  switch (RecoveryConflictReason)
2460  {
2462  errdetail("User was holding shared buffer pin for too long.");
2463  break;
2465  errdetail("User was holding a relation lock for too long.");
2466  break;
2468  errdetail("User was or might have been using tablespace that must be dropped.");
2469  break;
2471  errdetail("User query might have needed to see row versions that must be removed.");
2472  break;
2474  errdetail("User transaction caused buffer deadlock with recovery.");
2475  break;
2477  errdetail("User was connected to a database that must be dropped.");
2478  break;
2479  default:
2480  break;
2481  /* no errdetail */
2482  }
2483 
2484  return 0;
2485 }
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:163
@ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
Definition: procsignal.h:44
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:42
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:40
@ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
Definition: procsignal.h:43
@ PROCSIG_RECOVERY_CONFLICT_TABLESPACE
Definition: procsignal.h:41
@ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition: procsignal.h:45

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

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

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

2637 {
2638  Portal portal;
2639 
2640  /*
2641  * Start up a transaction command. (Note that this will normally change
2642  * current memory context.) Nothing happens if we are already in one.
2643  */
2645 
2646  /* Switch back to message context */
2648 
2649  portal = GetPortalByName(portal_name);
2650  if (!PortalIsValid(portal))
2651  ereport(ERROR,
2652  (errcode(ERRCODE_UNDEFINED_CURSOR),
2653  errmsg("portal \"%s\" does not exist", portal_name)));
2654 
2655  /*
2656  * If we are in aborted transaction state, we can't run
2657  * SendRowDescriptionMessage(), because that needs catalog accesses.
2658  * Hence, refuse to Describe portals that return data. (We shouldn't just
2659  * refuse all Describes, since that might break the ability of some
2660  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2661  * blindly Describes whatever it does.)
2662  */
2664  portal->tupDesc)
2665  ereport(ERROR,
2666  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2667  errmsg("current transaction is aborted, "
2668  "commands ignored until end of transaction block"),
2669  errdetail_abort()));
2670 
2672  return; /* can't actually do anything... */
2673 
2674  if (portal->tupDesc)
2676  portal->tupDesc,
2677  FetchPortalTargetList(portal),
2678  portal->formats);
2679  else
2680  pq_putemptymessage('n'); /* NoData */
2681 }
#define PortalIsValid(p)
Definition: portal.h:212
Portal GetPortalByName(const char *name)
Definition: portalmem.c:131
static StringInfoData row_description_buf
Definition: postgres.c:167
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 2542 of file postgres.c.

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

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

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

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

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

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

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

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, GetCommandTagName(), GetPortalByName(), GetTransactionSnapshot(), if(), InvalidSnapshot, IsA, IsAbortedTransactionBlockState(), FetchStmt::ismove, 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, FetchStmt::portalname, PortalRun(), PortalSetResultFormat(), PortalStart(), PushActiveSnapshot(), _DestReceiver::rDestroy, ResetUsage(), set_ps_display(), SetRemoteDestReceiverParams(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, PortalData::visible, whereToSendOutput, and XACT_FLAGS_NEEDIMMEDIATECOMMIT.

Referenced by PostgresMain().

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2716 of file postgres.c.

2717 {
2718  /* cancel active statement timeout after each command */
2720 
2721  if (xact_started)
2722  {
2724 
2725 #ifdef MEMORY_CONTEXT_CHECKING
2726  /* Check all memory contexts that weren't freed during commit */
2727  /* (those that were, were checked before being deleted) */
2728  MemoryContextCheck(TopMemoryContext);
2729 #endif
2730 
2731 #ifdef SHOW_MEMORY_STATS
2732  /* Print mem stats after each commit for leak tracking */
2734 #endif
2735 
2736  xact_started = false;
2737  }
2738 }
MemoryContext TopMemoryContext
Definition: mcxt.c:130
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:672
void CommitTransactionCommand(void)
Definition: xact.c:3022

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

2973 {
2974  /* We're not returning, so no need to save errno */
2975  ereport(ERROR,
2976  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2977  errmsg("floating-point exception"),
2978  errdetail("An invalid floating-point operation was signaled. "
2979  "This probably means an out-of-range result or an "
2980  "invalid operation, such as division by zero.")));
2981 }

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

4796 {
4797  if (am_walsender)
4798  {
4799  if (firstchar == 'F')
4800  ereport(ERROR,
4801  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4802  errmsg("fastpath function calls not supported in a replication connection")));
4803  else
4804  ereport(ERROR,
4805  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4806  errmsg("extended query protocol not supported in a replication connection")));
4807  }
4808 }
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 4817 of file postgres.c.

4818 {
4819 #if defined(HAVE_GETRLIMIT)
4820  static long val = 0;
4821 
4822  /* This won't change after process launch, so check just once */
4823  if (val == 0)
4824  {
4825  struct rlimit rlim;
4826 
4827  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4828  val = -1;
4829  else if (rlim.rlim_cur == RLIM_INFINITY)
4830  val = LONG_MAX;
4831  /* rlim_cur is probably of an unsigned type, so check for overflow */
4832  else if (rlim.rlim_cur >= LONG_MAX)
4833  val = LONG_MAX;
4834  else
4835  val = rlim.rlim_cur;
4836  }
4837  return val;
4838 #else
4839  /* On Windows we set the backend stack size in src/backend/Makefile */
4840  return WIN32_STACK_RLIMIT;
4841 #endif
4842 }
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 3642 of file postgres.c.

3643 {
3644  switch (arg[0])
3645  {
3646  case 'p':
3647  if (optarg[1] == 'a') /* "parser" */
3648  return "log_parser_stats";
3649  else if (optarg[1] == 'l') /* "planner" */
3650  return "log_planner_stats";
3651  break;
3652 
3653  case 'e': /* "executor" */
3654  return "log_executor_stats";
3655  break;
3656  }
3657 
3658  return NULL;
3659 }
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 299 of file postgres.c.

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

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 211 of file postgres.c.

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

2749 {
2750  if (parsetree && IsA(parsetree, TransactionStmt))
2751  {
2752  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2753 
2754  if (stmt->kind == TRANS_STMT_COMMIT ||
2755  stmt->kind == TRANS_STMT_PREPARE ||
2756  stmt->kind == TRANS_STMT_ROLLBACK ||
2757  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2758  return true;
2759  }
2760  return false;
2761 }
@ TRANS_STMT_ROLLBACK_TO
Definition: parsenodes.h:3299
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3296
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3295
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3300
TransactionStmtKind kind
Definition: parsenodes.h:3308

References IsA, TransactionStmt::kind, 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 2765 of file postgres.c.

2766 {
2767  if (list_length(pstmts) == 1)
2768  {
2769  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2770 
2771  if (pstmt->commandType == CMD_UTILITY &&
2773  return true;
2774  }
2775  return false;
2776 }
@ CMD_UTILITY
Definition: nodes.h:270
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 2780 of file postgres.c.

2781 {
2782  if (list_length(pstmts) == 1)
2783  {
2784  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2785 
2786  if (pstmt->commandType == CMD_UTILITY &&
2787  IsA(pstmt->utilityStmt, TransactionStmt))
2788  return true;
2789  }
2790  return false;
2791 }

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

4966 {
4967  Port *port = MyProcPort;
4968  long secs;
4969  int usecs;
4970  int msecs;
4971  int hours,
4972  minutes,
4973  seconds;
4974 
4977  &secs, &usecs);
4978  msecs = usecs / 1000;
4979 
4980  hours = secs / SECS_PER_HOUR;
4981  secs %= SECS_PER_HOUR;
4982  minutes = secs / SECS_PER_MINUTE;
4983  seconds = secs % SECS_PER_MINUTE;
4984 
4985  ereport(LOG,
4986  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4987  "user=%s database=%s host=%s%s%s",
4988  hours, minutes, seconds, msecs,
4989  port->user_name, port->database_name, port->remote_host,
4990  port->remote_port[0] ? " port=" : "", port->remote_port)));
4991 }
#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 638 of file postgres.c.

643 {
644  Query *query;
645  List *querytree_list;
646 
647  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
648 
649  /*
650  * (1) Perform parse analysis.
651  */
652  if (log_parser_stats)
653  ResetUsage();
654 
655  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
656  queryEnv);
657 
658  if (log_parser_stats)
659  ShowUsage("PARSE ANALYSIS STATISTICS");
660 
661  /*
662  * (2) Rewrite the queries, as necessary
663  */
664  querytree_list = pg_rewrite_query(query);
665 
666  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
667 
668  return querytree_list;
669 }
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:106
List * pg_rewrite_query(Query *query)
Definition: postgres.c:771

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

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

736 {
737  Query *query;
738  List *querytree_list;
739 
740  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
741 
742  /*
743  * (1) Perform parse analysis.
744  */
745  if (log_parser_stats)
746  ResetUsage();
747 
748  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
749  queryEnv);
750 
751  if (log_parser_stats)
752  ShowUsage("PARSE ANALYSIS STATISTICS");
753 
754  /*
755  * (2) Rewrite the queries, as necessary
756  */
757  querytree_list = pg_rewrite_query(query);
758 
759  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
760 
761  return querytree_list;
762 }
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:187

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

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

941 {
942  List *stmt_list = NIL;
943  ListCell *query_list;
944 
945  foreach(query_list, querytrees)
946  {
947  Query *query = lfirst_node(Query, query_list);
948  PlannedStmt *stmt;
949 
950  if (query->commandType == CMD_UTILITY)
951  {
952  /* Utility commands require no planning. */
953  stmt = makeNode(PlannedStmt);
954  stmt->commandType = CMD_UTILITY;
955  stmt->canSetTag = query->canSetTag;
956  stmt->utilityStmt = query->utilityStmt;
957  stmt->stmt_location = query->stmt_location;
958  stmt->stmt_len = query->stmt_len;
959  stmt->queryId = query->queryId;
960  }
961  else
962  {
963  stmt = pg_plan_query(query, query_string, cursorOptions,
964  boundParams);
965  }
966 
967  stmt_list = lappend(stmt_list, stmt);
968  }
969 
970  return stmt_list;
971 }
List * lappend(List *list, void *datum)
Definition: list.c:338
#define makeNode(_type_)
Definition: nodes.h:165
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:853
bool canSetTag
Definition: plannodes.h:61
int stmt_location
Definition: plannodes.h:102
int stmt_len
Definition: plannodes.h:103
uint64 queryId
Definition: plannodes.h:55
int stmt_location
Definition: parsenodes.h:206
int stmt_len
Definition: parsenodes.h:207
bool canSetTag
Definition: parsenodes.h:134
CmdType commandType
Definition: parsenodes.h:124
Node * utilityStmt
Definition: parsenodes.h:136

References Query::canSetTag, PlannedStmt::canSetTag, CMD_UTILITY, Query::commandType, PlannedStmt::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PlannedStmt::queryId, Query::stmt_len, PlannedStmt::stmt_len, Query::stmt_location, PlannedStmt::stmt_location, Query::utilityStmt, and PlannedStmt::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 853 of file postgres.c.

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

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

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

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

3936 {
3937  const char *dbname = NULL;
3938 
3940 
3941  /* Initialize startup process environment. */
3942  InitStandaloneProcess(argv[0]);
3943 
3944  /*
3945  * Set default values for command-line options.
3946  */
3948 
3949  /*
3950  * Parse command-line options.
3951  */
3953 
3954  /* Must have gotten a database name, or have a default (the username) */
3955  if (dbname == NULL)
3956  {
3957  dbname = username;
3958  if (dbname == NULL)
3959  ereport(FATAL,
3960  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3961  errmsg("%s: no database nor user name specified",
3962  progname)));
3963  }
3964 
3965  /* Acquire configuration parameters */
3967  proc_exit(1);
3968 
3969  /*
3970  * Validate we have been given a reasonable-looking DataDir and change
3971  * into it.
3972  */
3973  checkDataDir();
3974  ChangeToDataDir();
3975 
3976  /*
3977  * Create lockfile for data directory.
3978  */
3979  CreateDataDirLockFile(false);
3980 
3981  /* read control file (error checking and contains config ) */
3982  LocalProcessControlFile(false);
3983 
3984  /*
3985  * process any libraries that should be preloaded at postmaster start
3986  */
3988 
3989  /* Initialize MaxBackends */
3991 
3992  /*
3993  * Give preloaded libraries a chance to request additional shared memory.
3994  */
3996 
3997  /*
3998  * Now that loadable modules have had their chance to request additional
3999  * shared memory, determine the value of any runtime-computed GUCs that
4000  * depend on the amount of shared memory required.
4001  */
4003 
4004  /*
4005  * Now that modules have been loaded, we can process any custom resource
4006  * managers specified in the wal_consistency_checking GUC.
4007  */
4009 
4011 
4012  /*
4013  * Remember stand-alone backend startup time,roughly at the same point
4014  * during startup that postmaster does so.
4015  */
4017 
4018  /*
4019  * Create a per-backend PGPROC struct in shared memory. We must do this
4020  * before we can use LWLocks.
4021  */
4022  InitProcess();
4023 
4024  /*
4025  * Now that sufficient infrastructure has been initialized, PostgresMain()
4026  * can do the rest.
4027  */
4029 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1731
void InitializeGUCOptions(void)
Definition: guc.c:1477
@ 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:436
void process_shmem_requests(void)
Definition: miscinit.c:1858
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void process_shared_preload_libraries(void)
Definition: miscinit.c:1830
void checkDataDir(void)
Definition: miscinit.c:323
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1442
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3682
static const char * userDoption
Definition: postgres.c:156
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4044
void InitializeMaxBackends(void)
Definition: postinit.c:553
void InitProcess(void)
Definition: proc.c:301
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4404
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4467

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

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

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

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

3132 {
3133  /* OK to accept any interrupts now? */
3134  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3135  return;
3136  InterruptPending = false;
3137 
3138  if (ProcDiePending)
3139  {
3140  ProcDiePending = false;
3141  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3142  LockErrorCleanup();
3143  /* As in quickdie, don't risk sending to client during auth */
3147  ereport(FATAL,
3148  (errcode(ERRCODE_QUERY_CANCELED),
3149  errmsg("canceling authentication due to timeout")));
3150  else if (IsAutoVacuumWorkerProcess())
3151  ereport(FATAL,
3152  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3153  errmsg("terminating autovacuum process due to administrator command")));
3154  else if (IsLogicalWorker())
3155  ereport(FATAL,
3156  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3157  errmsg("terminating logical replication worker due to administrator command")));
3158  else if (IsLogicalLauncher())
3159  {
3160  ereport(DEBUG1,
3161  (errmsg_internal("logical replication launcher shutting down")));
3162 
3163  /*
3164  * The logical replication launcher can be stopped at any time.
3165  * Use exit status 1 so the background worker is restarted.
3166  */
3167  proc_exit(1);
3168  }
3170  {
3172  ereport(FATAL,
3174  errmsg("terminating connection due to conflict with recovery"),
3176  }
3177  else if (RecoveryConflictPending)
3178  {
3179  /* Currently there is only one non-retryable recovery conflict */
3182  ereport(FATAL,
3183  (errcode(ERRCODE_DATABASE_DROPPED),
3184  errmsg("terminating connection due to conflict with recovery"),
3186  }
3187  else if (IsBackgroundWorker)
3188  ereport(FATAL,
3189  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3190  errmsg("terminating background worker \"%s\" due to administrator command",
3192  else
3193  ereport(FATAL,
3194  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3195  errmsg("terminating connection due to administrator command")));
3196  }
3197 
3199  {
3201 
3202  /*
3203  * Check for lost connection and re-arm, if still configured, but not
3204  * if we've arrived back at DoingCommandRead state. We don't want to
3205  * wake up idle sessions, and they already know how to detect lost
3206  * connections.
3207  */
3209  {
3210  if (!pq_check_connection())
3211  ClientConnectionLost = true;
3212  else
3215  }
3216  }
3217 
3219  {
3220  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3221  LockErrorCleanup();
3222  /* don't send to client, we already know the connection to be dead. */
3224  ereport(FATAL,
3225  (errcode(ERRCODE_CONNECTION_FAILURE),
3226  errmsg("connection to client lost")));
3227  }
3228 
3229  /*
3230  * If a recovery conflict happens while we are waiting for input from the
3231  * client, the client is presumably just sitting idle in a transaction,
3232  * preventing recovery from making progress. Terminate the connection to
3233  * dislodge it.
3234  */
3236  {
3237  QueryCancelPending = false; /* this trumps QueryCancel */
3238  RecoveryConflictPending = false;
3239  LockErrorCleanup();
3241  ereport(FATAL,
3243  errmsg("terminating connection due to conflict with recovery"),
3245  errhint("In a moment you should be able to reconnect to the"
3246  " database and repeat your command.")));
3247  }
3248 
3249  /*
3250  * Don't allow query cancel interrupts while reading input from the
3251  * client, because we might lose sync in the FE/BE protocol. (Die
3252  * interrupts are OK, because we won't read any further messages from the
3253  * client in that case.)
3254  */
3256  {
3257  /*
3258  * Re-arm InterruptPending so that we process the cancel request as
3259  * soon as we're done reading the message. (XXX this is seriously
3260  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3261  * can't use that macro directly as the initial test in this function,
3262  * meaning that this code also creates opportunities for other bugs to
3263  * appear.)
3264  */
3265  InterruptPending = true;
3266  }
3267  else if (QueryCancelPending)
3268  {
3269  bool lock_timeout_occurred;
3270  bool stmt_timeout_occurred;
3271 
3272  QueryCancelPending = false;
3273 
3274  /*
3275  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3276  * need to clear both, so always fetch both.
3277  */
3278  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3279  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3280 
3281  /*
3282  * If both were set, we want to report whichever timeout completed
3283  * earlier; this ensures consistent behavior if the machine is slow
3284  * enough that the second timeout triggers before we get here. A tie
3285  * is arbitrarily broken in favor of reporting a lock timeout.
3286  */
3287  if (lock_timeout_occurred && stmt_timeout_occurred &&
3289  lock_timeout_occurred = false; /* report stmt timeout */
3290 
3291  if (lock_timeout_occurred)
3292  {
3293  LockErrorCleanup();
3294  ereport(ERROR,
3295  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3296  errmsg("canceling statement due to lock timeout")));
3297  }
3298  if (stmt_timeout_occurred)
3299  {
3300  LockErrorCleanup();
3301  ereport(ERROR,
3302  (errcode(ERRCODE_QUERY_CANCELED),
3303  errmsg("canceling statement due to statement timeout")));
3304  }
3306  {
3307  LockErrorCleanup();
3308  ereport(ERROR,
3309  (errcode(ERRCODE_QUERY_CANCELED),
3310  errmsg("canceling autovacuum task")));
3311  }
3313  {
3314  RecoveryConflictPending = false;
3315  LockErrorCleanup();
3317  ereport(ERROR,
3319  errmsg("canceling statement due to conflict with recovery"),
3321  }
3322 
3323  /*
3324  * If we are reading a command from the client, just ignore the cancel
3325  * request --- sending an extra error message won't accomplish
3326  * anything. Otherwise, go ahead and throw the error.
3327  */
3328  if (!DoingCommandRead)
3329  {
3330  LockErrorCleanup();
3331  ereport(ERROR,
3332  (errcode(ERRCODE_QUERY_CANCELED),
3333  errmsg("canceling statement due to user request")));
3334  }
3335  }
3336 
3338  {
3339  /*
3340  * If the GUC has been reset to zero, ignore the signal. This is
3341  * important because the GUC update itself won't disable any pending
3342  * interrupt.
3343  */
3345  ereport(FATAL,
3346  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3347  errmsg("terminating connection due to idle-in-transaction timeout")));
3348  else
3350  }
3351 
3353  {
3354  /* As above, ignore the signal if the GUC has been reset to zero. */
3355  if (IdleSessionTimeout > 0)
3356  ereport(FATAL,
3357  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3358  errmsg("terminating connection due to idle-session timeout")));
3359  else
3360  IdleSessionTimeoutPending = false;
3361  }
3362 
3363  /*
3364  * If there are pending stats updates and we currently are truly idle
3365  * (matching the conditions in PostgresMain(), report stats now.
3366  */
3369  {
3371  pgstat_report_stat(true);
3372  }
3373 
3376 
3379 
3382 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3314
void HandleParallelMessages(void)
Definition: parallel.c:1025
volatile sig_atomic_t ParallelMessagePending
Definition: parallel.c:116
bool IsLogicalWorker(void)
Definition: worker.c:3897
#define DEBUG1
Definition: elog.h:26
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:918
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1172
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:75
void pgstat_report_recovery_conflict(int reason)
int client_connection_check_interval
Definition: postgres.c:99
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2457
static bool RecoveryConflictRetryable
Definition: postgres.c:162
static bool RecoveryConflictPending
Definition: postgres.c:161
bool ClientAuthInProgress
Definition: postmaster.c:347
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
bool pq_check_connection(void)
Definition: pqcomm.c:2023
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:467
void LockErrorCleanup(void)
Definition: proc.c:699
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(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, IdleStatsUpdateTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsLogicalLauncher(), IsLogicalWorker(), IsTransactionOrTransactionBlock(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, 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 2820 of file postgres.c.

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

456 {
457  int result;
458 
460  result = SocketBackend(inBuf);
461  else
462  result = InteractiveBackend(inBuf);
463  return result;
464 }
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:327
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:211

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

Referenced by PostgresMain().

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2990 of file postgres.c.

2991 {
2992  int save_errno = errno;
2993 
2994  /*
2995  * Don't joggle the elbow of proc_exit
2996  */
2997  if (!proc_exit_inprogress)
2998  {
2999  RecoveryConflictReason = reason;
3000  switch (reason)
3001  {
3003 
3004  /*
3005  * If we aren't waiting for a lock we can never deadlock.
3006  */
3007  if (!IsWaitingForLock())
3008  return;
3009 
3010  /* Intentional fall through to check wait for pin */
3011  /* FALLTHROUGH */
3012 
3014 
3015  /*
3016  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3017  * aren't blocking the Startup process there is nothing more
3018  * to do.
3019  *
3020  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is
3021  * requested, if we're waiting for locks and the startup
3022  * process is not waiting for buffer pin (i.e., also waiting
3023  * for locks), we set the flag so that ProcSleep() will check
3024  * for deadlocks.
3025  */
3027  {
3031  return;
3032  }
3033 
3035 
3036  /* Intentional fall through to error handling */
3037  /* FALLTHROUGH */
3038 
3042 
3043  /*
3044  * If we aren't in a transaction any longer then ignore.
3045  */
3047  return;
3048 
3049  /*
3050  * If we can abort just the current subtransaction then we are
3051  * OK to throw an ERROR to resolve the conflict. Otherwise
3052  * drop through to the FATAL case.
3053  *
3054  * XXX other times that we can throw just an ERROR *may* be
3055  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
3056  * parent transactions
3057  *
3058  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
3059  * by parent transactions and the transaction is not
3060  * transaction-snapshot mode
3061  *
3062  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3063  * cursors open in parent transactions
3064  */
3065  if (!IsSubTransaction())