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 PostgresMain (int argc, char *argv[], 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 3521 of file postgres.c.

References max_stack_depth_bytes.

3522 {
3523  long newval_bytes = newval * 1024L;
3524 
3525  max_stack_depth_bytes = newval_bytes;
3526 }
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 2306 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().

2307 {
2308  if (log_duration || log_min_duration_sample >= 0 ||
2310  {
2311  long secs;
2312  int usecs;
2313  int msecs;
2314  bool exceeded_duration;
2315  bool exceeded_sample_duration;
2316  bool in_sample = false;
2317 
2320  &secs, &usecs);
2321  msecs = usecs / 1000;
2322 
2323  /*
2324  * This odd-looking test for log_min_duration_* being exceeded is
2325  * designed to avoid integer overflow with very long durations: don't
2326  * compute secs * 1000 until we've verified it will fit in int.
2327  */
2328  exceeded_duration = (log_min_duration_statement == 0 ||
2330  (secs > log_min_duration_statement / 1000 ||
2331  secs * 1000 + msecs >= log_min_duration_statement)));
2332 
2333  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2334  (log_min_duration_sample > 0 &&
2335  (secs > log_min_duration_sample / 1000 ||
2336  secs * 1000 + msecs >= log_min_duration_sample)));
2337 
2338  /*
2339  * Do not log if log_statement_sample_rate = 0. Log a sample if
2340  * log_statement_sample_rate <= 1 and avoid unnecessary random() call
2341  * if log_statement_sample_rate = 1.
2342  */
2343  if (exceeded_sample_duration)
2344  in_sample = log_statement_sample_rate != 0 &&
2345  (log_statement_sample_rate == 1 ||
2347 
2348  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2349  {
2350  snprintf(msec_str, 32, "%ld.%03d",
2351  secs * 1000 + msecs, usecs % 1000);
2352  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2353  return 2;
2354  else
2355  return 1;
2356  }
2357  }
2358 
2359  return 0;
2360 }
int log_min_duration_statement
Definition: guc.c:568
double log_statement_sample_rate
Definition: guc.c:572
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
long random(void)
Definition: random.c:22
int log_min_duration_sample
Definition: guc.c:567
#define MAX_RANDOM_VALUE
bool xact_is_sampled
Definition: xact.c:283
bool log_duration
Definition: guc.c:540
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 3504 of file postgres.c.

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

3505 {
3506  long newval_bytes = *newval * 1024L;
3507  long stack_rlimit = get_stack_depth_rlimit();
3508 
3509  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3510  {
3511  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3512  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3513  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3514  return false;
3515  }
3516  return true;
3517 }
#define GUC_check_errdetail
Definition: guc.h:417
long get_stack_depth_rlimit(void)
Definition: postgres.c:4724
#define newval
#define GUC_check_errhint
Definition: guc.h:421
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:26

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2897 of file postgres.c.

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

Referenced by PostgresMain().

2898 {
2899  int save_errno = errno;
2900 
2901  /* Don't joggle the elbow of proc_exit */
2902  if (!proc_exit_inprogress)
2903  {
2904  InterruptPending = true;
2905  ProcDiePending = true;
2906  }
2907 
2908  /* for the statistics collector */
2910 
2911  /* If we're still here, waken anything waiting on the process latch */
2912  SetLatch(MyLatch);
2913 
2914  /*
2915  * If we're in single user mode, we want to quit immediately - we can't
2916  * rely on latches as they wouldn't work when stdin/stdout is a file.
2917  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2918  * effort just for the benefit of single user mode.
2919  */
2922 
2923  errno = save_errno;
2924 }
SessionEndType pgStatSessionEndCause
Definition: pgstat.c:250
void SetLatch(Latch *latch)
Definition: latch.c:567
void ProcessInterrupts(void)
Definition: postgres.c:3105
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 2952 of file postgres.c.

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

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

