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

Go to the source code of this file.

Macros

#define STACK_DEPTH_SLOP   (512 * 1024L)
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE , LOGSTMT_DDL , LOGSTMT_MOD , LOGSTMT_ALL }
 

Functions

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

Variables

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

Macro Definition Documentation

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 26 of file tcopprot.h.

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 36 of file tcopprot.h.

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

Function Documentation

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2345 of file postgres.c.

2346 {
2347  if (log_duration || log_min_duration_sample >= 0 ||
2349  {
2350  long secs;
2351  int usecs;
2352  int msecs;
2353  bool exceeded_duration;
2354  bool exceeded_sample_duration;
2355  bool in_sample = false;
2356 
2359  &secs, &usecs);
2360  msecs = usecs / 1000;
2361 
2362  /*
2363  * This odd-looking test for log_min_duration_* being exceeded is
2364  * designed to avoid integer overflow with very long durations: don't
2365  * compute secs * 1000 until we've verified it will fit in int.
2366  */
2367  exceeded_duration = (log_min_duration_statement == 0 ||
2369  (secs > log_min_duration_statement / 1000 ||
2370  secs * 1000 + msecs >= log_min_duration_statement)));
2371 
2372  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2373  (log_min_duration_sample > 0 &&
2374  (secs > log_min_duration_sample / 1000 ||
2375  secs * 1000 + msecs >= log_min_duration_sample)));
2376 
2377  /*
2378  * Do not log if log_statement_sample_rate = 0. Log a sample if
2379  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2380  * log_statement_sample_rate = 1.
2381  */
2382  if (exceeded_sample_duration)
2383  in_sample = log_statement_sample_rate != 0 &&
2384  (log_statement_sample_rate == 1 ||
2386 
2387  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2388  {
2389  snprintf(msec_str, 32, "%ld.%03d",
2390  secs * 1000 + msecs, usecs % 1000);
2391  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2392  return 2;
2393  else
2394  return 1;
2395  }
2396  }
2397 
2398  return 0;
2399 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1667
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1582
int log_min_duration_statement
Definition: guc_tables.c:496
int log_min_duration_sample
Definition: guc_tables.c:495
double log_statement_sample_rate
Definition: guc_tables.c:500
bool log_duration
Definition: guc_tables.c:468
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:232
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define snprintf
Definition: port.h:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:864
bool xact_is_sampled
Definition: xact.c:290

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

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

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2935 of file postgres.c.

2936 {
2937  int save_errno = errno;
2938 
2939  /* Don't joggle the elbow of proc_exit */
2940  if (!proc_exit_inprogress)
2941  {
2942  InterruptPending = true;
2943  ProcDiePending = true;
2944  }
2945 
2946  /* for the cumulative stats system */
2948 
2949  /* If we're still here, waken anything waiting on the process latch */
2950  SetLatch(MyLatch);
2951 
2952  /*
2953  * If we're in single user mode, we want to quit immediately - we can't
2954  * rely on latches as they wouldn't work when stdin/stdout is a file.
2955  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2956  * effort just for the benefit of single user mode.
2957  */
2960 
2961  errno = save_errno;
2962 }
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:58
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:607
@ DISCONNECT_KILLED
Definition: pgstat.h:82
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:84
static bool DoingCommandRead
Definition: postgres.c:138
void ProcessInterrupts(void)
Definition: postgres.c:3149

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

Referenced by PostgresMain().

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2990 of file postgres.c.

2991 {
2992  /* We're not returning, so no need to save errno */
2993  ereport(ERROR,
2994  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2995  errmsg("floating-point exception"),
2996  errdetail("An invalid floating-point operation was signaled. "
2997  "This probably means an out-of-range result or an "
2998  "invalid operation, such as division by zero.")));
2999 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149

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

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

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4838 of file postgres.c.

