PostgreSQL Source Code  git master
tcopprot.h File Reference
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "storage/procsignal.h"
#include "utils/guc.h"
#include "utils/queryenvironment.h"
Include dependency graph for tcopprot.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define STACK_DEPTH_SLOP   (512 * 1024L)
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE , LOGSTMT_DDL , LOGSTMT_MOD , LOGSTMT_ALL }
 

Functions

Listpg_parse_query (const char *query_string)
 
Listpg_rewrite_query (Query *query)
 
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)
 
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)
 
bool check_max_stack_depth (int *newval, void **extra, GucSource source)
 
void assign_max_stack_depth (int newval, void *extra)
 
void die (SIGNAL_ARGS)
 
void quickdie (SIGNAL_ARGS) pg_attribute_noreturn()
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS) pg_attribute_noreturn()
 
void RecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresSingleUserMain (int argc, char *argv[], const char *username) pg_attribute_noreturn()
 
void PostgresMain (const char *dbname, const char *username) pg_attribute_noreturn()
 
long get_stack_depth_rlimit (void)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 
int check_log_duration (char *msec_str, bool was_logged)
 
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)
 

Variables

CommandDest whereToSendOutput
 
PGDLLIMPORT const char * debug_query_string
 
int max_stack_depth
 
int PostAuthDelay
 
int client_connection_check_interval
 
PGDLLIMPORT int log_statement
 

Macro Definition Documentation

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 26 of file tcopprot.h.

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 36 of file tcopprot.h.

37 {
38  LOGSTMT_NONE, /* log no statements */
39  LOGSTMT_DDL, /* log data definition statements */
40  LOGSTMT_MOD, /* log modification statements, plus DDL */
41  LOGSTMT_ALL /* log all statements */
42 } LogStmtLevel;
LogStmtLevel
Definition: tcopprot.h:37
@ LOGSTMT_NONE
Definition: tcopprot.h:38
@ LOGSTMT_MOD
Definition: tcopprot.h:40
@ LOGSTMT_DDL
Definition: tcopprot.h:39
@ LOGSTMT_ALL
Definition: tcopprot.h:41

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3550 of file postgres.c.

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

References max_stack_depth_bytes, and newval.

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2325 of file postgres.c.

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

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, pg_global_prng_state, pg_prng_double(), snprintf, TimestampDifference(), and xact_is_sampled.

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

◆ check_max_stack_depth()

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

Definition at line 3533 of file postgres.c.

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

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

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2916 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2971 of file postgres.c.

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

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

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

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4764 of file postgres.c.

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

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3636 of file postgres.c.

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

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ pg_analyze_and_rewrite()

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

Definition at line 643 of file postgres.c.

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

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

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

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

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, Query::queryId, ResetUsage(), ShowUsage(), and transformTopLevelStmt().

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

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 595 of file postgres.c.

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

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

◆ pg_plan_queries()

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

Definition at line 916 of file postgres.c.

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

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

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

◆ pg_plan_query()

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

Definition at line 830 of file postgres.c.

832 {
833  PlannedStmt *plan;
834 
835  /* Utility commands have no plans. */
836  if (querytree->commandType == CMD_UTILITY)
837  return NULL;
838 
839  /* Planner must have a snapshot in case it calls user-defined functions. */
841 
842  TRACE_POSTGRESQL_QUERY_PLAN_START();
843 
844  if (log_planner_stats)
845  ResetUsage();
846 
847  /* call the optimizer */
848  plan = planner(querytree, query_string, cursorOptions, boundParams);
849 
850  if (log_planner_stats)
851  ShowUsage("PLANNER STATISTICS");
852 
853 #ifdef COPY_PARSE_PLAN_TREES
854  /* Optional debugging check: pass plan tree through copyObject() */
855  {
856  PlannedStmt *new_plan = copyObject(plan);
857 
858  /*
859  * equal() currently does not have routines to compare Plan nodes, so
860  * don't try to test equality here. Perhaps fix someday?
861  */
862 #ifdef NOT_USED
863  /* This checks both copyObject() and the equal() routines... */
864  if (!equal(new_plan, plan))
865  elog(WARNING, "copyObject() failed to produce an equal plan tree");
866  else
867 #endif
868  plan = new_plan;
869  }
870 #endif
871 
872 #ifdef WRITE_READ_PARSE_PLAN_TREES
873  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
874  {
875  char *str;
876  PlannedStmt *new_plan;
877 
878  str = nodeToString(plan);
879  new_plan = stringToNodeWithLocations(str);
880  pfree(str);
881 
882  /*
883  * equal() currently does not have routines to compare Plan nodes, so
884  * don't try to test equality here. Perhaps fix someday?
885  */
886 #ifdef NOT_USED
887  /* This checks both outfuncs/readfuncs and the equal() routines... */
888  if (!equal(new_plan, plan))
889  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
890  else
891 #endif
892  plan = new_plan;
893  }
894 #endif
895 
896  /*
897  * Print plan if debugging.
898  */
899  if (Debug_print_plan)
900  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
901 
902  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
903 
904  return plan;
905 }
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:664
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
#define LOG
Definition: elog.h:25
bool Debug_print_plan
Definition: guc.c:574
bool Debug_pretty_print
Definition: guc.c:577
bool log_planner_stats
Definition: guc.c:580
void pfree(void *pointer)
Definition: mcxt.c:1169
char * nodeToString(const void *obj)
Definition: outfuncs.c:4558
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:269
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:813

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

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

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 738 of file postgres.c.

