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/socket.h>
#include "rusagestub.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 "executor/spi.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/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 (RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_params (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)
 
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 PostgresMain (int argc, char *argv[], 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
 
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 3549 of file postgres.c.

References max_stack_depth_bytes.

3550 {
3551  long newval_bytes = newval * 1024L;
3552 
3553  max_stack_depth_bytes = newval_bytes;
3554 }
static long max_stack_depth_bytes
Definition: postgres.c:127
#define newval

◆ bind_param_error_callback()

static void bind_param_error_callback ( void *  arg)
static

Definition at line 2490 of file postgres.c.

References appendStringInfoStringQuoted(), buf, StringInfoData::data, errcontext, initStringInfo(), log_parameter_max_length_on_error, BindParamCbData::paramno, BindParamCbData::paramval, pfree(), and BindParamCbData::portalName.

Referenced by exec_bind_message().

2491 {
2492  BindParamCbData *data = (BindParamCbData *) arg;
2494  char *quotedval;
2495 
2496  if (data->paramno < 0)
2497  return;
2498 
2499  /* If we have a textual value, quote it, and trim if necessary */
2500  if (data->paramval)
2501  {
2502  initStringInfo(&buf);
2505  quotedval = buf.data;
2506  }
2507  else
2508  quotedval = NULL;
2509 
2510  if (data->portalName && data->portalName[0] != '\0')
2511  {
2512  if (quotedval)
2513  errcontext("portal \"%s\" parameter $%d = %s",
2514  data->portalName, data->paramno + 1, quotedval);
2515  else
2516  errcontext("portal \"%s\" parameter $%d",
2517  data->portalName, data->paramno + 1);
2518  }
2519  else
2520  {
2521  if (quotedval)
2522  errcontext("unnamed portal parameter $%d = %s",
2523  data->paramno + 1, quotedval);
2524  else
2525  errcontext("unnamed portal parameter $%d",
2526  data->paramno + 1);
2527  }
2528 
2529  if (quotedval)
2530  pfree(quotedval);
2531 }
void pfree(void *pointer)
Definition: mcxt.c:1169
static char * buf
Definition: pg_test_fsync.c:68
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define errcontext
Definition: elog.h:204
void * arg
const char * portalName
Definition: postgres.c:116
const char * paramval
Definition: postgres.c:118
void appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen)
Definition: stringinfo_mb.c:34
int log_parameter_max_length_on_error
Definition: guc.c:601

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2324 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, MAX_RANDOM_VALUE, random(), snprintf, TimestampDifference(), and xact_is_sampled.

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

2325 {
2326  if (log_duration || log_min_duration_sample >= 0 ||
2328  {
2329  long secs;
2330  int usecs;
2331  int msecs;
2332  bool exceeded_duration;
2333  bool exceeded_sample_duration;
2334  bool in_sample = false;
2335 
2338  &secs, &usecs);
2339  msecs = usecs / 1000;
2340 
2341  /*
2342  * This odd-looking test for log_min_duration_* being exceeded is
2343  * designed to avoid integer overflow with very long durations: don't
2344  * compute secs * 1000 until we've verified it will fit in int.
2345  */
2346  exceeded_duration = (log_min_duration_statement == 0 ||
2348  (secs > log_min_duration_statement / 1000 ||
2349  secs * 1000 + msecs >= log_min_duration_statement)));
2350 
2351  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2352  (log_min_duration_sample > 0 &&
2353  (secs > log_min_duration_sample / 1000 ||
2354  secs * 1000 + msecs >= log_min_duration_sample)));
2355 
2356  /*
2357  * Do not log if log_statement_sample_rate = 0. Log a sample if
2358  * log_statement_sample_rate <= 1 and avoid unnecessary random() call
2359  * if log_statement_sample_rate = 1.
2360  */
2361  if (exceeded_sample_duration)
2362  in_sample = log_statement_sample_rate != 0 &&
2363  (log_statement_sample_rate == 1 ||
2365 
2366  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2367  {
2368  snprintf(msec_str, 32, "%ld.%03d",
2369  secs * 1000 + msecs, usecs % 1000);
2370  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2371  return 2;
2372  else
2373  return 1;
2374  }
2375  }
2376 
2377  return 0;
2378 }
int log_min_duration_statement
Definition: guc.c:599
double log_statement_sample_rate
Definition: guc.c:603
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
long random(void)
Definition: random.c:22
int log_min_duration_sample
Definition: guc.c:598
#define MAX_RANDOM_VALUE
bool xact_is_sampled
Definition: xact.c:283
bool log_duration
Definition: guc.c:571
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1656
#define snprintf
Definition: port.h:216
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:807

◆ check_log_statement()

static bool check_log_statement ( List stmt_list)
static

Definition at line 2285 of file postgres.c.

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

Referenced by exec_execute_message(), and exec_simple_query().

2286 {
2287  ListCell *stmt_item;
2288 
2289  if (log_statement == LOGSTMT_NONE)
2290  return false;
2291  if (log_statement == LOGSTMT_ALL)
2292  return true;
2293 
2294  /* Else we have to inspect the statement(s) to see whether to log */
2295  foreach(stmt_item, stmt_list)
2296  {
2297  Node *stmt = (Node *) lfirst(stmt_item);
2298 
2299  if (GetCommandLogLevel(stmt) <= log_statement)
2300  return true;
2301  }
2302 
2303  return false;
2304 }
Definition: nodes.h:539
#define lfirst(lc)
Definition: pg_list.h:169
int log_statement
Definition: postgres.c:97
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:3199

◆ check_max_stack_depth()

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

Definition at line 3532 of file postgres.c.

References get_stack_depth_rlimit(), GUC_check_errdetail, GUC_check_errhint, and STACK_DEPTH_SLOP.

3533 {
3534  long newval_bytes = *newval * 1024L;
3535  long stack_rlimit = get_stack_depth_rlimit();
3536 
3537  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3538  {
3539  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3540  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3541  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3542  return false;
3543  }
3544  return true;
3545 }
#define GUC_check_errdetail
Definition: guc.h:416
long get_stack_depth_rlimit(void)
Definition: postgres.c:4752
#define newval
#define GUC_check_errhint
Definition: guc.h:420
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3469 of file postgres.c.

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(), execute(), executeAnyItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator(), expression_tree_walker(), 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(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker(), 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(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), setPath(), split_array(), standard_ProcessUtility(), transformExprRecurse(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3470 {
3471  if (stack_is_too_deep())
3472  {
3473  ereport(ERROR,
3474  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3475  errmsg("stack depth limit exceeded"),
3476  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3477  "after ensuring the platform's stack depth limit is adequate.",
3478  max_stack_depth)));
3479  }
3480 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int max_stack_depth
Definition: postgres.c:100
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
bool stack_is_too_deep(void)
Definition: postgres.c:3483

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2915 of file postgres.c.

References DestRemote, DISCONNECT_KILLED, DoingCommandRead, InterruptPending, MyLatch, pgStatSessionEndCause, proc_exit_inprogress, ProcDiePending, ProcessInterrupts(), SetLatch(), and whereToSendOutput.

Referenced by PostgresMain().

2916 {
2917  int save_errno = errno;
2918 
2919  /* Don't joggle the elbow of proc_exit */
2920  if (!proc_exit_inprogress)
2921  {
2922  InterruptPending = true;
2923  ProcDiePending = true;
2924  }
2925 
2926  /* for the statistics collector */
2928 
2929  /* If we're still here, waken anything waiting on the process latch */
2930  SetLatch(MyLatch);
2931 
2932  /*
2933  * If we're in single user mode, we want to quit immediately - we can't
2934  * rely on latches as they wouldn't work when stdin/stdout is a file.
2935  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2936  * effort just for the benefit of single user mode.
2937  */
2940 
2941  errno = save_errno;
2942 }
SessionEndType pgStatSessionEndCause
Definition: pgstat.c:250
void SetLatch(Latch *latch)
Definition: latch.c:567
void ProcessInterrupts(void)
Definition: postgres.c:3129
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:155
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:57
CommandDest whereToSendOutput
Definition: postgres.c:92

◆ disable_statement_timeout()

static void disable_statement_timeout ( void  )
static

Definition at line 4954 of file postgres.c.

References disable_timeout(), get_timeout_active(), and STATEMENT_TIMEOUT.

Referenced by exec_execute_message(), exec_simple_query(), and finish_xact_command().

4955 {
4958 }
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:716

◆ drop_unnamed_stmt()

static void drop_unnamed_stmt ( void  )
static

Definition at line 2793 of file postgres.c.

References DropCachedPlan(), and unnamed_stmt_psrc.

Referenced by exec_parse_message(), exec_simple_query(), and PostgresMain().

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

◆ enable_statement_timeout()

static void enable_statement_timeout ( void  )
static

Definition at line 4933 of file postgres.c.

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

Referenced by start_xact_command().

4934 {
4935  /* must be within an xact */
4937 
4938  if (StatementTimeout > 0)
4939  {
4942  }
4943  else
4944  {
4947  }
4948 }
static bool xact_started
Definition: postgres.c:148
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:524
#define Assert(condition)
Definition: c.h:804
int StatementTimeout
Definition: proc.c:61
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:716

◆ errdetail_abort()

static int errdetail_abort ( void  )
static

Definition at line 2440 of file postgres.c.

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().

2441 {
2443  errdetail("abort reason: recovery conflict");
2444 
2445  return 0;
2446 }
PGPROC * MyProc
Definition: proc.c:68
bool recoveryConflictPending
Definition: proc.h:167
int errdetail(const char *fmt,...)
Definition: elog.c:1042

◆ errdetail_execute()

static int errdetail_execute ( List raw_parsetree_list)
static

Definition at line 2387 of file postgres.c.

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

Referenced by exec_simple_query().

2388 {
2389  ListCell *parsetree_item;
2390 
2391  foreach(parsetree_item, raw_parsetree_list)
2392  {
2393  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2394 
2395  if (IsA(parsetree->stmt, ExecuteStmt))
2396  {
2397  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2398  PreparedStatement *pstmt;
2399 
2400  pstmt = FetchPreparedStatement(stmt->name, false);
2401  if (pstmt)
2402  {
2403  errdetail("prepare: %s", pstmt->plansource->query_string);
2404  return 0;
2405  }
2406  }
2407  }
2408 
2409  return 0;
2410 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Node * stmt
Definition: parsenodes.h:1560
int errdetail(const char *fmt,...)
Definition: elog.c:1042
char * name
Definition: parsenodes.h:3552
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:468

◆ errdetail_params()

static int errdetail_params ( ParamListInfo  params)
static

Definition at line 2420 of file postgres.c.

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

Referenced by exec_bind_message(), and exec_execute_message().

2421 {
2422  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2423  {
2424  char *str;
2425 
2426  str = BuildParamLogString(params, NULL, log_parameter_max_length);
2427  if (str && str[0] != '\0')
2428  errdetail("parameters: %s", str);
2429  }
2430 
2431  return 0;
2432 }
int log_parameter_max_length
Definition: guc.c:600
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335
int errdetail(const char *fmt,...)
Definition: elog.c:1042

◆ errdetail_recovery_conflict()

static int errdetail_recovery_conflict ( void  )
static

Definition at line 2454 of file postgres.c.

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().

2455 {
2456  switch (RecoveryConflictReason)
2457  {
2459  errdetail("User was holding shared buffer pin for too long.");
2460  break;
2462  errdetail("User was holding a relation lock for too long.");
2463  break;
2465  errdetail("User was or might have been using tablespace that must be dropped.");
2466  break;
2468  errdetail("User query might have needed to see row versions that must be removed.");
2469  break;
2471  errdetail("User transaction caused buffer deadlock with recovery.");
2472  break;
2474  errdetail("User was connected to a database that must be dropped.");
2475  break;
2476  default:
2477  break;
2478  /* no errdetail */
2479  }
2480 
2481  return 0;
2482 }
int errdetail(const char *fmt,...)
Definition: elog.c:1042
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:179

◆ exec_bind_message()

static void exec_bind_message ( StringInfo  input_message)
static

Definition at line 1581 of file postgres.c.

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(), palloc(), palloc0(), 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().

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

◆ exec_describe_portal_message()

static void exec_describe_portal_message ( const char *  portal_name)
static

Definition at line 2634 of file postgres.c.

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

Referenced by PostgresMain().

2635 {
2636  Portal portal;
2637 
2638  /*
2639  * Start up a transaction command. (Note that this will normally change
2640  * current memory context.) Nothing happens if we are already in one.
2641  */
2643 
2644  /* Switch back to message context */
2646 
2647  portal = GetPortalByName(portal_name);
2648  if (!PortalIsValid(portal))
2649  ereport(ERROR,
2650  (errcode(ERRCODE_UNDEFINED_CURSOR),
2651  errmsg("portal \"%s\" does not exist", portal_name)));
2652 
2653  /*
2654  * If we are in aborted transaction state, we can't run
2655  * SendRowDescriptionMessage(), because that needs catalog accesses.
2656  * Hence, refuse to Describe portals that return data. (We shouldn't just
2657  * refuse all Describes, since that might break the ability of some
2658  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2659  * blindly Describes whatever it does.)
2660  */
2662  portal->tupDesc)
2663  ereport(ERROR,
2664  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2665  errmsg("current transaction is aborted, "
2666  "commands ignored until end of transaction block"),
2667  errdetail_abort()));
2668 
2670  return; /* can't actually do anything... */
2671 
2672  if (portal->tupDesc)
2674  portal->tupDesc,
2675  FetchPortalTargetList(portal),
2676  portal->formats);
2677  else
2678  pq_putemptymessage('n'); /* NoData */
2679 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2440
#define ERROR
Definition: elog.h:46
#define PortalIsValid(p)
Definition: portal.h:211
static void start_xact_command(void)
Definition: postgres.c:2686
int16 * formats
Definition: portal.h:161
static StringInfoData row_description_buf
Definition: postgres.c:183
TupleDesc tupDesc
Definition: portal.h:159
#define ereport(elevel,...)
Definition: elog.h:157
MemoryContext MessageContext
Definition: mcxt.c:52
int errmsg(const char *fmt,...)
Definition: elog.c:909
CommandDest whereToSendOutput
Definition: postgres.c:92
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:323
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:166

