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_fixedparams (RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_varparams (RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_withcb (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
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)
 
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

PGDLLIMPORT CommandDest whereToSendOutput
 
PGDLLIMPORT const char * debug_query_string
 
PGDLLIMPORT int max_stack_depth
 
PGDLLIMPORT int PostAuthDelay
 
PGDLLIMPORT 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

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2327 of file postgres.c.

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

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

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

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2917 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2972 of file postgres.c.

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

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

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

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3642 of file postgres.c.

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

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ pg_analyze_and_rewrite_fixedparams()

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

Definition at line 638 of file postgres.c.

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

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

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

◆ pg_analyze_and_rewrite_varparams()

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

Definition at line 677 of file postgres.c.

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

References ereport, errcode(), errmsg(), ERROR, i, InvalidOid, log_parser_stats, parse_analyze_varparams(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by exec_parse_message(), and PrepareQuery().

◆ pg_analyze_and_rewrite_withcb()

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

Definition at line 731 of file postgres.c.

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

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

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

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 578 of file postgres.c.

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

References copyObject, elog(), equal(), log_parser_stats, new_list(), nodeToString(), pfree(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), generate_unaccent_rules::str, and WARNING.

Referenced by exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

◆ pg_plan_queries()

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

Definition at line 939 of file postgres.c.

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

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

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

◆ pg_plan_query()

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

Definition at line 853 of file postgres.c.

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

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

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

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 771 of file postgres.c.

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

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

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), and pg_analyze_and_rewrite_withcb().

◆ PostgresMain()

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

Definition at line 4044 of file postgres.c.

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

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

Referenced by BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 3934 of file postgres.c.

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

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

Referenced by main().

◆ process_postgres_switches()

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

Definition at line 3682 of file postgres.c.

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

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

Referenced by PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 476 of file postgres.c.

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

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 522 of file postgres.c.

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

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

Referenced by secure_write().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2820 of file postgres.c.

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

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

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

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  )

◆ set_debug_options()

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

Definition at line 3571 of file postgres.c.

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

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

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

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4856 of file postgres.c.

4857 {
4859  struct timeval user,
4860  sys;
4861  struct timeval elapse_t;
4862  struct rusage r;
4863 
4864  getrusage(RUSAGE_SELF, &r);
4865  gettimeofday(&elapse_t, NULL);
4866  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4867  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4868  if (elapse_t.tv_usec < Save_t.tv_usec)
4869  {
4870  elapse_t.tv_sec--;
4871  elapse_t.tv_usec += 1000000;
4872  }
4873  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4874  {
4875  r.ru_utime.tv_sec--;
4876  r.ru_utime.tv_usec += 1000000;
4877  }
4878  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4879  {
4880  r.ru_stime.tv_sec--;
4881  r.ru_stime.tv_usec += 1000000;
4882  }
4883 
4884  /*
4885  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4886  * some work to interpret them, and most platforms don't fill them in.
4887  */
4888  initStringInfo(&str);
4889 
4890  appendStringInfoString(&str, "! system usage stats:\n");
4892  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4893  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4894  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4895  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4896  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4897  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4898  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4900  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4901  (long) user.tv_sec,
4902  (long) user.tv_usec,
4903  (long) sys.tv_sec,
4904  (long) sys.tv_usec);
4905 #ifndef WIN32
4906 
4907  /*
4908  * The following rusage fields are not defined by POSIX, but they're
4909  * present on all current Unix-like systems so we use them without any
4910  * special checks. Some of these could be provided in our Windows
4911  * emulation in src/port/win32getrusage.c with more work.
4912  */
4914  "!\t%ld kB max resident size\n",
4915 #if defined(__darwin__)
4916  /* in bytes on macOS */
4917  r.ru_maxrss / 1024
4918 #else
4919  /* in kilobytes on most other platforms */
4920  r.ru_maxrss
4921 #endif
4922  );
4924  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4925  r.ru_inblock - Save_r.ru_inblock,
4926  /* they only drink coffee at dec */
4927  r.ru_oublock - Save_r.ru_oublock,
4928  r.ru_inblock, r.ru_oublock);
4930  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4931  r.ru_majflt - Save_r.ru_majflt,
4932  r.ru_minflt - Save_r.ru_minflt,
4933  r.ru_majflt, r.ru_minflt,
4934  r.ru_nswap - Save_r.ru_nswap,
4935  r.ru_nswap);
4937  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4938  r.ru_nsignals - Save_r.ru_nsignals,
4939  r.ru_nsignals,
4940  r.ru_msgrcv - Save_r.ru_msgrcv,
4941  r.ru_msgsnd - Save_r.ru_msgsnd,
4942  r.ru_msgrcv, r.ru_msgsnd);
4944  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4945  r.ru_nvcsw - Save_r.ru_nvcsw,
4946  r.ru_nivcsw - Save_r.ru_nivcsw,
4947  r.ru_nvcsw, r.ru_nivcsw);
4948 #endif /* !WIN32 */
4949 
4950  /* remove trailing newline */
4951  if (str.data[str.len - 1] == '\n')
4952  str.data[--str.len] = '\0';
4953 
4954  ereport(LOG,
4955  (errmsg_internal("%s", title),
4956  errdetail_internal("%s", str.data)));
4957 
4958  pfree(str.data);
4959 }
#define __darwin__
Definition: darwin.h:3
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1066
static char * user
Definition: pg_regress.c:93
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: resource.h:14
struct timeval ru_stime
Definition: resource.h:15

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_fixedparams(), pg_analyze_and_rewrite_varparams(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2951 of file postgres.c.

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

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

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

Variable Documentation

◆ client_connection_check_interval

PGDLLIMPORT int client_connection_check_interval
extern

Definition at line 99 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 90 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 93 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ whereToSendOutput