2953 {
2954  /* We're not returning, so no need to save errno */
2955  ereport(ERROR,
2956  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2957  errmsg("floating-point exception"),
2958  errdetail("An invalid floating-point operation was signaled. "
2959  "This probably means an out-of-range result or an "
2960  "invalid operation, such as division by zero.")));
2961 }
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 4724 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4725 {
4726 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4727  static long val = 0;
4728 
4729  /* This won't change after process launch, so check just once */
4730  if (val == 0)
4731  {
4732  struct rlimit rlim;
4733 
4734  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4735  val = -1;
4736  else if (rlim.rlim_cur == RLIM_INFINITY)
4737  val = LONG_MAX;
4738  /* rlim_cur is probably of an unsigned type, so check for overflow */
4739  else if (rlim.rlim_cur >= LONG_MAX)
4740  val = LONG_MAX;
4741  else
4742  val = rlim.rlim_cur;
4743  }
4744  return val;
4745 #else /* no getrlimit */
4746 #if defined(WIN32) || defined(__CYGWIN__)
4747  /* On Windows we set the backend stack size in src/backend/Makefile */
4748  return WIN32_STACK_RLIMIT;
4749 #else /* not windows ... give up */
4750  return -1;
4751 #endif
4752 #endif
4753 }
long val
Definition: informix.c:664

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3607 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3608 {
3609  switch (arg[0])
3610  {
3611  case 'p':
3612  if (optarg[1] == 'a') /* "parser" */
3613  return "log_parser_stats";
3614  else if (optarg[1] == 'l') /* "planner" */
3615  return "log_planner_stats";
3616  break;
3617 
3618  case 'e': /* "executor" */
3619  return "log_executor_stats";
3620  break;
3621  }
3622 
3623  return NULL;
3624 }
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 624 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().

627 {
628  Query *query;
629  List *querytree_list;
630 
631  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
632 
633  /*
634  * (1) Perform parse analysis.
635  */
636  if (log_parser_stats)
637  ResetUsage();
638 
639  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
640  queryEnv);
641 
642  if (log_parser_stats)
643  ShowUsage("PARSE ANALYSIS STATISTICS");
644 
645  /*
646  * (2) Rewrite the queries, as necessary
647  */
648  querytree_list = pg_rewrite_query(query);
649 
650  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
651 
652  return querytree_list;
653 }
bool log_parser_stats
Definition: guc.c:546
void ShowUsage(const char *title)
Definition: postgres.c:4767
void ResetUsage(void)
Definition: postgres.c:4760
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:108
List * pg_rewrite_query(Query *query)
Definition: postgres.c:719
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 661 of file postgres.c.

References Assert, compute_query_id, free_parsestate(), 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().

666 {
667  ParseState *pstate;
668  Query *query;
669  List *querytree_list;
670  JumbleState *jstate = NULL;
671 
672  Assert(query_string != NULL); /* required as of 8.4 */
673 
674  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
675 
676  /*
677  * (1) Perform parse analysis.
678  */
679  if (log_parser_stats)
680  ResetUsage();
681 
682  pstate = make_parsestate(NULL);
683  pstate->p_sourcetext = query_string;
684  pstate->p_queryEnv = queryEnv;
685  (*parserSetup) (pstate, parserSetupArg);
686 
687  query = transformTopLevelStmt(pstate, parsetree);
688 
689  if (compute_query_id)
690  jstate = JumbleQuery(query, query_string);
691 
693  (*post_parse_analyze_hook) (pstate, query, jstate);
694 
695  free_parsestate(pstate);
696 
697  pgstat_report_query_id(query->queryId, false);
698 
699  if (log_parser_stats)
700  ShowUsage("PARSE ANALYSIS STATISTICS");
701 
702  /*
703  * (2) Rewrite the queries, as necessary
704  */
705  querytree_list = pg_rewrite_query(query);
706 
707  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
708 
709  return querytree_list;
710 }
bool log_parser_stats
Definition: guc.c:546
QueryEnvironment * p_queryEnv
Definition: parse_node.h:205
void ShowUsage(const char *title)
Definition: postgres.c:4767
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4760
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
bool compute_query_id
Definition: guc.c:539
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:211
List * pg_rewrite_query(Query *query)
Definition: postgres.c:719
JumbleState * JumbleQuery(Query *query, const char *querytext)
Definition: queryjumble.c:95
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:56

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 576 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().

