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 HandleRecoveryConflictInterrupt (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 2381 of file postgres.c.

2382 {
2383  if (log_duration || log_min_duration_sample >= 0 ||
2385  {
2386  long secs;
2387  int usecs;
2388  int msecs;
2389  bool exceeded_duration;
2390  bool exceeded_sample_duration;
2391  bool in_sample = false;
2392 
2395  &secs, &usecs);
2396  msecs = usecs / 1000;
2397 
2398  /*
2399  * This odd-looking test for log_min_duration_* being exceeded is
2400  * designed to avoid integer overflow with very long durations: don't
2401  * compute secs * 1000 until we've verified it will fit in int.
2402  */
2403  exceeded_duration = (log_min_duration_statement == 0 ||
2405  (secs > log_min_duration_statement / 1000 ||
2406  secs * 1000 + msecs >= log_min_duration_statement)));
2407 
2408  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2409  (log_min_duration_sample > 0 &&
2410  (secs > log_min_duration_sample / 1000 ||
2411  secs * 1000 + msecs >= log_min_duration_sample)));
2412 
2413  /*
2414  * Do not log if log_statement_sample_rate = 0. Log a sample if
2415  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2416  * log_statement_sample_rate = 1.
2417  */
2418  if (exceeded_sample_duration)
2419  in_sample = log_statement_sample_rate != 0 &&
2420  (log_statement_sample_rate == 1 ||
2422 
2423  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2424  {
2425  snprintf(msec_str, 32, "%ld.%03d",
2426  secs * 1000 + msecs, usecs % 1000);
2427  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2428  return 2;
2429  else
2430  return 1;
2431  }
2432  }
2433 
2434  return 0;
2435 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1659
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int log_min_duration_statement
Definition: guc_tables.c:521
int log_min_duration_sample
Definition: guc_tables.c:520
double log_statement_sample_rate
Definition: guc_tables.c:525
bool log_duration
Definition: guc_tables.c:493
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 2974 of file postgres.c.

2975 {
2976  int save_errno = errno;
2977 
2978  /* Don't joggle the elbow of proc_exit */
2979  if (!proc_exit_inprogress)
2980  {
2981  InterruptPending = true;
2982  ProcDiePending = true;
2983  }
2984 
2985  /* for the cumulative stats system */
2987 
2988  /* If we're still here, waken anything waiting on the process latch */
2989  SetLatch(MyLatch);
2990 
2991  /*
2992  * If we're in single user mode, we want to quit immediately - we can't
2993  * rely on latches as they wouldn't work when stdin/stdout is a file.
2994  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2995  * effort just for the benefit of single user mode.
2996  */
2999 
3000  errno = save_errno;
3001 }
@ 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:605
@ DISCONNECT_KILLED
Definition: pgstat.h:82
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:88
static bool DoingCommandRead
Definition: postgres.c:142
void ProcessInterrupts(void)
Definition: postgres.c:3254

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

3030 {
3031  /* We're not returning, so no need to save errno */
3032  ereport(ERROR,
3033  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3034  errmsg("floating-point exception"),
3035  errdetail("An invalid floating-point operation was signaled. "
3036  "This probably means an out-of-range result or an "
3037  "invalid operation, such as division by zero.")));
3038 }
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 4933 of file postgres.c.

4934 {
4935 #if defined(HAVE_GETRLIMIT)
4936  static long val = 0;
4937 
4938  /* This won't change after process launch, so check just once */
4939  if (val == 0)
4940  {
4941  struct rlimit rlim;
4942 
4943  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4944  val = -1;
4945  else if (rlim.rlim_cur == RLIM_INFINITY)
4946  val = LONG_MAX;
4947  /* rlim_cur is probably of an unsigned type, so check for overflow */
4948  else if (rlim.rlim_cur >= LONG_MAX)
4949  val = LONG_MAX;
4950  else
4951  val = rlim.rlim_cur;
4952  }
4953  return val;
4954 #else
4955  /* On Windows we set the backend stack size in src/backend/Makefile */
4956  return WIN32_STACK_RLIMIT;
4957 #endif
4958 }
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 3725 of file postgres.c.

3726 {
3727  switch (arg[0])
3728  {
3729  case 'p':
3730  if (optarg[1] == 'a') /* "parser" */
3731  return "log_parser_stats";
3732  else if (optarg[1] == 'l') /* "planner" */
3733  return "log_planner_stats";
3734  break;
3735 
3736  case 'e': /* "executor" */
3737  return "log_executor_stats";
3738  break;
3739  }
3740 
3741  return NULL;
3742 }
void * arg
PGDLLIMPORT char * optarg
Definition: getopt.c:52

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3045 of file postgres.c.

3046 {
3047  RecoveryConflictPendingReasons[reason] = true;
3048  RecoveryConflictPending = true;
3049  InterruptPending = true;
3050  /* latch will be set by procsignal_sigusr1_handler */
3051 }
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:165
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:164

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

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

674 {
675  Query *query;
676  List *querytree_list;
677 
678  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
679 
680  /*
681  * (1) Perform parse analysis.
682  */
683  if (log_parser_stats)
684  ResetUsage();
685 
686  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
687  queryEnv);
688 
689  if (log_parser_stats)
690  ShowUsage("PARSE ANALYSIS STATISTICS");
691 
692  /*
693  * (2) Rewrite the queries, as necessary
694  */
695  querytree_list = pg_rewrite_query(query);
696 
697  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
698 
699  return querytree_list;
700 }
bool log_parser_stats
Definition: guc_tables.c:499
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:4972
List * pg_rewrite_query(Query *query)
Definition: postgres.c:802
void ResetUsage(void)
Definition: postgres.c:4965
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 708 of file postgres.c.

713 {
714  Query *query;
715  List *querytree_list;
716 
717  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
718 
719  /*
720  * (1) Perform parse analysis.
721  */
722  if (log_parser_stats)
723  ResetUsage();
724 
725  query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
726  queryEnv);
727 
728  /*
729  * Check all parameter types got determined.
730  */
731  for (int i = 0; i < *numParams; i++)
732  {
733  Oid ptype = (*paramTypes)[i];
734 
735  if (ptype == InvalidOid || ptype == UNKNOWNOID)
736  ereport(ERROR,
737  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
738  errmsg("could not determine data type of parameter $%d",
739  i + 1)));
740  }
741 
742  if (log_parser_stats)
743  ShowUsage("PARSE ANALYSIS STATISTICS");
744 
745  /*
746  * (2) Rewrite the queries, as necessary
747  */
748  querytree_list = pg_rewrite_query(query);
749 
750  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
751 
752  return querytree_list;
753 }
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 762 of file postgres.c.

767 {
768  Query *query;
769  List *querytree_list;
770 
771  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
772 
773  /*
774  * (1) Perform parse analysis.
775  */
776  if (log_parser_stats)
777  ResetUsage();
778 
779  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
780  queryEnv);
781 
782  if (log_parser_stats)
783  ShowUsage("PARSE ANALYSIS STATISTICS");
784 
785  /*
786  * (2) Rewrite the queries, as necessary
787  */
788  querytree_list = pg_rewrite_query(query);
789 
790  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
791 
792  return querytree_list;
793 }
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 609 of file postgres.c.