739 {
740  List *querytree_list;
741 
742  if (Debug_print_parse)
743  elog_node_display(LOG, "parse tree", query,
745 
746  if (log_parser_stats)
747  ResetUsage();
748 
749  if (query->commandType == CMD_UTILITY)
750  {
751  /* don't rewrite utilities, just dump 'em into result list */
752  querytree_list = list_make1(query);
753  }
754  else
755  {
756  /* rewrite regular queries */
757  querytree_list = QueryRewrite(query);
758  }
759 
760  if (log_parser_stats)
761  ShowUsage("REWRITER STATISTICS");
762 
763 #ifdef COPY_PARSE_PLAN_TREES
764  /* Optional debugging check: pass querytree through copyObject() */
765  {
766  List *new_list;
767 
768  new_list = copyObject(querytree_list);
769  /* This checks both copyObject() and the equal() routines... */
770  if (!equal(new_list, querytree_list))
771  elog(WARNING, "copyObject() failed to produce equal parse tree");
772  else
773  querytree_list = new_list;
774  }
775 #endif
776 
777 #ifdef WRITE_READ_PARSE_PLAN_TREES
778  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
779  {
780  List *new_list = NIL;
781  ListCell *lc;
782 
783  /*
784  * We currently lack outfuncs/readfuncs support for most utility
785  * statement types, so only attempt to write/read non-utility queries.
786  */
787  foreach(lc, querytree_list)
788  {
789  Query *query = lfirst_node(Query, lc);
790 
791  if (query->commandType != CMD_UTILITY)
792  {
793  char *str = nodeToString(query);
794  Query *new_query = stringToNodeWithLocations(str);
795 
796  /*
797  * queryId is not saved in stored rules, but we must preserve
798  * it here to avoid breaking pg_stat_statements.
799  */
800  new_query->queryId = query->queryId;
801 
802  new_list = lappend(new_list, new_query);
803  pfree(str);
804  }
805  else
806  new_list = lappend(new_list, query);
807  }
808 
809  /* This checks both outfuncs/readfuncs and the equal() routines... */
810  if (!equal(new_list, querytree_list))
811  elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
812  else
813  querytree_list = new_list;
814  }
815 #endif
816 
818  elog_node_display(LOG, "rewritten parse tree", querytree_list,
820 
821  return querytree_list;
822 }
bool Debug_print_rewritten
Definition: guc.c:576
bool Debug_print_parse
Definition: guc.c:575
#define list_make1(x1)
Definition: pg_list.h:206
List * QueryRewrite(Query *parsetree)

References CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), lappend(), lfirst_node, list_make1, LOG, log_parser_stats, new_list(), NIL, nodeToString(), pfree(), Query::queryId, QueryRewrite(), ResetUsage(), ShowUsage(), generate_unaccent_rules::str, and WARNING.

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

◆ PostgresMain()

void PostgresMain ( const char *  dbname,
const char *  username 
)

Definition at line 4016 of file postgres.c.

4017 {
4018  int firstchar;
4019  StringInfoData input_message;
4020  sigjmp_buf local_sigjmp_buf;
4021  volatile bool send_ready_for_query = true;
4022  bool idle_in_transaction_timeout_enabled = false;
4023  bool idle_session_timeout_enabled = false;
4024 
4025  AssertArg(dbname != NULL);
4026  AssertArg(username != NULL);
4027 
4029 
4030  /*
4031  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4032  * has already set up BlockSig and made that the active signal mask.)
4033  *
4034  * Note that postmaster blocked all signals before forking child process,
4035  * so there is no race condition whereby we might receive a signal before
4036  * we have set up the handler.
4037  *
4038  * Also note: it's best not to use any signals that are SIG_IGNored in the
4039  * postmaster. If such a signal arrives before we are able to change the
4040  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4041  * handler in the postmaster to reserve the signal. (Of course, this isn't
4042  * an issue for signals that are locally generated, such as SIGALRM and
4043  * SIGPIPE.)
4044  */
4045  if (am_walsender)
4046  WalSndSignals();
4047  else
4048  {
4050  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4051  pqsignal(SIGTERM, die); /* cancel current query and exit */
4052 
4053  /*
4054  * In a postmaster child backend, replace SignalHandlerForCrashExit
4055  * with quickdie, so we can tell the client we're dying.
4056  *
4057  * In a standalone backend, SIGQUIT can be generated from the keyboard
4058  * easily, while SIGTERM cannot, so we make both signals do die()
4059  * rather than quickdie().
4060  */
4061  if (IsUnderPostmaster)
4062  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4063  else
4064  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4065  InitializeTimeouts(); /* establishes SIGALRM handler */
4066 
4067  /*
4068  * Ignore failure to write to frontend. Note: if frontend closes
4069  * connection, we will notice it and exit cleanly when control next
4070  * returns to outer loop. This seems safer than forcing exit in the
4071  * midst of output during who-knows-what operation...
4072  */
4077 
4078  /*
4079  * Reset some signals that are accepted by postmaster but not by
4080  * backend
4081  */
4082  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4083  * platforms */
4084  }
4085 
4086  /* Early initialization */
4087  BaseInit();
4088 
4089  /* We need to allow SIGINT, etc during the initial transaction */
4091 
4092  /*
4093  * General initialization.
4094  *
4095  * NOTE: if you are tempted to add code in this vicinity, consider putting
4096  * it inside InitPostgres() instead. In particular, anything that
4097  * involves database access should be there, not here.
4098  */
4100 
4101  /*
4102  * If the PostmasterContext is still around, recycle the space; we don't
4103  * need it anymore after InitPostgres completes. Note this does not trash
4104  * *MyProcPort, because ConnCreate() allocated that space with malloc()
4105  * ... else we'd need to copy the Port data first. Also, subsidiary data
4106  * such as the username isn't lost either; see ProcessStartupPacket().
4107  */
4108  if (PostmasterContext)
4109  {
4111  PostmasterContext = NULL;
4112  }
4113 
4115 
4116  /*
4117  * Now all GUC states are fully set up. Report them to client if
4118  * appropriate.
4119  */
4121 
4122  /*
4123  * Also set up handler to log session end; we have to wait till now to be
4124  * sure Log_disconnections has its final value.
4125  */
4128 
4130 
4131  /* Perform initialization specific to a WAL sender process. */
4132  if (am_walsender)
4133  InitWalSender();
4134 
4135  /*
4136  * process any libraries that should be preloaded at backend start (this
4137  * likewise can't be done until GUC settings are complete)
4138  */
4140 
4141  /*
4142  * Send this backend's cancellation info to the frontend.
4143  */
4145  {
4147 
4148  pq_beginmessage(&buf, 'K');
4151  pq_endmessage(&buf);
4152  /* Need not flush since ReadyForQuery will do it. */
4153  }
4154 
4155  /* Welcome banner for standalone case */
4157  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4158 
4159  /*
4160  * Create the memory context we will use in the main loop.
4161  *
4162  * MessageContext is reset once per iteration of the main loop, ie, upon
4163  * completion of processing of each command message from the client.
4164  */
4166  "MessageContext",
4168 
4169  /*
4170  * Create memory context and buffer used for RowDescription messages. As
4171  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4172  * frequently executed for ever single statement, we don't want to
4173  * allocate a separate buffer every time.
4174  */
4176  "RowDescriptionContext",
4181 
4182  /*
4183  * POSTGRES main processing loop begins here
4184  *
4185  * If an exception is encountered, processing resumes here so we abort the
4186  * current transaction and start a new one.
4187  *
4188  * You might wonder why this isn't coded as an infinite loop around a
4189  * PG_TRY construct. The reason is that this is the bottom of the
4190  * exception stack, and so with PG_TRY there would be no exception handler
4191  * in force at all during the CATCH part. By leaving the outermost setjmp
4192  * always active, we have at least some chance of recovering from an error
4193  * during error recovery. (If we get into an infinite loop thereby, it
4194  * will soon be stopped by overflow of elog.c's internal state stack.)
4195  *
4196  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4197  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4198  * is essential in case we longjmp'd out of a signal handler on a platform
4199  * where that leaves the signal blocked. It's not redundant with the
4200  * unblock in AbortTransaction() because the latter is only called if we
4201  * were inside a transaction.
4202  */
4203 
4204  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4205  {
4206  /*
4207  * NOTE: if you are tempted to add more code in this if-block,
4208  * consider the high probability that it should be in
4209  * AbortTransaction() instead. The only stuff done directly here
4210  * should be stuff that is guaranteed to apply *only* for outer-level
4211  * error recovery, such as adjusting the FE/BE protocol status.
4212  */
4213 
4214  /* Since not using PG_TRY, must reset error stack by hand */
4215  error_context_stack = NULL;
4216 
4217  /* Prevent interrupts while cleaning up */
4218  HOLD_INTERRUPTS();
4219 
4220  /*
4221  * Forget any pending QueryCancel request, since we're returning to
4222  * the idle loop anyway, and cancel any active timeout requests. (In
4223  * future we might want to allow some timeout requests to survive, but
4224  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4225  * we got here because of a query cancel interrupting the SIGALRM
4226  * interrupt handler.) Note in particular that we must clear the
4227  * statement and lock timeout indicators, to prevent any future plain
4228  * query cancels from being misreported as timeouts in case we're
4229  * forgetting a timeout cancel.
4230  */
4231  disable_all_timeouts(false);
4232  QueryCancelPending = false; /* second to avoid race condition */
4233 
4234  /* Not reading from the client anymore. */
4235  DoingCommandRead = false;
4236 
4237  /* Make sure libpq is in a good state */
4238  pq_comm_reset();
4239 
4240  /* Report the error to the client and/or server log */
4241  EmitErrorReport();
4242 
4243  /*
4244  * Make sure debug_query_string gets reset before we possibly clobber
4245  * the storage it points at.
4246  */
4247  debug_query_string = NULL;
4248 
4249  /*
4250  * Abort the current transaction in order to recover.
4251  */
4253 
4254  if (am_walsender)
4256 
4258  SPICleanup();
4259 
4260  /*
4261  * We can't release replication slots inside AbortTransaction() as we
4262  * need to be able to start and abort transactions while having a slot
4263  * acquired. But we never need to hold them across top level errors,
4264  * so releasing here is fine. There's another cleanup in ProcKill()
4265  * ensuring we'll correctly cleanup on FATAL errors as well.
4266  */
4267  if (MyReplicationSlot != NULL)
4269 
4270  /* We also want to cleanup temporary slots on error. */
4272 
4274 
4275  /*
4276  * Now return to normal top-level context and clear ErrorContext for
4277  * next time.
4278  */
4280  FlushErrorState();
4281 
4282  /*
4283  * If we were handling an extended-query-protocol message, initiate
4284  * skip till next Sync. This also causes us not to issue
4285  * ReadyForQuery (until we get Sync).
4286  */
4288  ignore_till_sync = true;
4289 
4290  /* We don't have a transaction command open anymore */
4291  xact_started = false;
4292 
4293  /*
4294  * If an error occurred while we were reading a message from the
4295  * client, we have potentially lost track of where the previous
4296  * message ends and the next one begins. Even though we have
4297  * otherwise recovered from the error, we cannot safely read any more
4298  * messages from the client, so there isn't much we can do with the
4299  * connection anymore.
4300  */
4301  if (pq_is_reading_msg())
4302  ereport(FATAL,
4303  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4304  errmsg("terminating connection because protocol synchronization was lost")));
4305 
4306  /* Now we can allow interrupts again */
4308  }
4309 
4310  /* We can now handle ereport(ERROR) */
4311  PG_exception_stack = &local_sigjmp_buf;
4312 
4313  if (!ignore_till_sync)
4314  send_ready_for_query = true; /* initially, or after error */
4315 
4316  /*
4317  * Non-error queries loop here.
4318  */
4319 
4320  for (;;)
4321  {
4322  /*
4323  * At top of loop, reset extended-query-message flag, so that any
4324  * errors encountered in "idle" state don't provoke skip.
4325  */
4327 
4328  /*
4329  * Release storage left over from prior query cycle, and create a new
4330  * query input buffer in the cleared MessageContext.
4331  */
4334 
4335  initStringInfo(&input_message);
4336 
4337  /*
4338  * Also consider releasing our catalog snapshot if any, so that it's
4339  * not preventing advance of global xmin while we wait for the client.
4340  */
4342 
4343  /*
4344  * (1) If we've reached idle state, tell the frontend we're ready for
4345  * a new query.
4346  *
4347  * Note: this includes fflush()'ing the last of the prior output.
4348  *
4349  * This is also a good time to send collected statistics to the
4350  * collector, and to update the PS stats display. We avoid doing
4351  * those every time through the message loop because it'd slow down
4352  * processing of batched messages, and because we don't want to report
4353  * uncommitted updates (that confuses autovacuum). The notification
4354  * processor wants a call too, if we are not in a transaction block.
4355  *
4356  * Also, if an idle timeout is enabled, start the timer for that.
4357  */
4358  if (send_ready_for_query)
4359  {
4361  {
4362  set_ps_display("idle in transaction (aborted)");
4364 
4365  /* Start the idle-in-transaction timer */
4367  {
4368  idle_in_transaction_timeout_enabled = true;
4371  }
4372  }
4374  {
4375  set_ps_display("idle in transaction");
4377 
4378  /* Start the idle-in-transaction timer */
4380  {
4381  idle_in_transaction_timeout_enabled = true;
4384  }
4385  }
4386  else
4387  {
4388  /*
4389  * Process incoming notifies (including self-notifies), if
4390  * any, and send relevant messages to the client. Doing it
4391  * here helps ensure stable behavior in tests: if any notifies
4392  * were received during the just-finished transaction, they'll
4393  * be seen by the client before ReadyForQuery is.
4394  */
4396  ProcessNotifyInterrupt(false);
4397 
4398  pgstat_report_stat(false);
4399 
4400  set_ps_display("idle");
4402 
4403  /* Start the idle-session timer */
4404  if (IdleSessionTimeout > 0)
4405  {
4406  idle_session_timeout_enabled = true;
4409  }
4410  }
4411 
4412  /* Report any recently-changed GUC options */
4414 
4416  send_ready_for_query = false;
4417  }
4418 
4419  /*
4420  * (2) Allow asynchronous signals to be executed immediately if they
4421  * come in while we are waiting for client input. (This must be
4422  * conditional since we don't want, say, reads on behalf of COPY FROM
4423  * STDIN doing the same thing.)
4424  */
4425  DoingCommandRead = true;
4426 
4427  /*
4428  * (3) read a command (loop blocks here)
4429  */
4430  firstchar = ReadCommand(&input_message);
4431 
4432  /*
4433  * (4) turn off the idle-in-transaction and idle-session timeouts, if
4434  * active. We do this before step (5) so that any last-moment timeout
4435  * is certain to be detected in step (5).
4436  *
4437  * At most one of these timeouts will be active, so there's no need to
4438  * worry about combining the timeout.c calls into one.
4439  */
4440  if (idle_in_transaction_timeout_enabled)
4441  {
4443  idle_in_transaction_timeout_enabled = false;
4444  }
4445  if (idle_session_timeout_enabled)
4446  {
4448  idle_session_timeout_enabled = false;
4449  }
4450 
4451  /*
4452  * (5) disable async signal conditions again.
4453  *
4454  * Query cancel is supposed to be a no-op when there is no query in
4455  * progress, so if a query cancel arrived while we were idle, just
4456  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4457  * it's called when DoingCommandRead is set, so check for interrupts
4458  * before resetting DoingCommandRead.
4459  */
4461  DoingCommandRead = false;
4462 
4463  /*
4464  * (6) check for any other interesting events that happened while we
4465  * slept.
4466  */
4467  if (ConfigReloadPending)
4468  {
4469  ConfigReloadPending = false;
4471  }
4472 
4473  /*
4474  * (7) process the command. But ignore it if we're skipping till
4475  * Sync.
4476  */
4477  if (ignore_till_sync && firstchar != EOF)
4478  continue;
4479 
4480  switch (firstchar)
4481  {
4482  case 'Q': /* simple query */
4483  {
4484  const char *query_string;
4485 
4486  /* Set statement_timestamp() */
4488 
4489  query_string = pq_getmsgstring(&input_message);
4490  pq_getmsgend(&input_message);
4491 
4492  if (am_walsender)
4493  {
4494  if (!exec_replication_command(query_string))
4495  exec_simple_query(query_string);
4496  }
4497  else
4498  exec_simple_query(query_string);
4499 
4500  send_ready_for_query = true;
4501  }
4502  break;
4503 
4504  case 'P': /* parse */
4505  {
4506  const char *stmt_name;
4507  const char *query_string;
4508  int numParams;
4509  Oid *paramTypes = NULL;
4510 
4511  forbidden_in_wal_sender(firstchar);
4512 
4513  /* Set statement_timestamp() */
4515 
4516  stmt_name = pq_getmsgstring(&input_message);
4517  query_string = pq_getmsgstring(&input_message);
4518  numParams = pq_getmsgint(&input_message, 2);
4519  if (numParams > 0)
4520  {
4521  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4522  for (int i = 0; i < numParams; i++)
4523  paramTypes[i] = pq_getmsgint(&input_message, 4);
4524  }
4525  pq_getmsgend(&input_message);
4526 
4527  exec_parse_message(query_string, stmt_name,
4528  paramTypes, numParams);
4529  }
4530  break;
4531 
4532  case 'B': /* bind */
4533  forbidden_in_wal_sender(firstchar);
4534 
4535  /* Set statement_timestamp() */
4537 
4538  /*
4539  * this message is complex enough that it seems best to put
4540  * the field extraction out-of-line
4541  */
4542  exec_bind_message(&input_message);
4543  break;
4544 
4545  case 'E': /* execute */
4546  {
4547  const char *portal_name;
4548  int max_rows;
4549 
4550  forbidden_in_wal_sender(firstchar);
4551 
4552  /* Set statement_timestamp() */
4554 
4555  portal_name = pq_getmsgstring(&input_message);
4556  max_rows = pq_getmsgint(&input_message, 4);
4557  pq_getmsgend(&input_message);
4558 
4559  exec_execute_message(portal_name, max_rows);
4560  }
4561  break;
4562 
4563  case 'F': /* fastpath function call */
4564  forbidden_in_wal_sender(firstchar);
4565 
4566  /* Set statement_timestamp() */
4568 
4569  /* Report query to various monitoring facilities. */
4571  set_ps_display("<FASTPATH>");
4572 
4573  /* start an xact for this function invocation */
4575 
4576  /*
4577  * Note: we may at this point be inside an aborted
4578  * transaction. We can't throw error for that until we've
4579  * finished reading the function-call message, so
4580  * HandleFunctionRequest() must check for it after doing so.
4581  * Be careful not to do anything that assumes we're inside a
4582  * valid transaction here.
4583  */
4584 
4585  /* switch back to message context */
4587 
4588  HandleFunctionRequest(&input_message);
4589 
4590  /* commit the function-invocation transaction */
4592 
4593  send_ready_for_query = true;
4594  break;
4595 
4596  case 'C': /* close */
4597  {
4598  int close_type;
4599  const char *close_target;
4600 
4601  forbidden_in_wal_sender(firstchar);
4602 
4603  close_type = pq_getmsgbyte(&input_message);
4604  close_target = pq_getmsgstring(&input_message);
4605  pq_getmsgend(&input_message);
4606 
4607  switch (close_type)
4608  {
4609  case 'S':
4610  if (close_target[0] != '\0')
4611  DropPreparedStatement(close_target, false);
4612  else
4613  {
4614  /* special-case the unnamed statement */
4616  }
4617  break;
4618  case 'P':
4619  {
4620  Portal portal;
4621 
4622  portal = GetPortalByName(close_target);
4623  if (PortalIsValid(portal))
4624  PortalDrop(portal, false);
4625  }
4626  break;
4627  default:
4628  ereport(ERROR,
4629  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4630  errmsg("invalid CLOSE message subtype %d",
4631  close_type)));
4632  break;
4633  }
4634 
4636  pq_putemptymessage('3'); /* CloseComplete */
4637  }
4638  break;
4639 
4640  case 'D': /* describe */
4641  {
4642  int describe_type;
4643  const char *describe_target;
4644 
4645  forbidden_in_wal_sender(firstchar);
4646 
4647  /* Set statement_timestamp() (needed for xact) */
4649 
4650  describe_type = pq_getmsgbyte(&input_message);
4651  describe_target = pq_getmsgstring(&input_message);
4652  pq_getmsgend(&input_message);
4653 
4654  switch (describe_type)
4655  {
4656  case 'S':
4657  exec_describe_statement_message(describe_target);
4658  break;
4659  case 'P':
4660  exec_describe_portal_message(describe_target);
4661  break;
4662  default:
4663  ereport(ERROR,
4664  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4665  errmsg("invalid DESCRIBE message subtype %d",
4666  describe_type)));
4667  break;
4668  }
4669  }
4670  break;
4671 
4672  case 'H': /* flush */
4673  pq_getmsgend(&input_message);
4675  pq_flush();
4676  break;
4677 
4678  case 'S': /* sync */
4679  pq_getmsgend(&input_message);
4681  send_ready_for_query = true;
4682  break;
4683 
4684  /*
4685  * 'X' means that the frontend is closing down the socket. EOF
4686  * means unexpected loss of frontend connection. Either way,
4687  * perform normal shutdown.
4688  */
4689  case EOF:
4690 
4691  /* for the statistics collector */
4693 
4694  /* FALLTHROUGH */
4695 
4696  case 'X':
4697 
4698  /*
4699  * Reset whereToSendOutput to prevent ereport from attempting
4700  * to send any more messages to client.
4701  */
4704 
4705  /*
4706  * NOTE: if you are tempted to add more code here, DON'T!
4707  * Whatever you had in mind to do should be set up as an
4708  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4709  * it will fail to be called during other backend-shutdown
4710  * scenarios.
4711  */
4712  proc_exit(0);
4713 
4714  case 'd': /* copy data */
4715  case 'c': /* copy done */
4716  case 'f': /* copy fail */
4717 
4718  /*
4719  * Accept but ignore these messages, per protocol spec; we
4720  * probably got here because a COPY failed, and the frontend
4721  * is still sending data.
4722  */
4723  break;
4724 
4725  default:
4726  ereport(FATAL,
4727  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4728  errmsg("invalid frontend message type %d",
4729  firstchar)));
4730  }
4731  } /* end of input-reading loop */
4732 }
void ProcessNotifyInterrupt(bool flush)
Definition: async.c:1883
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:431
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:553
sigset_t UnBlockSig
Definition: pqsignal.c:22
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
signed int int32
Definition: c.h:429
#define AssertArg(condition)
Definition: c.h:806
void ReadyForQuery(CommandDest dest)
Definition: dest.c:271
@ DestDebug
Definition: dest.h:90
@ DestNone
Definition: dest.h:89
void EmitErrorReport(void)
Definition: elog.c:1504
ErrorContextCallback * error_context_stack
Definition: elog.c:93
void FlushErrorState(void)
Definition: elog.c:1649
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
#define FATAL
Definition: elog.h:35
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:188
int32 MyCancelKey
Definition: globals.c:47
int MyProcPid
Definition: globals.c:43
bool IsUnderPostmaster
Definition: globals.c:112
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
Oid MyDatabaseId
Definition: globals.c:88
void BeginReportingGUCOptions(void)
Definition: guc.c:6558
void ReportChangedGUCOptions(void)
Definition: guc.c:6604
@ PGC_SIGHUP
Definition: guc.h:72
void ProcessConfigFile(GucContext context)
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void proc_exit(int code)
Definition: ipc.c:104
int i
Definition: isn.c:73
void jit_reset_after_error(void)
Definition: jit.c:128
#define pq_flush()
Definition: libpq.h:46
#define pq_comm_reset()
Definition: libpq.h:45
MemoryContext MessageContext
Definition: mcxt.c:52
MemoryContext TopMemoryContext
Definition: mcxt.c:48
MemoryContext PostmasterContext
Definition: mcxt.c:50
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
void * palloc(Size size)
Definition: mcxt.c:1062
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
@ NormalProcessing
Definition: miscadmin.h:401
@ InitProcessing
Definition: miscadmin.h:400
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
void process_session_preload_libraries(void)
Definition: miscinit.c:1689
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static char * buf
Definition: pg_test_fsync.c:70
const char * username
Definition: pgbench.c:282
void pgstat_report_connect(Oid dboid)
Definition: pgstat.c:1830
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:861
@ DISCONNECT_CLIENT_EOF
Definition: pgstat.h:49
#define printf(...)
Definition: port.h:231
#define PortalIsValid(p)
Definition: portal.h:212
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:468
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void PortalErrorCleanup(void)
Definition: portalmem.c:917
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2540
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2819
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4909
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4742
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2044
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2971
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2950
static bool ignore_till_sync
Definition: postgres.c:163
static void finish_xact_command(void)
Definition: postgres.c:2715
const char * debug_query_string
Definition: postgres.c:90
static void exec_simple_query(const char *query_string)
Definition: postgres.c:957
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1325
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1582
void die(SIGNAL_ARGS)
Definition: postgres.c:2916
static bool xact_started
Definition: postgres.c:149
static MemoryContext row_description_context
Definition: postgres.c:183
static StringInfoData row_description_buf
Definition: postgres.c:184
static bool doing_extended_query_message
Definition: postgres.c:162
static void start_xact_command(void)
Definition: postgres.c:2687
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2635
bool Log_disconnections
Definition: postgres.c:96
static void drop_unnamed_stmt(void)
Definition: postgres.c:2794
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:472
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void BaseInit(void)
Definition: postinit.c:511
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:578
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1219
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
void set_ps_display(const char *activity)
Definition: ps_status.c:349
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
void ReplicationSlotCleanup(void)
Definition: slot.c:525
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
void ReplicationSlotRelease(void)
Definition: slot.c:469
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:477
void SPICleanup(void)
Definition: spi.c:354
int IdleSessionTimeout
Definition: proc.c:64
int IdleInTransactionSessionTimeout
Definition: proc.c:63
char * dbname
Definition: streamutil.c:51
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:551
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:742
void InitializeTimeouts(void)
Definition: timeout.c:461
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:676
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:34
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
void WalSndErrorCleanup(void)
Definition: walsender.c:297
bool am_walsender
Definition: walsender.c:115
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1611
void WalSndSignals(void)
Definition: walsender.c:3166
void InitWalSender(void)
#define SIGCHLD
Definition: win32_port.h:177
#define SIGHUP
Definition: win32_port.h:167
#define SIG_DFL
Definition: win32_port.h:162
#define SIGPIPE
Definition: win32_port.h:172
#define SIGQUIT
Definition: win32_port.h:168
#define SIGUSR1
Definition: win32_port.h:179
#define SIGUSR2
Definition: win32_port.h:180
#define SIG_IGN
Definition: win32_port.h:164
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4772
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:393
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:885
void AbortCurrentTransaction(void)
Definition: xact.c:3281

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, AssertArg, BaseInit(), BeginReportingGUCOptions(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, dbname, debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), DISCONNECT_CLIENT_EOF, doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), ereport, errcode(), errmsg(), ERROR, error_context_stack, exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), FATAL, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), GetPortalByName(), HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, IdleSessionTimeout, ignore_till_sync, InitializeTimeouts(), InitPostgres(), InitProcessing, initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyDatabaseId, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_SIGHUP, pgstat_report_activity(), pgstat_report_connect(), pgstat_report_stat(), pgStatSessionEndCause, PortalDrop(), PortalErrorCleanup(), PortalIsValid, PostmasterContext, pq_beginmessage(), pq_comm_reset, pq_endmessage(), pq_flush, pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_is_reading_msg(), pq_putemptymessage(), pq_sendint32(), pqsignal(), printf, proc_exit(), process_session_preload_libraries(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, row_description_buf, row_description_context, set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SPICleanup(), start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, UnBlockSig, username, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 3929 of file postgres.c.

3931 {
3932  const char *dbname = NULL;
3933 
3935 
3936  /* Initialize startup process environment. */
3937  InitStandaloneProcess(argv[0]);
3938 
3939  /*
3940  * Set default values for command-line options.
3941  */
3943 
3944  /*
3945  * Parse command-line options.
3946  */
3948 
3949  /* Must have gotten a database name, or have a default (the username) */
3950  if (dbname == NULL)
3951  {
3952  dbname = username;
3953  if (dbname == NULL)
3954  ereport(FATAL,
3955  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3956  errmsg("%s: no database nor user name specified",
3957  progname)));
3958  }
3959 
3960  /* Acquire configuration parameters */
3962  proc_exit(1);
3963 
3964  /*
3965  * Validate we have been given a reasonable-looking DataDir and change
3966  * into it.
3967  */
3968  checkDataDir();
3969  ChangeToDataDir();
3970 
3971  /*
3972  * Create lockfile for data directory.
3973  */
3974  CreateDataDirLockFile(false);
3975 
3976  /* read control file (error checking and contains config ) */
3977  LocalProcessControlFile(false);
3978 
3979  /* Initialize MaxBackends */
3981 
3983 
3984  /*
3985  * Remember stand-alone backend startup time,roughly at the same point
3986  * during startup that postmaster does so.
3987  */
3989 
3990  /*
3991  * Create a per-backend PGPROC struct in shared memory. We must do this
3992  * before we can use LWLocks.
3993  */
3994  InitProcess();
3995 
3996  /*
3997  * Now that sufficient infrastructure has been initialized, PostgresMain()
3998  * can do the rest.
3999  */
4001 }
TimestampTz PgStartTime
Definition: timestamp.c:52
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5880
void InitializeGUCOptions(void)
Definition: guc.c:5657
@ PGC_POSTMASTER
Definition: guc.h:71
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:176
const char * progname
Definition: main.c:46
void ChangeToDataDir(void)
Definition: miscinit.c:435
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void checkDataDir(void)
Definition: miscinit.c:321
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1292
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3676
static const char * userDoption
Definition: postgres.c:173
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4016
void InitializeMaxBackends(void)
Definition: postinit.c:489
void InitProcess(void)
Definition: proc.c:301
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5182