◆ exec_describe_statement_message()

static void exec_describe_statement_message ( const char *  stmt_name)
static

Definition at line 2539 of file postgres.c.

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, SendRowDescriptionMessage(), start_xact_command(), unnamed_stmt_psrc, and whereToSendOutput.

Referenced by PostgresMain().

2540 {
2541  CachedPlanSource *psrc;
2542 
2543  /*
2544  * Start up a transaction command. (Note that this will normally change
2545  * current memory context.) Nothing happens if we are already in one.
2546  */
2548 
2549  /* Switch back to message context */
2551 
2552  /* Find prepared statement */
2553  if (stmt_name[0] != '\0')
2554  {
2555  PreparedStatement *pstmt;
2556 
2557  pstmt = FetchPreparedStatement(stmt_name, true);
2558  psrc = pstmt->plansource;
2559  }
2560  else
2561  {
2562  /* special-case the unnamed statement */
2563  psrc = unnamed_stmt_psrc;
2564  if (!psrc)
2565  ereport(ERROR,
2566  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2567  errmsg("unnamed prepared statement does not exist")));
2568  }
2569 
2570  /* Prepared statements shouldn't have changeable result descs */
2571  Assert(psrc->fixed_result);
2572 
2573  /*
2574  * If we are in aborted transaction state, we can't run
2575  * SendRowDescriptionMessage(), because that needs catalog accesses.
2576  * Hence, refuse to Describe statements that return data. (We shouldn't
2577  * just refuse all Describes, since that might break the ability of some
2578  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2579  * blindly Describes whatever it does.) We can Describe parameters
2580  * without doing anything dangerous, so we don't restrict that.
2581  */
2583  psrc->resultDesc)
2584  ereport(ERROR,
2585  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2586  errmsg("current transaction is aborted, "
2587  "commands ignored until end of transaction block"),
2588  errdetail_abort()));
2589 
2591  return; /* can't actually do anything... */
2592 
2593  /*
2594  * First describe the parameters...
2595  */
2596  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2597  * message type */
2599 
2600  for (int i = 0; i < psrc->num_params; i++)
2601  {
2602  Oid ptype = psrc->param_types[i];
2603 
2604  pq_sendint32(&row_description_buf, (int) ptype);
2605  }
2607 
2608  /*
2609  * Next send RowDescription or NoData to describe the result...
2610  */
2611  if (psrc->resultDesc)
2612  {
2613  List *tlist;
2614 
2615  /* Get the plan's primary targetlist */
2616  tlist = CachedPlanGetTargetList(psrc, NULL);
2617 
2619  psrc->resultDesc,
2620  tlist,
2621  NULL);
2622  }
2623  else
2624  pq_putemptymessage('n'); /* NoData */
2625 
2626 }
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
CachedPlanSource * plansource
Definition: prepare.h:31
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2440
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc resultDesc
Definition: plancache.h:108
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define ERROR
Definition: elog.h:46
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1611
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:169
static void start_xact_command(void)
Definition: postgres.c:2686
static StringInfoData row_description_buf
Definition: postgres.c:183
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
MemoryContext MessageContext
Definition: mcxt.c:52
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
CommandDest whereToSendOutput
Definition: postgres.c:92
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:166
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:468
Definition: pg_list.h:50
void pq_endmessage_reuse(StringInfo buf)
Definition: pqformat.c:316
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition: pqformat.c:108

◆ exec_execute_message()

static void exec_execute_message ( const char *  portal_name,
long  max_rows 
)
static

Definition at line 2043 of file postgres.c.

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

Referenced by PostgresMain().

2044 {
2045  CommandDest dest;
2046  DestReceiver *receiver;
2047  Portal portal;
2048  bool completed;
2049  QueryCompletion qc;
2050  const char *sourceText;
2051  const char *prepStmtName;
2052  ParamListInfo portalParams;
2053  bool save_log_statement_stats = log_statement_stats;
2054  bool is_xact_command;
2055  bool execute_is_fetch;
2056  bool was_logged = false;
2057  char msec_str[32];
2058  ParamsErrorCbData params_data;
2059  ErrorContextCallback params_errcxt;
2060 
2061  /* Adjust destination to tell printtup.c what to do */
2062  dest = whereToSendOutput;
2063  if (dest == DestRemote)
2064  dest = DestRemoteExecute;
2065 
2066  portal = GetPortalByName(portal_name);
2067  if (!PortalIsValid(portal))
2068  ereport(ERROR,
2069  (errcode(ERRCODE_UNDEFINED_CURSOR),
2070  errmsg("portal \"%s\" does not exist", portal_name)));
2071 
2072  /*
2073  * If the original query was a null string, just return
2074  * EmptyQueryResponse.
2075  */
2076  if (portal->commandTag == CMDTAG_UNKNOWN)
2077  {
2078  Assert(portal->stmts == NIL);
2079  NullCommand(dest);
2080  return;
2081  }
2082 
2083  /* Does the portal contain a transaction command? */
2084  is_xact_command = IsTransactionStmtList(portal->stmts);
2085 
2086  /*
2087  * We must copy the sourceText and prepStmtName into MessageContext in
2088  * case the portal is destroyed during finish_xact_command. Can avoid the
2089  * copy if it's not an xact command, though.
2090  */
2091  if (is_xact_command)
2092  {
2093  sourceText = pstrdup(portal->sourceText);
2094  if (portal->prepStmtName)
2095  prepStmtName = pstrdup(portal->prepStmtName);
2096  else
2097  prepStmtName = "<unnamed>";
2098 
2099  /*
2100  * An xact command shouldn't have any parameters, which is a good
2101  * thing because they wouldn't be around after finish_xact_command.
2102  */
2103  portalParams = NULL;
2104  }
2105  else
2106  {
2107  sourceText = portal->sourceText;
2108  if (portal->prepStmtName)
2109  prepStmtName = portal->prepStmtName;
2110  else
2111  prepStmtName = "<unnamed>";
2112  portalParams = portal->portalParams;
2113  }
2114 
2115  /*
2116  * Report query to various monitoring facilities.
2117  */
2118  debug_query_string = sourceText;
2119 
2121 
2123 
2124  if (save_log_statement_stats)
2125  ResetUsage();
2126 
2127  BeginCommand(portal->commandTag, dest);
2128 
2129  /*
2130  * Create dest receiver in MessageContext (we don't want it in transaction
2131  * context, because that may get deleted if portal contains VACUUM).
2132  */
2133  receiver = CreateDestReceiver(dest);
2134  if (dest == DestRemoteExecute)
2135  SetRemoteDestReceiverParams(receiver, portal);
2136 
2137  /*
2138  * Ensure we are in a transaction command (this should normally be the
2139  * case already due to prior BIND).
2140  */
2142 
2143  /*
2144  * If we re-issue an Execute protocol request against an existing portal,
2145  * then we are only fetching more rows rather than completely re-executing
2146  * the query from the start. atStart is never reset for a v3 portal, so we
2147  * are safe to use this check.
2148  */
2149  execute_is_fetch = !portal->atStart;
2150 
2151  /* Log immediately if dictated by log_statement */
2152  if (check_log_statement(portal->stmts))
2153  {
2154  ereport(LOG,
2155  (errmsg("%s %s%s%s: %s",
2156  execute_is_fetch ?
2157  _("execute fetch from") :
2158  _("execute"),
2159  prepStmtName,
2160  *portal_name ? "/" : "",
2161  *portal_name ? portal_name : "",
2162  sourceText),
2163  errhidestmt(true),
2164  errdetail_params(portalParams)));
2165  was_logged = true;
2166  }
2167 
2168  /*
2169  * If we are in aborted transaction state, the only portals we can
2170  * actually run are those containing COMMIT or ROLLBACK commands.
2171  */
2173  !IsTransactionExitStmtList(portal->stmts))
2174  ereport(ERROR,
2175  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2176  errmsg("current transaction is aborted, "
2177  "commands ignored until end of transaction block"),
2178  errdetail_abort()));
2179 
2180  /* Check for cancel signal before we start execution */
2182 
2183  /*
2184  * Okay to run the portal. Set the error callback so that parameters are
2185  * logged. The parameters must have been saved during the bind phase.
2186  */
2187  params_data.portalName = portal->name;
2188  params_data.params = portalParams;
2189  params_errcxt.previous = error_context_stack;
2190  params_errcxt.callback = ParamsErrorCallback;
2191  params_errcxt.arg = (void *) &params_data;
2192  error_context_stack = &params_errcxt;
2193 
2194  if (max_rows <= 0)
2195  max_rows = FETCH_ALL;
2196 
2197  completed = PortalRun(portal,
2198  max_rows,
2199  true, /* always top level */
2200  !execute_is_fetch && max_rows == FETCH_ALL,
2201  receiver,
2202  receiver,
2203  &qc);
2204 
2205  receiver->rDestroy(receiver);
2206 
2207  /* Done executing; remove the params error callback */
2209 
2210  if (completed)
2211  {
2212  if (is_xact_command)
2213  {
2214  /*
2215  * If this was a transaction control statement, commit it. We
2216  * will start a new xact command for the next command (if any).
2217  */
2219  }
2220  else
2221  {
2222  /*
2223  * We need a CommandCounterIncrement after every query, except
2224  * those that start or end a transaction block.
2225  */
2227 
2228  /*
2229  * Disable statement timeout whenever we complete an Execute
2230  * message. The next protocol message will start a fresh timeout.
2231  */
2233  }
2234 
2235  /* Send appropriate CommandComplete to client */
2236  EndCommand(&qc, dest, false);
2237  }
2238  else
2239  {
2240  /* Portal run not complete, so send PortalSuspended */
2242  pq_putemptymessage('s');
2243  }
2244 
2245  /*
2246  * Emit duration logging if appropriate.
2247  */
2248  switch (check_log_duration(msec_str, was_logged))
2249  {
2250  case 1:
2251  ereport(LOG,
2252  (errmsg("duration: %s ms", msec_str),
2253  errhidestmt(true)));
2254  break;
2255  case 2:
2256  ereport(LOG,
2257  (errmsg("duration: %s ms %s %s%s%s: %s",
2258  msec_str,
2259  execute_is_fetch ?
2260  _("execute fetch from") :
2261  _("execute"),
2262  prepStmtName,
2263  *portal_name ? "/" : "",
2264  *portal_name ? portal_name : "",
2265  sourceText),
2266  errhidestmt(true),
2267  errdetail_params(portalParams)));
2268  break;
2269  }
2270 
2271  if (save_log_statement_stats)
2272  ShowUsage("EXECUTE MESSAGE STATISTICS");
2273 
2274  debug_query_string = NULL;
2275 }
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2778
#define NIL
Definition: pg_list.h:65
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:100
ParamListInfo params
Definition: params.h:157
static void finish_xact_command(void)
Definition: postgres.c:2714
CommandTag commandTag
Definition: portal.h:136
CommandDest
Definition: dest.h:87
bool log_statement_stats
Definition: guc.c:580
void ShowUsage(const char *title)
Definition: postgres.c:4795
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
char * pstrdup(const char *in)
Definition: mcxt.c:1299
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
int errcode(int sqlerrcode)
Definition: elog.c:698
int errhidestmt(bool hide_stmt)
Definition: elog.c:1250
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2440
#define LOG
Definition: elog.h:26
List * stmts
Definition: portal.h:138
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
ErrorContextCallback * error_context_stack
Definition: elog.c:93
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2324
void set_ps_display(const char *activity)
Definition: ps_status.c:349
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:679
void ResetUsage(void)
Definition: postgres.c:4788
static void disable_statement_timeout(void)
Definition: postgres.c:4954
ParamListInfo portalParams
Definition: portal.h:141
const char * name
Definition: portal.h:118
#define ERROR
Definition: elog.h:46
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:166
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2420
const char * debug_query_string
Definition: postgres.c:89
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2285
#define PortalIsValid(p)
Definition: portal.h:211
static void start_xact_command(void)
Definition: postgres.c:2686
void CommandCounterIncrement(void)
Definition: xact.c:1021
const char * sourceText
Definition: portal.h:135
#define ereport(elevel,...)
Definition: elog.h:157
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
const char * portalName
Definition: params.h:156
#define Assert(condition)
Definition: c.h:804
static bool IsTransactionExitStmtList(List *pstmts)
Definition: postgres.c:2763
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:45
bool atStart
Definition: portal.h:198
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:103
int errmsg(const char *fmt,...)
Definition: elog.c:909
void pgstat_report_activity(BackendState state, const char *cmd_str)
void ParamsErrorCallback(void *arg)
Definition: params.c:407
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
CommandDest whereToSendOutput
Definition: postgres.c:92
#define _(x)
Definition: elog.c:89
const char * prepStmtName
Definition: portal.h:119
void NullCommand(CommandDest dest)
Definition: dest.c:234
#define FETCH_ALL
Definition: parsenodes.h:2851

