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

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

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3583 of file postgres.c.

3584 {
3585  long newval_bytes = newval * 1024L;
3586 
3587  max_stack_depth_bytes = newval_bytes;
3588 }
#define newval
static long max_stack_depth_bytes
Definition: postgres.c:127

References max_stack_depth_bytes, and newval.

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2338 of file postgres.c.

2339 {
2340  if (log_duration || log_min_duration_sample >= 0 ||
2342  {
2343  long secs;
2344  int usecs;
2345  int msecs;
2346  bool exceeded_duration;
2347  bool exceeded_sample_duration;
2348  bool in_sample = false;
2349 
2352  &secs, &usecs);
2353  msecs = usecs / 1000;
2354 
2355  /*
2356  * This odd-looking test for log_min_duration_* being exceeded is
2357  * designed to avoid integer overflow with very long durations: don't
2358  * compute secs * 1000 until we've verified it will fit in int.
2359  */
2360  exceeded_duration = (log_min_duration_statement == 0 ||
2362  (secs > log_min_duration_statement / 1000 ||
2363  secs * 1000 + msecs >= log_min_duration_statement)));
2364 
2365  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2366  (log_min_duration_sample > 0 &&
2367  (secs > log_min_duration_sample / 1000 ||
2368  secs * 1000 + msecs >= log_min_duration_sample)));
2369 
2370  /*
2371  * Do not log if log_statement_sample_rate = 0. Log a sample if
2372  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2373  * log_statement_sample_rate = 1.
2374  */
2375  if (exceeded_sample_duration)
2376  in_sample = log_statement_sample_rate != 0 &&
2377  (log_statement_sample_rate == 1 ||
2379 
2380  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2381  {
2382  snprintf(msec_str, 32, "%ld.%03d",
2383  secs * 1000 + msecs, usecs % 1000);
2384  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2385  return 2;
2386  else
2387  return 1;
2388  }
2389  }
2390 
2391  return 0;
2392 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1650
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int log_min_duration_statement
Definition: guc.c:639
int log_min_duration_sample
Definition: guc.c:638
double log_statement_sample_rate
Definition: guc.c:643
bool log_duration
Definition: guc.c:611
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:860
bool xact_is_sampled
Definition: xact.c:286

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

3567 {
3568  long newval_bytes = *newval * 1024L;
3569  long stack_rlimit = get_stack_depth_rlimit();
3570 
3571  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3572  {
3573  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3574  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3575  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3576  return false;
3577  }
3578  return true;
3579 }
#define GUC_check_errdetail
Definition: guc.h:431
#define GUC_check_errhint
Definition: guc.h:435
long get_stack_depth_rlimit(void)
Definition: postgres.c:4823
#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 2928 of file postgres.c.

2929 {
2930  int save_errno = errno;
2931 
2932  /* Don't joggle the elbow of proc_exit */
2933  if (!proc_exit_inprogress)
2934  {
2935  InterruptPending = true;
2936  ProcDiePending = true;
2937  }
2938 
2939  /* for the cumulative stats system */
2941 
2942  /* If we're still here, waken anything waiting on the process latch */
2943  SetLatch(MyLatch);
2944 
2945  /*
2946  * If we're in single user mode, we want to quit immediately - we can't
2947  * rely on latches as they wouldn't work when stdin/stdout is a file.
2948  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2949  * effort just for the benefit of single user mode.
2950  */
2953 
2954  errno = save_errno;
2955 }
@ 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:92
static bool DoingCommandRead
Definition: postgres.c:153
void ProcessInterrupts(void)
Definition: postgres.c:3142

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

2984 {
2985  /* We're not returning, so no need to save errno */
2986  ereport(ERROR,
2987  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2988  errmsg("floating-point exception"),
2989  errdetail("An invalid floating-point operation was signaled. "
2990  "This probably means an out-of-range result or an "
2991  "invalid operation, such as division by zero.")));
2992 }
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 4823 of file postgres.c.

