PostgreSQL Source Code  git master
tcopprot.h File Reference
#include "nodes/params.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 bool Log_disconnections
 
PGDLLIMPORT int log_statement
 

Macro Definition Documentation

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 25 of file tcopprot.h.

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 35 of file tcopprot.h.

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

Function Documentation

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2379 of file postgres.c.

2380 {
2381  if (log_duration || log_min_duration_sample >= 0 ||
2383  {
2384  long secs;
2385  int usecs;
2386  int msecs;
2387  bool exceeded_duration;
2388  bool exceeded_sample_duration;
2389  bool in_sample = false;
2390 
2393  &secs, &usecs);
2394  msecs = usecs / 1000;
2395 
2396  /*
2397  * This odd-looking test for log_min_duration_* being exceeded is
2398  * designed to avoid integer overflow with very long durations: don't
2399  * compute secs * 1000 until we've verified it will fit in int.
2400  */
2401  exceeded_duration = (log_min_duration_statement == 0 ||
2403  (secs > log_min_duration_statement / 1000 ||
2404  secs * 1000 + msecs >= log_min_duration_statement)));
2405 
2406  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2407  (log_min_duration_sample > 0 &&
2408  (secs > log_min_duration_sample / 1000 ||
2409  secs * 1000 + msecs >= log_min_duration_sample)));
2410 
2411  /*
2412  * Do not log if log_statement_sample_rate = 0. Log a sample if
2413  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2414  * log_statement_sample_rate = 1.
2415  */
2416  if (exceeded_sample_duration)
2417  in_sample = log_statement_sample_rate != 0 &&
2418  (log_statement_sample_rate == 1 ||
2420 
2421  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2422  {
2423  snprintf(msec_str, 32, "%ld.%03d",
2424  secs * 1000 + msecs, usecs % 1000);
2425  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2426  return 2;
2427  else
2428  return 1;
2429  }
2430  }
2431 
2432  return 0;
2433 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1731
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1655
int log_min_duration_statement
Definition: guc_tables.c:519
int log_min_duration_sample
Definition: guc_tables.c:518
double log_statement_sample_rate
Definition: guc_tables.c:523
bool log_duration
Definition: guc_tables.c:490
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define snprintf
Definition: port.h:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:877
bool xact_is_sampled
Definition: xact.c:294

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

2972 {
2973  /* Don't joggle the elbow of proc_exit */
2974  if (!proc_exit_inprogress)
2975  {
2976  InterruptPending = true;
2977  ProcDiePending = true;
2978  }
2979 
2980  /* for the cumulative stats system */
2982 
2983  /* If we're still here, waken anything waiting on the process latch */
2984  SetLatch(MyLatch);
2985 
2986  /*
2987  * If we're in single user mode, we want to quit immediately - we can't
2988  * rely on latches as they wouldn't work when stdin/stdout is a file.
2989  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2990  * effort just for the benefit of single user mode.
2991  */
2994 }
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:61
volatile sig_atomic_t ProcDiePending
Definition: globals.c:33
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:632
@ DISCONNECT_KILLED
Definition: pgstat.h:82
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool DoingCommandRead
Definition: postgres.c:144
void ProcessInterrupts(void)
Definition: postgres.c:3243

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

3019 {
3020  /* We're not returning, so no need to save errno */
3021  ereport(ERROR,
3022  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3023  errmsg("floating-point exception"),
3024  errdetail("An invalid floating-point operation was signaled. "
3025  "This probably means an out-of-range result or an "
3026  "invalid operation, such as division by zero.")));
3027 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149

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

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), plperl_init_interp(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4960 of file postgres.c.

4961 {
4962 #if defined(HAVE_GETRLIMIT)
4963  static long val = 0;
4964 
4965  /* This won't change after process launch, so check just once */
4966  if (val == 0)
4967  {
4968  struct rlimit rlim;
4969 
4970  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4971  val = -1;
4972  else if (rlim.rlim_cur == RLIM_INFINITY)
4973  val = LONG_MAX;
4974  /* rlim_cur is probably of an unsigned type, so check for overflow */
4975  else if (rlim.rlim_cur >= LONG_MAX)
4976  val = LONG_MAX;
4977  else
4978  val = rlim.rlim_cur;
4979  }
4980  return val;
4981 #else
4982  /* On Windows we set the backend stack size in src/backend/Makefile */
4983  return WIN32_STACK_RLIMIT;
4984 #endif
4985 }
long val
Definition: informix.c:670

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

3750 {
3751  switch (arg[0])
3752  {
3753  case 'p':
3754  if (optarg[1] == 'a') /* "parser" */
3755  return "log_parser_stats";
3756  else if (optarg[1] == 'l') /* "planner" */
3757  return "log_planner_stats";
3758  break;
3759 
3760  case 'e': /* "executor" */
3761  return "log_executor_stats";
3762  break;
3763  }
3764 
3765  return NULL;
3766 }
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 3034 of file postgres.c.

3035 {
3036  RecoveryConflictPendingReasons[reason] = true;
3037  RecoveryConflictPending = true;
3038  InterruptPending = true;
3039  /* latch will be set by procsignal_sigusr1_handler */
3040 }
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:167
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:166

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

676 {
677  Query *query;
678  List *querytree_list;
679 
680  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
681 
682  /*
683  * (1) Perform parse analysis.
684  */
685  if (log_parser_stats)
686  ResetUsage();
687 
688  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
689  queryEnv);
690 
691  if (log_parser_stats)
692  ShowUsage("PARSE ANALYSIS STATISTICS");
693 
694  /*
695  * (2) Rewrite the queries, as necessary
696  */
697  querytree_list = pg_rewrite_query(query);
698 
699  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
700 
701  return querytree_list;
702 }
bool log_parser_stats
Definition: guc_tables.c:496
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:104
void ShowUsage(const char *title)
Definition: postgres.c:4999
List * pg_rewrite_query(Query *query)
Definition: postgres.c:804
void ResetUsage(void)
Definition: postgres.c:4992
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 710 of file postgres.c.

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