610 {
611  List *raw_parsetree_list;
612 
613  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
614 
615  if (log_parser_stats)
616  ResetUsage();
617 
618  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
619 
620  if (log_parser_stats)
621  ShowUsage("PARSER STATISTICS");
622 
623 #ifdef COPY_PARSE_PLAN_TREES
624  /* Optional debugging check: pass raw parsetrees through copyObject() */
625  {
626  List *new_list = copyObject(raw_parsetree_list);
627 
628  /* This checks both copyObject() and the equal() routines... */
629  if (!equal(new_list, raw_parsetree_list))
630  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
631  else
632  raw_parsetree_list = new_list;
633  }
634 #endif
635 
636  /*
637  * Optional debugging check: pass raw parsetrees through
638  * outfuncs/readfuncs
639  */
640 #ifdef WRITE_READ_PARSE_PLAN_TREES
641  {
642  char *str = nodeToString(raw_parsetree_list);
643  List *new_list = stringToNodeWithLocations(str);
644 
645  pfree(str);
646  /* This checks both outfuncs/readfuncs and the equal() routines... */
647  if (!equal(new_list, raw_parsetree_list))
648  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
649  else
650  raw_parsetree_list = new_list;
651  }
652 #endif
653 
654  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
655 
656  return raw_parsetree_list;
657 }
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:1456
#define copyObject(obj)
Definition: nodes.h:244
char * nodeToString(const void *obj)
Definition: outfuncs.c:883
@ 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 970 of file postgres.c.

972 {
973  List *stmt_list = NIL;
974  ListCell *query_list;
975 
976  foreach(query_list, querytrees)
977  {
978  Query *query = lfirst_node(Query, query_list);
979  PlannedStmt *stmt;
980 
981  if (query->commandType == CMD_UTILITY)
982  {
983  /* Utility commands require no planning. */
985  stmt->commandType = CMD_UTILITY;
986  stmt->canSetTag = query->canSetTag;
987  stmt->utilityStmt = query->utilityStmt;
988  stmt->stmt_location = query->stmt_location;
989  stmt->stmt_len = query->stmt_len;
990  stmt->queryId = query->queryId;
991  }
992  else
993  {
994  stmt = pg_plan_query(query, query_string, cursorOptions,
995  boundParams);
996  }
997 
998  stmt_list = lappend(stmt_list, stmt);
999  }
1000 
1001  return stmt_list;
1002 }
#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:884
int stmt_location
Definition: parsenodes.h:235
CmdType commandType
Definition: parsenodes.h:127
Node * utilityStmt
Definition: parsenodes.h:142

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

886 {
887  PlannedStmt *plan;
888 
889  /* Utility commands have no plans. */
890  if (querytree->commandType == CMD_UTILITY)
891  return NULL;
892 
893  /* Planner must have a snapshot in case it calls user-defined functions. */
895 
896  TRACE_POSTGRESQL_QUERY_PLAN_START();
897 
898  if (log_planner_stats)
899  ResetUsage();
900 
901  /* call the optimizer */
902  plan = planner(querytree, query_string, cursorOptions, boundParams);
903 
904  if (log_planner_stats)
905  ShowUsage("PLANNER STATISTICS");
906 
907 #ifdef COPY_PARSE_PLAN_TREES
908  /* Optional debugging check: pass plan tree through copyObject() */
909  {
910  PlannedStmt *new_plan = copyObject(plan);
911 
912  /*
913  * equal() currently does not have routines to compare Plan nodes, so
914  * don't try to test equality here. Perhaps fix someday?
915  */
916 #ifdef NOT_USED
917  /* This checks both copyObject() and the equal() routines... */
918  if (!equal(new_plan, plan))
919  elog(WARNING, "copyObject() failed to produce an equal plan tree");
920  else
921 #endif
922  plan = new_plan;
923  }
924 #endif
925 
926 #ifdef WRITE_READ_PARSE_PLAN_TREES
927  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
928  {
929  char *str;
930  PlannedStmt *new_plan;
931 
932  str = nodeToString(plan);
933  new_plan = stringToNodeWithLocations(str);
934  pfree(str);
935 
936  /*
937  * equal() currently does not have routines to compare Plan nodes, so
938  * don't try to test equality here. Perhaps fix someday?
939  */
940 #ifdef NOT_USED
941  /* This checks both outfuncs/readfuncs and the equal() routines... */
942  if (!equal(new_plan, plan))
943  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
944  else
945 #endif
946  plan = new_plan;
947  }
948 #endif
949 
950  /*
951  * Print plan if debugging.
952  */
953  if (Debug_print_plan)
955 
956  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
957 
958  return plan;
959 }
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:494
bool Debug_pretty_print
Definition: guc_tables.c:497
bool log_planner_stats
Definition: guc_tables.c:500
Assert(fmt[strlen(fmt) - 1] !='\n')
#define plan(x)
Definition: pg_regress.c:154
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:273
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:763

References ActiveSnapshotSet(), Assert(), CMD_UTILITY, copyObject, Debug_pretty_print, Debug_print_plan, elog(), elog_node_display(), equal(), LOG, log_planner_stats, nodeToString(), pfree(), plan, 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 802 of file postgres.c.