References Assert(), ChangeToDataDir(), checkDataDir(), CreateDataDirLockFile(), CreateSharedMemoryAndSemaphores(), dbname, ereport, errcode(), errmsg(), FATAL, GetCurrentTimestamp(), InitializeGUCOptions(), InitializeMaxBackends(), InitProcess(), InitStandaloneProcess(), IsUnderPostmaster, LocalProcessControlFile(), PGC_POSTMASTER, PgStartTime, PostgresMain(), proc_exit(), process_postgres_switches(), progname, SelectConfigFiles(), userDoption, and username.

Referenced by main().

◆ process_postgres_switches()

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

Definition at line 3676 of file postgres.c.

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

References dbname, 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 PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 493 of file postgres.c.

494 {
495  int save_errno = errno;
496 
497  if (DoingCommandRead)
498  {
499  /* Check for general interrupts that arrived before/while reading */
501 
502  /* Process sinval catchup interrupts, if any */
505 
506  /* Process notify interrupts, if any */
509  }
510  else if (ProcDiePending)
511  {
512  /*
513  * We're dying. If there is no data available to read, then it's safe
514  * (and sane) to handle that now. If we haven't tried to read yet,
515  * make sure the process latch is set, so that if there is no data
516  * then we'll come back here and die. If we're done reading, also
517  * make sure the process latch is set, as we might've undesirably
518  * cleared it while reading.
519  */
520  if (blocked)
522  else
523  SetLatch(MyLatch);
524  }
525 
526  errno = save_errno;
527 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 539 of file postgres.c.

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

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

Referenced by secure_write().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2819 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2989 of file postgres.c.

2990 {
2991  int save_errno = errno;
2992 
2993  /*
2994  * Don't joggle the elbow of proc_exit
2995  */
2996  if (!proc_exit_inprogress)
2997  {
2998  RecoveryConflictReason = reason;
2999  switch (reason)
3000  {
3002 
3003  /*
3004  * If we aren't waiting for a lock we can never deadlock.
3005  */
3006  if (!IsWaitingForLock())
3007  return;
3008 
3009  /* Intentional fall through to check wait for pin */
3010  /* FALLTHROUGH */
3011 
3013 
3014  /*
3015  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3016  * aren't blocking the Startup process there is nothing more
3017  * to do.
3018  *
3019  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is
3020  * requested, if we're waiting for locks and the startup
3021  * process is not waiting for buffer pin (i.e., also waiting
3022  * for locks), we set the flag so that ProcSleep() will check
3023  * for deadlocks.
3024  */
3026  {
3030  return;
3031  }
3032 
3034 
3035  /* Intentional fall through to error handling */
3036  /* FALLTHROUGH */
3037 
3041 
3042  /*
3043  * If we aren't in a transaction any longer then ignore.
3044  */
3046  return;
3047 
3048  /*
3049  * If we can abort just the current subtransaction then we are
3050  * OK to throw an ERROR to resolve the conflict. Otherwise
3051  * drop through to the FATAL case.
3052  *
3053  * XXX other times that we can throw just an ERROR *may* be
3054  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
3055  * parent transactions
3056  *
3057  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
3058  * by parent transactions and the transaction is not
3059  * transaction-snapshot mode
3060  *
3061  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3062  * cursors open in parent transactions
3063  */
3064  if (!IsSubTransaction())
3065  {
3066  /*
3067  * If we already aborted then we no longer need to cancel.
3068  * We do this here since we do not wish to ignore aborted
3069  * subtransactions, which must cause FATAL, currently.
3070  */
3072  return;
3073 
3074  RecoveryConflictPending = true;
3075  QueryCancelPending = true;
3076  InterruptPending = true;
3077  break;
3078  }
3079 
3080  /* Intentional fall through to session cancel */
3081  /* FALLTHROUGH */
3082 
3084  RecoveryConflictPending = true;
3085  ProcDiePending = true;
3086  InterruptPending = true;
3087  break;
3088 
3089  default:
3090  elog(FATAL, "unrecognized conflict mode: %d",
3091  (int) reason);
3092  }
3093 
3095 
3096  /*
3097  * All conflicts apart from database cause dynamic errors where the
3098  * command or transaction can be retried at a later point with some
3099  * potential for success. No need to reset this, since non-retryable
3100  * conflict errors are currently FATAL.
3101  */
3102  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
3103  RecoveryConflictRetryable = false;
3104  }
3105 
3106  /*
3107  * Set the process latch. This function essentially emulates signal
3108  * handlers like die() and StatementCancelHandler() and it seems prudent
3109  * to behave similarly as they do.
3110  */
3111  SetLatch(MyLatch);
3112 
3113  errno = save_errno;
3114 }
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:4204
static bool RecoveryConflictRetryable
Definition: postgres.c:179
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:180
static bool RecoveryConflictPending
Definition: postgres.c:178
@ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
Definition: procsignal.h:44
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:42
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:40
@ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
Definition: procsignal.h:43
@ PROCSIG_RECOVERY_CONFLICT_TABLESPACE
Definition: procsignal.h:41
@ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition: procsignal.h:45
PGPROC * MyProc
Definition: proc.c:68
bool IsWaitingForLock(void)
Definition: proc.c:682
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:645
void CheckDeadLockAlert(void)
Definition: proc.c:1854
bool recoveryConflictPending
Definition: proc.h:170
bool IsSubTransaction(void)
Definition: xact.c:4827

References Assert(), CheckDeadLockAlert(), elog, FATAL, GetStartupBufferPinWaitBufId(), HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), IsWaitingForLock(), MyLatch, MyProc, proc_exit_inprogress, ProcDiePending, 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, QueryCancelPending, RecoveryConflictPending, PGPROC::recoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

