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

Go to the source code of this file.

Macros

#define STACK_DEPTH_SLOP   (512 * 1024L)
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE, LOGSTMT_DDL, LOGSTMT_MOD, LOGSTMT_ALL }
 

Functions

Listpg_parse_query (const char *query_string)
 
Listpg_rewrite_query (Query *query)
 
Listpg_analyze_and_rewrite (RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
PlannedStmtpg_plan_query (Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
bool check_max_stack_depth (int *newval, void **extra, GucSource source)
 
void assign_max_stack_depth (int newval, void *extra)
 
void die (SIGNAL_ARGS)
 
void quickdie (SIGNAL_ARGS) pg_attribute_noreturn()
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS) pg_attribute_noreturn()
 
void RecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresSingleUserMain (int argc, char *argv[], const char *username) pg_attribute_noreturn()
 
void PostgresMain (const char *dbname, const char *username) pg_attribute_noreturn()
 
long get_stack_depth_rlimit (void)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 
int check_log_duration (char *msec_str, bool was_logged)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 

Variables

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

Macro Definition Documentation

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 26 of file tcopprot.h.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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:36

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3549 of file postgres.c.

References max_stack_depth_bytes.

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

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2324 of file postgres.c.

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

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

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

◆ check_max_stack_depth()

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

Definition at line 3532 of file postgres.c.

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

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

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2915 of file postgres.c.

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

Referenced by PostgresMain().

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

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2970 of file postgres.c.

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

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

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

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4763 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3635 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

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

◆ pg_analyze_and_rewrite()

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

Definition at line 642 of file postgres.c.

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

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

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

◆ pg_analyze_and_rewrite_params()

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

Definition at line 679 of file postgres.c.

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

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

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

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 594 of file postgres.c.

References copyObject, elog, equal(), log_parser_stats, new_list(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), and WARNING.

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

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

◆ pg_plan_queries()

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

Definition at line 915 of file postgres.c.

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

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

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

◆ pg_plan_query()

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

Definition at line 829 of file postgres.c.

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

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

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

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 737 of file postgres.c.

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

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

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

◆ PostgresMain()

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

Definition at line 4015 of file postgres.c.

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

Referenced by BackendRun(), and PostgresSingleUserMain().

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

◆ PostgresSingleUserMain()

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

Definition at line 3928 of file postgres.c.

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

3930 {
3931  const char *dbname = NULL;
3932 
3934 
3935  /* Initialize startup process environment. */
3936  InitStandaloneProcess(argv[0]);
3937 
3938  /*
3939  * Set default values for command-line options.
3940  */
3942 
3943  /*
3944  * Parse command-line options.
3945  */
3946  process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3947 
3948  /* Must have gotten a database name, or have a default (the username) */
3949  if (dbname == NULL)
3950  {
3951  dbname = username;
3952  if (dbname == NULL)
3953  ereport(FATAL,
3954  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3955  errmsg("%s: no database nor user name specified",
3956  progname)));
3957  }
3958 
3959  /* Acquire configuration parameters */
3961  proc_exit(1);
3962 
3963  /*
3964  * Validate we have been given a reasonable-looking DataDir and change
3965  * into it.
3966  */
3967  checkDataDir();
3968  ChangeToDataDir();
3969 
3970  /*
3971  * Create lockfile for data directory.
3972  */
3973  CreateDataDirLockFile(false);
3974 
3975  /* read control file (error checking and contains config ) */
3976  LocalProcessControlFile(false);
3977 
3978  /* Initialize MaxBackends */
3980 
3982 
3983  /*
3984  * Remember stand-alone backend startup time,roughly at the same point
3985  * during startup that postmaster does so.
3986  */
3988 
3989  /*
3990  * Create a per-backend PGPROC struct in shared memory. We must do this
3991  * before we can use LWLocks.
3992  */
3993  InitProcess();
3994 
3995  /*
3996  * Now that sufficient infrastructure has been initialized, PostgresMain()
3997  * can do the rest.
3998  */
3999  PostgresMain(dbname, username);
4000 }
const char * progname
Definition: main.c:46
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:698
void checkDataDir(void)
Definition: miscinit.c:321
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1292
#define FATAL
Definition: elog.h:49
void InitProcess(void)
Definition: proc.c:303
bool IsUnderPostmaster
Definition: globals.c:112
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4015
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5078
void ChangeToDataDir(void)
Definition: miscinit.c:435
const char * username
Definition: pgbench.c:282
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5849
TimestampTz PgStartTime
Definition: timestamp.c:52
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void InitializeMaxBackends(void)
Definition: postinit.c:489
char * dbname
Definition: streamutil.c:51
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:176
static const char * userDoption
Definition: postgres.c:172
int errmsg(const char *fmt,...)
Definition: elog.c:909
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3675
void InitializeGUCOptions(void)
Definition: guc.c:5626

◆ process_postgres_switches()

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

Definition at line 3675 of file postgres.c.

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

Referenced by PostgresSingleUserMain(), and process_startup_options().

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

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 492 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

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

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 538 of file postgres.c.

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

Referenced by secure_write().

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

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2818 of file postgres.c.

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

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

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2988 of file postgres.c.

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, PGPROC::recoveryConflictPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

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

◆ ResetUsage()

void ResetUsage ( void  )

Definition at line 4799 of file postgres.c.

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

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

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

◆ set_debug_options()

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

Definition at line 3564 of file postgres.c.

References PGC_POSTMASTER, SetConfigOption(), and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

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

◆ set_plan_disabling_options()

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

Definition at line 3593 of file postgres.c.

References SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

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

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4806 of file postgres.c.

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

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

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

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2949 of file postgres.c.

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

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

2950 {
2951  int save_errno = errno;
2952 
2953  /*
2954  * Don't joggle the elbow of proc_exit
2955  */
2956  if (!proc_exit_inprogress)
2957  {
2958  InterruptPending = true;
2959  QueryCancelPending = true;
2960  }
2961 
2962  /* If we're still here, waken anything waiting on the process latch */
2963  SetLatch(MyLatch);
2964 
2965  errno = save_errno;
2966 }
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void SetLatch(Latch *latch)
Definition: latch.c:567
bool proc_exit_inprogress
Definition: ipc.c:40
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:57

Variable Documentation

◆ client_connection_check_interval

int client_connection_check_interval

Definition at line 106 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement

Definition at line 97 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

int max_stack_depth

Definition at line 100 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

int PostAuthDelay

◆ whereToSendOutput