803 {
804  List *querytree_list;
805 
806  if (Debug_print_parse)
807  elog_node_display(LOG, "parse tree", query,
809 
810  if (log_parser_stats)
811  ResetUsage();
812 
813  if (query->commandType == CMD_UTILITY)
814  {
815  /* don't rewrite utilities, just dump 'em into result list */
816  querytree_list = list_make1(query);
817  }
818  else
819  {
820  /* rewrite regular queries */
821  querytree_list = QueryRewrite(query);
822  }
823 
824  if (log_parser_stats)
825  ShowUsage("REWRITER STATISTICS");
826 
827 #ifdef COPY_PARSE_PLAN_TREES
828  /* Optional debugging check: pass querytree through copyObject() */
829  {
830  List *new_list;
831 
832  new_list = copyObject(querytree_list);
833  /* This checks both copyObject() and the equal() routines... */
834  if (!equal(new_list, querytree_list))
835  elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
836  else
837  querytree_list = new_list;
838  }
839 #endif
840 
841 #ifdef WRITE_READ_PARSE_PLAN_TREES
842  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
843  {
844  List *new_list = NIL;
845  ListCell *lc;
846 
847  foreach(lc, querytree_list)
848  {
849  Query *curr_query = lfirst_node(Query, lc);
850  char *str = nodeToString(curr_query);
851  Query *new_query = stringToNodeWithLocations(str);
852 
853  /*
854  * queryId is not saved in stored rules, but we must preserve it
855  * here to avoid breaking pg_stat_statements.
856  */
857  new_query->queryId = curr_query->queryId;
858 
859  new_list = lappend(new_list, new_query);
860  pfree(str);
861  }
862 
863  /* This checks both outfuncs/readfuncs and the equal() routines... */
864  if (!equal(new_list, querytree_list))
865  elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
866  else
867  querytree_list = new_list;
868  }
869 #endif
870 
872  elog_node_display(LOG, "rewritten parse tree", querytree_list,
874 
875  return querytree_list;
876 }
bool Debug_print_rewritten
Definition: guc_tables.c:496
bool Debug_print_parse
Definition: guc_tables.c:495
#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 4127 of file postgres.c.

4128 {
4129  sigjmp_buf local_sigjmp_buf;
4130 
4131  /* these must be volatile to ensure state is preserved across longjmp: */
4132  volatile bool send_ready_for_query = true;
4133  volatile bool idle_in_transaction_timeout_enabled = false;
4134  volatile bool idle_session_timeout_enabled = false;
4135 
4136  Assert(dbname != NULL);
4137  Assert(username != NULL);
4138 
4140 
4141  /*
4142  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4143  * has already set up BlockSig and made that the active signal mask.)
4144  *
4145  * Note that postmaster blocked all signals before forking child process,
4146  * so there is no race condition whereby we might receive a signal before
4147  * we have set up the handler.
4148  *
4149  * Also note: it's best not to use any signals that are SIG_IGNored in the
4150  * postmaster. If such a signal arrives before we are able to change the
4151  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4152  * handler in the postmaster to reserve the signal. (Of course, this isn't
4153  * an issue for signals that are locally generated, such as SIGALRM and
4154  * SIGPIPE.)
4155  */
4156  if (am_walsender)
4157  WalSndSignals();
4158  else
4159  {
4161  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4162  pqsignal(SIGTERM, die); /* cancel current query and exit */
4163 
4164  /*
4165  * In a postmaster child backend, replace SignalHandlerForCrashExit
4166  * with quickdie, so we can tell the client we're dying.
4167  *
4168  * In a standalone backend, SIGQUIT can be generated from the keyboard
4169  * easily, while SIGTERM cannot, so we make both signals do die()
4170  * rather than quickdie().
4171  */
4172  if (IsUnderPostmaster)
4173  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4174  else
4175  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4176  InitializeTimeouts(); /* establishes SIGALRM handler */
4177 
4178  /*
4179  * Ignore failure to write to frontend. Note: if frontend closes
4180  * connection, we will notice it and exit cleanly when control next
4181  * returns to outer loop. This seems safer than forcing exit in the
4182  * midst of output during who-knows-what operation...
4183  */
4188 
4189  /*
4190  * Reset some signals that are accepted by postmaster but not by
4191  * backend
4192  */
4193  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4194  * platforms */
4195  }
4196 
4197  /* Early initialization */
4198  BaseInit();
4199 
4200  /* We need to allow SIGINT, etc during the initial transaction */
4201  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4202 
4203  /*
4204  * General initialization.
4205  *
4206  * NOTE: if you are tempted to add code in this vicinity, consider putting
4207  * it inside InitPostgres() instead. In particular, anything that
4208  * involves database access should be there, not here.
4209  */
4210  InitPostgres(dbname, InvalidOid, /* database to connect to */
4211  username, InvalidOid, /* role to connect as */
4212  !am_walsender, /* honor session_preload_libraries? */
4213  false, /* don't ignore datallowconn */
4214  NULL); /* no out_dbname */
4215 
4216  /*
4217  * If the PostmasterContext is still around, recycle the space; we don't
4218  * need it anymore after InitPostgres completes. Note this does not trash
4219  * *MyProcPort, because ConnCreate() allocated that space with malloc()
4220  * ... else we'd need to copy the Port data first. Also, subsidiary data
4221  * such as the username isn't lost either; see ProcessStartupPacket().
4222  */
4223  if (PostmasterContext)
4224  {
4226  PostmasterContext = NULL;
4227  }
4228 
4230 
4231  /*
4232  * Now all GUC states are fully set up. Report them to client if
4233  * appropriate.
4234  */
4236 
4237  /*
4238  * Also set up handler to log session end; we have to wait till now to be
4239  * sure Log_disconnections has its final value.
4240  */
4243 
4245 
4246  /* Perform initialization specific to a WAL sender process. */
4247  if (am_walsender)
4248  InitWalSender();
4249 
4250  /*
4251  * Send this backend's cancellation info to the frontend.
4252  */
4254  {
4256 
4260  pq_endmessage(&buf);
4261  /* Need not flush since ReadyForQuery will do it. */
4262  }
4263 
4264  /* Welcome banner for standalone case */
4266  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4267 
4268  /*
4269  * Create the memory context we will use in the main loop.
4270  *
4271  * MessageContext is reset once per iteration of the main loop, ie, upon
4272  * completion of processing of each command message from the client.
4273  */
4275  "MessageContext",
4277 
4278  /*
4279  * Create memory context and buffer used for RowDescription messages. As
4280  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4281  * frequently executed for ever single statement, we don't want to
4282  * allocate a separate buffer every time.
4283  */
4285  "RowDescriptionContext",
4290 
4291  /*
4292  * POSTGRES main processing loop begins here
4293  *
4294  * If an exception is encountered, processing resumes here so we abort the
4295  * current transaction and start a new one.
4296  *
4297  * You might wonder why this isn't coded as an infinite loop around a
4298  * PG_TRY construct. The reason is that this is the bottom of the
4299  * exception stack, and so with PG_TRY there would be no exception handler
4300  * in force at all during the CATCH part. By leaving the outermost setjmp
4301  * always active, we have at least some chance of recovering from an error
4302  * during error recovery. (If we get into an infinite loop thereby, it
4303  * will soon be stopped by overflow of elog.c's internal state stack.)
4304  *
4305  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4306  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4307  * is essential in case we longjmp'd out of a signal handler on a platform
4308  * where that leaves the signal blocked. It's not redundant with the
4309  * unblock in AbortTransaction() because the latter is only called if we
4310  * were inside a transaction.
4311  */
4312 
4313  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4314  {
4315  /*
4316  * NOTE: if you are tempted to add more code in this if-block,
4317  * consider the high probability that it should be in
4318  * AbortTransaction() instead. The only stuff done directly here
4319  * should be stuff that is guaranteed to apply *only* for outer-level
4320  * error recovery, such as adjusting the FE/BE protocol status.
4321  */
4322 
4323  /* Since not using PG_TRY, must reset error stack by hand */
4324  error_context_stack = NULL;
4325 
4326  /* Prevent interrupts while cleaning up */
4327  HOLD_INTERRUPTS();
4328 
4329  /*
4330  * Forget any pending QueryCancel request, since we're returning to
4331  * the idle loop anyway, and cancel any active timeout requests. (In
4332  * future we might want to allow some timeout requests to survive, but
4333  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4334  * we got here because of a query cancel interrupting the SIGALRM
4335  * interrupt handler.) Note in particular that we must clear the
4336  * statement and lock timeout indicators, to prevent any future plain
4337  * query cancels from being misreported as timeouts in case we're
4338  * forgetting a timeout cancel.
4339  */
4340  disable_all_timeouts(false); /* do first to avoid race condition */
4341  QueryCancelPending = false;
4342  idle_in_transaction_timeout_enabled = false;
4343  idle_session_timeout_enabled = false;
4344 
4345  /* Not reading from the client anymore. */
4346  DoingCommandRead = false;
4347 
4348  /* Make sure libpq is in a good state */
4349  pq_comm_reset();
4350 
4351  /* Report the error to the client and/or server log */
4352  EmitErrorReport();
4353 
4354  /*
4355  * If Valgrind noticed something during the erroneous query, print the
4356  * query string, assuming we have one.
4357  */
4359 
4360  /*
4361  * Make sure debug_query_string gets reset before we possibly clobber
4362  * the storage it points at.
4363  */
4364  debug_query_string = NULL;
4365 
4366  /*
4367  * Abort the current transaction in order to recover.
4368  */
4370 
4371  if (am_walsender)
4373 
4375 
4376  /*
4377  * We can't release replication slots inside AbortTransaction() as we
4378  * need to be able to start and abort transactions while having a slot
4379  * acquired. But we never need to hold them across top level errors,
4380  * so releasing here is fine. There also is a before_shmem_exit()
4381  * callback ensuring correct cleanup on FATAL errors.
4382  */
4383  if (MyReplicationSlot != NULL)
4385 
4386  /* We also want to cleanup temporary slots on error. */
4388 
4390 
4391  /*
4392  * Now return to normal top-level context and clear ErrorContext for
4393  * next time.
4394  */
4396  FlushErrorState();
4397 
4398  /*
4399  * If we were handling an extended-query-protocol message, initiate
4400  * skip till next Sync. This also causes us not to issue
4401  * ReadyForQuery (until we get Sync).
4402  */
4404  ignore_till_sync = true;
4405 
4406  /* We don't have a transaction command open anymore */
4407  xact_started = false;
4408 
4409  /*
4410  * If an error occurred while we were reading a message from the
4411  * client, we have potentially lost track of where the previous
4412  * message ends and the next one begins. Even though we have
4413  * otherwise recovered from the error, we cannot safely read any more
4414  * messages from the client, so there isn't much we can do with the
4415  * connection anymore.
4416  */
4417  if (pq_is_reading_msg())
4418  ereport(FATAL,
4419  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4420  errmsg("terminating connection because protocol synchronization was lost")));
4421 
4422  /* Now we can allow interrupts again */
4424  }
4425 
4426  /* We can now handle ereport(ERROR) */
4427  PG_exception_stack = &local_sigjmp_buf;
4428 
4429  if (!ignore_till_sync)
4430  send_ready_for_query = true; /* initially, or after error */
4431 
4432  /*
4433  * Non-error queries loop here.
4434  */
4435 
4436  for (;;)
4437  {
4438  int firstchar;
4439  StringInfoData input_message;
4440 
4441  /*
4442  * At top of loop, reset extended-query-message flag, so that any
4443  * errors encountered in "idle" state don't provoke skip.
4444  */
4446 
4447  /*
4448  * For valgrind reporting purposes, the "current query" begins here.
4449  */
4450 #ifdef USE_VALGRIND
4451  old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4452 #endif
4453 
4454  /*
4455  * Release storage left over from prior query cycle, and create a new
4456  * query input buffer in the cleared MessageContext.
4457  */
4460 
4461  initStringInfo(&input_message);
4462 
4463  /*
4464  * Also consider releasing our catalog snapshot if any, so that it's
4465  * not preventing advance of global xmin while we wait for the client.
4466  */
4468 
4469  /*
4470  * (1) If we've reached idle state, tell the frontend we're ready for
4471  * a new query.
4472  *
4473  * Note: this includes fflush()'ing the last of the prior output.
4474  *
4475  * This is also a good time to flush out collected statistics to the
4476  * cumulative stats system, and to update the PS stats display. We
4477  * avoid doing those every time through the message loop because it'd
4478  * slow down processing of batched messages, and because we don't want
4479  * to report uncommitted updates (that confuses autovacuum). The
4480  * notification processor wants a call too, if we are not in a
4481  * transaction block.
4482  *
4483  * Also, if an idle timeout is enabled, start the timer for that.
4484  */
4485  if (send_ready_for_query)
4486  {
4488  {
4489  set_ps_display("idle in transaction (aborted)");
4491 
4492  /* Start the idle-in-transaction timer */
4494  {
4495  idle_in_transaction_timeout_enabled = true;
4498  }
4499  }
4501  {
4502  set_ps_display("idle in transaction");
4504 
4505  /* Start the idle-in-transaction timer */
4507  {
4508  idle_in_transaction_timeout_enabled = true;
4511  }
4512  }
4513  else
4514  {
4515  long stats_timeout;
4516 
4517  /*
4518  * Process incoming notifies (including self-notifies), if
4519  * any, and send relevant messages to the client. Doing it
4520  * here helps ensure stable behavior in tests: if any notifies
4521  * were received during the just-finished transaction, they'll
4522  * be seen by the client before ReadyForQuery is.
4523  */
4525  ProcessNotifyInterrupt(false);
4526 
4527  /*
4528  * Check if we need to report stats. If pgstat_report_stat()
4529  * decides it's too soon to flush out pending stats / lock
4530  * contention prevented reporting, it'll tell us when we
4531  * should try to report stats again (so that stats updates
4532  * aren't unduly delayed if the connection goes idle for a
4533  * long time). We only enable the timeout if we don't already
4534  * have a timeout in progress, because we don't disable the
4535  * timeout below. enable_timeout_after() needs to determine
4536  * the current timestamp, which can have a negative
4537  * performance impact. That's OK because pgstat_report_stat()
4538  * won't have us wake up sooner than a prior call.
4539  */
4540  stats_timeout = pgstat_report_stat(false);
4541  if (stats_timeout > 0)
4542  {
4545  stats_timeout);
4546  }
4547  else
4548  {
4549  /* all stats flushed, no need for the timeout */
4552  }
4553 
4554  set_ps_display("idle");
4556 
4557  /* Start the idle-session timer */
4558  if (IdleSessionTimeout > 0)
4559  {
4560  idle_session_timeout_enabled = true;
4563  }
4564  }
4565 
4566  /* Report any recently-changed GUC options */
4568 
4570  send_ready_for_query = false;
4571  }
4572 
4573  /*
4574  * (2) Allow asynchronous signals to be executed immediately if they
4575  * come in while we are waiting for client input. (This must be
4576  * conditional since we don't want, say, reads on behalf of COPY FROM
4577  * STDIN doing the same thing.)
4578  */
4579  DoingCommandRead = true;
4580 
4581  /*
4582  * (3) read a command (loop blocks here)
4583  */
4584  firstchar = ReadCommand(&input_message);
4585 
4586  /*
4587  * (4) turn off the idle-in-transaction and idle-session timeouts if
4588  * active. We do this before step (5) so that any last-moment timeout
4589  * is certain to be detected in step (5).
4590  *
4591  * At most one of these timeouts will be active, so there's no need to
4592  * worry about combining the timeout.c calls into one.
4593  */
4594  if (idle_in_transaction_timeout_enabled)
4595  {
4597  idle_in_transaction_timeout_enabled = false;
4598  }
4599  if (idle_session_timeout_enabled)
4600  {
4602  idle_session_timeout_enabled = false;
4603  }
4604 
4605  /*
4606  * (5) disable async signal conditions again.
4607  *
4608  * Query cancel is supposed to be a no-op when there is no query in
4609  * progress, so if a query cancel arrived while we were idle, just
4610  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4611  * it's called when DoingCommandRead is set, so check for interrupts
4612  * before resetting DoingCommandRead.
4613  */
4615  DoingCommandRead = false;
4616 
4617  /*
4618  * (6) check for any other interesting events that happened while we
4619  * slept.
4620  */
4621  if (ConfigReloadPending)
4622  {
4623  ConfigReloadPending = false;
4625  }
4626 
4627  /*
4628  * (7) process the command. But ignore it if we're skipping till
4629  * Sync.
4630  */
4631  if (ignore_till_sync && firstchar != EOF)
4632  continue;
4633 
4634  switch (firstchar)
4635  {
4636  case PqMsg_Query:
4637  {
4638  const char *query_string;
4639 
4640  /* Set statement_timestamp() */
4642 
4643  query_string = pq_getmsgstring(&input_message);
4644  pq_getmsgend(&input_message);
4645 
4646  if (am_walsender)
4647  {
4648  if (!exec_replication_command(query_string))
4649  exec_simple_query(query_string);
4650  }
4651  else
4652  exec_simple_query(query_string);
4653 
4654  valgrind_report_error_query(query_string);
4655 
4656  send_ready_for_query = true;
4657  }
4658  break;
4659 
4660  case PqMsg_Parse:
4661  {
4662  const char *stmt_name;
4663  const char *query_string;
4664  int numParams;
4665  Oid *paramTypes = NULL;
4666 
4667  forbidden_in_wal_sender(firstchar);
4668 
4669  /* Set statement_timestamp() */
4671 
4672  stmt_name = pq_getmsgstring(&input_message);
4673  query_string = pq_getmsgstring(&input_message);
4674  numParams = pq_getmsgint(&input_message, 2);
4675  if (numParams > 0)
4676  {
4677  paramTypes = palloc_array(Oid, numParams);
4678  for (int i = 0; i < numParams; i++)
4679  paramTypes[i] = pq_getmsgint(&input_message, 4);
4680  }
4681  pq_getmsgend(&input_message);
4682 
4683  exec_parse_message(query_string, stmt_name,
4684  paramTypes, numParams);
4685 
4686  valgrind_report_error_query(query_string);
4687  }
4688  break;
4689 
4690  case PqMsg_Bind:
4691  forbidden_in_wal_sender(firstchar);
4692 
4693  /* Set statement_timestamp() */
4695 
4696  /*
4697  * this message is complex enough that it seems best to put
4698  * the field extraction out-of-line
4699  */
4700  exec_bind_message(&input_message);
4701 
4702  /* exec_bind_message does valgrind_report_error_query */
4703  break;
4704 
4705  case PqMsg_Execute:
4706  {
4707  const char *portal_name;
4708  int max_rows;
4709 
4710  forbidden_in_wal_sender(firstchar);
4711 
4712  /* Set statement_timestamp() */
4714 
4715  portal_name = pq_getmsgstring(&input_message);
4716  max_rows = pq_getmsgint(&input_message, 4);
4717  pq_getmsgend(&input_message);
4718 
4719  exec_execute_message(portal_name, max_rows);
4720 
4721  /* exec_execute_message does valgrind_report_error_query */
4722  }
4723  break;
4724 
4725  case PqMsg_FunctionCall:
4726  forbidden_in_wal_sender(firstchar);
4727 
4728  /* Set statement_timestamp() */
4730 
4731  /* Report query to various monitoring facilities. */
4733  set_ps_display("<FASTPATH>");
4734 
4735  /* start an xact for this function invocation */
4737 
4738  /*
4739  * Note: we may at this point be inside an aborted
4740  * transaction. We can't throw error for that until we've
4741  * finished reading the function-call message, so
4742  * HandleFunctionRequest() must check for it after doing so.
4743  * Be careful not to do anything that assumes we're inside a
4744  * valid transaction here.
4745  */
4746 
4747  /* switch back to message context */
4749 
4750  HandleFunctionRequest(&input_message);
4751 
4752  /* commit the function-invocation transaction */
4754 
4755  valgrind_report_error_query("fastpath function call");
4756 
4757  send_ready_for_query = true;
4758  break;
4759 
4760  case PqMsg_Close:
4761  {
4762  int close_type;
4763  const char *close_target;
4764 
4765  forbidden_in_wal_sender(firstchar);
4766 
4767  close_type = pq_getmsgbyte(&input_message);
4768  close_target = pq_getmsgstring(&input_message);
4769  pq_getmsgend(&input_message);
4770 
4771  switch (close_type)
4772  {
4773  case 'S':
4774  if (close_target[0] != '\0')
4775  DropPreparedStatement(close_target, false);
4776  else
4777  {
4778  /* special-case the unnamed statement */
4780  }
4781  break;
4782  case 'P':
4783  {
4784  Portal portal;
4785 
4786  portal = GetPortalByName(close_target);
4787  if (PortalIsValid(portal))
4788  PortalDrop(portal, false);
4789  }
4790  break;
4791  default:
4792  ereport(ERROR,
4793  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4794  errmsg("invalid CLOSE message subtype %d",
4795  close_type)));
4796  break;
4797  }
4798 
4801 
4802  valgrind_report_error_query("CLOSE message");
4803  }
4804  break;
4805 
4806  case PqMsg_Describe:
4807  {
4808  int describe_type;
4809  const char *describe_target;
4810 
4811  forbidden_in_wal_sender(firstchar);
4812 
4813  /* Set statement_timestamp() (needed for xact) */
4815 
4816  describe_type = pq_getmsgbyte(&input_message);
4817  describe_target = pq_getmsgstring(&input_message);
4818  pq_getmsgend(&input_message);
4819 
4820  switch (describe_type)
4821  {
4822  case 'S':
4823  exec_describe_statement_message(describe_target);
4824  break;
4825  case 'P':
4826  exec_describe_portal_message(describe_target);
4827  break;
4828  default:
4829  ereport(ERROR,
4830  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4831  errmsg("invalid DESCRIBE message subtype %d",
4832  describe_type)));
4833  break;
4834  }
4835 
4836  valgrind_report_error_query("DESCRIBE message");
4837  }
4838  break;
4839 
4840  case PqMsg_Flush:
4841  pq_getmsgend(&input_message);
4843  pq_flush();
4844  break;
4845 
4846  case PqMsg_Sync:
4847  pq_getmsgend(&input_message);
4849  valgrind_report_error_query("SYNC message");
4850  send_ready_for_query = true;
4851  break;
4852 
4853  /*
4854  * 'X' means that the frontend is closing down the socket. EOF
4855  * means unexpected loss of frontend connection. Either way,
4856  * perform normal shutdown.
4857  */
4858  case EOF:
4859 
4860  /* for the cumulative statistics system */
4862 
4863  /* FALLTHROUGH */
4864 
4865  case PqMsg_Terminate:
4866 
4867  /*
4868  * Reset whereToSendOutput to prevent ereport from attempting
4869  * to send any more messages to client.
4870  */
4873 
4874  /*
4875  * NOTE: if you are tempted to add more code here, DON'T!
4876  * Whatever you had in mind to do should be set up as an
4877  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4878  * it will fail to be called during other backend-shutdown
4879  * scenarios.
4880  */
4881  proc_exit(0);
4882 
4883  case PqMsg_CopyData:
4884  case PqMsg_CopyDone:
4885  case PqMsg_CopyFail:
4886 
4887  /*
4888  * Accept but ignore these messages, per protocol spec; we
4889  * probably got here because a COPY failed, and the frontend
4890  * is still sending data.
4891  */
4892  break;
4893 
4894  default:
4895  ereport(FATAL,
4896  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4897  errmsg("invalid frontend message type %d",
4898  firstchar)));
4899  }
4900  } /* end of input-reading loop */
4901 }
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:483
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:403
#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:409
@ InitProcessing
Definition: miscadmin.h:408
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
#define SetProcessingMode(mode)
Definition: miscadmin.h:420
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static char * buf
Definition: pg_test_fsync.c:67
const char * username
Definition: pgbench.c:296
long pgstat_report_stat(bool force)
Definition: pgstat.c:582
@ 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:2599
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2877
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5081
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4911
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2087
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3029
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3008
static bool ignore_till_sync
Definition: postgres.c:149
static void finish_xact_command(void)
Definition: postgres.c:2773
const char * debug_query_string
Definition: postgres.c:85
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1011
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1389
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1624
void die(SIGNAL_ARGS)
Definition: postgres.c:2974
static bool xact_started
Definition: postgres.c:135
static MemoryContext row_description_context
Definition: postgres.c:168
static StringInfoData row_description_buf
Definition: postgres.c:169
static bool doing_extended_query_message
Definition: postgres.c:148
static void start_xact_command(void)
Definition: postgres.c:2745
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2693
bool Log_disconnections
Definition: postgres.c:91
static void drop_unnamed_stmt(void)
Definition: postgres.c:2852
#define valgrind_report_error_query(query)
Definition: postgres.c:222
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:486
void BaseInit(void)
Definition: postinit.c:629
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:718
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1190
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
#define PqMsg_CloseComplete
Definition: protocol.h:40
#define PqMsg_CopyDone
Definition: protocol.h:64
#define PqMsg_CopyData
Definition: protocol.h:65
#define PqMsg_FunctionCall
Definition: protocol.h:23
#define PqMsg_Describe
Definition: protocol.h:21
#define PqMsg_Parse
Definition: protocol.h:25
#define PqMsg_Bind
Definition: protocol.h:19
#define PqMsg_Sync
Definition: protocol.h:27
#define PqMsg_CopyFail
Definition: protocol.h:29
#define PqMsg_Flush
Definition: protocol.h:24
#define PqMsg_BackendKeyData
Definition: protocol.h:48
#define PqMsg_Query
Definition: protocol.h:26
#define PqMsg_Terminate
Definition: protocol.h:28
#define PqMsg_Execute
Definition: protocol.h:22
#define PqMsg_Close
Definition: protocol.h:20
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
void ReplicationSlotCleanup(void)
Definition: slot.c:605
ReplicationSlot * MyReplicationSlot
Definition: slot.c:99
void ReplicationSlotRelease(void)
Definition: slot.c:549
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:424
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:1672
void WalSndSignals(void)
Definition: walsender.c:3258
void InitWalSender(void)
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define SIGPIPE
Definition: win32_port.h:173
#define SIGQUIT
Definition: win32_port.h:169
#define SIGUSR1
Definition: win32_port.h:180
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4834
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:398
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899
void AbortCurrentTransaction(void)
Definition: xact.c:3305

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(), PqMsg_BackendKeyData, PqMsg_Bind, PqMsg_Close, PqMsg_CloseComplete, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Describe, PqMsg_Execute, PqMsg_Flush, PqMsg_FunctionCall, PqMsg_Parse, PqMsg_Query, PqMsg_Sync, PqMsg_Terminate, 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, valgrind_report_error_query, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4017 of file postgres.c.