4839 {
4840 #if defined(HAVE_GETRLIMIT)
4841  static long val = 0;
4842 
4843  /* This won't change after process launch, so check just once */
4844  if (val == 0)
4845  {
4846  struct rlimit rlim;
4847 
4848  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4849  val = -1;
4850  else if (rlim.rlim_cur == RLIM_INFINITY)
4851  val = LONG_MAX;
4852  /* rlim_cur is probably of an unsigned type, so check for overflow */
4853  else if (rlim.rlim_cur >= LONG_MAX)
4854  val = LONG_MAX;
4855  else
4856  val = rlim.rlim_cur;
4857  }
4858  return val;
4859 #else
4860  /* On Windows we set the backend stack size in src/backend/Makefile */
4861  return WIN32_STACK_RLIMIT;
4862 #endif
4863 }
long val
Definition: informix.c:664

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3663 of file postgres.c.

3664 {
3665  switch (arg[0])
3666  {
3667  case 'p':
3668  if (optarg[1] == 'a') /* "parser" */
3669  return "log_parser_stats";
3670  else if (optarg[1] == 'l') /* "planner" */
3671  return "log_planner_stats";
3672  break;
3673 
3674  case 'e': /* "executor" */
3675  return "log_executor_stats";
3676  break;
3677  }
3678 
3679  return NULL;
3680 }
void * arg
PGDLLIMPORT char * optarg
Definition: getopt.c:52

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ pg_analyze_and_rewrite_fixedparams()

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

Definition at line 637 of file postgres.c.

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

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

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

◆ pg_analyze_and_rewrite_varparams()

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

Definition at line 676 of file postgres.c.

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

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

Referenced by exec_parse_message(), and PrepareQuery().

◆ pg_analyze_and_rewrite_withcb()

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

Definition at line 730 of file postgres.c.

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

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

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

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 577 of file postgres.c.

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

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

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

◆ pg_plan_queries()

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

Definition at line 938 of file postgres.c.

940 {
941  List *stmt_list = NIL;
942  ListCell *query_list;
943 
944  foreach(query_list, querytrees)
945  {
946  Query *query = lfirst_node(Query, query_list);
947  PlannedStmt *stmt;
948 
949  if (query->commandType == CMD_UTILITY)
950  {
951  /* Utility commands require no planning. */
953  stmt->commandType = CMD_UTILITY;
954  stmt->canSetTag = query->canSetTag;
955  stmt->utilityStmt = query->utilityStmt;
956  stmt->stmt_location = query->stmt_location;
957  stmt->stmt_len = query->stmt_len;
958  stmt->queryId = query->queryId;
959  }
960  else
961  {
962  stmt = pg_plan_query(query, query_string, cursorOptions,
963  boundParams);
964  }
965 
966  stmt_list = lappend(stmt_list, stmt);
967  }
968 
969  return stmt_list;
970 }
#define stmt
Definition: indent_codes.h:59
List * lappend(List *list, void *datum)
Definition: list.c:338
@ CMD_UTILITY
Definition: nodes.h:281
#define makeNode(_type_)
Definition: nodes.h:176
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:852
int stmt_location
Definition: parsenodes.h:236
CmdType commandType
Definition: parsenodes.h:128
Node * utilityStmt
Definition: parsenodes.h:143

References CMD_UTILITY, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), stmt, Query::stmt_location, and Query::utilityStmt.

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

◆ pg_plan_query()

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

Definition at line 852 of file postgres.c.

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

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

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

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 770 of file postgres.c.

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

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

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

◆ PostgresMain()

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

Definition at line 4065 of file postgres.c.

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

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

Referenced by BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 3955 of file postgres.c.