◆ ResetUsage()

void ResetUsage ( void  )

Definition at line 4800 of file postgres.c.

4801 {
4803  gettimeofday(&Save_t, NULL);
4804 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
static struct timeval Save_t
Definition: postgres.c:4797
static struct rusage Save_r
Definition: postgres.c:4796
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
#define RUSAGE_SELF
Definition: rusagestub.h:23

References getrusage(), gettimeofday(), RUSAGE_SELF, Save_r, and Save_t.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

◆ set_debug_options()

void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3565 of file postgres.c.

3566 {
3567  if (debug_flag > 0)
3568  {
3569  char debugstr[64];
3570 
3571  sprintf(debugstr, "debug%d", debug_flag);
3572  SetConfigOption("log_min_messages", debugstr, context, source);
3573  }
3574  else
3575  SetConfigOption("log_min_messages", "notice", context, source);
3576 
3577  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3578  {
3579  SetConfigOption("log_connections", "true", context, source);
3580  SetConfigOption("log_disconnections", "true", context, source);
3581  }
3582  if (debug_flag >= 2)
3583  SetConfigOption("log_statement", "all", context, source);
3584  if (debug_flag >= 3)
3585  SetConfigOption("debug_print_parse", "true", context, source);
3586  if (debug_flag >= 4)
3587  SetConfigOption("debug_print_plan", "true", context, source);
3588  if (debug_flag >= 5)
3589  SetConfigOption("debug_print_rewritten", "true", context, source);
3590 }
static rewind_source * source
Definition: pg_rewind.c:79
#define sprintf
Definition: port.h:227

References PGC_POSTMASTER, SetConfigOption(), source, and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_plan_disabling_options()

bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3594 of file postgres.c.

3595 {
3596  const char *tmp = NULL;
3597 
3598  switch (arg[0])
3599  {
3600  case 's': /* seqscan */
3601  tmp = "enable_seqscan";
3602  break;
3603  case 'i': /* indexscan */
3604  tmp = "enable_indexscan";
3605  break;
3606  case 'o': /* indexonlyscan */
3607  tmp = "enable_indexonlyscan";
3608  break;
3609  case 'b': /* bitmapscan */
3610  tmp = "enable_bitmapscan";
3611  break;
3612  case 't': /* tidscan */
3613  tmp = "enable_tidscan";
3614  break;
3615  case 'n': /* nestloop */
3616  tmp = "enable_nestloop";
3617  break;
3618  case 'm': /* mergejoin */
3619  tmp = "enable_mergejoin";
3620  break;
3621  case 'h': /* hashjoin */
3622  tmp = "enable_hashjoin";
3623  break;
3624  }
3625  if (tmp)
3626  {
3627  SetConfigOption(tmp, "false", context, source);
3628  return true;
3629  }
3630  else
3631  return false;
3632 }

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4807 of file postgres.c.

4808 {
4810  struct timeval user,
4811  sys;
4812  struct timeval elapse_t;
4813  struct rusage r;
4814 
4815  getrusage(RUSAGE_SELF, &r);
4816  gettimeofday(&elapse_t, NULL);
4817  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4818  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4819  if (elapse_t.tv_usec < Save_t.tv_usec)
4820  {
4821  elapse_t.tv_sec--;
4822  elapse_t.tv_usec += 1000000;
4823  }
4824  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4825  {
4826  r.ru_utime.tv_sec--;
4827  r.ru_utime.tv_usec += 1000000;
4828  }
4829  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4830  {
4831  r.ru_stime.tv_sec--;
4832  r.ru_stime.tv_usec += 1000000;
4833  }
4834 
4835  /*
4836  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4837  * some work to interpret them, and most platforms don't fill them in.
4838  */
4839  initStringInfo(&str);
4840 
4841  appendStringInfoString(&str, "! system usage stats:\n");
4843  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4844  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4845  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4846  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4847  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4848  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4849  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4851  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4852  (long) user.tv_sec,
4853  (long) user.tv_usec,
4854  (long) sys.tv_sec,
4855  (long) sys.tv_usec);
4856 #if defined(HAVE_GETRUSAGE)
4858  "!\t%ld kB max resident size\n",
4859 #if defined(__darwin__)
4860  /* in bytes on macOS */
4861  r.ru_maxrss / 1024
4862 #else
4863  /* in kilobytes on most other platforms */
4864  r.ru_maxrss
4865 #endif
4866  );
4868  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4869  r.ru_inblock - Save_r.ru_inblock,
4870  /* they only drink coffee at dec */
4871  r.ru_oublock - Save_r.ru_oublock,
4872  r.ru_inblock, r.ru_oublock);
4874  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4875  r.ru_majflt - Save_r.ru_majflt,
4876  r.ru_minflt - Save_r.ru_minflt,
4877  r.ru_majflt, r.ru_minflt,
4878  r.ru_nswap - Save_r.ru_nswap,
4879  r.ru_nswap);
4881  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4882  r.ru_nsignals - Save_r.ru_nsignals,
4883  r.ru_nsignals,
4884  r.ru_msgrcv - Save_r.ru_msgrcv,
4885  r.ru_msgsnd - Save_r.ru_msgsnd,
4886  r.ru_msgrcv, r.ru_msgsnd);
4888  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4889  r.ru_nvcsw - Save_r.ru_nvcsw,
4890  r.ru_nivcsw - Save_r.ru_nivcsw,
4891  r.ru_nvcsw, r.ru_nivcsw);
4892 #endif /* HAVE_GETRUSAGE */
4893 
4894  /* remove trailing newline */
4895  if (str.data[str.len - 1] == '\n')
4896  str.data[--str.len] = '\0';
4897 
4898  ereport(LOG,
4899  (errmsg_internal("%s", title),
4900  errdetail_internal("%s", str.data)));
4901 
4902  pfree(str.data);
4903 }
#define __darwin__
Definition: darwin.h:3
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1064
static char * user
Definition: pg_regress.c:95
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
struct timeval ru_utime
Definition: rusagestub.h:28
struct timeval ru_stime
Definition: rusagestub.h:29

References __darwin__, appendStringInfo(), appendStringInfoString(), ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), LOG, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, Save_t, generate_unaccent_rules::str, and user.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2950 of file postgres.c.

2951 {
2952  int save_errno = errno;
2953 
2954  /*
2955  * Don't joggle the elbow of proc_exit
2956  */
2957  if (!proc_exit_inprogress)
2958  {
2959  InterruptPending = true;
2960  QueryCancelPending = true;
2961  }
2962 
2963  /* If we're still here, waken anything waiting on the process latch */
2964  SetLatch(MyLatch);
2965 
2966  errno = save_errno;
2967 }

References InterruptPending, MyLatch, proc_exit_inprogress, QueryCancelPending, and SetLatch().

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

Variable Documentation

◆ client_connection_check_interval

int client_connection_check_interval
extern

Definition at line 107 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 98 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

int max_stack_depth
extern

Definition at line 101 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

int PostAuthDelay
extern

◆ whereToSendOutput