◆ exec_parse_message()

static void exec_parse_message ( const char *  query_string,
const char *  stmt_name,
Oid paramTypes,
int  numParams 
)
static

Definition at line 1324 of file postgres.c.

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(), i, InvalidOid, IsAbortedTransactionBlockState(), IsTransactionExitStmt(), linitial_node, list_length(), LOG, log_parser_stats, log_statement_stats, MemoryContextSetParent(), MemoryContextSwitchTo(), MessageContext, NIL, parse_analyze_varparams(), pg_parse_query(), pg_rewrite_query(), pgstat_report_activity(), PopActiveSnapshot(), pq_putemptymessage(), PushActiveSnapshot(), ResetUsage(), SaveCachedPlan(), set_ps_display(), ShowUsage(), start_xact_command(), STATE_RUNNING, RawStmt::stmt, StorePreparedStatement(), and whereToSendOutput.

Referenced by PostgresMain().

1328 {
1329  MemoryContext unnamed_stmt_context = NULL;
1330  MemoryContext oldcontext;
1331  List *parsetree_list;
1332  RawStmt *raw_parse_tree;
1333  List *querytree_list;
1334  CachedPlanSource *psrc;
1335  bool is_named;
1336  bool save_log_statement_stats = log_statement_stats;
1337  char msec_str[32];
1338 
1339  /*
1340  * Report query to various monitoring facilities.
1341  */
1342  debug_query_string = query_string;
1343 
1344  pgstat_report_activity(STATE_RUNNING, query_string);
1345 
1346  set_ps_display("PARSE");
1347 
1348  if (save_log_statement_stats)
1349  ResetUsage();
1350 
1351  ereport(DEBUG2,
1352  (errmsg_internal("parse %s: %s",
1353  *stmt_name ? stmt_name : "<unnamed>",
1354  query_string)));
1355 
1356  /*
1357  * Start up a transaction command so we can run parse analysis etc. (Note
1358  * that this will normally change current memory context.) Nothing happens
1359  * if we are already in one. This also arms the statement timeout if
1360  * necessary.
1361  */
1363 
1364  /*
1365  * Switch to appropriate context for constructing parsetrees.
1366  *
1367  * We have two strategies depending on whether the prepared statement is
1368  * named or not. For a named prepared statement, we do parsing in
1369  * MessageContext and copy the finished trees into the prepared
1370  * statement's plancache entry; then the reset of MessageContext releases
1371  * temporary space used by parsing and rewriting. For an unnamed prepared
1372  * statement, we assume the statement isn't going to hang around long, so
1373  * getting rid of temp space quickly is probably not worth the costs of
1374  * copying parse trees. So in this case, we create the plancache entry's
1375  * query_context here, and do all the parsing work therein.
1376  */
1377  is_named = (stmt_name[0] != '\0');
1378  if (is_named)
1379  {
1380  /* Named prepared statement --- parse in MessageContext */
1381  oldcontext = MemoryContextSwitchTo(MessageContext);
1382  }
1383  else
1384  {
1385  /* Unnamed prepared statement --- release any prior unnamed stmt */
1387  /* Create context for parsing */
1388  unnamed_stmt_context =
1390  "unnamed prepared statement",
1392  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1393  }
1394 
1395  /*
1396  * Do basic parsing of the query or queries (this should be safe even if
1397  * we are in aborted transaction state!)
1398  */
1399  parsetree_list = pg_parse_query(query_string);
1400 
1401  /*
1402  * We only allow a single user statement in a prepared statement. This is
1403  * mainly to keep the protocol simple --- otherwise we'd need to worry
1404  * about multiple result tupdescs and things like that.
1405  */
1406  if (list_length(parsetree_list) > 1)
1407  ereport(ERROR,
1408  (errcode(ERRCODE_SYNTAX_ERROR),
1409  errmsg("cannot insert multiple commands into a prepared statement")));
1410 
1411  if (parsetree_list != NIL)
1412  {
1413  Query *query;
1414  bool snapshot_set = false;
1415 
1416  raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1417 
1418  /*
1419  * If we are in an aborted transaction, reject all commands except
1420  * COMMIT/ROLLBACK. It is important that this test occur before we
1421  * try to do parse analysis, rewrite, or planning, since all those
1422  * phases try to do database accesses, which may fail in abort state.
1423  * (It might be safe to allow some additional utility commands in this
1424  * state, but not many...)
1425  */
1427  !IsTransactionExitStmt(raw_parse_tree->stmt))
1428  ereport(ERROR,
1429  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1430  errmsg("current transaction is aborted, "
1431  "commands ignored until end of transaction block"),
1432  errdetail_abort()));
1433 
1434  /*
1435  * Create the CachedPlanSource before we do parse analysis, since it
1436  * needs to see the unmodified raw parse tree.
1437  */
1438  psrc = CreateCachedPlan(raw_parse_tree, query_string,
1439  CreateCommandTag(raw_parse_tree->stmt));
1440 
1441  /*
1442  * Set up a snapshot if parse analysis will need one.
1443  */
1444  if (analyze_requires_snapshot(raw_parse_tree))
1445  {
1447  snapshot_set = true;
1448  }
1449 
1450  /*
1451  * Analyze and rewrite the query. Note that the originally specified
1452  * parameter set is not required to be complete, so we have to use
1453  * parse_analyze_varparams().
1454  */
1455  if (log_parser_stats)
1456  ResetUsage();
1457 
1458  query = parse_analyze_varparams(raw_parse_tree,
1459  query_string,
1460  &paramTypes,
1461  &numParams);
1462 
1463  /*
1464  * Check all parameter types got determined.
1465  */
1466  for (int i = 0; i < numParams; i++)
1467  {
1468  Oid ptype = paramTypes[i];
1469 
1470  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1471  ereport(ERROR,
1472  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1473  errmsg("could not determine data type of parameter $%d",
1474  i + 1)));
1475  }
1476 
1477  if (log_parser_stats)
1478  ShowUsage("PARSE ANALYSIS STATISTICS");
1479 
1480  querytree_list = pg_rewrite_query(query);
1481 
1482  /* Done with the snapshot used for parsing */
1483  if (snapshot_set)
1485  }
1486  else
1487  {
1488  /* Empty input string. This is legal. */
1489  raw_parse_tree = NULL;
1490  psrc = CreateCachedPlan(raw_parse_tree, query_string,
1491  CMDTAG_UNKNOWN);
1492  querytree_list = NIL;
1493  }
1494 
1495  /*
1496  * CachedPlanSource must be a direct child of MessageContext before we
1497  * reparent unnamed_stmt_context under it, else we have a disconnected
1498  * circular subgraph. Klugy, but less so than flipping contexts even more
1499  * above.
1500  */
1501  if (unnamed_stmt_context)
1503 
1504  /* Finish filling in the CachedPlanSource */
1505  CompleteCachedPlan(psrc,
1506  querytree_list,
1507  unnamed_stmt_context,
1508  paramTypes,
1509  numParams,
1510  NULL,
1511  NULL,
1512  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1513  true); /* fixed result */
1514 
1515  /* If we got a cancel signal during analysis, quit */
1517 
1518  if (is_named)
1519  {
1520  /*
1521  * Store the query as a prepared statement.
1522  */
1523  StorePreparedStatement(stmt_name, psrc, false);
1524  }
1525  else
1526  {
1527  /*
1528  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1529  */
1530  SaveCachedPlan(psrc);
1531  unnamed_stmt_psrc = psrc;
1532  }
1533 
1534  MemoryContextSwitchTo(oldcontext);
1535 
1536  /*
1537  * We do NOT close the open transaction command here; that only happens
1538  * when the client sends Sync. Instead, do CommandCounterIncrement just
1539  * in case something happened during parse/plan.
1540  */
1542 
1543  /*
1544  * Send ParseComplete.
1545  */
1547  pq_putemptymessage('1');
1548 
1549  /*
1550  * Emit duration logging if appropriate.
1551  */
1552  switch (check_log_duration(msec_str, false))
1553  {
1554  case 1:
1555  ereport(LOG,
1556  (errmsg("duration: %s ms", msec_str),
1557  errhidestmt(true)));
1558  break;
1559  case 2:
1560  ereport(LOG,
1561  (errmsg("duration: %s ms parse %s: %s",
1562  msec_str,
1563  *stmt_name ? stmt_name : "<unnamed>",
1564  query_string),
1565  errhidestmt(true)));
1566  break;
1567  }
1568 
1569  if (save_log_statement_stats)
1570  ShowUsage("PARSE MESSAGE STATISTICS");
1571 
1572  debug_query_string = NULL;
1573 }
MemoryContext context
Definition: plancache.h:109
#define NIL
Definition: pg_list.h:65
#define AllocSetContextCreate
Definition: memutils.h:173
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:388
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:164
bool log_parser_stats
Definition: guc.c:577
bool log_statement_stats
Definition: guc.c:580
void ShowUsage(const char *title)
Definition: postgres.c:4795
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:361
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
int errhidestmt(bool hide_stmt)
Definition: elog.c:1250
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams)
Definition: analyze.c:150
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
static int errdetail_abort(void)
Definition: postgres.c:2440
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2746
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2324
void set_ps_display(const char *activity)
Definition: ps_status.c:349
void ResetUsage(void)
Definition: postgres.c:4788
#define ERROR
Definition: elog.h:46
List * pg_parse_query(const char *query_string)
Definition: postgres.c:594
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define DEBUG2
Definition: elog.h:24
Node * stmt
Definition: parsenodes.h:1560
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:169
const char * debug_query_string
Definition: postgres.c:89
static void start_xact_command(void)
Definition: postgres.c:2686
void CommandCounterIncrement(void)
Definition: xact.c:1021
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:426
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:454
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2320
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
List * pg_rewrite_query(Query *query)
Definition: postgres.c:737
static int list_length(const List *l)
Definition: pg_list.h:149
MemoryContext MessageContext
Definition: mcxt.c:52
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2816
int errmsg(const char *fmt,...)
Definition: elog.c:909
void pgstat_report_activity(BackendState state, const char *cmd_str)
int i
static void drop_unnamed_stmt(void)
Definition: postgres.c:2793
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
CommandDest whereToSendOutput
Definition: postgres.c:92
Definition: pg_list.h:50

◆ exec_simple_query()

static void exec_simple_query ( const char *  query_string)
static

Definition at line 956 of file postgres.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_requires_snapshot(), 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(), InvalidSnapshot, IsA, IsAbortedTransactionBlockState(), FetchStmt::ismove, IsTransactionExitStmt(), lfirst_node, list_length(), lnext(), LOG, log_statement_stats, MemoryContextDelete(), MemoryContextSwitchTo(), MessageContext, NullCommand(), pg_analyze_and_rewrite(), 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, and whereToSendOutput.

Referenced by PostgresMain().