4824 {
4825 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4826  static long val = 0;
4827 
4828  /* This won't change after process launch, so check just once */
4829  if (val == 0)
4830  {
4831  struct rlimit rlim;
4832 
4833  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4834  val = -1;
4835  else if (rlim.rlim_cur == RLIM_INFINITY)
4836  val = LONG_MAX;
4837  /* rlim_cur is probably of an unsigned type, so check for overflow */
4838  else if (rlim.rlim_cur >= LONG_MAX)
4839  val = LONG_MAX;
4840  else
4841  val = rlim.rlim_cur;
4842  }
4843  return val;
4844 #else /* no getrlimit */
4845 #if defined(WIN32) || defined(__CYGWIN__)
4846  /* On Windows we set the backend stack size in src/backend/Makefile */
4847  return WIN32_STACK_RLIMIT;
4848 #else /* not windows ... give up */
4849  return -1;
4850 #endif
4851 #endif
4852 }
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 3669 of file postgres.c.

3670 {
3671  switch (arg[0])
3672  {
3673  case 'p':
3674  if (optarg[1] == 'a') /* "parser" */
3675  return "log_parser_stats";
3676  else if (optarg[1] == 'l') /* "planner" */
3677  return "log_planner_stats";
3678  break;
3679 
3680  case 'e': /* "executor" */
3681  return "log_executor_stats";
3682  break;
3683  }
3684 
3685  return NULL;
3686 }
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 640 of file postgres.c.

645 {
646  Query *query;
647  List *querytree_list;
648 
649  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
650 
651  /*
652  * (1) Perform parse analysis.
653  */
654  if (log_parser_stats)
655  ResetUsage();
656 
657  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
658  queryEnv);
659 
660  if (log_parser_stats)
661  ShowUsage("PARSE ANALYSIS STATISTICS");
662 
663  /*
664  * (2) Rewrite the queries, as necessary
665  */
666  querytree_list = pg_rewrite_query(query);
667 
668  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
669 
670  return querytree_list;
671 }
bool log_parser_stats
Definition: guc.c:617
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:4866
List * pg_rewrite_query(Query *query)
Definition: postgres.c:773
void ResetUsage(void)
Definition: postgres.c:4859
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 679 of file postgres.c.

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

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

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

953 {
954  List *stmt_list = NIL;
955  ListCell *query_list;
956 
957  foreach(query_list, querytrees)
958  {
959  Query *query = lfirst_node(Query, query_list);
960  PlannedStmt *stmt;
961 
962  if (query->commandType == CMD_UTILITY)
963  {
964  /* Utility commands require no planning. */
965  stmt = makeNode(PlannedStmt);
966  stmt->commandType = CMD_UTILITY;
967  stmt->canSetTag = query->canSetTag;
968  stmt->utilityStmt = query->utilityStmt;
969  stmt->stmt_location = query->stmt_location;
970  stmt->stmt_len = query->stmt_len;
971  stmt->queryId = query->queryId;
972  }
973  else
974  {
975  stmt = pg_plan_query(query, query_string, cursorOptions,
976  boundParams);
977  }
978 
979  stmt_list = lappend(stmt_list, stmt);
980  }
981 
982  return stmt_list;
983 }
List * lappend(List *list, void *datum)
Definition: list.c:338
@ CMD_UTILITY
Definition: nodes.h:727
#define makeNode(_type_)
Definition: nodes.h:622
#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:865
bool canSetTag
Definition: plannodes.h:55
int stmt_location
Definition: plannodes.h:90
int stmt_len
Definition: plannodes.h:91
CmdType commandType
Definition: plannodes.h:47
Node * utilityStmt
Definition: plannodes.h:87
uint64 queryId
Definition: plannodes.h:49
int stmt_location
Definition: parsenodes.h:198
uint64 queryId
Definition: parsenodes.h:126
int stmt_len
Definition: parsenodes.h:199
bool canSetTag
Definition: parsenodes.h:128
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:130

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