4019 {
4020  const char *dbname = NULL;
4021 
4023 
4024  /* Initialize startup process environment. */
4025  InitStandaloneProcess(argv[0]);
4026 
4027  /*
4028  * Set default values for command-line options.
4029  */
4031 
4032  /*
4033  * Parse command-line options.
4034  */
4036 
4037  /* Must have gotten a database name, or have a default (the username) */
4038  if (dbname == NULL)
4039  {
4040  dbname = username;
4041  if (dbname == NULL)
4042  ereport(FATAL,
4043  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4044  errmsg("%s: no database nor user name specified",
4045  progname)));
4046  }
4047 
4048  /* Acquire configuration parameters */
4050  proc_exit(1);
4051 
4052  /*
4053  * Validate we have been given a reasonable-looking DataDir and change
4054  * into it.
4055  */
4056  checkDataDir();
4057  ChangeToDataDir();
4058 
4059  /*
4060  * Create lockfile for data directory.
4061  */
4062  CreateDataDirLockFile(false);
4063 
4064  /* read control file (error checking and contains config ) */
4065  LocalProcessControlFile(false);
4066 
4067  /*
4068  * process any libraries that should be preloaded at postmaster start
4069  */
4071 
4072  /* Initialize MaxBackends */
4074 
4075  /*
4076  * Give preloaded libraries a chance to request additional shared memory.
4077  */
4079 
4080  /*
4081  * Now that loadable modules have had their chance to request additional
4082  * shared memory, determine the value of any runtime-computed GUCs that
4083  * depend on the amount of shared memory required.
4084  */
4086 
4087  /*
4088  * Now that modules have been loaded, we can process any custom resource
4089  * managers specified in the wal_consistency_checking GUC.
4090  */
4092 
4094 
4095  /*
4096  * Remember stand-alone backend startup time,roughly at the same point
4097  * during startup that postmaster does so.
4098  */
4100 
4101  /*
4102  * Create a per-backend PGPROC struct in shared memory. We must do this
4103  * before we can use LWLocks.
4104  */
4105  InitProcess();
4106 
4107  /*
4108  * Now that sufficient infrastructure has been initialized, PostgresMain()
4109  * can do the rest.
4110  */
4112 }
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:333
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:175
const char * progname
Definition: main.c:45
void ChangeToDataDir(void)
Definition: miscinit.c:449
void process_shmem_requests(void)
Definition: miscinit.c:1857
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void process_shared_preload_libraries(void)
Definition: miscinit.c:1829
void checkDataDir(void)
Definition: miscinit.c:336
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1441
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3765
static const char * userDoption
Definition: postgres.c:159
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4127
void InitializeMaxBackends(void)
Definition: postinit.c:559
void InitProcess(void)
Definition: proc.c:297
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4426
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4488

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