3957 {
3958  const char *dbname = NULL;
3959 
3961 
3962  /* Initialize startup process environment. */
3963  InitStandaloneProcess(argv[0]);
3964 
3965  /*
3966  * Set default values for command-line options.
3967  */
3969 
3970  /*
3971  * Parse command-line options.
3972  */
3974 
3975  /* Must have gotten a database name, or have a default (the username) */
3976  if (dbname == NULL)
3977  {
3978  dbname = username;
3979  if (dbname == NULL)
3980  ereport(FATAL,
3981  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3982  errmsg("%s: no database nor user name specified",
3983  progname)));
3984  }
3985 
3986  /* Acquire configuration parameters */
3988  proc_exit(1);
3989 
3990  /*
3991  * Validate we have been given a reasonable-looking DataDir and change
3992  * into it.
3993  */
3994  checkDataDir();
3995  ChangeToDataDir();
3996 
3997  /*
3998  * Create lockfile for data directory.
3999  */
4000  CreateDataDirLockFile(false);
4001 
4002  /* read control file (error checking and contains config ) */
4003  LocalProcessControlFile(false);
4004 
4005  /*
4006  * process any libraries that should be preloaded at postmaster start
4007  */
4009 
4010  /* Initialize MaxBackends */
4012 
4013  /*
4014  * Give preloaded libraries a chance to request additional shared memory.
4015  */
4017 
4018  /*
4019  * Now that loadable modules have had their chance to request additional
4020  * shared memory, determine the value of any runtime-computed GUCs that
4021  * depend on the amount of shared memory required.
4022  */
4024 
4025  /*
4026  * Now that modules have been loaded, we can process any custom resource
4027  * managers specified in the wal_consistency_checking GUC.
4028  */
4030 
4032 
4033  /*
4034  * Remember stand-alone backend startup time,roughly at the same point
4035  * during startup that postmaster does so.
4036  */
4038 
4039  /*
4040  * Create a per-backend PGPROC struct in shared memory. We must do this
4041  * before we can use LWLocks.
4042  */
4043  InitProcess();
4044 
4045  /*
4046  * Now that sufficient infrastructure has been initialized, PostgresMain()
4047  * can do the rest.
4048  */
4050 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1749
void InitializeGUCOptions(void)
Definition: guc.c:1495
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:325
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:174
const char * progname
Definition: main.c:45
void ChangeToDataDir(void)
Definition: miscinit.c:449
void process_shmem_requests(void)
Definition: miscinit.c:1875
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void process_shared_preload_libraries(void)
Definition: miscinit.c:1847
void checkDataDir(void)
Definition: miscinit.c:336
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1459
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3703
static const char * userDoption
Definition: postgres.c:155
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4065
void InitializeMaxBackends(void)
Definition: postinit.c:566
void InitProcess(void)
Definition: proc.c:297
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4400
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4463

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

Referenced by main().

◆ process_postgres_switches()

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

Definition at line 3703 of file postgres.c.

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

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

Referenced by PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 475 of file postgres.c.

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

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 521 of file postgres.c.

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

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

Referenced by secure_write().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2838 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3008 of file postgres.c.

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

References Assert(), CheckDeadLockAlert(), elog(), FATAL, GetStartupBufferPinWaitBufId(), HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), IsWaitingForLock(), MyLatch, MyProc, proc_exit_inprogress, ProcDiePending, PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelPending, RecoveryConflictPending, PGPROC::recoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

◆ ResetUsage()

void ResetUsage ( void  )

◆ set_debug_options()

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

Definition at line 3592 of file postgres.c.

3593 {
3594  if (debug_flag > 0)
3595  {
3596  char debugstr[64];
3597 
3598  sprintf(debugstr, "debug%d", debug_flag);
3599  SetConfigOption("log_min_messages", debugstr, context, source);
3600  }
3601  else
3602  SetConfigOption("log_min_messages", "notice", context, source);
3603 
3604  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3605  {
3606  SetConfigOption("log_connections", "true", context, source);
3607  SetConfigOption("log_disconnections", "true", context, source);
3608  }
3609  if (debug_flag >= 2)
3610  SetConfigOption("log_statement", "all", context, source);
3611  if (debug_flag >= 3)
3612  SetConfigOption("debug_print_parse", "true", context, source);
3613  if (debug_flag >= 4)
3614  SetConfigOption("debug_print_plan", "true", context, source);
3615  if (debug_flag >= 5)
3616  SetConfigOption("debug_print_rewritten", "true", context, source);
3617 }
static rewind_source * source
Definition: pg_rewind.c:87
#define sprintf
Definition: port.h:240

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_plan_disabling_options()

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

Definition at line 3621 of file postgres.c.

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

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4877 of file postgres.c.