957 {
959  MemoryContext oldcontext;
960  List *parsetree_list;
961  ListCell *parsetree_item;
962  bool save_log_statement_stats = log_statement_stats;
963  bool was_logged = false;
964  bool use_implicit_block;
965  char msec_str[32];
966 
967  /*
968  * Report query to various monitoring facilities.
969  */
970  debug_query_string = query_string;
971 
972  pgstat_report_activity(STATE_RUNNING, query_string);
973 
974  TRACE_POSTGRESQL_QUERY_START(query_string);
975 
976  /*
977  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
978  * results because ResetUsage wasn't called.
979  */
980  if (save_log_statement_stats)
981  ResetUsage();
982 
983  /*
984  * Start up a transaction command. All queries generated by the
985  * query_string will be in this same command block, *unless* we find a
986  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
987  * one of those, else bad things will happen in xact.c. (Note that this
988  * will normally change current memory context.)
989  */
991 
992  /*
993  * Zap any pre-existing unnamed statement. (While not strictly necessary,
994  * it seems best to define simple-Query mode as if it used the unnamed
995  * statement and portal; this ensures we recover any storage used by prior
996  * unnamed operations.)
997  */
999 
1000  /*
1001  * Switch to appropriate context for constructing parsetrees.
1002  */
1003  oldcontext = MemoryContextSwitchTo(MessageContext);
1004 
1005  /*
1006  * Do basic parsing of the query or queries (this should be safe even if
1007  * we are in aborted transaction state!)
1008  */
1009  parsetree_list = pg_parse_query(query_string);
1010 
1011  /* Log immediately if dictated by log_statement */
1012  if (check_log_statement(parsetree_list))
1013  {
1014  ereport(LOG,
1015  (errmsg("statement: %s", query_string),
1016  errhidestmt(true),
1017  errdetail_execute(parsetree_list)));
1018  was_logged = true;
1019  }
1020 
1021  /*
1022  * Switch back to transaction context to enter the loop.
1023  */
1024  MemoryContextSwitchTo(oldcontext);
1025 
1026  /*
1027  * For historical reasons, if multiple SQL statements are given in a
1028  * single "simple Query" message, we execute them as a single transaction,
1029  * unless explicit transaction control commands are included to make
1030  * portions of the list be separate transactions. To represent this
1031  * behavior properly in the transaction machinery, we use an "implicit"
1032  * transaction block.
1033  */
1034  use_implicit_block = (list_length(parsetree_list) > 1);
1035 
1036  /*
1037  * Run through the raw parsetree(s) and process each one.
1038  */
1039  foreach(parsetree_item, parsetree_list)
1040  {
1041  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1042  bool snapshot_set = false;
1043  CommandTag commandTag;
1044  QueryCompletion qc;
1045  MemoryContext per_parsetree_context = NULL;
1046  List *querytree_list,
1047  *plantree_list;
1048  Portal portal;
1049  DestReceiver *receiver;
1050  int16 format;
1051 
1052  pgstat_report_query_id(0, true);
1053 
1054  /*
1055  * Get the command name for use in status display (it also becomes the
1056  * default completion tag, down inside PortalRun). Set ps_status and
1057  * do any special start-of-SQL-command processing needed by the
1058  * destination.
1059  */
1060  commandTag = CreateCommandTag(parsetree->stmt);
1061 
1062  set_ps_display(GetCommandTagName(commandTag));
1063 
1064  BeginCommand(commandTag, dest);
1065 
1066  /*
1067  * If we are in an aborted transaction, reject all commands except
1068  * COMMIT/ABORT. It is important that this test occur before we try
1069  * to do parse analysis, rewrite, or planning, since all those phases
1070  * try to do database accesses, which may fail in abort state. (It
1071  * might be safe to allow some additional utility commands in this
1072  * state, but not many...)
1073  */
1075  !IsTransactionExitStmt(parsetree->stmt))
1076  ereport(ERROR,
1077  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1078  errmsg("current transaction is aborted, "
1079  "commands ignored until end of transaction block"),
1080  errdetail_abort()));
1081 
1082  /* Make sure we are in a transaction command */
1084 
1085  /*
1086  * If using an implicit transaction block, and we're not already in a
1087  * transaction block, start an implicit block to force this statement
1088  * to be grouped together with any following ones. (We must do this
1089  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1090  * list would cause later statements to not be grouped.)
1091  */
1092  if (use_implicit_block)
1094 
1095  /* If we got a cancel signal in parsing or prior command, quit */
1097 
1098  /*
1099  * Set up a snapshot if parse analysis/planning will need one.
1100  */
1101  if (analyze_requires_snapshot(parsetree))
1102  {
1104  snapshot_set = true;
1105  }
1106 
1107  /*
1108  * OK to analyze, rewrite, and plan this query.
1109  *
1110  * Switch to appropriate context for constructing query and plan trees
1111  * (these can't be in the transaction context, as that will get reset
1112  * when the command is COMMIT/ROLLBACK). If we have multiple
1113  * parsetrees, we use a separate context for each one, so that we can
1114  * free that memory before moving on to the next one. But for the
1115  * last (or only) parsetree, just use MessageContext, which will be
1116  * reset shortly after completion anyway. In event of an error, the
1117  * per_parsetree_context will be deleted when MessageContext is reset.
1118  */
1119  if (lnext(parsetree_list, parsetree_item) != NULL)
1120  {
1121  per_parsetree_context =
1123  "per-parsetree message context",
1125  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1126  }
1127  else
1128  oldcontext = MemoryContextSwitchTo(MessageContext);
1129 
1130  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1131  NULL, 0, NULL);
1132 
1133  plantree_list = pg_plan_queries(querytree_list, query_string,
1134  CURSOR_OPT_PARALLEL_OK, NULL);
1135 
1136  /*
1137  * Done with the snapshot used for parsing/planning.
1138  *
1139  * While it looks promising to reuse the same snapshot for query
1140  * execution (at least for simple protocol), unfortunately it causes
1141  * execution to use a snapshot that has been acquired before locking
1142  * any of the tables mentioned in the query. This creates user-
1143  * visible anomalies, so refrain. Refer to
1144  * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1145  */
1146  if (snapshot_set)
1148 
1149  /* If we got a cancel signal in analysis or planning, quit */
1151 
1152  /*
1153  * Create unnamed portal to run the query or queries in. If there
1154  * already is one, silently drop it.
1155  */
1156  portal = CreatePortal("", true, true);
1157  /* Don't display the portal in pg_cursors */
1158  portal->visible = false;
1159 
1160  /*
1161  * We don't have to copy anything into the portal, because everything
1162  * we are passing here is in MessageContext or the
1163  * per_parsetree_context, and so will outlive the portal anyway.
1164  */
1165  PortalDefineQuery(portal,
1166  NULL,
1167  query_string,
1168  commandTag,
1169  plantree_list,
1170  NULL);
1171 
1172  /*
1173  * Start the portal. No parameters here.
1174  */
1175  PortalStart(portal, NULL, 0, InvalidSnapshot);
1176 
1177  /*
1178  * Select the appropriate output format: text unless we are doing a
1179  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1180  * --- but it avoids grottiness in other places. Ah, the joys of
1181  * backward compatibility...)
1182  */
1183  format = 0; /* TEXT is default */
1184  if (IsA(parsetree->stmt, FetchStmt))
1185  {
1186  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1187 
1188  if (!stmt->ismove)
1189  {
1190  Portal fportal = GetPortalByName(stmt->portalname);
1191 
1192  if (PortalIsValid(fportal) &&
1193  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1194  format = 1; /* BINARY */
1195  }
1196  }
1197  PortalSetResultFormat(portal, 1, &format);
1198 
1199  /*
1200  * Now we can create the destination receiver object.
1201  */
1202  receiver = CreateDestReceiver(dest);
1203  if (dest == DestRemote)
1204  SetRemoteDestReceiverParams(receiver, portal);
1205 
1206  /*
1207  * Switch back to transaction context for execution.
1208  */
1209  MemoryContextSwitchTo(oldcontext);
1210 
1211  /*
1212  * Run the portal to completion, and then drop it (and the receiver).
1213  */
1214  (void) PortalRun(portal,
1215  FETCH_ALL,
1216  true, /* always top level */
1217  true,
1218  receiver,
1219  receiver,
1220  &qc);
1221 
1222  receiver->rDestroy(receiver);
1223 
1224  PortalDrop(portal, false);
1225 
1226  if (lnext(parsetree_list, parsetree_item) == NULL)
1227  {
1228  /*
1229  * If this is the last parsetree of the query string, close down
1230  * transaction statement before reporting command-complete. This
1231  * is so that any end-of-transaction errors are reported before
1232  * the command-complete message is issued, to avoid confusing
1233  * clients who will expect either a command-complete message or an
1234  * error, not one and then the other. Also, if we're using an
1235  * implicit transaction block, we must close that out first.
1236  */
1237  if (use_implicit_block)
1240  }
1241  else if (IsA(parsetree->stmt, TransactionStmt))
1242  {
1243  /*
1244  * If this was a transaction control statement, commit it. We will
1245  * start a new xact command for the next command.
1246  */
1248  }
1249  else
1250  {
1251  /*
1252  * We need a CommandCounterIncrement after every query, except
1253  * those that start or end a transaction block.
1254  */
1256 
1257  /*
1258  * Disable statement timeout between queries of a multi-query
1259  * string, so that the timeout applies separately to each query.
1260  * (Our next loop iteration will start a fresh timeout.)
1261  */
1263  }
1264 
1265  /*
1266  * Tell client that we're done with this query. Note we emit exactly
1267  * one EndCommand report for each raw parsetree, thus one for each SQL
1268  * command the client sent, regardless of rewriting. (But a command
1269  * aborted by error will not send an EndCommand report at all.)
1270  */
1271  EndCommand(&qc, dest, false);
1272 
1273  /* Now we may drop the per-parsetree context, if one was created. */
1274  if (per_parsetree_context)
1275  MemoryContextDelete(per_parsetree_context);
1276  } /* end loop over parsetrees */
1277 
1278  /*
1279  * Close down transaction statement, if one is open. (This will only do
1280  * something if the parsetree list was empty; otherwise the last loop
1281  * iteration already did it.)
1282  */
1284 
1285  /*
1286  * If there were no parsetrees, return EmptyQueryResponse message.
1287  */
1288  if (!parsetree_list)
1289  NullCommand(dest);
1290 
1291  /*
1292  * Emit duration logging if appropriate.
1293  */
1294  switch (check_log_duration(msec_str, was_logged))
1295  {
1296  case 1:
1297  ereport(LOG,
1298  (errmsg("duration: %s ms", msec_str),
1299  errhidestmt(true)));
1300  break;
1301  case 2:
1302  ereport(LOG,
1303  (errmsg("duration: %s ms statement: %s",
1304  msec_str, query_string),
1305  errhidestmt(true),
1306  errdetail_execute(parsetree_list)));
1307  break;
1308  }
1309 
1310  if (save_log_statement_stats)
1311  ShowUsage("QUERY STATISTICS");
1312 
1313  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1314 
1315  debug_query_string = NULL;
1316 }
signed short int16
Definition: c.h:428
CommandTag
Definition: cmdtag.h:20
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:100
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:618
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:388
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:430
static void finish_xact_command(void)
Definition: postgres.c:2714
bool visible
Definition: portal.h:204
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
CommandDest
Definition: dest.h:87
bool log_statement_stats
Definition: guc.c:580
void ShowUsage(const char *title)
Definition: postgres.c:4795
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:915
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2806
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
int errhidestmt(bool hide_stmt)
Definition: elog.c:1250
static int errdetail_abort(void)
Definition: postgres.c:2440
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
#define LOG
Definition: elog.h:26
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, CommandTag commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:281
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:642
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2746
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2324
void set_ps_display(const char *activity)
Definition: ps_status.c:349
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:679
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2387
void ResetUsage(void)
Definition: postgres.c:4788
static void disable_statement_timeout(void)
Definition: postgres.c:4954
#define ERROR
Definition: elog.h:46
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition: dest.c:166
List * pg_parse_query(const char *query_string)
Definition: postgres.c:594
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Node * stmt
Definition: parsenodes.h:1560
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
void BeginImplicitTransactionBlock(void)
Definition: xact.c:4039
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
char * portalname
Definition: parsenodes.h:2858
const char * debug_query_string
Definition: postgres.c:89
#define InvalidSnapshot
Definition: snapshot.h:123
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2285
#define PortalIsValid(p)
Definition: portal.h:211
static void start_xact_command(void)
Definition: postgres.c:2686
void EndImplicitTransactionBlock(void)
Definition: xact.c:4064
bool ismove
Definition: parsenodes.h:2859
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define ereport(elevel,...)
Definition: elog.h:157
void pgstat_report_query_id(uint64 query_id, bool force)
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2320
static int list_length(const List *l)
Definition: pg_list.h:149
MemoryContext MessageContext
Definition: mcxt.c:52
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:45
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2816
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:103
int errmsg(const char *fmt,...)
Definition: elog.c:909
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:467
void pgstat_report_activity(BackendState state, const char *cmd_str)
static void drop_unnamed_stmt(void)
Definition: postgres.c:2793
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static char format
int cursorOptions
Definition: portal.h:146
CommandDest whereToSendOutput
Definition: postgres.c:92
Definition: pg_list.h:50
void NullCommand(CommandDest dest)
Definition: dest.c:234
#define FETCH_ALL
Definition: parsenodes.h:2851

◆ finish_xact_command()

static void finish_xact_command ( void  )
static

Definition at line 2714 of file postgres.c.

References CommitTransactionCommand(), disable_statement_timeout(), MemoryContextStats(), TopMemoryContext, and xact_started.

Referenced by exec_execute_message(), exec_simple_query(), and PostgresMain().