577 {
578  List *raw_parsetree_list;
579 
580  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
581 
582  if (log_parser_stats)
583  ResetUsage();
584 
585  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
586 
587  if (log_parser_stats)
588  ShowUsage("PARSER STATISTICS");
589 
590 #ifdef COPY_PARSE_PLAN_TREES
591  /* Optional debugging check: pass raw parsetrees through copyObject() */
592  {
593  List *new_list = copyObject(raw_parsetree_list);
594 
595  /* This checks both copyObject() and the equal() routines... */
596  if (!equal(new_list, raw_parsetree_list))
597  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
598  else
599  raw_parsetree_list = new_list;
600  }
601 #endif
602 
603  /*
604  * Currently, outfuncs/readfuncs support is missing for many raw parse
605  * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
606  * here.
607  */
608 
609  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
610 
611  return raw_parsetree_list;
612 }
bool log_parser_stats
Definition: guc.c:546
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3105
void ShowUsage(const char *title)
Definition: postgres.c:4767
void ResetUsage(void)
Definition: postgres.c:4760
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:232
#define copyObject(obj)
Definition: nodes.h:655
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:88

◆ pg_plan_queries()

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

Definition at line 897 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().

899 {
900  List *stmt_list = NIL;
901  ListCell *query_list;
902 
903  foreach(query_list, querytrees)
904  {
905  Query *query = lfirst_node(Query, query_list);
906  PlannedStmt *stmt;
907 
908  if (query->commandType == CMD_UTILITY)
909  {
910  /* Utility commands require no planning. */
911  stmt = makeNode(PlannedStmt);
912  stmt->commandType = CMD_UTILITY;
913  stmt->canSetTag = query->canSetTag;
914  stmt->utilityStmt = query->utilityStmt;
915  stmt->stmt_location = query->stmt_location;
916  stmt->stmt_len = query->stmt_len;
917  stmt->queryId = query->queryId;
918  }
919  else
920  {
921  stmt = pg_plan_query(query, query_string, cursorOptions,
922  boundParams);
923  }
924 
925  stmt_list = lappend(stmt_list, stmt);
926  }
927 
928  return stmt_list;
929 }
#define NIL
Definition: pg_list.h:65
int stmt_location
Definition: parsenodes.h:192
Node * utilityStmt
Definition: parsenodes.h:128
int stmt_len
Definition: plannodes.h:90
#define lfirst_node(type, lc)
Definition: pg_list.h:172
int stmt_location
Definition: plannodes.h:89
Node * utilityStmt
Definition: plannodes.h:86
List * lappend(List *list, void *datum)
Definition: list.c:336
uint64 queryId
Definition: parsenodes.h:124
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:120
#define makeNode(_type_)
Definition: nodes.h:587
bool canSetTag
Definition: parsenodes.h:126
uint64 queryId
Definition: plannodes.h:48
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:811
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 811 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().