3767 {
3768  bool secure = (ctx == PGC_POSTMASTER);
3769  int errs = 0;
3770  GucSource gucsource;
3771  int flag;
3772 
3773  if (secure)
3774  {
3775  gucsource = PGC_S_ARGV; /* switches came from command line */
3776 
3777  /* Ignore the initial --single argument, if present */
3778  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3779  {
3780  argv++;
3781  argc--;
3782  }
3783  }
3784  else
3785  {
3786  gucsource = PGC_S_CLIENT; /* switches came from client */
3787  }
3788 
3789 #ifdef HAVE_INT_OPTERR
3790 
3791  /*
3792  * Turn this off because it's either printed to stderr and not the log
3793  * where we'd want it, or argv[0] is now "--single", which would make for
3794  * a weird error message. We print our own error message below.
3795  */
3796  opterr = 0;
3797 #endif
3798 
3799  /*
3800  * Parse command-line options. CAUTION: keep this in sync with
3801  * postmaster/postmaster.c (the option sets should not conflict) and with
3802  * the common help() function in main/main.c.
3803  */
3804  while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3805  {
3806  switch (flag)
3807  {
3808  case 'B':
3809  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3810  break;
3811 
3812  case 'b':
3813  /* Undocumented flag used for binary upgrades */
3814  if (secure)
3815  IsBinaryUpgrade = true;
3816  break;
3817 
3818  case 'C':
3819  /* ignored for consistency with the postmaster */
3820  break;
3821 
3822  case 'c':
3823  case '-':
3824  {
3825  char *name,
3826  *value;
3827 
3829  if (!value)
3830  {
3831  if (flag == '-')
3832  ereport(ERROR,
3833  (errcode(ERRCODE_SYNTAX_ERROR),
3834  errmsg("--%s requires a value",
3835  optarg)));
3836  else
3837  ereport(ERROR,
3838  (errcode(ERRCODE_SYNTAX_ERROR),
3839  errmsg("-c %s requires a value",
3840  optarg)));
3841  }
3842  SetConfigOption(name, value, ctx, gucsource);
3843  pfree(name);
3844  pfree(value);
3845  break;
3846  }
3847 
3848  case 'D':
3849  if (secure)
3850  userDoption = strdup(optarg);
3851  break;
3852 
3853  case 'd':
3854  set_debug_options(atoi(optarg), ctx, gucsource);
3855  break;
3856 
3857  case 'E':
3858  if (secure)
3859  EchoQuery = true;
3860  break;
3861 
3862  case 'e':
3863  SetConfigOption("datestyle", "euro", ctx, gucsource);
3864  break;
3865 
3866  case 'F':
3867  SetConfigOption("fsync", "false", ctx, gucsource);
3868  break;
3869 
3870  case 'f':
3871  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3872  errs++;
3873  break;
3874 
3875  case 'h':
3876  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3877  break;
3878 
3879  case 'i':
3880  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3881  break;
3882 
3883  case 'j':
3884  if (secure)
3885  UseSemiNewlineNewline = true;
3886  break;
3887 
3888  case 'k':
3889  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3890  break;
3891 
3892  case 'l':
3893  SetConfigOption("ssl", "true", ctx, gucsource);
3894  break;
3895 
3896  case 'N':
3897  SetConfigOption("max_connections", optarg, ctx, gucsource);
3898  break;
3899 
3900  case 'n':
3901  /* ignored for consistency with postmaster */
3902  break;
3903 
3904  case 'O':
3905  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3906  break;
3907 
3908  case 'P':
3909  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3910  break;
3911 
3912  case 'p':
3913  SetConfigOption("port", optarg, ctx, gucsource);
3914  break;
3915 
3916  case 'r':
3917  /* send output (stdout and stderr) to the given file */
3918  if (secure)
3920  break;
3921 
3922  case 'S':
3923  SetConfigOption("work_mem", optarg, ctx, gucsource);
3924  break;
3925 
3926  case 's':
3927  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3928  break;
3929 
3930  case 'T':
3931  /* ignored for consistency with the postmaster */
3932  break;
3933 
3934  case 't':
3935  {
3936  const char *tmp = get_stats_option_name(optarg);
3937 
3938  if (tmp)
3939  SetConfigOption(tmp, "true", ctx, gucsource);
3940  else
3941  errs++;
3942  break;
3943  }
3944 
3945  case 'v':
3946 
3947  /*
3948  * -v is no longer used in normal operation, since
3949  * FrontendProtocol is already set before we get here. We keep
3950  * the switch only for possible use in standalone operation,
3951  * in case we ever support using normal FE/BE protocol with a
3952  * standalone backend.
3953  */
3954  if (secure)
3956  break;
3957 
3958  case 'W':
3959  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3960  break;
3961 
3962  default:
3963  errs++;
3964  break;
3965  }
3966 
3967  if (errs)
3968  break;
3969  }
3970 
3971  /*
3972  * Optional database name should be there only if *dbname is NULL.
3973  */
3974  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3975  *dbname = strdup(argv[optind++]);
3976 
3977  if (errs || argc != optind)
3978  {
3979  if (errs)
3980  optind--; /* complain about the previous argument */
3981 
3982  /* spell the error message a bit differently depending on context */
3983  if (IsUnderPostmaster)
3984  ereport(FATAL,
3985  errcode(ERRCODE_SYNTAX_ERROR),
3986  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3987  errhint("Try \"%s --help\" for more information.", progname));
3988  else
3989  ereport(FATAL,
3990  errcode(ERRCODE_SYNTAX_ERROR),
3991  errmsg("%s: invalid command-line argument: %s",
3992  progname, argv[optind]),
3993  errhint("Try \"%s --help\" for more information.", progname));
3994  }
3995 
3996  /*
3997  * Reset getopt(3) library so that it will work correctly in subprocesses
3998  * or when this function is called a second time with another array.
3999  */
4000  optind = 1;
4001 #ifdef HAVE_INT_OPTRESET
4002  optreset = 1; /* some systems need this too */
4003 #endif
4004 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
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 @148 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:3654
static bool UseSemiNewlineNewline
Definition: postgres.c:161
static bool EchoQuery
Definition: postgres.c:160
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3683
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3725
uint32 ProtocolVersion
Definition: pqcomm.h:99
char * flag(int b)
Definition: test-ctype.c:33
const char * name

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

508 {
509  int save_errno = errno;
510 
511  if (DoingCommandRead)
512  {
513  /* Check for general interrupts that arrived before/while reading */
515 
516  /* Process sinval catchup interrupts, if any */
519 
520  /* Process notify interrupts, if any */
523  }
524  else if (ProcDiePending)
525  {
526  /*
527  * We're dying. If there is no data available to read, then it's safe
528  * (and sane) to handle that now. If we haven't tried to read yet,
529  * make sure the process latch is set, so that if there is no data
530  * then we'll come back here and die. If we're done reading, also
531  * make sure the process latch is set, as we might've undesirably
532  * cleared it while reading.
533  */
534  if (blocked)
536  else
537  SetLatch(MyLatch);
538  }
539 
540  errno = save_errno;
541 }
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 553 of file postgres.c.

554 {
555  int save_errno = errno;
556 
557  if (ProcDiePending)
558  {
559  /*
560  * We're dying. If it's not possible to write, then we should handle
561  * that immediately, else a stuck client could indefinitely delay our
562  * response to the signal. If we haven't tried to write yet, make
563  * sure the process latch is set, so that if the write would block
564  * then we'll come back here and die. If we're done writing, also
565  * make sure the process latch is set, as we might've undesirably
566  * cleared it while writing.
567  */
568  if (blocked)
569  {
570  /*
571  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
572  * service ProcDiePending.
573  */
574  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
575  {
576  /*
577  * We don't want to send the client the error message, as a)
578  * that would possibly block again, and b) it would likely
579  * lead to loss of protocol sync because we may have already
580  * sent a partial protocol message.
581  */
584 
586  }
587  }
588  else
589  SetLatch(MyLatch);
590  }
591 
592  errno = save_errno;
593 }
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 2877 of file postgres.c.

2878 {
2879  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2880  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
2881 
2882  /*
2883  * Prevent interrupts while exiting; though we just blocked signals that
2884  * would queue new interrupts, one may have been pending. We don't want a
2885  * quickdie() downgraded to a mere query cancel.
2886  */
2887  HOLD_INTERRUPTS();
2888 
2889  /*
2890  * If we're aborting out of client auth, don't risk trying to send
2891  * anything to the client; we will likely violate the protocol, not to
2892  * mention that we may have interrupted the guts of OpenSSL or some
2893  * authentication library.
2894  */
2897 
2898  /*
2899  * Notify the client before exiting, to give a clue on what happened.
2900  *
2901  * It's dubious to call ereport() from a signal handler. It is certainly
2902  * not async-signal safe. But it seems better to try, than to disconnect
2903  * abruptly and leave the client wondering what happened. It's remotely
2904  * possible that we crash or hang while trying to send the message, but
2905  * receiving a SIGQUIT is a sign that something has already gone badly
2906  * wrong, so there's not much to lose. Assuming the postmaster is still
2907  * running, it will SIGKILL us soon if we get stuck for some reason.
2908  *
2909  * One thing we can do to make this a tad safer is to clear the error
2910  * context stack, so that context callbacks are not called. That's a lot
2911  * less code that could be reached here, and the context info is unlikely
2912  * to be very relevant to a SIGQUIT report anyway.
2913  */
2914  error_context_stack = NULL;
2915 
2916  /*
2917  * When responding to a postmaster-issued signal, we send the message only
2918  * to the client; sending to the server log just creates log spam, plus
2919  * it's more code that we need to hope will work in a signal handler.
2920  *
2921  * Ideally these should be ereport(FATAL), but then we'd not get control
2922  * back to force the correct type of process exit.
2923  */
2924  switch (GetQuitSignalReason())
2925  {
2926  case PMQUIT_NOT_SENT:
2927  /* Hmm, SIGQUIT arrived out of the blue */
2928  ereport(WARNING,
2929  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2930  errmsg("terminating connection because of unexpected SIGQUIT signal")));
2931  break;
2932  case PMQUIT_FOR_CRASH:
2933  /* A crash-and-restart cycle is in progress */
2935  (errcode(ERRCODE_CRASH_SHUTDOWN),
2936  errmsg("terminating connection because of crash of another server process"),
2937  errdetail("The postmaster has commanded this server process to roll back"
2938  " the current transaction and exit, because another"
2939  " server process exited abnormally and possibly corrupted"
2940  " shared memory."),
2941  errhint("In a moment you should be able to reconnect to the"
2942  " database and repeat your command.")));
2943  break;
2944  case PMQUIT_FOR_STOP:
2945  /* Immediate-mode stop */
2947  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2948  errmsg("terminating connection due to immediate shutdown command")));
2949  break;
2950  }
2951 
2952  /*
2953  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2954  * because shared memory may be corrupted, so we don't want to try to
2955  * clean up our transaction. Just nail the windows shut and get out of
2956  * town. The callbacks wouldn't be safe to run from a signal handler,
2957  * anyway.
2958  *
2959  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2960  * a system reset cycle if someone sends a manual SIGQUIT to a random
2961  * backend. This is necessary precisely because we don't clean up our
2962  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2963  * should ensure the postmaster sees this as a crash, too, but no harm in
2964  * being doubly sure.)
2965  */
2966  _exit(2);
2967 }
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().