769 {
770  Query *query;
771  List *querytree_list;
772 
773  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
774 
775  /*
776  * (1) Perform parse analysis.
777  */
778  if (log_parser_stats)
779  ResetUsage();
780 
781  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
782  queryEnv);
783 
784  if (log_parser_stats)
785  ShowUsage("PARSE ANALYSIS STATISTICS");
786 
787  /*
788  * (2) Rewrite the queries, as necessary
789  */
790  querytree_list = pg_rewrite_query(query);
791 
792  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
793 
794  return querytree_list;
795 }
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:185

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

612 {
613  List *raw_parsetree_list;
614 
615  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
616 
617  if (log_parser_stats)
618  ResetUsage();
619 
620  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
621 
622  if (log_parser_stats)
623  ShowUsage("PARSER STATISTICS");
624 
625 #ifdef COPY_PARSE_PLAN_TREES
626  /* Optional debugging check: pass raw parsetrees through copyObject() */
627  {
628  List *new_list = copyObject(raw_parsetree_list);
629 
630  /* This checks both copyObject() and the equal() routines... */
631  if (!equal(new_list, raw_parsetree_list))
632  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
633  else
634  raw_parsetree_list = new_list;
635  }
636 #endif
637 
638  /*
639  * Optional debugging check: pass raw parsetrees through
640  * outfuncs/readfuncs
641  */
642 #ifdef WRITE_READ_PARSE_PLAN_TREES
643  {
644  char *str = nodeToStringWithLocations(raw_parsetree_list);
645  List *new_list = stringToNodeWithLocations(str);
646 
647  pfree(str);
648  /* This checks both outfuncs/readfuncs and the equal() routines... */
649  if (!equal(new_list, raw_parsetree_list))
650  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
651  else
652  raw_parsetree_list = new_list;
653  }
654 #endif
655 
656  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
657 
658  return raw_parsetree_list;
659 }
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:224
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
const char * str
static List * new_list(NodeTag type, int min_size)
Definition: list.c:91
void pfree(void *pointer)
Definition: mcxt.c:1521
#define copyObject(obj)
Definition: nodes.h:224
char * nodeToStringWithLocations(const void *obj)
Definition: outfuncs.c:797
@ RAW_PARSE_DEFAULT
Definition: parser.h:39

References copyObject, elog, equal(), log_parser_stats, new_list(), nodeToStringWithLocations(), pfree(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), 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 972 of file postgres.c.

974 {
975  List *stmt_list = NIL;
976  ListCell *query_list;
977 
978  foreach(query_list, querytrees)
979  {
980  Query *query = lfirst_node(Query, query_list);
981  PlannedStmt *stmt;
982 
983  if (query->commandType == CMD_UTILITY)
984  {
985  /* Utility commands require no planning. */
987  stmt->commandType = CMD_UTILITY;
988  stmt->canSetTag = query->canSetTag;
989  stmt->utilityStmt = query->utilityStmt;
990  stmt->stmt_location = query->stmt_location;
991  stmt->stmt_len = query->stmt_len;
992  stmt->queryId = query->queryId;
993  }
994  else
995  {
996  stmt = pg_plan_query(query, query_string, cursorOptions,
997  boundParams);
998  }
999 
1000  stmt_list = lappend(stmt_list, stmt);
1001  }
1002 
1003  return stmt_list;
1004 }
#define stmt
Definition: indent_codes.h:59
List * lappend(List *list, void *datum)
Definition: list.c:339
@ CMD_UTILITY
Definition: nodes.h:270
#define makeNode(_type_)
Definition: nodes.h:155
#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:886
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
ParseLoc stmt_location
Definition: parsenodes.h:238

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

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

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

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

◆ pg_rewrite_query()

List* pg_rewrite_query ( Query query)

Definition at line 804 of file postgres.c.

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