867 {
868  PlannedStmt *plan;
869 
870  /* Utility commands have no plans. */
871  if (querytree->commandType == CMD_UTILITY)
872  return NULL;
873 
874  /* Planner must have a snapshot in case it calls user-defined functions. */
876 
877  TRACE_POSTGRESQL_QUERY_PLAN_START();
878 
879  if (log_planner_stats)
880  ResetUsage();
881 
882  /* call the optimizer */
883  plan = planner(querytree, query_string, cursorOptions, boundParams);
884 
885  if (log_planner_stats)
886  ShowUsage("PLANNER STATISTICS");
887 
888 #ifdef COPY_PARSE_PLAN_TREES
889  /* Optional debugging check: pass plan tree through copyObject() */
890  {
891  PlannedStmt *new_plan = copyObject(plan);
892 
893  /*
894  * equal() currently does not have routines to compare Plan nodes, so
895  * don't try to test equality here. Perhaps fix someday?
896  */
897 #ifdef NOT_USED
898  /* This checks both copyObject() and the equal() routines... */
899  if (!equal(new_plan, plan))
900  elog(WARNING, "copyObject() failed to produce an equal plan tree");
901  else
902 #endif
903  plan = new_plan;
904  }
905 #endif
906 
907 #ifdef WRITE_READ_PARSE_PLAN_TREES
908  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
909  {
910  char *str;
911  PlannedStmt *new_plan;
912 
913  str = nodeToString(plan);
914  new_plan = stringToNodeWithLocations(str);
915  pfree(str);
916 
917  /*
918  * equal() currently does not have routines to compare Plan nodes, so
919  * don't try to test equality here. Perhaps fix someday?
920  */
921 #ifdef NOT_USED
922  /* This checks both outfuncs/readfuncs and the equal() routines... */
923  if (!equal(new_plan, plan))
924  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
925  else
926 #endif
927  plan = new_plan;
928  }
929 #endif
930 
931  /*
932  * Print plan if debugging.
933  */
934  if (Debug_print_plan)
935  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
936 
937  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
938 
939  return plan;
940 }
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:25
bool Debug_print_plan
Definition: guc.c:612
bool Debug_pretty_print
Definition: guc.c:615
bool log_planner_stats
Definition: guc.c:618
Assert(fmt[strlen(fmt) - 1] !='\n')
void pfree(void *pointer)
Definition: mcxt.c:1175
char * nodeToString(const void *obj)
Definition: outfuncs.c:4789
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:269
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:815

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

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

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

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

3963 {
3964  const char *dbname = NULL;
3965 
3967 
3968  /* Initialize startup process environment. */
3969  InitStandaloneProcess(argv[0]);
3970 
3971  /*
3972  * Set default values for command-line options.
3973  */
3975 
3976  /*
3977  * Parse command-line options.
3978  */
3980 
3981  /* Must have gotten a database name, or have a default (the username) */
3982  if (dbname == NULL)
3983  {
3984  dbname = username;
3985  if (dbname == NULL)
3986  ereport(FATAL,
3987  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3988  errmsg("%s: no database nor user name specified",
3989  progname)));
3990  }
3991 
3992  /* Acquire configuration parameters */
3994  proc_exit(1);
3995 
3996  /*
3997  * Validate we have been given a reasonable-looking DataDir and change
3998  * into it.
3999  */
4000  checkDataDir();
4001  ChangeToDataDir();
4002 
4003  /*
4004  * Create lockfile for data directory.
4005  */
4006  CreateDataDirLockFile(false);
4007 
4008  /* read control file (error checking and contains config ) */
4009  LocalProcessControlFile(false);
4010 
4011  /* Initialize MaxBackends */
4013 
4015 
4016  /*
4017  * Remember stand-alone backend startup time,roughly at the same point
4018  * during startup that postmaster does so.
4019  */
4021 
4022  /*
4023  * Create a per-backend PGPROC struct in shared memory. We must do this
4024  * before we can use LWLocks.
4025  */
4026  InitProcess();
4027 
4028  /*
4029  * Now that sufficient infrastructure has been initialized, PostgresMain()
4030  * can do the rest.
4031  */
4033 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:6096
void InitializeGUCOptions(void)
Definition: guc.c:5835
@ PGC_POSTMASTER
Definition: guc.h:71
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:173
const char * progname
Definition: main.c:50
void ChangeToDataDir(void)
Definition: miscinit.c:431
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void checkDataDir(void)
Definition: miscinit.c:318
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1294
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3709
static const char * userDoption
Definition: postgres.c:170
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4048
void InitializeMaxBackends(void)
Definition: postinit.c:551
void InitProcess(void)
Definition: proc.c:301
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4323

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

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

