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

2379 {
2380  if (log_duration || log_min_duration_sample >= 0 ||
2382  {
2383  long secs;
2384  int usecs;
2385  int msecs;
2386  bool exceeded_duration;
2387  bool exceeded_sample_duration;
2388  bool in_sample = false;
2389 
2392  &secs, &usecs);
2393  msecs = usecs / 1000;
2394 
2395  /*
2396  * This odd-looking test for log_min_duration_* being exceeded is
2397  * designed to avoid integer overflow with very long durations: don't
2398  * compute secs * 1000 until we've verified it will fit in int.
2399  */
2400  exceeded_duration = (log_min_duration_statement == 0 ||
2402  (secs > log_min_duration_statement / 1000 ||
2403  secs * 1000 + msecs >= log_min_duration_statement)));
2404 
2405  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2406  (log_min_duration_sample > 0 &&
2407  (secs > log_min_duration_sample / 1000 ||
2408  secs * 1000 + msecs >= log_min_duration_sample)));
2409 
2410  /*
2411  * Do not log if log_statement_sample_rate = 0. Log a sample if
2412  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2413  * log_statement_sample_rate = 1.
2414  */
2415  if (exceeded_sample_duration)
2416  in_sample = log_statement_sample_rate != 0 &&
2417  (log_statement_sample_rate == 1 ||
2419 
2420  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2421  {
2422  snprintf(msec_str, 32, "%ld.%03d",
2423  secs * 1000 + msecs, usecs % 1000);
2424  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2425  return 2;
2426  else
2427  return 1;
2428  }
2429  }
2430 
2431  return 0;
2432 }
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:523
int log_min_duration_sample
Definition: guc_tables.c:522
double log_statement_sample_rate
Definition: guc_tables.c:527
bool log_duration
Definition: guc_tables.c:495
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 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:30
struct Latch * MyLatch
Definition: globals.c:59
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:633
@ DISCONNECT_KILLED
Definition: pgstat.h:82
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:89
static bool DoingCommandRead
Definition: postgres.c:143
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:1208
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149

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

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

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4956 of file postgres.c.

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

3743 {
3744  switch (arg[0])
3745  {
3746  case 'p':
3747  if (optarg[1] == 'a') /* "parser" */
3748  return "log_parser_stats";
3749  else if (optarg[1] == 'l') /* "planner" */
3750  return "log_planner_stats";
3751  break;
3752 
3753  case 'e': /* "executor" */
3754  return "log_executor_stats";
3755  break;
3756  }
3757 
3758  return NULL;
3759 }
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:166
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:165

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

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

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

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

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

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

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

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

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

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

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

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(), 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 BackendRun(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4034 of file postgres.c.

4036 {
4037  const char *dbname = NULL;
4038 
4040 
4041  /* Initialize startup process environment. */
4042  InitStandaloneProcess(argv[0]);
4043 
4044  /*
4045  * Set default values for command-line options.
4046  */
4048 
4049  /*
4050  * Parse command-line options.
4051  */
4053 
4054  /* Must have gotten a database name, or have a default (the username) */
4055  if (dbname == NULL)
4056  {
4057  dbname = username;
4058  if (dbname == NULL)
4059  ereport(FATAL,
4060  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4061  errmsg("%s: no database nor user name specified",
4062  progname)));
4063  }
4064 
4065  /* Acquire configuration parameters */
4067  proc_exit(1);
4068 
4069  /*
4070  * Validate we have been given a reasonable-looking DataDir and change
4071  * into it.
4072  */
4073  checkDataDir();
4074  ChangeToDataDir();
4075 
4076  /*
4077  * Create lockfile for data directory.
4078  */
4079  CreateDataDirLockFile(false);
4080 
4081  /* read control file (error checking and contains config ) */
4082  LocalProcessControlFile(false);
4083 
4084  /*
4085  * process any libraries that should be preloaded at postmaster start
4086  */
4088 
4089  /* Initialize MaxBackends */
4091 
4092  /*
4093  * Give preloaded libraries a chance to request additional shared memory.
4094  */
4096 
4097  /*
4098  * Now that loadable modules have had their chance to request additional
4099  * shared memory, determine the value of any runtime-computed GUCs that
4100  * depend on the amount of shared memory required.
4101  */
4103 
4104  /*
4105  * Now that modules have been loaded, we can process any custom resource
4106  * managers specified in the wal_consistency_checking GUC.
4107  */
4109 
4111 
4112  /*
4113  * Remember stand-alone backend startup time,roughly at the same point
4114  * during startup that postmaster does so.
4115  */
4117 
4118  /*
4119  * Create a per-backend PGPROC struct in shared memory. We must do this
4120  * before we can use LWLocks.
4121  */
4122  InitProcess();
4123 
4124  /*
4125  * Now that sufficient infrastructure has been initialized, PostgresMain()
4126  * can do the rest.
4127  */
4129 }
TimestampTz PgStartTime
Definition: timestamp.c:53
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1779
void InitializeGUCOptions(void)
Definition: guc.c:1525
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:372
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:202
const char * progname
Definition: main.c:45
void ChangeToDataDir(void)
Definition: miscinit.c:451
void process_shmem_requests(void)
Definition: miscinit.c:1867
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:181
void process_shared_preload_libraries(void)
Definition: miscinit.c:1839
void checkDataDir(void)
Definition: miscinit.c:338
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1451
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3782
static const char * userDoption
Definition: postgres.c:160
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4144
void InitializeMaxBackends(void)
Definition: postinit.c:560
void InitProcess(void)
Definition: proc.c:298
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4686
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4748

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

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

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

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

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

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

3672 {
3673  if (debug_flag > 0)
3674  {
3675  char debugstr[64];
3676 
3677  sprintf(debugstr, "debug%d", debug_flag);
3678  SetConfigOption("log_min_messages", debugstr, context, source);
3679  }
3680  else
3681  SetConfigOption("log_min_messages", "notice", context, source);
3682 
3683  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3684  {
3685  SetConfigOption("log_connections", "true", context, source);
3686  SetConfigOption("log_disconnections", "true", context, source);
3687  }
3688  if (debug_flag >= 2)
3689  SetConfigOption("log_statement", "all", context, source);
3690  if (debug_flag >= 3)
3691  SetConfigOption("debug_print_parse", "true", context, source);
3692  if (debug_flag >= 4)
3693  SetConfigOption("debug_print_plan", "true", context, source);
3694  if (debug_flag >= 5)
3695  SetConfigOption("debug_print_rewritten", "true", context, source);
3696 }
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 3700 of file postgres.c.

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

References arg, SetConfigOption(), and source.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4995 of file postgres.c.

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

Variable Documentation

◆ client_connection_check_interval

PGDLLIMPORT int client_connection_check_interval
extern

Definition at line 103 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 94 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 97 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ whereToSendOutput