4152 {
4153  sigjmp_buf local_sigjmp_buf;
4154 
4155  /* these must be volatile to ensure state is preserved across longjmp: */
4156  volatile bool send_ready_for_query = true;
4157  volatile bool idle_in_transaction_timeout_enabled = false;
4158  volatile bool idle_session_timeout_enabled = false;
4159 
4160  Assert(dbname != NULL);
4161  Assert(username != NULL);
4162 
4164 
4165  /*
4166  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4167  * has already set up BlockSig and made that the active signal mask.)
4168  *
4169  * Note that postmaster blocked all signals before forking child process,
4170  * so there is no race condition whereby we might receive a signal before
4171  * we have set up the handler.
4172  *
4173  * Also note: it's best not to use any signals that are SIG_IGNored in the
4174  * postmaster. If such a signal arrives before we are able to change the
4175  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4176  * handler in the postmaster to reserve the signal. (Of course, this isn't
4177  * an issue for signals that are locally generated, such as SIGALRM and
4178  * SIGPIPE.)
4179  */
4180  if (am_walsender)
4181  WalSndSignals();
4182  else
4183  {
4185  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4186  pqsignal(SIGTERM, die); /* cancel current query and exit */
4187 
4188  /*
4189  * In a postmaster child backend, replace SignalHandlerForCrashExit
4190  * with quickdie, so we can tell the client we're dying.
4191  *
4192  * In a standalone backend, SIGQUIT can be generated from the keyboard
4193  * easily, while SIGTERM cannot, so we make both signals do die()
4194  * rather than quickdie().
4195  */
4196  if (IsUnderPostmaster)
4197  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4198  else
4199  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4200  InitializeTimeouts(); /* establishes SIGALRM handler */
4201 
4202  /*
4203  * Ignore failure to write to frontend. Note: if frontend closes
4204  * connection, we will notice it and exit cleanly when control next
4205  * returns to outer loop. This seems safer than forcing exit in the
4206  * midst of output during who-knows-what operation...
4207  */
4212 
4213  /*
4214  * Reset some signals that are accepted by postmaster but not by
4215  * backend
4216  */
4217  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4218  * platforms */
4219  }
4220 
4221  /* Early initialization */
4222  BaseInit();
4223 
4224  /* We need to allow SIGINT, etc during the initial transaction */
4225  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4226 
4227  /*
4228  * General initialization.
4229  *
4230  * NOTE: if you are tempted to add code in this vicinity, consider putting
4231  * it inside InitPostgres() instead. In particular, anything that
4232  * involves database access should be there, not here.
4233  *
4234  * Honor session_preload_libraries if not dealing with a WAL sender.
4235  */
4236  InitPostgres(dbname, InvalidOid, /* database to connect to */
4237  username, InvalidOid, /* role to connect as */
4239  NULL); /* no out_dbname */
4240 
4241  /*
4242  * If the PostmasterContext is still around, recycle the space; we don't
4243  * need it anymore after InitPostgres completes.
4244  */
4245  if (PostmasterContext)
4246  {
4248  PostmasterContext = NULL;
4249  }
4250 
4252 
4253  /*
4254  * Now all GUC states are fully set up. Report them to client if
4255  * appropriate.
4256  */
4258 
4259  /*
4260  * Also set up handler to log session end; we have to wait till now to be
4261  * sure Log_disconnections has its final value.
4262  */
4265 
4267 
4268  /* Perform initialization specific to a WAL sender process. */
4269  if (am_walsender)
4270  InitWalSender();
4271 
4272  /*
4273  * Send this backend's cancellation info to the frontend.
4274  */
4276  {
4278 
4282  pq_endmessage(&buf);
4283  /* Need not flush since ReadyForQuery will do it. */
4284  }
4285 
4286  /* Welcome banner for standalone case */
4288  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4289 
4290  /*
4291  * Create the memory context we will use in the main loop.
4292  *
4293  * MessageContext is reset once per iteration of the main loop, ie, upon
4294  * completion of processing of each command message from the client.
4295  */
4297  "MessageContext",
4299 
4300  /*
4301  * Create memory context and buffer used for RowDescription messages. As
4302  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4303  * frequently executed for ever single statement, we don't want to
4304  * allocate a separate buffer every time.
4305  */
4307  "RowDescriptionContext",
4312 
4313  /* Fire any defined login event triggers, if appropriate */
4315 
4316  /*
4317  * POSTGRES main processing loop begins here
4318  *
4319  * If an exception is encountered, processing resumes here so we abort the
4320  * current transaction and start a new one.
4321  *
4322  * You might wonder why this isn't coded as an infinite loop around a
4323  * PG_TRY construct. The reason is that this is the bottom of the
4324  * exception stack, and so with PG_TRY there would be no exception handler
4325  * in force at all during the CATCH part. By leaving the outermost setjmp
4326  * always active, we have at least some chance of recovering from an error
4327  * during error recovery. (If we get into an infinite loop thereby, it
4328  * will soon be stopped by overflow of elog.c's internal state stack.)
4329  *
4330  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4331  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4332  * is essential in case we longjmp'd out of a signal handler on a platform
4333  * where that leaves the signal blocked. It's not redundant with the
4334  * unblock in AbortTransaction() because the latter is only called if we
4335  * were inside a transaction.
4336  */
4337 
4338  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4339  {
4340  /*
4341  * NOTE: if you are tempted to add more code in this if-block,
4342  * consider the high probability that it should be in
4343  * AbortTransaction() instead. The only stuff done directly here
4344  * should be stuff that is guaranteed to apply *only* for outer-level
4345  * error recovery, such as adjusting the FE/BE protocol status.
4346  */
4347 
4348  /* Since not using PG_TRY, must reset error stack by hand */
4349  error_context_stack = NULL;
4350 
4351  /* Prevent interrupts while cleaning up */
4352  HOLD_INTERRUPTS();
4353 
4354  /*
4355  * Forget any pending QueryCancel request, since we're returning to
4356  * the idle loop anyway, and cancel any active timeout requests. (In
4357  * future we might want to allow some timeout requests to survive, but
4358  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4359  * we got here because of a query cancel interrupting the SIGALRM
4360  * interrupt handler.) Note in particular that we must clear the
4361  * statement and lock timeout indicators, to prevent any future plain
4362  * query cancels from being misreported as timeouts in case we're
4363  * forgetting a timeout cancel.
4364  */
4365  disable_all_timeouts(false); /* do first to avoid race condition */
4366  QueryCancelPending = false;
4367  idle_in_transaction_timeout_enabled = false;
4368  idle_session_timeout_enabled = false;
4369 
4370  /* Not reading from the client anymore. */
4371  DoingCommandRead = false;
4372 
4373  /* Make sure libpq is in a good state */
4374  pq_comm_reset();
4375 
4376  /* Report the error to the client and/or server log */
4377  EmitErrorReport();
4378 
4379  /*
4380  * If Valgrind noticed something during the erroneous query, print the
4381  * query string, assuming we have one.
4382  */
4384 
4385  /*
4386  * Make sure debug_query_string gets reset before we possibly clobber
4387  * the storage it points at.
4388  */
4389  debug_query_string = NULL;
4390 
4391  /*
4392  * Abort the current transaction in order to recover.
4393  */
4395 
4396  if (am_walsender)
4398 
4400 
4401  /*
4402  * We can't release replication slots inside AbortTransaction() as we
4403  * need to be able to start and abort transactions while having a slot
4404  * acquired. But we never need to hold them across top level errors,
4405  * so releasing here is fine. There also is a before_shmem_exit()
4406  * callback ensuring correct cleanup on FATAL errors.
4407  */
4408  if (MyReplicationSlot != NULL)
4410 
4411  /* We also want to cleanup temporary slots on error. */
4412  ReplicationSlotCleanup(false);
4413 
4415 
4416  /*
4417  * Now return to normal top-level context and clear ErrorContext for
4418  * next time.
4419  */
4421  FlushErrorState();
4422 
4423  /*
4424  * If we were handling an extended-query-protocol message, initiate
4425  * skip till next Sync. This also causes us not to issue
4426  * ReadyForQuery (until we get Sync).
4427  */
4429  ignore_till_sync = true;
4430 
4431  /* We don't have a transaction command open anymore */
4432  xact_started = false;
4433 
4434  /*
4435  * If an error occurred while we were reading a message from the
4436  * client, we have potentially lost track of where the previous
4437  * message ends and the next one begins. Even though we have
4438  * otherwise recovered from the error, we cannot safely read any more
4439  * messages from the client, so there isn't much we can do with the
4440  * connection anymore.
4441  */
4442  if (pq_is_reading_msg())
4443  ereport(FATAL,
4444  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4445  errmsg("terminating connection because protocol synchronization was lost")));
4446 
4447  /* Now we can allow interrupts again */
4449  }
4450 
4451  /* We can now handle ereport(ERROR) */
4452  PG_exception_stack = &local_sigjmp_buf;
4453 
4454  if (!ignore_till_sync)
4455  send_ready_for_query = true; /* initially, or after error */
4456 
4457  /*
4458  * Non-error queries loop here.
4459  */
4460 
4461  for (;;)
4462  {
4463  int firstchar;
4464  StringInfoData input_message;
4465 
4466  /*
4467  * At top of loop, reset extended-query-message flag, so that any
4468  * errors encountered in "idle" state don't provoke skip.
4469  */
4471 
4472  /*
4473  * For valgrind reporting purposes, the "current query" begins here.
4474  */
4475 #ifdef USE_VALGRIND
4476  old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4477 #endif
4478 
4479  /*
4480  * Release storage left over from prior query cycle, and create a new
4481  * query input buffer in the cleared MessageContext.
4482  */
4485 
4486  initStringInfo(&input_message);
4487 
4488  /*
4489  * Also consider releasing our catalog snapshot if any, so that it's
4490  * not preventing advance of global xmin while we wait for the client.
4491  */
4493 
4494  /*
4495  * (1) If we've reached idle state, tell the frontend we're ready for
4496  * a new query.
4497  *
4498  * Note: this includes fflush()'ing the last of the prior output.
4499  *
4500  * This is also a good time to flush out collected statistics to the
4501  * cumulative stats system, and to update the PS stats display. We
4502  * avoid doing those every time through the message loop because it'd
4503  * slow down processing of batched messages, and because we don't want
4504  * to report uncommitted updates (that confuses autovacuum). The
4505  * notification processor wants a call too, if we are not in a
4506  * transaction block.
4507  *
4508  * Also, if an idle timeout is enabled, start the timer for that.
4509  */
4510  if (send_ready_for_query)
4511  {
4513  {
4514  set_ps_display("idle in transaction (aborted)");
4516 
4517  /* Start the idle-in-transaction timer */
4520  {
4521  idle_in_transaction_timeout_enabled = true;
4524  }
4525  }
4527  {
4528  set_ps_display("idle in transaction");
4530 
4531  /* Start the idle-in-transaction timer */
4534  {
4535  idle_in_transaction_timeout_enabled = true;
4538  }
4539  }
4540  else
4541  {
4542  long stats_timeout;
4543 
4544  /*
4545  * Process incoming notifies (including self-notifies), if
4546  * any, and send relevant messages to the client. Doing it
4547  * here helps ensure stable behavior in tests: if any notifies
4548  * were received during the just-finished transaction, they'll
4549  * be seen by the client before ReadyForQuery is.
4550  */
4552  ProcessNotifyInterrupt(false);
4553 
4554  /*
4555  * Check if we need to report stats. If pgstat_report_stat()
4556  * decides it's too soon to flush out pending stats / lock
4557  * contention prevented reporting, it'll tell us when we
4558  * should try to report stats again (so that stats updates
4559  * aren't unduly delayed if the connection goes idle for a
4560  * long time). We only enable the timeout if we don't already
4561  * have a timeout in progress, because we don't disable the
4562  * timeout below. enable_timeout_after() needs to determine
4563  * the current timestamp, which can have a negative
4564  * performance impact. That's OK because pgstat_report_stat()
4565  * won't have us wake up sooner than a prior call.
4566  */
4567  stats_timeout = pgstat_report_stat(false);
4568  if (stats_timeout > 0)
4569  {
4572  stats_timeout);
4573  }
4574  else
4575  {
4576  /* all stats flushed, no need for the timeout */
4579  }
4580 
4581  set_ps_display("idle");
4583 
4584  /* Start the idle-session timer */
4585  if (IdleSessionTimeout > 0)
4586  {
4587  idle_session_timeout_enabled = true;
4590  }
4591  }
4592 
4593  /* Report any recently-changed GUC options */
4595 
4597  send_ready_for_query = false;
4598  }
4599 
4600  /*
4601  * (2) Allow asynchronous signals to be executed immediately if they
4602  * come in while we are waiting for client input. (This must be
4603  * conditional since we don't want, say, reads on behalf of COPY FROM
4604  * STDIN doing the same thing.)
4605  */
4606  DoingCommandRead = true;
4607 
4608  /*
4609  * (3) read a command (loop blocks here)
4610  */
4611  firstchar = ReadCommand(&input_message);
4612 
4613  /*
4614  * (4) turn off the idle-in-transaction and idle-session timeouts if
4615  * active. We do this before step (5) so that any last-moment timeout
4616  * is certain to be detected in step (5).
4617  *
4618  * At most one of these timeouts will be active, so there's no need to
4619  * worry about combining the timeout.c calls into one.
4620  */
4621  if (idle_in_transaction_timeout_enabled)
4622  {
4624  idle_in_transaction_timeout_enabled = false;
4625  }
4626  if (idle_session_timeout_enabled)
4627  {
4629  idle_session_timeout_enabled = false;
4630  }
4631 
4632  /*
4633  * (5) disable async signal conditions again.
4634  *
4635  * Query cancel is supposed to be a no-op when there is no query in
4636  * progress, so if a query cancel arrived while we were idle, just
4637  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4638  * it's called when DoingCommandRead is set, so check for interrupts
4639  * before resetting DoingCommandRead.
4640  */
4642  DoingCommandRead = false;
4643 
4644  /*
4645  * (6) check for any other interesting events that happened while we
4646  * slept.
4647  */
4648  if (ConfigReloadPending)
4649  {
4650  ConfigReloadPending = false;
4652  }
4653 
4654  /*
4655  * (7) process the command. But ignore it if we're skipping till
4656  * Sync.
4657  */
4658  if (ignore_till_sync && firstchar != EOF)
4659  continue;
4660 
4661  switch (firstchar)
4662  {
4663  case PqMsg_Query:
4664  {
4665  const char *query_string;
4666 
4667  /* Set statement_timestamp() */
4669 
4670  query_string = pq_getmsgstring(&input_message);
4671  pq_getmsgend(&input_message);
4672 
4673  if (am_walsender)
4674  {
4675  if (!exec_replication_command(query_string))
4676  exec_simple_query(query_string);
4677  }
4678  else
4679  exec_simple_query(query_string);
4680 
4681  valgrind_report_error_query(query_string);
4682 
4683  send_ready_for_query = true;
4684  }
4685  break;
4686 
4687  case PqMsg_Parse:
4688  {
4689  const char *stmt_name;
4690  const char *query_string;
4691  int numParams;
4692  Oid *paramTypes = NULL;
4693 
4694  forbidden_in_wal_sender(firstchar);
4695 
4696  /* Set statement_timestamp() */
4698 
4699  stmt_name = pq_getmsgstring(&input_message);
4700  query_string = pq_getmsgstring(&input_message);
4701  numParams = pq_getmsgint(&input_message, 2);
4702  if (numParams > 0)
4703  {
4704  paramTypes = palloc_array(Oid, numParams);
4705  for (int i = 0; i < numParams; i++)
4706  paramTypes[i] = pq_getmsgint(&input_message, 4);
4707  }
4708  pq_getmsgend(&input_message);
4709 
4710  exec_parse_message(query_string, stmt_name,
4711  paramTypes, numParams);
4712 
4713  valgrind_report_error_query(query_string);
4714  }
4715  break;
4716 
4717  case PqMsg_Bind:
4718  forbidden_in_wal_sender(firstchar);
4719 
4720  /* Set statement_timestamp() */
4722 
4723  /*
4724  * this message is complex enough that it seems best to put
4725  * the field extraction out-of-line
4726  */
4727  exec_bind_message(&input_message);
4728 
4729  /* exec_bind_message does valgrind_report_error_query */
4730  break;
4731 
4732  case PqMsg_Execute:
4733  {
4734  const char *portal_name;
4735  int max_rows;
4736 
4737  forbidden_in_wal_sender(firstchar);
4738 
4739  /* Set statement_timestamp() */
4741 
4742  portal_name = pq_getmsgstring(&input_message);
4743  max_rows = pq_getmsgint(&input_message, 4);
4744  pq_getmsgend(&input_message);
4745 
4746  exec_execute_message(portal_name, max_rows);
4747 
4748  /* exec_execute_message does valgrind_report_error_query */
4749  }
4750  break;
4751 
4752  case PqMsg_FunctionCall:
4753  forbidden_in_wal_sender(firstchar);
4754 
4755  /* Set statement_timestamp() */
4757 
4758  /* Report query to various monitoring facilities. */
4760  set_ps_display("<FASTPATH>");
4761 
4762  /* start an xact for this function invocation */
4764 
4765  /*
4766  * Note: we may at this point be inside an aborted
4767  * transaction. We can't throw error for that until we've
4768  * finished reading the function-call message, so
4769  * HandleFunctionRequest() must check for it after doing so.
4770  * Be careful not to do anything that assumes we're inside a
4771  * valid transaction here.
4772  */
4773 
4774  /* switch back to message context */
4776 
4777  HandleFunctionRequest(&input_message);
4778 
4779  /* commit the function-invocation transaction */
4781 
4782  valgrind_report_error_query("fastpath function call");
4783 
4784  send_ready_for_query = true;
4785  break;
4786 
4787  case PqMsg_Close:
4788  {
4789  int close_type;
4790  const char *close_target;
4791 
4792  forbidden_in_wal_sender(firstchar);
4793 
4794  close_type = pq_getmsgbyte(&input_message);
4795  close_target = pq_getmsgstring(&input_message);
4796  pq_getmsgend(&input_message);
4797 
4798  switch (close_type)
4799  {
4800  case 'S':
4801  if (close_target[0] != '\0')
4802  DropPreparedStatement(close_target, false);
4803  else
4804  {
4805  /* special-case the unnamed statement */
4807  }
4808  break;
4809  case 'P':
4810  {
4811  Portal portal;
4812 
4813  portal = GetPortalByName(close_target);
4814  if (PortalIsValid(portal))
4815  PortalDrop(portal, false);
4816  }
4817  break;
4818  default:
4819  ereport(ERROR,
4820  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4821  errmsg("invalid CLOSE message subtype %d",
4822  close_type)));
4823  break;
4824  }
4825 
4828 
4829  valgrind_report_error_query("CLOSE message");
4830  }
4831  break;
4832 
4833  case PqMsg_Describe:
4834  {
4835  int describe_type;
4836  const char *describe_target;
4837 
4838  forbidden_in_wal_sender(firstchar);
4839 
4840  /* Set statement_timestamp() (needed for xact) */
4842 
4843  describe_type = pq_getmsgbyte(&input_message);
4844  describe_target = pq_getmsgstring(&input_message);
4845  pq_getmsgend(&input_message);
4846 
4847  switch (describe_type)
4848  {
4849  case 'S':
4850  exec_describe_statement_message(describe_target);
4851  break;
4852  case 'P':
4853  exec_describe_portal_message(describe_target);
4854  break;
4855  default:
4856  ereport(ERROR,
4857  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4858  errmsg("invalid DESCRIBE message subtype %d",
4859  describe_type)));
4860  break;
4861  }
4862 
4863  valgrind_report_error_query("DESCRIBE message");
4864  }
4865  break;
4866 
4867  case PqMsg_Flush:
4868  pq_getmsgend(&input_message);
4870  pq_flush();
4871  break;
4872 
4873  case PqMsg_Sync:
4874  pq_getmsgend(&input_message);
4876  valgrind_report_error_query("SYNC message");
4877  send_ready_for_query = true;
4878  break;
4879 
4880  /*
4881  * 'X' means that the frontend is closing down the socket. EOF
4882  * means unexpected loss of frontend connection. Either way,
4883  * perform normal shutdown.
4884  */
4885  case EOF:
4886 
4887  /* for the cumulative statistics system */
4889 
4890  /* FALLTHROUGH */
4891 
4892  case PqMsg_Terminate:
4893 
4894  /*
4895  * Reset whereToSendOutput to prevent ereport from attempting
4896  * to send any more messages to client.
4897  */
4900 
4901  /*
4902  * NOTE: if you are tempted to add more code here, DON'T!
4903  * Whatever you had in mind to do should be set up as an
4904  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4905  * it will fail to be called during other backend-shutdown
4906  * scenarios.
4907  */
4908  proc_exit(0);
4909 
4910  case PqMsg_CopyData:
4911  case PqMsg_CopyDone:
4912  case PqMsg_CopyFail:
4913 
4914  /*
4915  * Accept but ignore these messages, per protocol spec; we
4916  * probably got here because a COPY failed, and the frontend
4917  * is still sending data.
4918  */
4919  break;
4920 
4921  default:
4922  ereport(FATAL,
4923  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4924  errmsg("invalid frontend message type %d",
4925  firstchar)));
4926  }
4927  } /* end of input-reading loop */
4928 }
void ProcessNotifyInterrupt(bool flush)
Definition: async.c:1834
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:413
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:516
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:494
void ReadyForQuery(CommandDest dest)
Definition: dest.c:256
@ DestDebug
Definition: dest.h:88
@ DestNone
Definition: dest.h:87
void EmitErrorReport(void)
Definition: elog.c:1670
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void FlushErrorState(void)
Definition: elog.c:1850
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
#define FATAL
Definition: elog.h:41
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:189
#define palloc_array(type, count)
Definition: fe_memutils.h:64
int32 MyCancelKey
Definition: globals.c:51
int MyProcPid
Definition: globals.c:46
bool IsUnderPostmaster
Definition: globals.c:118
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:32
Oid MyDatabaseId
Definition: globals.c:92
void BeginReportingGUCOptions(void)
Definition: guc.c:2545
void ReportChangedGUCOptions(void)
Definition: guc.c:2595
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
static char * username
Definition: initdb.c:153
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:309
void proc_exit(int code)
Definition: ipc.c:104
void jit_reset_after_error(void)
Definition: jit.c:127
#define pq_flush()
Definition: libpq.h:46
#define pq_comm_reset()
Definition: libpq.h:45
MemoryContext MessageContext
Definition: mcxt.c:153
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
MemoryContext TopMemoryContext
Definition: mcxt.c:149
MemoryContext PostmasterContext
Definition: mcxt.c:151
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:449
@ InitProcessing
Definition: miscadmin.h:448
#define GetProcessingMode()
Definition: miscadmin.h:458
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:476
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
static char * buf
Definition: pg_test_fsync.c:73
long pgstat_report_stat(bool force)
Definition: pgstat.c:622
@ 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:468
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
void PortalErrorCleanup(void)
Definition: portalmem.c:917
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2597
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2874
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5108
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4938
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2085
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3018
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3001
static bool ignore_till_sync
Definition: postgres.c:151
static void finish_xact_command(void)
Definition: postgres.c:2770
const char * debug_query_string
Definition: postgres.c:87
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1013
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1391
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1626
void die(SIGNAL_ARGS)
Definition: postgres.c:2971
static bool xact_started
Definition: postgres.c:137
static MemoryContext row_description_context
Definition: postgres.c:170
static StringInfoData row_description_buf
Definition: postgres.c:171
static bool doing_extended_query_message
Definition: postgres.c:150
static void start_xact_command(void)
Definition: postgres.c:2742
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2690
bool Log_disconnections
Definition: postgres.c:93
static void drop_unnamed_stmt(void)
Definition: postgres.c:2849
#define valgrind_report_error_query(query)
Definition: postgres.c:224
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:488
void BaseInit(void)
Definition: postinit.c:602
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:693
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1181
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:415
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:579
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:635
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:388
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:399
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:144
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:635
#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
MemoryContextSwitchTo(old_ctx)
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotRelease(void)
Definition: slot.c:652
void ReplicationSlotCleanup(bool synced_only)
Definition: slot.c:745
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:443
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:60
int TransactionTimeout
Definition: proc.c:61
char * dbname
Definition: streamutil.c:52
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:780
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:751
void InitializeTimeouts(void)
Definition: timeout.c:470
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
void WalSndErrorCleanup(void)
Definition: walsender.c:327
bool am_walsender
Definition: walsender.c:115
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1980
void WalSndSignals(void)
Definition: walsender.c:3593
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:4976
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:405
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:912
void AbortCurrentTransaction(void)
Definition: xact.c:3425

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, EventTriggerOnLogin(), 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(), GetProcessingMode, HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeout, IdleSessionTimeout, ignore_till_sync, INIT_PG_LOAD_SESSION_LIBS, InitializeTimeouts(), InitPostgres(), InitProcessing, initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextReset(), 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, TransactionTimeout, UnBlockSig, username, valgrind_report_error_query, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendMain(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4041 of file postgres.c.

4043 {
4044  const char *dbname = NULL;
4045 
4047 
4048  /* Initialize startup process environment. */
4049  InitStandaloneProcess(argv[0]);
4050 
4051  /*
4052  * Set default values for command-line options.
4053  */
4055 
4056  /*
4057  * Parse command-line options.
4058  */
4060 
4061  /* Must have gotten a database name, or have a default (the username) */
4062  if (dbname == NULL)
4063  {
4064  dbname = username;
4065  if (dbname == NULL)
4066  ereport(FATAL,
4067  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4068  errmsg("%s: no database nor user name specified",
4069  progname)));
4070  }
4071 
4072  /* Acquire configuration parameters */
4074  proc_exit(1);
4075 
4076  /*
4077  * Validate we have been given a reasonable-looking DataDir and change
4078  * into it.
4079  */
4080  checkDataDir();
4081  ChangeToDataDir();
4082 
4083  /*
4084  * Create lockfile for data directory.
4085  */
4086  CreateDataDirLockFile(false);
4087 
4088  /* read control file (error checking and contains config ) */
4089  LocalProcessControlFile(false);
4090 
4091  /*
4092  * process any libraries that should be preloaded at postmaster start
4093  */
4095 
4096  /* Initialize MaxBackends */
4098 
4099  /*
4100  * Give preloaded libraries a chance to request additional shared memory.
4101  */
4103 
4104  /*
4105  * Now that loadable modules have had their chance to request additional
4106  * shared memory, determine the value of any runtime-computed GUCs that
4107  * depend on the amount of shared memory required.
4108  */
4110 
4111  /*
4112  * Now that modules have been loaded, we can process any custom resource
4113  * managers specified in the wal_consistency_checking GUC.
4114  */
4116 
4118 
4119  /*
4120  * Remember stand-alone backend startup time,roughly at the same point
4121  * during startup that postmaster does so.
4122  */
4124 
4125  /*
4126  * Create a per-backend PGPROC struct in shared memory. We must do this
4127  * before we can use LWLocks.
4128  */
4129  InitProcess();
4130 
4131  /*
4132  * Now that sufficient infrastructure has been initialized, PostgresMain()
4133  * can do the rest.
4134  */
4136 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1783
void InitializeGUCOptions(void)
Definition: guc.c:1529
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:369
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:199
const char * progname
Definition: main.c:44
void ChangeToDataDir(void)
Definition: miscinit.c:454
void process_shmem_requests(void)
Definition: miscinit.c:1871
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:181
void process_shared_preload_libraries(void)
Definition: miscinit.c:1843
void checkDataDir(void)
Definition: miscinit.c:341
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1455
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3789
static const char * userDoption
Definition: postgres.c:161
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4151
void InitializeMaxBackends(void)
Definition: postinit.c:575
void InitProcess(void)
Definition: proc.c:296
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4749
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4811

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

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

510 {
511  int save_errno = errno;
512 
513  if (DoingCommandRead)
514  {
515  /* Check for general interrupts that arrived before/while reading */
517 
518  /* Process sinval catchup interrupts, if any */
521 
522  /* Process notify interrupts, if any */
525  }
526  else if (ProcDiePending)
527  {
528  /*
529  * We're dying. If there is no data available to read, then it's safe
530  * (and sane) to handle that now. If we haven't tried to read yet,
531  * make sure the process latch is set, so that if there is no data
532  * then we'll come back here and die. If we're done reading, also
533  * make sure the process latch is set, as we might've undesirably
534  * cleared it while reading.
535  */
536  if (blocked)
538  else
539  SetLatch(MyLatch);
540  }
541 
542  errno = save_errno;
543 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:174
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:39

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

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

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

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

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

3679 {
3680  if (debug_flag > 0)
3681  {
3682  char debugstr[64];
3683 
3684  sprintf(debugstr, "debug%d", debug_flag);
3685  SetConfigOption("log_min_messages", debugstr, context, source);
3686  }
3687  else
3688  SetConfigOption("log_min_messages", "notice", context, source);
3689 
3690  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3691  {
3692  SetConfigOption("log_connections", "true", context, source);
3693  SetConfigOption("log_disconnections", "true", context, source);
3694  }
3695  if (debug_flag >= 2)
3696  SetConfigOption("log_statement", "all", context, source);
3697  if (debug_flag >= 3)
3698  SetConfigOption("debug_print_parse", "true", context, source);
3699  if (debug_flag >= 4)
3700  SetConfigOption("debug_print_plan", "true", context, source);
3701  if (debug_flag >= 5)
3702  SetConfigOption("debug_print_rewritten", "true", context, source);
3703 }
static rewind_source * source
Definition: pg_rewind.c:89
#define sprintf
Definition: port.h:240
tree context
Definition: radixtree.h:1835

References context, 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 3707 of file postgres.c.

3708 {
3709  const char *tmp = NULL;
3710 
3711  switch (arg[0])
3712  {
3713  case 's': /* seqscan */
3714  tmp = "enable_seqscan";
3715  break;
3716  case 'i': /* indexscan */
3717  tmp = "enable_indexscan";
3718  break;
3719  case 'o': /* indexonlyscan */
3720  tmp = "enable_indexonlyscan";
3721  break;
3722  case 'b': /* bitmapscan */
3723  tmp = "enable_bitmapscan";
3724  break;
3725  case 't': /* tidscan */
3726  tmp = "enable_tidscan";
3727  break;
3728  case 'n': /* nestloop */
3729  tmp = "enable_nestloop";
3730  break;
3731  case 'm': /* mergejoin */
3732  tmp = "enable_mergejoin";
3733  break;
3734  case 'h': /* hashjoin */
3735  tmp = "enable_hashjoin";
3736  break;
3737  }
3738  if (tmp)
3739  {
3740  SetConfigOption(tmp, "false", context, source);
3741  return true;
3742  }
3743  else
3744  return false;
3745 }

References arg, context, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4999 of file postgres.c.

5000 {
5002  struct timeval user,
5003  sys;
5004  struct timeval elapse_t;
5005  struct rusage r;
5006 
5007  getrusage(RUSAGE_SELF, &r);
5008  gettimeofday(&elapse_t, NULL);
5009  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
5010  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
5011  if (elapse_t.tv_usec < Save_t.tv_usec)
5012  {
5013  elapse_t.tv_sec--;
5014  elapse_t.tv_usec += 1000000;
5015  }
5016  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5017  {
5018  r.ru_utime.tv_sec--;
5019  r.ru_utime.tv_usec += 1000000;
5020  }
5021  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5022  {
5023  r.ru_stime.tv_sec--;
5024  r.ru_stime.tv_usec += 1000000;
5025  }
5026 
5027  /*
5028  * The only stats we don't show here are ixrss, idrss, isrss. It takes
5029  * some work to interpret them, and most platforms don't fill them in.
5030  */
5031  initStringInfo(&str);
5032 
5033  appendStringInfoString(&str, "! system usage stats:\n");
5035  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5036  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5037  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5038  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5039  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5040  (long) (elapse_t.tv_sec - Save_t.tv_sec),
5041  (long) (elapse_t.tv_usec - Save_t.tv_usec));
5043  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5044  (long) user.tv_sec,
5045  (long) user.tv_usec,
5046  (long) sys.tv_sec,
5047  (long) sys.tv_usec);
5048 #ifndef WIN32
5049 
5050  /*
5051  * The following rusage fields are not defined by POSIX, but they're
5052  * present on all current Unix-like systems so we use them without any
5053  * special checks. Some of these could be provided in our Windows
5054  * emulation in src/port/win32getrusage.c with more work.
5055  */
5057  "!\t%ld kB max resident size\n",
5058 #if defined(__darwin__)
5059  /* in bytes on macOS */
5060  r.ru_maxrss / 1024
5061 #else
5062  /* in kilobytes on most other platforms */
5063  r.ru_maxrss
5064 #endif
5065  );
5067  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5068  r.ru_inblock - Save_r.ru_inblock,
5069  /* they only drink coffee at dec */
5070  r.ru_oublock - Save_r.ru_oublock,
5071  r.ru_inblock, r.ru_oublock);
5073  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5074  r.ru_majflt - Save_r.ru_majflt,
5075  r.ru_minflt - Save_r.ru_minflt,
5076  r.ru_majflt, r.ru_minflt,
5077  r.ru_nswap - Save_r.ru_nswap,
5078  r.ru_nswap);
5080  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5081  r.ru_nsignals - Save_r.ru_nsignals,
5082  r.ru_nsignals,
5083  r.ru_msgrcv - Save_r.ru_msgrcv,
5084  r.ru_msgsnd - Save_r.ru_msgsnd,
5085  r.ru_msgrcv, r.ru_msgsnd);
5087  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5088  r.ru_nvcsw - Save_r.ru_nvcsw,
5089  r.ru_nivcsw - Save_r.ru_nivcsw,
5090  r.ru_nvcsw, r.ru_nivcsw);
5091 #endif /* !WIN32 */
5092 
5093  /* remove trailing newline */
5094  if (str.data[str.len - 1] == '\n')
5095  str.data[--str.len] = '\0';
5096 
5097  ereport(LOG,
5098  (errmsg_internal("%s", title),
5099  errdetail_internal("%s", str.data)));
5100 
5101  pfree(str.data);
5102 }
#define __darwin__
Definition: darwin.h:3
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
static char * user
Definition: pg_regress.c:120
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
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, 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 3001 of file postgres.c.

3002 {
3003  /*
3004  * Don't joggle the elbow of proc_exit
3005  */
3006  if (!proc_exit_inprogress)
3007  {
3008  InterruptPending = true;
3009  QueryCancelPending = true;
3010  }
3011 
3012  /* If we're still here, waken anything waiting on the process latch */
3013  SetLatch(MyLatch);
3014 }

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

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), PostgresMain(), and WalSndSignals().

Variable Documentation

◆ client_connection_check_interval

PGDLLIMPORT int client_connection_check_interval
extern

Definition at line 104 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ Log_disconnections

PGDLLIMPORT bool Log_disconnections
extern

Definition at line 93 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 95 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 98 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

Definition at line 101 of file postgres.c.

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), and InitPostgres().

◆ whereToSendOutput