813 {
814  PlannedStmt *plan;
815 
816  /* Utility commands have no plans. */
817  if (querytree->commandType == CMD_UTILITY)
818  return NULL;
819 
820  /* Planner must have a snapshot in case it calls user-defined functions. */
822 
823  TRACE_POSTGRESQL_QUERY_PLAN_START();
824 
825  if (log_planner_stats)
826  ResetUsage();
827 
828  /* call the optimizer */
829  plan = planner(querytree, query_string, cursorOptions, boundParams);
830 
831  if (log_planner_stats)
832  ShowUsage("PLANNER STATISTICS");
833 
834 #ifdef COPY_PARSE_PLAN_TREES
835  /* Optional debugging check: pass plan tree through copyObject() */
836  {
837  PlannedStmt *new_plan = copyObject(plan);
838 
839  /*
840  * equal() currently does not have routines to compare Plan nodes, so
841  * don't try to test equality here. Perhaps fix someday?
842  */
843 #ifdef NOT_USED
844  /* This checks both copyObject() and the equal() routines... */
845  if (!equal(new_plan, plan))
846  elog(WARNING, "copyObject() failed to produce an equal plan tree");
847  else
848 #endif
849  plan = new_plan;
850  }
851 #endif
852 
853 #ifdef WRITE_READ_PARSE_PLAN_TREES
854  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
855  {
856  char *str;
857  PlannedStmt *new_plan;
858 
859  str = nodeToString(plan);
860  new_plan = stringToNodeWithLocations(str);
861  pfree(str);
862 
863  /*
864  * equal() currently does not have routines to compare Plan nodes, so
865  * don't try to test equality here. Perhaps fix someday?
866  */
867 #ifdef NOT_USED
868  /* This checks both outfuncs/readfuncs and the equal() routines... */
869  if (!equal(new_plan, plan))
870  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
871  else
872 #endif
873  plan = new_plan;
874  }
875 #endif
876 
877  /*
878  * Print plan if debugging.
879  */
880  if (Debug_print_plan)
881  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
882 
883  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
884 
885  return plan;
886 }
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:3105
void ShowUsage(const char *title)
Definition: postgres.c:4767
#define LOG
Definition: elog.h:26
void ResetUsage(void)
Definition: postgres.c:4760
bool Debug_print_plan
Definition: guc.c:541
void pfree(void *pointer)
Definition: mcxt.c:1169
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
#define WARNING
Definition: elog.h:40
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:263
CmdType commandType
Definition: parsenodes.h:120
#define Assert(condition)
Definition: c.h:804
#define elog(elevel,...)
Definition: elog.h:232
bool Debug_pretty_print
Definition: guc.c:544
char * nodeToString(const void *obj)
Definition: outfuncs.c:4526
#define copyObject(obj)
Definition: nodes.h:655
bool log_planner_stats
Definition: guc.c:547

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 719 of file postgres.c.

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

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