◆ ResetUsage()

void ResetUsage ( void  )

◆ set_debug_options()

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

Definition at line 3654 of file postgres.c.

3655 {
3656  if (debug_flag > 0)
3657  {
3658  char debugstr[64];
3659 
3660  sprintf(debugstr, "debug%d", debug_flag);
3661  SetConfigOption("log_min_messages", debugstr, context, source);
3662  }
3663  else
3664  SetConfigOption("log_min_messages", "notice", context, source);
3665 
3666  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3667  {
3668  SetConfigOption("log_connections", "true", context, source);
3669  SetConfigOption("log_disconnections", "true", context, source);
3670  }
3671  if (debug_flag >= 2)
3672  SetConfigOption("log_statement", "all", context, source);
3673  if (debug_flag >= 3)
3674  SetConfigOption("debug_print_parse", "true", context, source);
3675  if (debug_flag >= 4)
3676  SetConfigOption("debug_print_plan", "true", context, source);
3677  if (debug_flag >= 5)
3678  SetConfigOption("debug_print_rewritten", "true", context, source);
3679 }
static rewind_source * source
Definition: pg_rewind.c:89
#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 3683 of file postgres.c.

3684 {
3685  const char *tmp = NULL;
3686 
3687  switch (arg[0])
3688  {
3689  case 's': /* seqscan */
3690  tmp = "enable_seqscan";
3691  break;
3692  case 'i': /* indexscan */
3693  tmp = "enable_indexscan";
3694  break;
3695  case 'o': /* indexonlyscan */
3696  tmp = "enable_indexonlyscan";
3697  break;
3698  case 'b': /* bitmapscan */
3699  tmp = "enable_bitmapscan";
3700  break;
3701  case 't': /* tidscan */
3702  tmp = "enable_tidscan";
3703  break;
3704  case 'n': /* nestloop */
3705  tmp = "enable_nestloop";
3706  break;
3707  case 'm': /* mergejoin */
3708  tmp = "enable_mergejoin";
3709  break;
3710  case 'h': /* hashjoin */
3711  tmp = "enable_hashjoin";
3712  break;
3713  }
3714  if (tmp)
3715  {
3716  SetConfigOption(tmp, "false", context, source);
3717  return true;
3718  }
3719  else
3720  return false;
3721 }

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4972 of file postgres.c.