2715 {
2716  /* cancel active statement timeout after each command */
2718 
2719  if (xact_started)
2720  {
2722 
2723 #ifdef MEMORY_CONTEXT_CHECKING
2724  /* Check all memory contexts that weren't freed during commit */
2725  /* (those that were, were checked before being deleted) */
2726  MemoryContextCheck(TopMemoryContext);
2727 #endif
2728 
2729 #ifdef SHOW_MEMORY_STATS
2730  /* Print mem stats after each commit for leak tracking */
2732 #endif
2733 
2734  xact_started = false;
2735  }
2736 }
void CommitTransactionCommand(void)
Definition: xact.c:2939
static void disable_statement_timeout(void)
Definition: postgres.c:4954
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:505
static bool xact_started
Definition: postgres.c:148
MemoryContext TopMemoryContext
Definition: mcxt.c:48

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2970 of file postgres.c.

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

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

2971 {
2972  /* We're not returning, so no need to save errno */
2973  ereport(ERROR,
2974  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2975  errmsg("floating-point exception"),
2976  errdetail("An invalid floating-point operation was signaled. "
2977  "This probably means an out-of-range result or an "
2978  "invalid operation, such as division by zero.")));
2979 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ forbidden_in_wal_sender()

static void forbidden_in_wal_sender ( char  firstchar)
static

Definition at line 4730 of file postgres.c.

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

Referenced by PostgresMain().

4731 {
4732  if (am_walsender)
4733  {
4734  if (firstchar == 'F')
4735  ereport(ERROR,
4736  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4737  errmsg("fastpath function calls not supported in a replication connection")));
4738  else
4739  ereport(ERROR,
4740  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4741  errmsg("extended query protocol not supported in a replication connection")));
4742  }
4743 }
int errcode(int sqlerrcode)
Definition: elog.c:698
bool am_walsender
Definition: walsender.c:115
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4752 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4753 {
4754 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4755  static long val = 0;
4756 
4757  /* This won't change after process launch, so check just once */
4758  if (val == 0)
4759  {
4760  struct rlimit rlim;
4761 
4762  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4763  val = -1;
4764  else if (rlim.rlim_cur == RLIM_INFINITY)
4765  val = LONG_MAX;
4766  /* rlim_cur is probably of an unsigned type, so check for overflow */
4767  else if (rlim.rlim_cur >= LONG_MAX)
4768  val = LONG_MAX;
4769  else
4770  val = rlim.rlim_cur;
4771  }
4772  return val;
4773 #else /* no getrlimit */
4774 #if defined(WIN32) || defined(__CYGWIN__)
4775  /* On Windows we set the backend stack size in src/backend/Makefile */
4776  return WIN32_STACK_RLIMIT;
4777 #else /* not windows ... give up */
4778  return -1;
4779 #endif
4780 #endif
4781 }
long val
Definition: informix.c:664

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3635 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3636 {
3637  switch (arg[0])
3638  {
3639  case 'p':
3640  if (optarg[1] == 'a') /* "parser" */
3641  return "log_parser_stats";
3642  else if (optarg[1] == 'l') /* "planner" */
3643  return "log_planner_stats";
3644  break;
3645 
3646  case 'e': /* "executor" */
3647  return "log_executor_stats";
3648  break;
3649  }
3650 
3651  return NULL;
3652 }
char * optarg
Definition: getopt.c:52
void * arg

◆ interactive_getc()

static int interactive_getc ( void  )
static

Definition at line 315 of file postgres.c.

References CHECK_FOR_INTERRUPTS, and ProcessClientReadInterrupt().

Referenced by InteractiveBackend().

316 {
317  int c;
318 
319  /*
320  * This will not process catchup interrupts or notifications while
321  * reading. But those can't really be relevant for a standalone backend
322  * anyway. To properly handle SIGTERM there's a hack in die() that
323  * directly processes interrupts at this stage...
324  */
326 
327  c = getc(stdin);
328 
330 
331  return c;
332 }
char * c
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:492
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120

◆ InteractiveBackend()

static int InteractiveBackend ( StringInfo  inBuf)
static

Definition at line 227 of file postgres.c.

References appendStringInfoChar(), StringInfoData::data, EchoQuery, interactive_getc(), StringInfoData::len, printf, resetStringInfo(), generate_unaccent_rules::stdout, and UseSemiNewlineNewline.

Referenced by ReadCommand().

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

◆ IsTransactionExitStmt()

static bool IsTransactionExitStmt ( Node parsetree)
static

Definition at line 2746 of file postgres.c.

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().