720 {
721  List *querytree_list;
722 
723  if (Debug_print_parse)
724  elog_node_display(LOG, "parse tree", query,
726 
727  if (log_parser_stats)
728  ResetUsage();
729 
730  if (query->commandType == CMD_UTILITY)
731  {
732  /* don't rewrite utilities, just dump 'em into result list */
733  querytree_list = list_make1(query);
734  }
735  else
736  {
737  /* rewrite regular queries */
738  querytree_list = QueryRewrite(query);
739  }
740 
741  if (log_parser_stats)
742  ShowUsage("REWRITER STATISTICS");
743 
744 #ifdef COPY_PARSE_PLAN_TREES
745  /* Optional debugging check: pass querytree through copyObject() */
746  {
747  List *new_list;
748 
749  new_list = copyObject(querytree_list);
750  /* This checks both copyObject() and the equal() routines... */
751  if (!equal(new_list, querytree_list))
752  elog(WARNING, "copyObject() failed to produce equal parse tree");
753  else
754  querytree_list = new_list;
755  }
756 #endif
757 
758 #ifdef WRITE_READ_PARSE_PLAN_TREES
759  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
760  {
761  List *new_list = NIL;
762  ListCell *lc;
763 
764  /*
765  * We currently lack outfuncs/readfuncs support for most utility
766  * statement types, so only attempt to write/read non-utility queries.
767  */
768  foreach(lc, querytree_list)
769  {
770  Query *query = castNode(Query, lfirst(lc));
771 
772  if (query->commandType != CMD_UTILITY)
773  {
774  char *str = nodeToString(query);
775  Query *new_query = stringToNodeWithLocations(str);
776 
777  /*
778  * queryId is not saved in stored rules, but we must preserve
779  * it here to avoid breaking pg_stat_statements.
780  */
781  new_query->queryId = query->queryId;
782 
783  new_list = lappend(new_list, new_query);
784  pfree(str);
785  }
786  else
787  new_list = lappend(new_list, query);
788  }
789 
790  /* This checks both outfuncs/readfuncs and the equal() routines... */
791  if (!equal(new_list, querytree_list))
792  elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
793  else
794  querytree_list = new_list;
795  }
796 #endif
797 
799  elog_node_display(LOG, "rewritten parse tree", querytree_list,
801 
802  return querytree_list;
803 }
#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:546
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3105
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
void ShowUsage(const char *title)
Definition: postgres.c:4767
#define LOG
Definition: elog.h:26
#define list_make1(x1)
Definition: pg_list.h:206
void ResetUsage(void)
Definition: postgres.c:4760
void pfree(void *pointer)
Definition: mcxt.c:1169
bool Debug_print_parse
Definition: guc.c:542
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 lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:232
bool Debug_pretty_print
Definition: guc.c:544
char * nodeToString(const void *obj)
Definition: outfuncs.c:4526
bool Debug_print_rewritten
Definition: guc.c:543
#define copyObject(obj)
Definition: nodes.h:655
Definition: pg_list.h:50
static List * new_list(NodeTag type, int min_size)
Definition: list.c:88

◆ PostgresMain()

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

Definition at line 3902 of file postgres.c.

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

Referenced by BackendRun(), and main().

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

◆ process_postgres_switches()

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

Definition at line 3647 of file postgres.c.

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

Referenced by PostgresMain(), and process_startup_options().

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

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 474 of file postgres.c.

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

Referenced by interactive_getc(), and secure_read().

475 {
476  int save_errno = errno;
477 
478  if (DoingCommandRead)
479  {
480  /* Check for general interrupts that arrived before/while reading */
482 
483  /* Process sinval catchup interrupts, if any */
486 
487  /* Process notify interrupts, if any */
490  }
491  else if (ProcDiePending)
492  {
493  /*
494  * We're dying. If there is no data available to read, then it's safe
495  * (and sane) to handle that now. If we haven't tried to read yet,
496  * make sure the process latch is set, so that if there is no data
497  * then we'll come back here and die. If we're done reading, also
498  * make sure the process latch is set, as we might've undesirably
499  * cleared it while reading.
500  */
501  if (blocked)
503  else
504  SetLatch(MyLatch);
505  }
506 
507  errno = save_errno;
508 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
void SetLatch(Latch *latch)
Definition: latch.c:567
void ProcessNotifyInterrupt(void)
Definition: async.c:1915
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
static bool DoingCommandRead
Definition: postgres.c:155
struct Latch * MyLatch
Definition: globals.c:57
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:421
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 520 of file postgres.c.

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

Referenced by secure_write().

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

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2800 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().

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

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2970 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().

2971 {
2972  int save_errno = errno;
2973 
2974  /*
2975  * Don't joggle the elbow of proc_exit
2976  */
2977  if (!proc_exit_inprogress)
2978  {
2979  RecoveryConflictReason = reason;
2980  switch (reason)
2981  {
2983 
2984  /*
2985  * If we aren't waiting for a lock we can never deadlock.
2986  */
2987  if (!IsWaitingForLock())
2988  return;
2989 
2990  /* Intentional fall through to check wait for pin */
2991  /* FALLTHROUGH */
2992 
2994 
2995  /*
2996  * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
2997  * aren't blocking the Startup process there is nothing more
2998  * to do.
2999  *
3000  * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is
3001  * requested, if we're waiting for locks and the startup
3002  * process is not waiting for buffer pin (i.e., also waiting
3003  * for locks), we set the flag so that ProcSleep() will check
3004  * for deadlocks.
3005  */
3007  {
3011  return;
3012  }
3013 
3015 
3016  /* Intentional fall through to error handling */
3017  /* FALLTHROUGH */
3018 
3022 
3023  /*
3024  * If we aren't in a transaction any longer then ignore.
3025  */
3027  return;
3028 
3029  /*
3030  * If we can abort just the current subtransaction then we are
3031  * OK to throw an ERROR to resolve the conflict. Otherwise
3032  * drop through to the FATAL case.
3033  *
3034  * XXX other times that we can throw just an ERROR *may* be
3035  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
3036  * parent transactions
3037  *
3038  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
3039  * by parent transactions and the transaction is not
3040  * transaction-snapshot mode
3041  *
3042  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3043  * cursors open in parent transactions
3044  */
3045  if (!IsSubTransaction())
3046  {
3047  /*
3048  * If we already aborted then we no longer need to cancel.
3049  * We do this here since we do not wish to ignore aborted
3050  * subtransactions, which must cause FATAL, currently.
3051  */
3053  return;
3054 
3055  RecoveryConflictPending = true;
3056  QueryCancelPending = true;
3057  InterruptPending = true;
3058  break;
3059  }
3060 
3061  /* Intentional fall through to session cancel */
3062  /* FALLTHROUGH */
3063 
3065  RecoveryConflictPending = true;
3066  ProcDiePending = true;
3067  InterruptPending = true;
3068  break;
3069 
3070  default:
3071  elog(FATAL, "unrecognized conflict mode: %d",
3072  (int) reason);
3073  }
3074 
3076 
3077  /*
3078  * All conflicts apart from database cause dynamic errors where the
3079  * command or transaction can be retried at a later point with some
3080  * potential for success. No need to reset this, since non-retryable
3081  * conflict errors are currently FATAL.
3082  */
3083  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
3084  RecoveryConflictRetryable = false;
3085  }
3086 
3087  /*
3088  * Set the process latch. This function essentially emulates signal
3089  * handlers like die() and StatementCancelHandler() and it seems prudent
3090  * to behave similarly as they do.
3091  */
3092  SetLatch(MyLatch);
3093 
3094  errno = save_errno;
3095 }
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:4701
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:4231
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
bool IsSubTransaction(void)
Definition: xact.c:4756
#define elog(elevel,...)
Definition: elog.h:232
struct Latch * MyLatch
Definition: globals.c:57
void CheckDeadLockAlert(void)
Definition: proc.c:1870

◆ ResetUsage()

void ResetUsage ( void  )

Definition at line 4760 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().

4761 {
4763  gettimeofday(&Save_t, NULL);
4764 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
static struct rusage Save_r
Definition: postgres.c:4756
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4757
#define RUSAGE_SELF
Definition: rusagestub.h:23

◆ set_debug_options()

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

Definition at line 3536 of file postgres.c.

References PGC_POSTMASTER, SetConfigOption(), and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

3537 {
3538  if (debug_flag > 0)
3539  {
3540  char debugstr[64];
3541 
3542  sprintf(debugstr, "debug%d", debug_flag);
3543  SetConfigOption("log_min_messages", debugstr, context, source);
3544  }
3545  else
3546  SetConfigOption("log_min_messages", "notice", context, source);
3547 
3548  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3549  {
3550  SetConfigOption("log_connections", "true", context, source);
3551  SetConfigOption("log_disconnections", "true", context, source);
3552  }
3553  if (debug_flag >= 2)
3554  SetConfigOption("log_statement", "all", context, source);
3555  if (debug_flag >= 3)
3556  SetConfigOption("debug_print_parse", "true", context, source);
3557  if (debug_flag >= 4)
3558  SetConfigOption("debug_print_plan", "true", context, source);
3559  if (debug_flag >= 5)
3560  SetConfigOption("debug_print_rewritten", "true", context, source);
3561 }
#define sprintf
Definition: port.h:218
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8103
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 3565 of file postgres.c.

References SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3566 {
3567  const char *tmp = NULL;
3568 
3569  switch (arg[0])
3570  {
3571  case 's': /* seqscan */
3572  tmp = "enable_seqscan";
3573  break;
3574  case 'i': /* indexscan */
3575  tmp = "enable_indexscan";
3576  break;
3577  case 'o': /* indexonlyscan */
3578  tmp = "enable_indexonlyscan";
3579  break;
3580  case 'b': /* bitmapscan */
3581  tmp = "enable_bitmapscan";
3582  break;
3583  case 't': /* tidscan */
3584  tmp = "enable_tidscan";
3585  break;
3586  case 'n': /* nestloop */
3587  tmp = "enable_nestloop";
3588  break;
3589  case 'm': /* mergejoin */
3590  tmp = "enable_mergejoin";
3591  break;
3592  case 'h': /* hashjoin */
3593  tmp = "enable_hashjoin";
3594  break;
3595  }
3596  if (tmp)
3597  {
3598  SetConfigOption(tmp, "false", context, source);
3599  return true;
3600  }
3601  else
3602  return false;
3603 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8103
static rewind_source * source
Definition: pg_rewind.c:79
void * arg

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4767 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().

4768 {
4770  struct timeval user,
4771  sys;
4772  struct timeval elapse_t;
4773  struct rusage r;
4774 
4775  getrusage(RUSAGE_SELF, &r);
4776  gettimeofday(&elapse_t, NULL);
4777  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4778  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4779  if (elapse_t.tv_usec < Save_t.tv_usec)
4780  {
4781  elapse_t.tv_sec--;
4782  elapse_t.tv_usec += 1000000;
4783  }
4784  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4785  {
4786  r.ru_utime.tv_sec--;
4787  r.ru_utime.tv_usec += 1000000;
4788  }
4789  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4790  {
4791  r.ru_stime.tv_sec--;
4792  r.ru_stime.tv_usec += 1000000;
4793  }
4794 
4795  /*
4796  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4797  * some work to interpret them, and most platforms don't fill them in.
4798  */
4799  initStringInfo(&str);
4800 
4801  appendStringInfoString(&str, "! system usage stats:\n");
4802  appendStringInfo(&str,
4803  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4804  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4805  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4806  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4807  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4808  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4809  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4810  appendStringInfo(&str,
4811  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4812  (long) user.tv_sec,
4813  (long) user.tv_usec,
4814  (long) sys.tv_sec,
4815  (long) sys.tv_usec);
4816 #if defined(HAVE_GETRUSAGE)
4817  appendStringInfo(&str,
4818  "!\t%ld kB max resident size\n",
4819 #if defined(__darwin__)
4820  /* in bytes on macOS */
4821  r.ru_maxrss / 1024
4822 #else
4823  /* in kilobytes on most other platforms */
4824  r.ru_maxrss
4825 #endif
4826  );
4827  appendStringInfo(&str,
4828  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4829  r.ru_inblock - Save_r.ru_inblock,
4830  /* they only drink coffee at dec */
4831  r.ru_oublock - Save_r.ru_oublock,
4832  r.ru_inblock, r.ru_oublock);
4833  appendStringInfo(&str,
4834  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4835  r.ru_majflt - Save_r.ru_majflt,
4836  r.ru_minflt - Save_r.ru_minflt,
4837  r.ru_majflt, r.ru_minflt,
4838  r.ru_nswap - Save_r.ru_nswap,
4839  r.ru_nswap);
4840  appendStringInfo(&str,
4841  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4842  r.ru_nsignals - Save_r.ru_nsignals,
4843  r.ru_nsignals,
4844  r.ru_msgrcv - Save_r.ru_msgrcv,
4845  r.ru_msgsnd - Save_r.ru_msgsnd,
4846  r.ru_msgrcv, r.ru_msgsnd);
4847  appendStringInfo(&str,
4848  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4849  r.ru_nvcsw - Save_r.ru_nvcsw,
4850  r.ru_nivcsw - Save_r.ru_nivcsw,
4851  r.ru_nvcsw, r.ru_nivcsw);
4852 #endif /* HAVE_GETRUSAGE */
4853 
4854  /* remove trailing newline */
4855  if (str.data[str.len - 1] == '\n')
4856  str.data[--str.len] = '\0';
4857 
4858  ereport(LOG,
4859  (errmsg_internal("%s", title),
4860  errdetail_internal("%s", str.data)));
4861 
4862  pfree(str.data);
4863 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
static struct rusage Save_r
Definition: postgres.c:4756
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:4757
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 2931 of file postgres.c.

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

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

2932 {
2933  int save_errno = errno;
2934 
2935  /*
2936  * Don't joggle the elbow of proc_exit
2937  */
2938  if (!proc_exit_inprogress)
2939  {
2940  InterruptPending = true;
2941  QueryCancelPending = true;
2942  }
2943 
2944  /* If we're still here, waken anything waiting on the process latch */
2945  SetLatch(MyLatch);
2946 
2947  errno = save_errno;
2948 }
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