4878 {
4880  struct timeval user,
4881  sys;
4882  struct timeval elapse_t;
4883  struct rusage r;
4884 
4885  getrusage(RUSAGE_SELF, &r);
4886  gettimeofday(&elapse_t, NULL);
4887  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4888  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4889  if (elapse_t.tv_usec < Save_t.tv_usec)
4890  {
4891  elapse_t.tv_sec--;
4892  elapse_t.tv_usec += 1000000;
4893  }
4894  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4895  {
4896  r.ru_utime.tv_sec--;
4897  r.ru_utime.tv_usec += 1000000;
4898  }
4899  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4900  {
4901  r.ru_stime.tv_sec--;
4902  r.ru_stime.tv_usec += 1000000;
4903  }
4904 
4905  /*
4906  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4907  * some work to interpret them, and most platforms don't fill them in.
4908  */
4909  initStringInfo(&str);
4910 
4911  appendStringInfoString(&str, "! system usage stats:\n");
4913  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4914  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4915  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4916  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4917  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4918  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4919  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4921  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4922  (long) user.tv_sec,
4923  (long) user.tv_usec,
4924  (long) sys.tv_sec,
4925  (long) sys.tv_usec);
4926 #ifndef WIN32
4927 
4928  /*
4929  * The following rusage fields are not defined by POSIX, but they're
4930  * present on all current Unix-like systems so we use them without any
4931  * special checks. Some of these could be provided in our Windows
4932  * emulation in src/port/win32getrusage.c with more work.
4933  */
4935  "!\t%ld kB max resident size\n",
4936 #if defined(__darwin__)
4937  /* in bytes on macOS */
4938  r.ru_maxrss / 1024
4939 #else
4940  /* in kilobytes on most other platforms */
4941  r.ru_maxrss
4942 #endif
4943  );
4945  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4946  r.ru_inblock - Save_r.ru_inblock,
4947  /* they only drink coffee at dec */
4948  r.ru_oublock - Save_r.ru_oublock,
4949  r.ru_inblock, r.ru_oublock);
4951  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4952  r.ru_majflt - Save_r.ru_majflt,
4953  r.ru_minflt - Save_r.ru_minflt,
4954  r.ru_majflt, r.ru_minflt,
4955  r.ru_nswap - Save_r.ru_nswap,
4956  r.ru_nswap);
4958  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4959  r.ru_nsignals - Save_r.ru_nsignals,
4960  r.ru_nsignals,
4961  r.ru_msgrcv - Save_r.ru_msgrcv,
4962  r.ru_msgsnd - Save_r.ru_msgsnd,
4963  r.ru_msgrcv, r.ru_msgsnd);
4965  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4966  r.ru_nvcsw - Save_r.ru_nvcsw,
4967  r.ru_nivcsw - Save_r.ru_nivcsw,
4968  r.ru_nvcsw, r.ru_nivcsw);
4969 #endif /* !WIN32 */
4970 
4971  /* remove trailing newline */
4972  if (str.data[str.len - 1] == '\n')
4973  str.data[--str.len] = '\0';
4974 
4975  ereport(LOG,
4976  (errmsg_internal("%s", title),
4977  errdetail_internal("%s", str.data)));
4978 
4979  pfree(str.data);
4980 }
#define __darwin__
Definition: darwin.h:3
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
static char * user
Definition: pg_regress.c:93
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
struct timeval ru_utime
Definition: resource.h:14
struct timeval ru_stime
Definition: resource.h:15

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

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

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2969 of file postgres.c.

2970 {
2971  int save_errno = errno;
2972 
2973  /*
2974  * Don't joggle the elbow of proc_exit
2975  */
2976  if (!proc_exit_inprogress)
2977  {
2978  InterruptPending = true;
2979  QueryCancelPending = true;
2980  }
2981 
2982  /* If we're still here, waken anything waiting on the process latch */
2983  SetLatch(MyLatch);
2984 
2985  errno = save_errno;
2986 }

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

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

Variable Documentation

◆ client_connection_check_interval

PGDLLIMPORT int client_connection_check_interval
extern

Definition at line 98 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 89 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 92 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ whereToSendOutput