4973 {
4975  struct timeval user,
4976  sys;
4977  struct timeval elapse_t;
4978  struct rusage r;
4979 
4980  getrusage(RUSAGE_SELF, &r);
4981  gettimeofday(&elapse_t, NULL);
4982  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4983  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4984  if (elapse_t.tv_usec < Save_t.tv_usec)
4985  {
4986  elapse_t.tv_sec--;
4987  elapse_t.tv_usec += 1000000;
4988  }
4989  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4990  {
4991  r.ru_utime.tv_sec--;
4992  r.ru_utime.tv_usec += 1000000;
4993  }
4994  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4995  {
4996  r.ru_stime.tv_sec--;
4997  r.ru_stime.tv_usec += 1000000;
4998  }
4999 
5000  /*
5001  * The only stats we don't show here are ixrss, idrss, isrss. It takes
5002  * some work to interpret them, and most platforms don't fill them in.
5003  */
5004  initStringInfo(&str);
5005 
5006  appendStringInfoString(&str, "! system usage stats:\n");
5008  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5009  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5010  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5011  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5012  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5013  (long) (elapse_t.tv_sec - Save_t.tv_sec),
5014  (long) (elapse_t.tv_usec - Save_t.tv_usec));
5016  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5017  (long) user.tv_sec,
5018  (long) user.tv_usec,
5019  (long) sys.tv_sec,
5020  (long) sys.tv_usec);
5021 #ifndef WIN32
5022 
5023  /*
5024  * The following rusage fields are not defined by POSIX, but they're
5025  * present on all current Unix-like systems so we use them without any
5026  * special checks. Some of these could be provided in our Windows
5027  * emulation in src/port/win32getrusage.c with more work.
5028  */
5030  "!\t%ld kB max resident size\n",
5031 #if defined(__darwin__)
5032  /* in bytes on macOS */
5033  r.ru_maxrss / 1024
5034 #else
5035  /* in kilobytes on most other platforms */
5036  r.ru_maxrss
5037 #endif
5038  );
5040  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5041  r.ru_inblock - Save_r.ru_inblock,
5042  /* they only drink coffee at dec */
5043  r.ru_oublock - Save_r.ru_oublock,
5044  r.ru_inblock, r.ru_oublock);
5046  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5047  r.ru_majflt - Save_r.ru_majflt,
5048  r.ru_minflt - Save_r.ru_minflt,
5049  r.ru_majflt, r.ru_minflt,
5050  r.ru_nswap - Save_r.ru_nswap,
5051  r.ru_nswap);
5053  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5054  r.ru_nsignals - Save_r.ru_nsignals,
5055  r.ru_nsignals,
5056  r.ru_msgrcv - Save_r.ru_msgrcv,
5057  r.ru_msgsnd - Save_r.ru_msgsnd,
5058  r.ru_msgrcv, r.ru_msgsnd);
5060  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5061  r.ru_nvcsw - Save_r.ru_nvcsw,
5062  r.ru_nivcsw - Save_r.ru_nivcsw,
5063  r.ru_nvcsw, r.ru_nivcsw);
5064 #endif /* !WIN32 */
5065 
5066  /* remove trailing newline */
5067  if (str.data[str.len - 1] == '\n')
5068  str.data[--str.len] = '\0';
5069 
5070  ereport(LOG,
5071  (errmsg_internal("%s", title),
5072  errdetail_internal("%s", str.data)));
5073 
5074  pfree(str.data);
5075 }
#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:112
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 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  InterruptPending = true;
3018  QueryCancelPending = true;
3019  }
3020 
3021  /* If we're still here, waken anything waiting on the process latch */
3022  SetLatch(MyLatch);
3023 
3024  errno = save_errno;
3025 }

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

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 93 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 96 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ whereToSendOutput