491 {
492  int save_errno = errno;
493 
494  if (DoingCommandRead)
495  {
496  /* Check for general interrupts that arrived before/while reading */
498 
499  /* Process sinval catchup interrupts, if any */
502 
503  /* Process notify interrupts, if any */
506  }
507  else if (ProcDiePending)
508  {
509  /*
510  * We're dying. If there is no data available to read, then it's safe
511  * (and sane) to handle that now. If we haven't tried to read yet,
512  * make sure the process latch is set, so that if there is no data
513  * then we'll come back here and die. If we're done reading, also
514  * make sure the process latch is set, as we might've undesirably
515  * cleared it while reading.
516  */
517  if (blocked)
519  else
520  SetLatch(MyLatch);
521  }
522 
523  errno = save_errno;
524 }
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 536 of file postgres.c.

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

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

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

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

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

4860 {
4862  gettimeofday(&Save_t, NULL);
4863 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
static struct timeval Save_t
Definition: postgres.c:4856
static struct rusage Save_r
Definition: postgres.c:4855
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_fixedparams(), pg_analyze_and_rewrite_varparams(), pg_analyze_and_rewrite_withcb(), 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 3598 of file postgres.c.

3599 {
3600  if (debug_flag > 0)
3601  {
3602  char debugstr[64];
3603 
3604  sprintf(debugstr, "debug%d", debug_flag);
3605  SetConfigOption("log_min_messages", debugstr, context, source);
3606  }
3607  else
3608  SetConfigOption("log_min_messages", "notice", context, source);
3609 
3610  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3611  {
3612  SetConfigOption("log_connections", "true", context, source);
3613  SetConfigOption("log_disconnections", "true", context, source);
3614  }
3615  if (debug_flag >= 2)
3616  SetConfigOption("log_statement", "all", context, source);
3617  if (debug_flag >= 3)
3618  SetConfigOption("debug_print_parse", "true", context, source);
3619  if (debug_flag >= 4)
3620  SetConfigOption("debug_print_plan", "true", context, source);
3621  if (debug_flag >= 5)
3622  SetConfigOption("debug_print_rewritten", "true", context, source);
3623 }
static rewind_source * source
Definition: pg_rewind.c:81
#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 3627 of file postgres.c.

3628 {
3629  const char *tmp = NULL;
3630 
3631  switch (arg[0])
3632  {
3633  case 's': /* seqscan */
3634  tmp = "enable_seqscan";
3635  break;
3636  case 'i': /* indexscan */
3637  tmp = "enable_indexscan";
3638  break;
3639  case 'o': /* indexonlyscan */
3640  tmp = "enable_indexonlyscan";
3641  break;
3642  case 'b': /* bitmapscan */
3643  tmp = "enable_bitmapscan";
3644  break;
3645  case 't': /* tidscan */
3646  tmp = "enable_tidscan";
3647  break;
3648  case 'n': /* nestloop */
3649  tmp = "enable_nestloop";
3650  break;
3651  case 'm': /* mergejoin */
3652  tmp = "enable_mergejoin";
3653  break;
3654  case 'h': /* hashjoin */
3655  tmp = "enable_hashjoin";
3656  break;
3657  }
3658  if (tmp)
3659  {
3660  SetConfigOption(tmp, "false", context, source);
3661  return true;
3662  }
3663  else
3664  return false;
3665 }

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4866 of file postgres.c.

4867 {
4869  struct timeval user,
4870  sys;
4871  struct timeval elapse_t;
4872  struct rusage r;
4873 
4874  getrusage(RUSAGE_SELF, &r);
4875  gettimeofday(&elapse_t, NULL);
4876  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4877  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4878  if (elapse_t.tv_usec < Save_t.tv_usec)
4879  {
4880  elapse_t.tv_sec--;
4881  elapse_t.tv_usec += 1000000;
4882  }
4883  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4884  {
4885  r.ru_utime.tv_sec--;
4886  r.ru_utime.tv_usec += 1000000;
4887  }
4888  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4889  {
4890  r.ru_stime.tv_sec--;
4891  r.ru_stime.tv_usec += 1000000;
4892  }
4893 
4894  /*
4895  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4896  * some work to interpret them, and most platforms don't fill them in.
4897  */
4898  initStringInfo(&str);
4899 
4900  appendStringInfoString(&str, "! system usage stats:\n");
4902  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4903  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4904  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4905  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4906  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4907  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4908  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4910  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4911  (long) user.tv_sec,
4912  (long) user.tv_usec,
4913  (long) sys.tv_sec,
4914  (long) sys.tv_usec);
4915 #if defined(HAVE_GETRUSAGE)
4917  "!\t%ld kB max resident size\n",
4918 #if defined(__darwin__)
4919  /* in bytes on macOS */
4920  r.ru_maxrss / 1024
4921 #else
4922  /* in kilobytes on most other platforms */
4923  r.ru_maxrss
4924 #endif
4925  );
4927  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4928  r.ru_inblock - Save_r.ru_inblock,
4929  /* they only drink coffee at dec */
4930  r.ru_oublock - Save_r.ru_oublock,
4931  r.ru_inblock, r.ru_oublock);
4933  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4934  r.ru_majflt - Save_r.ru_majflt,
4935  r.ru_minflt - Save_r.ru_minflt,
4936  r.ru_majflt, r.ru_minflt,
4937  r.ru_nswap - Save_r.ru_nswap,
4938  r.ru_nswap);
4940  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4941  r.ru_nsignals - Save_r.ru_nsignals,
4942  r.ru_nsignals,
4943  r.ru_msgrcv - Save_r.ru_msgrcv,
4944  r.ru_msgsnd - Save_r.ru_msgsnd,
4945  r.ru_msgrcv, r.ru_msgsnd);
4947  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4948  r.ru_nvcsw - Save_r.ru_nvcsw,
4949  r.ru_nivcsw - Save_r.ru_nivcsw,
4950  r.ru_nvcsw, r.ru_nivcsw);
4951 #endif /* HAVE_GETRUSAGE */
4952 
4953  /* remove trailing newline */
4954  if (str.data[str.len - 1] == '\n')
4955  str.data[--str.len] = '\0';
4956 
4957  ereport(LOG,
4958  (errmsg_internal("%s", title),
4959  errdetail_internal("%s", str.data)));
4960 
4961  pfree(str.data);
4962 }
#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_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 2962 of file postgres.c.

2963 {
2964  int save_errno = errno;
2965 
2966  /*
2967  * Don't joggle the elbow of proc_exit
2968  */
2969  if (!proc_exit_inprogress)
2970  {
2971  InterruptPending = true;
2972  QueryCancelPending = true;
2973  }
2974 
2975  /* If we're still here, waken anything waiting on the process latch */
2976  SetLatch(MyLatch);
2977 
2978  errno = save_errno;
2979 }

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

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 97 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 100 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ whereToSendOutput