2747 {
2748  if (parsetree && IsA(parsetree, TransactionStmt))
2749  {
2750  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2751 
2752  if (stmt->kind == TRANS_STMT_COMMIT ||
2753  stmt->kind == TRANS_STMT_PREPARE ||
2754  stmt->kind == TRANS_STMT_ROLLBACK ||
2755  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2756  return true;
2757  }
2758  return false;
2759 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
TransactionStmtKind kind
Definition: parsenodes.h:3185

◆ IsTransactionExitStmtList()

static bool IsTransactionExitStmtList ( List pstmts)
static

Definition at line 2763 of file postgres.c.

References CMD_UTILITY, PlannedStmt::commandType, IsTransactionExitStmt(), linitial_node, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

2764 {
2765  if (list_length(pstmts) == 1)
2766  {
2767  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2768 
2769  if (pstmt->commandType == CMD_UTILITY &&
2771  return true;
2772  }
2773  return false;
2774 }
#define linitial_node(type, l)
Definition: pg_list.h:177
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2746
Node * utilityStmt
Definition: plannodes.h:86
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:149

◆ IsTransactionStmtList()

static bool IsTransactionStmtList ( List pstmts)
static

Definition at line 2778 of file postgres.c.

References CMD_UTILITY, PlannedStmt::commandType, IsA, linitial_node, list_length(), and PlannedStmt::utilityStmt.

Referenced by exec_execute_message().

2779 {
2780  if (list_length(pstmts) == 1)
2781  {
2782  PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2783 
2784  if (pstmt->commandType == CMD_UTILITY &&
2785  IsA(pstmt->utilityStmt, TransactionStmt))
2786  return true;
2787  }
2788  return false;
2789 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define linitial_node(type, l)
Definition: pg_list.h:177
Node * utilityStmt
Definition: plannodes.h:86
CmdType commandType
Definition: plannodes.h:46
static int list_length(const List *l)
Definition: pg_list.h:149

◆ log_disconnections()

static void log_disconnections ( int  code,
Datum  arg 
)
static

Definition at line 4897 of file postgres.c.

References Port::database_name, ereport, errmsg(), GetCurrentTimestamp(), LOG, MyProcPort, MyStartTimestamp, port, Port::remote_host, Port::remote_port, SECS_PER_HOUR, SECS_PER_MINUTE, TimestampDifference(), and Port::user_name.

Referenced by PostgresMain().

4898 {
4899  Port *port = MyProcPort;
4900  long secs;
4901  int usecs;
4902  int msecs;
4903  int hours,
4904  minutes,
4905  seconds;
4906 
4909  &secs, &usecs);
4910  msecs = usecs / 1000;
4911 
4912  hours = secs / SECS_PER_HOUR;
4913  secs %= SECS_PER_HOUR;
4914  minutes = secs / SECS_PER_MINUTE;
4915  seconds = secs % SECS_PER_MINUTE;
4916 
4917  ereport(LOG,
4918  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4919  "user=%s database=%s host=%s%s%s",
4920  hours, minutes, seconds, msecs,
4921  port->user_name, port->database_name, port->remote_host,
4922  port->remote_port[0] ? " port=" : "", port->remote_port)));
4923 }
struct Port * MyProcPort
Definition: globals.c:46
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
Definition: libpq-be.h:125
char * remote_port
Definition: libpq-be.h:137
#define LOG
Definition: elog.h:26
#define SECS_PER_MINUTE
Definition: timestamp.h:88
char * user_name
Definition: libpq-be.h:146
#define SECS_PER_HOUR
Definition: timestamp.h:87
static int port
Definition: pg_regress.c:92
TimestampTz MyStartTimestamp
Definition: globals.c:45
#define ereport(elevel,...)
Definition: elog.h:157
char * remote_host
Definition: libpq-be.h:132
int errmsg(const char *fmt,...)
Definition: elog.c:909
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1656
char * database_name
Definition: libpq-be.h:145

◆ pg_analyze_and_rewrite()

List* pg_analyze_and_rewrite ( RawStmt parsetree,
const char *  query_string,
Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 642 of file postgres.c.

References log_parser_stats, parse_analyze(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopyTo(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

645 {
646  Query *query;
647  List *querytree_list;
648 
649  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
650 
651  /*
652  * (1) Perform parse analysis.
653  */
654  if (log_parser_stats)
655  ResetUsage();
656 
657  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
658  queryEnv);
659 
660  if (log_parser_stats)
661  ShowUsage("PARSE ANALYSIS STATISTICS");
662 
663  /*
664  * (2) Rewrite the queries, as necessary
665  */
666  querytree_list = pg_rewrite_query(query);
667 
668  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
669 
670  return querytree_list;
671 }
bool log_parser_stats
Definition: guc.c:577
void ShowUsage(const char *title)
Definition: postgres.c:4795
void ResetUsage(void)
Definition: postgres.c:4788
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:110
List * pg_rewrite_query(Query *query)
Definition: postgres.c:737
Definition: pg_list.h:50

◆ pg_analyze_and_rewrite_params()

List* pg_analyze_and_rewrite_params ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 679 of file postgres.c.

References Assert, free_parsestate(), IsQueryIdEnabled(), JumbleQuery(), log_parser_stats, make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pg_rewrite_query(), pgstat_report_query_id(), post_parse_analyze_hook, ResetUsage(), ShowUsage(), and transformTopLevelStmt().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

684 {
685  ParseState *pstate;
686  Query *query;
687  List *querytree_list;
688  JumbleState *jstate = NULL;
689 
690  Assert(query_string != NULL); /* required as of 8.4 */
691 
692  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
693 
694  /*
695  * (1) Perform parse analysis.
696  */
697  if (log_parser_stats)
698  ResetUsage();
699 
700  pstate = make_parsestate(NULL);
701  pstate->p_sourcetext = query_string;
702  pstate->p_queryEnv = queryEnv;
703  (*parserSetup) (pstate, parserSetupArg);
704 
705  query = transformTopLevelStmt(pstate, parsetree);
706 
707  if (IsQueryIdEnabled())
708  jstate = JumbleQuery(query, query_string);
709 
711  (*post_parse_analyze_hook) (pstate, query, jstate);
712 
713  free_parsestate(pstate);
714 
715  pgstat_report_query_id(query->queryId, false);
716 
717  if (log_parser_stats)
718  ShowUsage("PARSE ANALYSIS STATISTICS");
719 
720  /*
721  * (2) Rewrite the queries, as necessary
722  */
723  querytree_list = pg_rewrite_query(query);
724 
725  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
726 
727  return querytree_list;
728 }
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:78
bool log_parser_stats
Definition: guc.c:577
QueryEnvironment * p_queryEnv
Definition: parse_node.h:205
void ShowUsage(const char *title)
Definition: postgres.c:4795
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4788
const char * p_sourcetext
Definition: parse_node.h:181
void pgstat_report_query_id(uint64 query_id, bool force)
#define Assert(condition)
Definition: c.h:804
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:213
List * pg_rewrite_query(Query *query)
Definition: postgres.c:737
JumbleState * JumbleQuery(Query *query, const char *querytext)
Definition: queryjumble.c:101
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:50
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:58

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 594 of file postgres.c.

References copyObject, elog, equal(), log_parser_stats, new_list(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), 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().

595 {
596  List *raw_parsetree_list;
597 
598  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
599 
600  if (log_parser_stats)
601  ResetUsage();
602 
603  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
604 
605  if (log_parser_stats)
606  ShowUsage("PARSER STATISTICS");
607 
608 #ifdef COPY_PARSE_PLAN_TREES
609  /* Optional debugging check: pass raw parsetrees through copyObject() */
610  {
611  List *new_list = copyObject(raw_parsetree_list);
612 
613  /* This checks both copyObject() and the equal() routines... */
614  if (!equal(new_list, raw_parsetree_list))
615  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
616  else
617  raw_parsetree_list = new_list;
618  }
619 #endif
620 
621  /*
622  * Currently, outfuncs/readfuncs support is missing for many raw parse
623  * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
624  * here.
625  */
626 
627  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
628 
629  return raw_parsetree_list;
630 }
bool log_parser_stats
Definition: guc.c:577
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
void ShowUsage(const char *title)
Definition: postgres.c:4795
void ResetUsage(void)
Definition: postgres.c:4788
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:232
#define copyObject(obj)
Definition: nodes.h:655
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:88

◆ pg_plan_queries()

List* pg_plan_queries ( List querytrees,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 915 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PlannedStmt::queryId, Query::queryId, PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

917 {
918  List *stmt_list = NIL;
919  ListCell *query_list;
920 
921  foreach(query_list, querytrees)
922  {
923  Query *query = lfirst_node(Query, query_list);
924  PlannedStmt *stmt;
925 
926  if (query->commandType == CMD_UTILITY)
927  {
928  /* Utility commands require no planning. */
929  stmt = makeNode(PlannedStmt);
930  stmt->commandType = CMD_UTILITY;
931  stmt->canSetTag = query->canSetTag;
932  stmt->utilityStmt = query->utilityStmt;
933  stmt->stmt_location = query->stmt_location;
934  stmt->stmt_len = query->stmt_len;
935  stmt->queryId = query->queryId;
936  }
937  else
938  {
939  stmt = pg_plan_query(query, query_string, cursorOptions,
940  boundParams);
941  }
942 
943  stmt_list = lappend(stmt_list, stmt);
944  }
945 
946  return stmt_list;
947 }
#define NIL
Definition: pg_list.h:65
int stmt_location
Definition: parsenodes.h:192
Node * utilityStmt
Definition: parsenodes.h:128
int stmt_len
Definition: plannodes.h:90
#define lfirst_node(type, lc)
Definition: pg_list.h:172
int stmt_location
Definition: plannodes.h:89
Node * utilityStmt
Definition: plannodes.h:86
List * lappend(List *list, void *datum)
Definition: list.c:336
uint64 queryId
Definition: parsenodes.h:124
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:120
#define makeNode(_type_)
Definition: nodes.h:587
bool canSetTag
Definition: parsenodes.h:126
uint64 queryId
Definition: plannodes.h:48
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:829
Definition: pg_list.h:50
int stmt_len
Definition: parsenodes.h:193

◆ pg_plan_query()

PlannedStmt* pg_plan_query ( Query querytree,
const char *  query_string,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 829 of file postgres.c.

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

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

831 {
832  PlannedStmt *plan;
833 
834  /* Utility commands have no plans. */
835  if (querytree->commandType == CMD_UTILITY)
836  return NULL;
837 
838  /* Planner must have a snapshot in case it calls user-defined functions. */
840 
841  TRACE_POSTGRESQL_QUERY_PLAN_START();
842 
843  if (log_planner_stats)
844  ResetUsage();
845 
846  /* call the optimizer */
847  plan = planner(querytree, query_string, cursorOptions, boundParams);
848 
849  if (log_planner_stats)
850  ShowUsage("PLANNER STATISTICS");
851 
852 #ifdef COPY_PARSE_PLAN_TREES
853  /* Optional debugging check: pass plan tree through copyObject() */
854  {
855  PlannedStmt *new_plan = copyObject(plan);
856 
857  /*
858  * equal() currently does not have routines to compare Plan nodes, so
859  * don't try to test equality here. Perhaps fix someday?
860  */
861 #ifdef NOT_USED
862  /* This checks both copyObject() and the equal() routines... */
863  if (!equal(new_plan, plan))
864  elog(WARNING, "copyObject() failed to produce an equal plan tree");
865  else
866 #endif
867  plan = new_plan;
868  }
869 #endif
870 
871 #ifdef WRITE_READ_PARSE_PLAN_TREES
872  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
873  {
874  char *str;
875  PlannedStmt *new_plan;
876 
877  str = nodeToString(plan);
878  new_plan = stringToNodeWithLocations(str);
879  pfree(str);
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 outfuncs/readfuncs and the equal() routines... */
887  if (!equal(new_plan, plan))
888  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
889  else
890 #endif
891  plan = new_plan;
892  }
893 #endif
894 
895  /*
896  * Print plan if debugging.
897  */
898  if (Debug_print_plan)
899  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
900 
901  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
902 
903  return plan;
904 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
void ShowUsage(const char *title)
Definition: postgres.c:4795
#define LOG
Definition: elog.h:26
void ResetUsage(void)
Definition: postgres.c:4788
bool Debug_print_plan
Definition: guc.c:572
void pfree(void *pointer)
Definition: mcxt.c:1169
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
#define WARNING
Definition: elog.h:40
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:263
CmdType commandType
Definition: parsenodes.h:120
#define Assert(condition)
Definition: c.h:804
#define elog(elevel,...)
Definition: elog.h:232
bool Debug_pretty_print
Definition: guc.c:575
char * nodeToString(const void *obj)
Definition: outfuncs.c:4542
#define copyObject(obj)
Definition: nodes.h:655
bool log_planner_stats
Definition: guc.c:578

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 737 of file postgres.c.

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(), Query::queryId, QueryRewrite(), ResetUsage(), ShowUsage(), generate_unaccent_rules::str, and WARNING.

Referenced by exec_parse_message(), init_sql_fcache(), inline_set_returning_function(), pg_analyze_and_rewrite(), and pg_analyze_and_rewrite_params().

738 {
739  List *querytree_list;
740 
741  if (Debug_print_parse)
742  elog_node_display(LOG, "parse tree", query,
744 
745  if (log_parser_stats)
746  ResetUsage();
747 
748  if (query->commandType == CMD_UTILITY)
749  {
750  /* don't rewrite utilities, just dump 'em into result list */
751  querytree_list = list_make1(query);
752  }
753  else
754  {
755  /* rewrite regular queries */
756  querytree_list = QueryRewrite(query);
757  }
758 
759  if (log_parser_stats)
760  ShowUsage("REWRITER STATISTICS");
761 
762 #ifdef COPY_PARSE_PLAN_TREES
763  /* Optional debugging check: pass querytree through copyObject() */
764  {
765  List *new_list;
766 
767  new_list = copyObject(querytree_list);
768  /* This checks both copyObject() and the equal() routines... */
769  if (!equal(new_list, querytree_list))
770  elog(WARNING, "copyObject() failed to produce equal parse tree");
771  else
772  querytree_list = new_list;
773  }
774 #endif
775 
776 #ifdef WRITE_READ_PARSE_PLAN_TREES
777  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
778  {
779  List *new_list = NIL;
780  ListCell *lc;
781 
782  /*
783  * We currently lack outfuncs/readfuncs support for most utility
784  * statement types, so only attempt to write/read non-utility queries.
785  */
786  foreach(lc, querytree_list)
787  {
788  Query *query = lfirst_node(Query, lc);
789 
790  if (query->commandType != CMD_UTILITY)
791  {
792  char *str = nodeToString(query);
793  Query *new_query = stringToNodeWithLocations(str);
794 
795  /*
796  * queryId is not saved in stored rules, but we must preserve
797  * it here to avoid breaking pg_stat_statements.
798  */
799  new_query->queryId = query->queryId;
800 
801  new_list = lappend(new_list, new_query);
802  pfree(str);
803  }
804  else
805  new_list = lappend(new_list, query);
806  }
807 
808  /* This checks both outfuncs/readfuncs and the equal() routines... */
809  if (!equal(new_list, querytree_list))
810  elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
811  else
812  querytree_list = new_list;
813  }
814 #endif
815 
817  elog_node_display(LOG, "rewritten parse tree", querytree_list,
819 
820  return querytree_list;
821 }
#define NIL
Definition: pg_list.h:65
List * QueryRewrite(Query *parsetree)
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
bool log_parser_stats
Definition: guc.c:577
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
void ShowUsage(const char *title)
Definition: postgres.c:4795
#define LOG
Definition: elog.h:26
#define list_make1(x1)
Definition: pg_list.h:206
void ResetUsage(void)
Definition: postgres.c:4788
void pfree(void *pointer)
Definition: mcxt.c:1169
bool Debug_print_parse
Definition: guc.c:573
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * lappend(List *list, void *datum)
Definition: list.c:336
uint64 queryId
Definition: parsenodes.h:124
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:120
#define elog(elevel,...)
Definition: elog.h:232
bool Debug_pretty_print
Definition: guc.c:575
char * nodeToString(const void *obj)
Definition: outfuncs.c:4542
bool Debug_print_rewritten
Definition: guc.c:574
#define copyObject(obj)
Definition: nodes.h:655
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:88

◆ PostgresMain()

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

Definition at line 3930 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, BaseInit(), BeginReportingGUCOptions(), buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, checkDataDir(), ConfigReloadPending, CreateDataDirLockFile(), 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(), GetCurrentTimestamp(), GetPortalByName(), HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, IdleSessionTimeout, ignore_till_sync, InitializeGUCOptions(), InitializeMaxBackends(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InitStandaloneProcess(), initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), LocalProcessControlFile(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_POSTMASTER, PGC_SIGHUP, PgStartTime, pgstat_report_activity(), 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(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), progname, QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, SelectConfigFiles(), set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SPICleanup(), start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, UnBlockSig, userDoption, username, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3933 {
3934  int firstchar;
3935  StringInfoData input_message;
3936  sigjmp_buf local_sigjmp_buf;
3937  volatile bool send_ready_for_query = true;
3938  bool idle_in_transaction_timeout_enabled = false;
3939  bool idle_session_timeout_enabled = false;
3940 
3941  /* Initialize startup process environment if necessary. */
3942  if (!IsUnderPostmaster)
3943  InitStandaloneProcess(argv[0]);
3944 
3946 
3947  /*
3948  * Set default values for command-line options.
3949  */
3950  if (!IsUnderPostmaster)
3952 
3953  /*
3954  * Parse command-line options.
3955  */
3957 
3958  /* Must have gotten a database name, or have a default (the username) */
3959  if (dbname == NULL)
3960  {
3961  dbname = username;
3962  if (dbname == NULL)
3963  ereport(FATAL,
3964  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3965  errmsg("%s: no database nor user name specified",
3966  progname)));
3967  }
3968 
3969  /* Acquire configuration parameters, unless inherited from postmaster */
3970  if (!IsUnderPostmaster)
3971  {
3973  proc_exit(1);
3974  }
3975 
3976  /*
3977  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
3978  * has already set up BlockSig and made that the active signal mask.)
3979  *
3980  * Note that postmaster blocked all signals before forking child process,
3981  * so there is no race condition whereby we might receive a signal before
3982  * we have set up the handler.
3983  *
3984  * Also note: it's best not to use any signals that are SIG_IGNored in the
3985  * postmaster. If such a signal arrives before we are able to change the
3986  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3987  * handler in the postmaster to reserve the signal. (Of course, this isn't
3988  * an issue for signals that are locally generated, such as SIGALRM and
3989  * SIGPIPE.)
3990  */
3991  if (am_walsender)
3992  WalSndSignals();
3993  else
3994  {
3996  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3997  pqsignal(SIGTERM, die); /* cancel current query and exit */
3998 
3999  /*
4000  * In a postmaster child backend, replace SignalHandlerForCrashExit
4001  * with quickdie, so we can tell the client we're dying.
4002  *
4003  * In a standalone backend, SIGQUIT can be generated from the keyboard
4004  * easily, while SIGTERM cannot, so we make both signals do die()
4005  * rather than quickdie().
4006  */
4007  if (IsUnderPostmaster)
4008  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4009  else
4010  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4011  InitializeTimeouts(); /* establishes SIGALRM handler */
4012 
4013  /*
4014  * Ignore failure to write to frontend. Note: if frontend closes
4015  * connection, we will notice it and exit cleanly when control next
4016  * returns to outer loop. This seems safer than forcing exit in the
4017  * midst of output during who-knows-what operation...
4018  */
4023 
4024  /*
4025  * Reset some signals that are accepted by postmaster but not by
4026  * backend
4027  */
4028  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4029  * platforms */
4030  }
4031 
4032  if (!IsUnderPostmaster)
4033  {
4034  /*
4035  * Validate we have been given a reasonable-looking DataDir (if under
4036  * postmaster, assume postmaster did this already).
4037  */
4038  checkDataDir();
4039 
4040  /* Change into DataDir (if under postmaster, was done already) */
4041  ChangeToDataDir();
4042 
4043  /*
4044  * Create lockfile for data directory.
4045  */
4046  CreateDataDirLockFile(false);
4047 
4048  /* read control file (error checking and contains config ) */
4049  LocalProcessControlFile(false);
4050 
4051  /* Initialize MaxBackends (if under postmaster, was done already) */
4053  }
4054 
4055  /* Early initialization */
4056  BaseInit();
4057 
4058  /*
4059  * Create a per-backend PGPROC struct in shared memory, except in the
4060  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
4061  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
4062  * had to do some stuff with LWLocks).
4063  */
4064 #ifdef EXEC_BACKEND
4065  if (!IsUnderPostmaster)
4066  InitProcess();
4067 #else
4068  InitProcess();
4069 #endif
4070 
4071  /* We need to allow SIGINT, etc during the initial transaction */
4073 
4074  /*
4075  * General initialization.
4076  *
4077  * NOTE: if you are tempted to add code in this vicinity, consider putting
4078  * it inside InitPostgres() instead. In particular, anything that
4079  * involves database access should be there, not here.
4080  */
4082 
4083  /*
4084  * If the PostmasterContext is still around, recycle the space; we don't
4085  * need it anymore after InitPostgres completes. Note this does not trash
4086  * *MyProcPort, because ConnCreate() allocated that space with malloc()
4087  * ... else we'd need to copy the Port data first. Also, subsidiary data
4088  * such as the username isn't lost either; see ProcessStartupPacket().
4089  */
4090  if (PostmasterContext)
4091  {
4093  PostmasterContext = NULL;
4094  }
4095 
4097 
4098  /*
4099  * Now all GUC states are fully set up. Report them to client if
4100  * appropriate.
4101  */
4103 
4104  /*
4105  * Also set up handler to log session end; we have to wait till now to be
4106  * sure Log_disconnections has its final value.
4107  */
4110 
4111  /* Perform initialization specific to a WAL sender process. */
4112  if (am_walsender)
4113  InitWalSender();
4114 
4115  /*
4116  * process any libraries that should be preloaded at backend start (this
4117  * likewise can't be done until GUC settings are complete)
4118  */
4120 
4121  /*
4122  * Send this backend's cancellation info to the frontend.
4123  */
4125  {
4127 
4128  pq_beginmessage(&buf, 'K');
4129  pq_sendint32(&buf, (int32) MyProcPid);
4130  pq_sendint32(&buf, (int32) MyCancelKey);
4131  pq_endmessage(&buf);
4132  /* Need not flush since ReadyForQuery will do it. */
4133  }
4134 
4135  /* Welcome banner for standalone case */
4137  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4138 
4139  /*
4140  * Create the memory context we will use in the main loop.
4141  *
4142  * MessageContext is reset once per iteration of the main loop, ie, upon
4143  * completion of processing of each command message from the client.
4144  */
4146  "MessageContext",
4148 
4149  /*
4150  * Create memory context and buffer used for RowDescription messages. As
4151  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4152  * frequently executed for ever single statement, we don't want to
4153  * allocate a separate buffer every time.
4154  */
4156  "RowDescriptionContext",
4161 
4162  /*
4163  * Remember stand-alone backend startup time
4164  */
4165  if (!IsUnderPostmaster)
4167 
4168  /*
4169  * POSTGRES main processing loop begins here
4170  *
4171  * If an exception is encountered, processing resumes here so we abort the
4172  * current transaction and start a new one.
4173  *
4174  * You might wonder why this isn't coded as an infinite loop around a
4175  * PG_TRY construct. The reason is that this is the bottom of the
4176  * exception stack, and so with PG_TRY there would be no exception handler
4177  * in force at all during the CATCH part. By leaving the outermost setjmp
4178  * always active, we have at least some chance of recovering from an error
4179  * during error recovery. (If we get into an infinite loop thereby, it
4180  * will soon be stopped by overflow of elog.c's internal state stack.)
4181  *
4182  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4183  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4184  * is essential in case we longjmp'd out of a signal handler on a platform
4185  * where that leaves the signal blocked. It's not redundant with the
4186  * unblock in AbortTransaction() because the latter is only called if we
4187  * were inside a transaction.
4188  */
4189 
4190  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4191  {
4192  /*
4193  * NOTE: if you are tempted to add more code in this if-block,
4194  * consider the high probability that it should be in
4195  * AbortTransaction() instead. The only stuff done directly here
4196  * should be stuff that is guaranteed to apply *only* for outer-level
4197  * error recovery, such as adjusting the FE/BE protocol status.
4198  */
4199 
4200  /* Since not using PG_TRY, must reset error stack by hand */
4201  error_context_stack = NULL;
4202 
4203  /* Prevent interrupts while cleaning up */
4204  HOLD_INTERRUPTS();
4205 
4206  /*
4207  * Forget any pending QueryCancel request, since we're returning to
4208  * the idle loop anyway, and cancel any active timeout requests. (In
4209  * future we might want to allow some timeout requests to survive, but
4210  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4211  * we got here because of a query cancel interrupting the SIGALRM
4212  * interrupt handler.) Note in particular that we must clear the
4213  * statement and lock timeout indicators, to prevent any future plain
4214  * query cancels from being misreported as timeouts in case we're
4215  * forgetting a timeout cancel.
4216  */
4217  disable_all_timeouts(false);
4218  QueryCancelPending = false; /* second to avoid race condition */
4219 
4220  /* Not reading from the client anymore. */
4221  DoingCommandRead = false;
4222 
4223  /* Make sure libpq is in a good state */
4224  pq_comm_reset();
4225 
4226  /* Report the error to the client and/or server log */
4227  EmitErrorReport();
4228 
4229  /*
4230  * Make sure debug_query_string gets reset before we possibly clobber
4231  * the storage it points at.
4232  */
4233  debug_query_string = NULL;
4234 
4235  /*
4236  * Abort the current transaction in order to recover.
4237  */
4239 
4240  if (am_walsender)
4242 
4244  SPICleanup();
4245 
4246  /*
4247  * We can't release replication slots inside AbortTransaction() as we
4248  * need to be able to start and abort transactions while having a slot
4249  * acquired. But we never need to hold them across top level errors,
4250  * so releasing here is fine. There's another cleanup in ProcKill()
4251  * ensuring we'll correctly cleanup on FATAL errors as well.
4252  */
4253  if (MyReplicationSlot != NULL)
4255 
4256  /* We also want to cleanup temporary slots on error. */
4258 
4260 
4261  /*
4262  * Now return to normal top-level context and clear ErrorContext for
4263  * next time.
4264  */
4266  FlushErrorState();
4267 
4268  /*
4269  * If we were handling an extended-query-protocol message, initiate
4270  * skip till next Sync. This also causes us not to issue
4271  * ReadyForQuery (until we get Sync).
4272  */
4274  ignore_till_sync = true;
4275 
4276  /* We don't have a transaction command open anymore */
4277  xact_started = false;
4278 
4279  /*
4280  * If an error occurred while we were reading a message from the
4281  * client, we have potentially lost track of where the previous
4282  * message ends and the next one begins. Even though we have
4283  * otherwise recovered from the error, we cannot safely read any more
4284  * messages from the client, so there isn't much we can do with the
4285  * connection anymore.
4286  */
4287  if (pq_is_reading_msg())
4288  ereport(FATAL,
4289  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4290  errmsg("terminating connection because protocol synchronization was lost")));
4291 
4292  /* Now we can allow interrupts again */
4294  }
4295 
4296  /* We can now handle ereport(ERROR) */
4297  PG_exception_stack = &local_sigjmp_buf;
4298 
4299  if (!ignore_till_sync)
4300  send_ready_for_query = true; /* initially, or after error */
4301 
4302  /*
4303  * Non-error queries loop here.
4304  */
4305 
4306  for (;;)
4307  {
4308  /*
4309  * At top of loop, reset extended-query-message flag, so that any
4310  * errors encountered in "idle" state don't provoke skip.
4311  */
4313 
4314  /*
4315  * Release storage left over from prior query cycle, and create a new
4316  * query input buffer in the cleared MessageContext.
4317  */
4320 
4321  initStringInfo(&input_message);
4322 
4323  /*
4324  * Also consider releasing our catalog snapshot if any, so that it's
4325  * not preventing advance of global xmin while we wait for the client.
4326  */
4328 
4329  /*
4330  * (1) If we've reached idle state, tell the frontend we're ready for
4331  * a new query.
4332  *
4333  * Note: this includes fflush()'ing the last of the prior output.
4334  *
4335  * This is also a good time to send collected statistics to the
4336  * collector, and to update the PS stats display. We avoid doing
4337  * those every time through the message loop because it'd slow down
4338  * processing of batched messages, and because we don't want to report
4339  * uncommitted updates (that confuses autovacuum). The notification
4340  * processor wants a call too, if we are not in a transaction block.
4341  *
4342  * Also, if an idle timeout is enabled, start the timer for that.
4343  */
4344  if (send_ready_for_query)
4345  {
4347  {
4348  set_ps_display("idle in transaction (aborted)");
4350 
4351  /* Start the idle-in-transaction timer */
4353  {
4354  idle_in_transaction_timeout_enabled = true;
4357  }
4358  }
4360  {
4361  set_ps_display("idle in transaction");
4363 
4364  /* Start the idle-in-transaction timer */
4366  {
4367  idle_in_transaction_timeout_enabled = true;
4370  }
4371  }
4372  else
4373  {
4374  /* Send out notify signals and transmit self-notifies */
4376 
4377  /*
4378  * Also process incoming notifies, if any. This is mostly to
4379  * ensure stable behavior in tests: if any notifies were
4380  * received during the just-finished transaction, they'll be
4381  * seen by the client before ReadyForQuery is.
4382  */
4385 
4386  pgstat_report_stat(false);
4387 
4388  set_ps_display("idle");
4390 
4391  /* Start the idle-session timer */
4392  if (IdleSessionTimeout > 0)
4393  {
4394  idle_session_timeout_enabled = true;
4397  }
4398  }
4399 
4400  /* Report any recently-changed GUC options */
4402 
4404  send_ready_for_query = false;
4405  }
4406 
4407  /*
4408  * (2) Allow asynchronous signals to be executed immediately if they
4409  * come in while we are waiting for client input. (This must be
4410  * conditional since we don't want, say, reads on behalf of COPY FROM
4411  * STDIN doing the same thing.)
4412  */
4413  DoingCommandRead = true;
4414 
4415  /*
4416  * (3) read a command (loop blocks here)
4417  */
4418  firstchar = ReadCommand(&input_message);
4419 
4420  /*
4421  * (4) turn off the idle-in-transaction and idle-session timeouts, if
4422  * active. We do this before step (5) so that any last-moment timeout
4423  * is certain to be detected in step (5).
4424  *
4425  * At most one of these timeouts will be active, so there's no need to
4426  * worry about combining the timeout.c calls into one.
4427  */
4428  if (idle_in_transaction_timeout_enabled)
4429  {
4431  idle_in_transaction_timeout_enabled = false;
4432  }
4433  if (idle_session_timeout_enabled)
4434  {
4436  idle_session_timeout_enabled = false;
4437  }
4438 
4439  /*
4440  * (5) disable async signal conditions again.
4441  *
4442  * Query cancel is supposed to be a no-op when there is no query in
4443  * progress, so if a query cancel arrived while we were idle, just
4444  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4445  * it's called when DoingCommandRead is set, so check for interrupts
4446  * before resetting DoingCommandRead.
4447  */
4449  DoingCommandRead = false;
4450 
4451  /*
4452  * (6) check for any other interesting events that happened while we
4453  * slept.
4454  */
4455  if (ConfigReloadPending)
4456  {
4457  ConfigReloadPending = false;
4459  }
4460 
4461  /*
4462  * (7) process the command. But ignore it if we're skipping till
4463  * Sync.
4464  */
4465  if (ignore_till_sync && firstchar != EOF)
4466  continue;
4467 
4468  switch (firstchar)
4469  {
4470  case 'Q': /* simple query */
4471  {
4472  const char *query_string;
4473 
4474  /* Set statement_timestamp() */
4476 
4477  query_string = pq_getmsgstring(&input_message);
4478  pq_getmsgend(&input_message);
4479 
4480  if (am_walsender)
4481  {
4482  if (!exec_replication_command(query_string))
4483  exec_simple_query(query_string);
4484  }
4485  else
4486  exec_simple_query(query_string);
4487 
4488  send_ready_for_query = true;
4489  }
4490  break;
4491 
4492  case 'P': /* parse */
4493  {
4494  const char *stmt_name;
4495  const char *query_string;
4496  int numParams;
4497  Oid *paramTypes = NULL;
4498 
4499  forbidden_in_wal_sender(firstchar);
4500 
4501  /* Set statement_timestamp() */
4503 
4504  stmt_name = pq_getmsgstring(&input_message);
4505  query_string = pq_getmsgstring(&input_message);
4506  numParams = pq_getmsgint(&input_message, 2);
4507  if (numParams > 0)
4508  {
4509  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4510  for (int i = 0; i < numParams; i++)
4511  paramTypes[i] = pq_getmsgint(&input_message, 4);
4512  }
4513  pq_getmsgend(&input_message);
4514 
4515  exec_parse_message(query_string, stmt_name,
4516  paramTypes, numParams);
4517  }
4518  break;
4519 
4520  case 'B': /* bind */
4521  forbidden_in_wal_sender(firstchar);
4522 
4523  /* Set statement_timestamp() */
4525 
4526  /*
4527  * this message is complex enough that it seems best to put
4528  * the field extraction out-of-line
4529  */
4530  exec_bind_message(&input_message);
4531  break;
4532 
4533  case 'E': /* execute */
4534  {
4535  const char *portal_name;
4536  int max_rows;
4537 
4538  forbidden_in_wal_sender(firstchar);
4539 
4540  /* Set statement_timestamp() */
4542 
4543  portal_name = pq_getmsgstring(&input_message);
4544  max_rows = pq_getmsgint(&input_message, 4);
4545  pq_getmsgend(&input_message);
4546 
4547  exec_execute_message(portal_name, max_rows);
4548  }
4549  break;
4550 
4551  case 'F': /* fastpath function call */
4552  forbidden_in_wal_sender(firstchar);
4553 
4554  /* Set statement_timestamp() */
4556 
4557  /* Report query to various monitoring facilities. */
4559  set_ps_display("<FASTPATH>");
4560 
4561  /* start an xact for this function invocation */
4563 
4564  /*
4565  * Note: we may at this point be inside an aborted
4566  * transaction. We can't throw error for that until we've
4567  * finished reading the function-call message, so
4568  * HandleFunctionRequest() must check for it after doing so.
4569  * Be careful not to do anything that assumes we're inside a
4570  * valid transaction here.
4571  */
4572 
4573  /* switch back to message context */
4575 
4576  HandleFunctionRequest(&input_message);
4577 
4578  /* commit the function-invocation transaction */
4580 
4581  send_ready_for_query = true;
4582  break;
4583 
4584  case 'C': /* close */
4585  {
4586  int close_type;
4587  const char *close_target;
4588 
4589  forbidden_in_wal_sender(firstchar);
4590 
4591  close_type = pq_getmsgbyte(&input_message);
4592  close_target = pq_getmsgstring(&input_message);
4593  pq_getmsgend(&input_message);
4594 
4595  switch (close_type)
4596  {
4597  case 'S':
4598  if (close_target[0] != '\0')
4599  DropPreparedStatement(close_target, false);
4600  else
4601  {
4602  /* special-case the unnamed statement */
4604  }
4605  break;
4606  case 'P':
4607  {
4608  Portal portal;
4609 
4610  portal = GetPortalByName(close_target);
4611  if (PortalIsValid(portal))
4612  PortalDrop(portal, false);
4613  }
4614  break;
4615  default:
4616  ereport(ERROR,
4617  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4618  errmsg("invalid CLOSE message subtype %d",
4619  close_type)));
4620  break;
4621  }
4622 
4624  pq_putemptymessage('3'); /* CloseComplete */
4625  }
4626  break;
4627 
4628  case 'D': /* describe */
4629  {
4630  int describe_type;
4631  const char *describe_target;
4632 
4633  forbidden_in_wal_sender(firstchar);
4634 
4635  /* Set statement_timestamp() (needed for xact) */
4637 
4638  describe_type = pq_getmsgbyte(&input_message);
4639  describe_target = pq_getmsgstring(&input_message);
4640  pq_getmsgend(&input_message);
4641 
4642  switch (describe_type)
4643  {
4644  case 'S':
4645  exec_describe_statement_message(describe_target);
4646  break;
4647  case 'P':
4648  exec_describe_portal_message(describe_target);
4649  break;
4650  default:
4651  ereport(ERROR,
4652  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4653  errmsg("invalid DESCRIBE message subtype %d",
4654  describe_type)));
4655  break;
4656  }
4657  }
4658  break;
4659 
4660  case 'H': /* flush */
4661  pq_getmsgend(&input_message);
4663  pq_flush();
4664  break;
4665 
4666  case 'S': /* sync */
4667  pq_getmsgend(&input_message);
4669  send_ready_for_query = true;
4670  break;
4671 
4672  /*
4673  * 'X' means that the frontend is closing down the socket. EOF
4674  * means unexpected loss of frontend connection. Either way,
4675  * perform normal shutdown.
4676  */
4677  case EOF:
4678 
4679  /* for the statistics collector */
4681 
4682  /* FALLTHROUGH */
4683 
4684  case 'X':
4685 
4686  /*
4687  * Reset whereToSendOutput to prevent ereport from attempting
4688  * to send any more messages to client.
4689  */
4692 
4693  /*
4694  * NOTE: if you are tempted to add more code here, DON'T!
4695  * Whatever you had in mind to do should be set up as an
4696  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4697  * it will fail to be called during other backend-shutdown
4698  * scenarios.
4699  */
4700  proc_exit(0);
4701 
4702  case 'd': /* copy data */
4703  case 'c': /* copy done */
4704  case 'f': /* copy fail */
4705 
4706  /*
4707  * Accept but ignore these messages, per protocol spec; we
4708  * probably got here because a COPY failed, and the frontend
4709  * is still sending data.
4710  */
4711  break;
4712 
4713  default:
4714  ereport(FATAL,
4715  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4716  errmsg("invalid frontend message type %d",
4717  firstchar)));
4718  }
4719  } /* end of input-reading loop */
4720 }
void InitializeTimeouts(void)
Definition: timeout.c:435
void AbortCurrentTransaction(void)
Definition: xact.c:3210
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2634
#define SIGQUIT
Definition: win32_port.h:160
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void BeginReportingGUCOptions(void)
Definition: guc.c:6503
int MyProcPid
Definition: globals.c:43
const char * progname
Definition: main.c:46
#define pq_flush()
Definition: libpq.h:46
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:471
static void finish_xact_command(void)
Definition: postgres.c:2714
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1509
#define SIGUSR1
Definition: win32_port.h:171
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
#define SIGCHLD
Definition: win32_port.h:169
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:165
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:391
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPICleanup(void)
Definition: spi.c:357
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4730
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:698
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4701
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
void BaseInit(void)
Definition: postinit.c:537
#define printf(...)
Definition: port.h:222
void checkDataDir(void)
Definition: miscinit.c:304
SessionEndType pgStatSessionEndCause
Definition: pgstat.c:250
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:843
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
unsigned int Oid
Definition: postgres_ext.h:31
void FlushErrorState(void)
Definition: elog.c:1654
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2949
signed int int32
Definition: c.h:429
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2043
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4897
void jit_reset_after_error(void)
Definition: jit.c:128
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
ErrorContextCallback * error_context_stack
Definition: elog.c:93
int IdleSessionTimeout
Definition: proc.c:64
void set_ps_display(const char *activity)
Definition: ps_status.c:349
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
bool am_walsender
Definition: walsender.c:115
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:687
#define ERROR
Definition: elog.h:46
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1275
void ProcessNotifyInterrupt(void)
Definition: async.c:1915
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1192
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:47
void WalSndSignals(void)
Definition: walsender.c:3057
#define FATAL
Definition: elog.h:49
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
void ReportChangedGUCOptions(void)
Definition: guc.c:6549
void InitProcess(void)
Definition: proc.c:303
Definition: dest.h:89
static char * buf
Definition: pg_test_fsync.c:68
bool IsUnderPostmaster
Definition: globals.c:112
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1581
Definition: dest.h:90
#define SIGHUP
Definition: win32_port.h:159
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5078
void ChangeToDataDir(void)
Definition: miscinit.c:418
void ReplicationSlotRelease(void)
Definition: slot.c:469
sigset_t UnBlockSig
Definition: pqsignal.c:22
void PortalErrorCleanup(void)
Definition: portalmem.c:915
static bool xact_started
Definition: postgres.c:148
void InitWalSender(void)
const char * username
Definition: pgbench.c:282
MemoryContext TopMemoryContext
Definition: mcxt.c:48
Definition: guc.h:72
#define SIG_IGN
Definition: win32_port.h:156
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
const char * debug_query_string
Definition: postgres.c:89
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1324
#define PortalIsValid(p)
Definition: portal.h:211
static void start_xact_command(void)
Definition: postgres.c:2686
static bool doing_extended_query_message
Definition: postgres.c:161
void process_session_preload_libraries(void)
Definition: miscinit.c:1672
void WalSndErrorCleanup(void)
Definition: walsender.c:296
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5825
void EmitErrorReport(void)
Definition: elog.c:1509
static StringInfoData row_description_buf
Definition: postgres.c:183
TimestampTz PgStartTime
Definition: timestamp.c:52
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:579
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:524
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:45
#define SIG_DFL
Definition: win32_port.h:154
void ProcessCompletedNotifies(void)
Definition: async.c:1226
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:188
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:477
static bool DoingCommandRead
Definition: postgres.c:155
void InitializeMaxBackends(void)
Definition: postinit.c:515
char * dbname
Definition: streamutil.c:51
MemoryContext MessageContext
Definition: mcxt.c:52
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
static const char * userDoption
Definition: postgres.c:172
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:467
void pgstat_report_activity(BackendState state, const char *cmd_str)
void ReadyForQuery(CommandDest dest)
Definition: dest.c:271
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2915
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2970
static void drop_unnamed_stmt(void)
Definition: postgres.c:2793
void ReplicationSlotCleanup(void)
Definition: slot.c:525
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:421
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
bool Log_disconnections
Definition: postgres.c:95
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3675
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
CommandDest whereToSendOutput
Definition: postgres.c:92
static bool ignore_till_sync
Definition: postgres.c:162
static MemoryContext row_description_context
Definition: postgres.c:182
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2818
MemoryContext PostmasterContext
Definition: mcxt.c:50
static void exec_simple_query(const char *query_string)
Definition: postgres.c:956
void InitializeGUCOptions(void)
Definition: guc.c:5602
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:553
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2539

◆ process_postgres_switches()

void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3675 of file postgres.c.

References EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), free, FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, optarg, opterr, optind, OutputFileName, ParseLongOption(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresMain(), and process_startup_options().

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

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 492 of file postgres.c.

References catchupInterruptPending, CHECK_FOR_INTERRUPTS, DoingCommandRead, MyLatch, notifyInterruptPending, ProcDiePending, ProcessCatchupInterrupt(), ProcessNotifyInterrupt(), and SetLatch().

Referenced by interactive_getc(), and secure_read().

493 {
494  int save_errno = errno;
495 
496  if (DoingCommandRead)
497  {
498  /* Check for general interrupts that arrived before/while reading */
500 
501  /* Process sinval catchup interrupts, if any */
504 
505  /* Process notify interrupts, if any */
508  }
509  else if (ProcDiePending)
510  {
511  /*
512  * We're dying. If there is no data available to read, then it's safe
513  * (and sane) to handle that now. If we haven't tried to read yet,
514  * make sure the process latch is set, so that if there is no data
515  * then we'll come back here and die. If we're done reading, also
516  * make sure the process latch is set, as we might've undesirably
517  * cleared it while reading.
518  */
519  if (blocked)
521  else
522  SetLatch(MyLatch);
523  }
524 
525  errno = save_errno;
526 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
void SetLatch(Latch *latch)
Definition: latch.c:567
void ProcessNotifyInterrupt(void)
Definition: async.c:1915
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
static bool DoingCommandRead
Definition: postgres.c:155
struct Latch * MyLatch
Definition: globals.c:57
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:421
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 538 of file postgres.c.

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

Referenced by secure_write().

539 {
540  int save_errno = errno;
541 
542  if (ProcDiePending)
543  {
544  /*
545  * We're dying. If it's not possible to write, then we should handle
546  * that immediately, else a stuck client could indefinitely delay our
547  * response to the signal. If we haven't tried to write yet, make
548  * sure the process latch is set, so that if the write would block
549  * then we'll come back here and die. If we're done writing, also
550  * make sure the process latch is set, as we might've undesirably
551  * cleared it while writing.
552  */
553  if (blocked)
554  {
555  /*
556  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
557  * service ProcDiePending.
558  */
559  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
560  {
561  /*
562  * We don't want to send the client the error message, as a)
563  * that would possibly block again, and b) it would likely
564  * lead to loss of protocol sync because we may have already
565  * sent a partial protocol message.
566  */
569 
571  }
572  }
573  else
574  SetLatch(MyLatch);
575  }
576 
577  errno = save_errno;
578 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:39
void SetLatch(Latch *latch)
Definition: latch.c:567
Definition: dest.h:89
volatile uint32 CritSectionCount
Definition: globals.c:41
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
CommandDest whereToSendOutput
Definition: postgres.c:92

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3129 of file postgres.c.

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(), errdetail_recovery_conflict(), errhint(), errmsg(), errmsg_internal(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsLogicalLauncher(), IsLogicalWorker(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, ParallelMessagePending, pgstat_report_recovery_conflict(), 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().

3130 {
3131  /* OK to accept any interrupts now? */
3132  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3133  return;
3134  InterruptPending = false;
3135 
3136  if (ProcDiePending)
3137  {
3138  ProcDiePending = false;
3139  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3140  LockErrorCleanup();
3141  /* As in quickdie, don't risk sending to client during auth */
3145  ereport(FATAL,
3146  (errcode(ERRCODE_QUERY_CANCELED),
3147  errmsg("canceling authentication due to timeout")));
3148  else if (IsAutoVacuumWorkerProcess())
3149  ereport(FATAL,
3150  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3151  errmsg("terminating autovacuum process due to administrator command")));
3152  else if (IsLogicalWorker())
3153  ereport(FATAL,
3154  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3155  errmsg("terminating logical replication worker due to administrator command")));
3156  else if (IsLogicalLauncher())
3157  {
3158  ereport(DEBUG1,
3159  (errmsg_internal("logical replication launcher shutting down")));
3160 
3161  /*
3162  * The logical replication launcher can be stopped at any time.
3163  * Use exit status 1 so the background worker is restarted.
3164  */
3165  proc_exit(1);
3166  }
3168  {
3170  ereport(FATAL,
3171  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3172  errmsg("terminating connection due to conflict with recovery"),
3174  }
3175  else if (RecoveryConflictPending)
3176  {
3177  /* Currently there is only one non-retryable recovery conflict */
3180  ereport(FATAL,
3181  (errcode(ERRCODE_DATABASE_DROPPED),