PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 RESTRICT_RELKIND_VIEW   0x01
 
#define RESTRICT_RELKIND_FOREIGN_TABLE   0x02
 

Typedefs

typedef struct ExplainState ExplainState
 

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, ExplainState *es)
 
Listpg_plan_queries (List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
void die (SIGNAL_ARGS)
 
pg_noreturn void quickdie (SIGNAL_ARGS)
 
void StatementCancelHandler (SIGNAL_ARGS)
 
pg_noreturn void FloatExceptionHandler (SIGNAL_ARGS)
 
void HandleRecoveryConflictInterrupt (void)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
pg_noreturn void PostgresSingleUserMain (int argc, char *argv[], const char *username)
 
pg_noreturn void PostgresMain (const char *dbname, const char *username)
 
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 charget_stats_option_name (const char *arg)
 

Variables

PGDLLIMPORT CommandDest whereToSendOutput
 
PGDLLIMPORT const chardebug_query_string
 
PGDLLIMPORT int PostAuthDelay
 
PGDLLIMPORT int client_connection_check_interval
 
PGDLLIMPORT bool Log_disconnections
 
PGDLLIMPORT int log_statement
 
PGDLLIMPORT int restrict_nonsystem_relation_kind
 

Macro Definition Documentation

◆ RESTRICT_RELKIND_FOREIGN_TABLE

#define RESTRICT_RELKIND_FOREIGN_TABLE   0x02

Definition at line 45 of file tcopprot.h.

◆ RESTRICT_RELKIND_VIEW

#define RESTRICT_RELKIND_VIEW   0x01

Definition at line 44 of file tcopprot.h.

Typedef Documentation

◆ ExplainState

Definition at line 23 of file tcopprot.h.

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 32 of file tcopprot.h.

33{
34 LOGSTMT_NONE, /* log no statements */
35 LOGSTMT_DDL, /* log data definition statements */
36 LOGSTMT_MOD, /* log modification statements, plus DDL */
37 LOGSTMT_ALL, /* log all statements */
LogStmtLevel
Definition tcopprot.h:33
@ LOGSTMT_NONE
Definition tcopprot.h:34
@ LOGSTMT_MOD
Definition tcopprot.h:36
@ LOGSTMT_DDL
Definition tcopprot.h:35
@ LOGSTMT_ALL
Definition tcopprot.h:37

Function Documentation

◆ check_log_duration()

int check_log_duration ( char msec_str,
bool  was_logged 
)
extern

Definition at line 2436 of file postgres.c.

2437{
2440 {
2441 long secs;
2442 int usecs;
2443 int msecs;
2444 bool exceeded_duration;
2446 bool in_sample = false;
2447
2450 &secs, &usecs);
2451 msecs = usecs / 1000;
2452
2453 /*
2454 * This odd-looking test for log_min_duration_* being exceeded is
2455 * designed to avoid integer overflow with very long durations: don't
2456 * compute secs * 1000 until we've verified it will fit in int.
2457 */
2460 (secs > log_min_duration_statement / 1000 ||
2461 secs * 1000 + msecs >= log_min_duration_statement)));
2462
2465 (secs > log_min_duration_sample / 1000 ||
2466 secs * 1000 + msecs >= log_min_duration_sample)));
2467
2468 /*
2469 * Do not log if log_statement_sample_rate = 0. Log a sample if
2470 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2471 * log_statement_sample_rate = 1.
2472 */
2477
2479 {
2480 snprintf(msec_str, 32, "%ld.%03d",
2481 secs * 1000 + msecs, usecs % 1000);
2483 return 2;
2484 else
2485 return 1;
2486 }
2487 }
2488
2489 return 0;
2490}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1715
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
int log_min_duration_statement
Definition guc_tables.c:570
int log_min_duration_sample
Definition guc_tables.c:569
double log_statement_sample_rate
Definition guc_tables.c:574
bool log_duration
Definition guc_tables.c:535
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:260
static int fb(int x)
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition xact.c:881
bool xact_is_sampled
Definition xact.c:298

References fb(), 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  )
extern

Definition at line 3023 of file postgres.c.

3024{
3025 /* Don't joggle the elbow of proc_exit */
3027 {
3028 InterruptPending = true;
3029 ProcDiePending = true;
3030
3031 /*
3032 * Record who sent the signal. Will be 0 on platforms without
3033 * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
3034 * Only set on the first SIGTERM so we report the original sender.
3035 */
3036 if (ProcDieSenderPid == 0)
3037 {
3040 }
3041 }
3042
3043 /* for the cumulative stats system */
3045
3046 /* If we're still here, waken anything waiting on the process latch */
3048
3049 /*
3050 * If we're in single user mode, we want to quit immediately - we can't
3051 * rely on latches as they wouldn't work when stdin/stdout is a file.
3052 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3053 * effort just for the benefit of single user mode.
3054 */
3057}
@ DestRemote
Definition dest.h:89
volatile sig_atomic_t InterruptPending
Definition globals.c:32
volatile int ProcDieSenderPid
Definition globals.c:46
volatile int ProcDieSenderUid
Definition globals.c:47
struct Latch * MyLatch
Definition globals.c:65
volatile sig_atomic_t ProcDiePending
Definition globals.c:34
bool proc_exit_inprogress
Definition ipc.c:41
void SetLatch(Latch *latch)
Definition latch.c:290
@ DISCONNECT_KILLED
Definition pgstat.h:64
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition postgres.c:97
static bool DoingCommandRead
Definition postgres.c:150
void ProcessInterrupts(void)
Definition postgres.c:3361

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

◆ FloatExceptionHandler()

pg_noreturn void FloatExceptionHandler ( SIGNAL_ARGS  )
extern

Definition at line 3081 of file postgres.c.

3082{
3083 /* We're not returning, so no need to save errno */
3084 ereport(ERROR,
3086 errmsg("floating-point exception"),
3087 errdetail("An invalid floating-point operation was signaled. "
3088 "This probably means an out-of-range result or an "
3089 "invalid operation, such as division by zero.")));
3090}
int errcode(int sqlerrcode)
Definition elog.c:875
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
static char * errmsg

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

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

◆ get_stats_option_name()

const char * get_stats_option_name ( const char arg)
extern

Definition at line 3834 of file postgres.c.

3835{
3836 switch (arg[0])
3837 {
3838 case 'p':
3839 if (arg[1] == 'a') /* "parser" */
3840 return "log_parser_stats";
3841 else if (arg[1] == 'l') /* "planner" */
3842 return "log_planner_stats";
3843 break;
3844
3845 case 'e': /* "executor" */
3846 return "log_executor_stats";
3847 break;
3848 }
3849
3850 return NULL;
3851}
Datum arg
Definition elog.c:1323

References arg, and fb().

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( void  )
extern

Definition at line 3097 of file postgres.c.

3098{
3100 InterruptPending = true;
3101 /* latch will be set by procsignal_sigusr1_handler */
3102}
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
PGPROC * MyProc
Definition proc.c:71
pg_atomic_uint32 pendingRecoveryConflicts
Definition proc.h:270

References InterruptPending, MyProc, PGPROC::pendingRecoveryConflicts, and pg_atomic_read_u32().

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 
)
extern

Definition at line 681 of file postgres.c.

686{
687 Query *query;
689
691
692 /*
693 * (1) Perform parse analysis.
694 */
696 ResetUsage();
697
698 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
699 queryEnv);
700
702 ShowUsage("PARSE ANALYSIS STATISTICS");
703
704 /*
705 * (2) Rewrite the queries, as necessary
706 */
708
710
711 return querytree_list;
712}
bool log_parser_stats
Definition guc_tables.c:548
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition analyze.c:127
List * pg_rewrite_query(Query *query)
Definition postgres.c:814
void ShowUsage(const char *title)
Definition postgres.c:5148
void ResetUsage(void)
Definition postgres.c:5141
Definition pg_list.h:54

References fb(), 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 
)
extern

Definition at line 720 of file postgres.c.

725{
726 Query *query;
728
730
731 /*
732 * (1) Perform parse analysis.
733 */
735 ResetUsage();
736
737 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
738 queryEnv);
739
740 /*
741 * Check all parameter types got determined.
742 */
743 for (int i = 0; i < *numParams; i++)
744 {
745 Oid ptype = (*paramTypes)[i];
746
747 if (ptype == InvalidOid || ptype == UNKNOWNOID)
750 errmsg("could not determine data type of parameter $%d",
751 i + 1)));
752 }
753
755 ShowUsage("PARSE ANALYSIS STATISTICS");
756
757 /*
758 * (2) Rewrite the queries, as necessary
759 */
761
763
764 return querytree_list;
765}
int i
Definition isn.c:77
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition analyze.c:167
#define InvalidOid
unsigned int Oid

References ereport, errcode(), errmsg, ERROR, fb(), 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 
)
extern

Definition at line 774 of file postgres.c.

779{
780 Query *query;
782
784
785 /*
786 * (1) Perform parse analysis.
787 */
789 ResetUsage();
790
791 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
792 queryEnv);
793
795 ShowUsage("PARSE ANALYSIS STATISTICS");
796
797 /*
798 * (2) Rewrite the queries, as necessary
799 */
801
803
804 return querytree_list;
805}
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition analyze.c:208

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

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), inline_sql_function_in_from(), prepare_next_query(), RevalidateCachedQuery(), and test_inline_in_from_support_func().

◆ pg_parse_query()

List * pg_parse_query ( const char query_string)
extern

Definition at line 615 of file postgres.c.

616{
618
620
622 ResetUsage();
623
625
627 ShowUsage("PARSER STATISTICS");
628
629#ifdef DEBUG_NODE_TESTS_ENABLED
630
631 /* Optional debugging check: pass raw parsetrees through copyObject() */
633 {
635
636 /* This checks both copyObject() and the equal() routines... */
638 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
639 else
641 }
642
643 /*
644 * Optional debugging check: pass raw parsetrees through
645 * outfuncs/readfuncs
646 */
648 {
651
652 pfree(str);
653 /* This checks both outfuncs/readfuncs and the equal() routines... */
655 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
656 else
658 }
659
660#endif /* DEBUG_NODE_TESTS_ENABLED */
661
663
665 elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
667
668 return raw_parsetree_list;
669}
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition print.c:72
List * raw_parser(const char *str, RawParseMode mode)
Definition parser.c:42
#define LOG
Definition elog.h:32
#define WARNING
Definition elog.h:37
#define elog(elevel,...)
Definition elog.h:228
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
bool Debug_print_raw_parse
Definition guc_tables.c:538
bool Debug_pretty_print
Definition guc_tables.c:540
const char * str
static List * new_list(NodeTag type, int min_size)
Definition list.c:91
void pfree(void *pointer)
Definition mcxt.c:1616
#define copyObject(obj)
Definition nodes.h:232
char * nodeToStringWithLocations(const void *obj)
Definition outfuncs.c:817
@ RAW_PARSE_DEFAULT
Definition parser.h:39

References copyObject, Debug_pretty_print, Debug_print_raw_parse, elog, elog_node_display(), equal(), fb(), LOG, 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(), inline_function(), inline_sql_function_in_from(), sql_compile_callback(), and test_inline_in_from_support_func().

◆ pg_plan_queries()

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

Definition at line 986 of file postgres.c.

988{
989 List *stmt_list = NIL;
990 ListCell *query_list;
991
992 foreach(query_list, querytrees)
993 {
994 Query *query = lfirst_node(Query, query_list);
996
997 if (query->commandType == CMD_UTILITY)
998 {
999 /* Utility commands require no planning. */
1001 stmt->commandType = CMD_UTILITY;
1002 stmt->canSetTag = query->canSetTag;
1003 stmt->utilityStmt = query->utilityStmt;
1004 stmt->stmt_location = query->stmt_location;
1005 stmt->stmt_len = query->stmt_len;
1006 stmt->queryId = query->queryId;
1007 stmt->planOrigin = PLAN_STMT_INTERNAL;
1008 }
1009 else
1010 {
1011 stmt = pg_plan_query(query, query_string, cursorOptions,
1012 boundParams, NULL);
1013 }
1014
1015 stmt_list = lappend(stmt_list, stmt);
1016 }
1017
1018 return stmt_list;
1019}
#define stmt
List * lappend(List *list, void *datum)
Definition list.c:339
@ CMD_UTILITY
Definition nodes.h:280
#define makeNode(_type_)
Definition nodes.h:161
#define lfirst_node(type, lc)
Definition pg_list.h:176
#define NIL
Definition pg_list.h:68
@ PLAN_STMT_INTERNAL
Definition plannodes.h:38
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition postgres.c:898
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
ParseLoc stmt_location
Definition parsenodes.h:258

References CMD_UTILITY, Query::commandType, fb(), lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PLAN_STMT_INTERNAL, 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,
ExplainState es 
)
extern

Definition at line 898 of file postgres.c.

900{
902
903 /* Utility commands have no plans. */
904 if (querytree->commandType == CMD_UTILITY)
905 return NULL;
906
907 /* Planner must have a snapshot in case it calls user-defined functions. */
909
911
913 ResetUsage();
914
915 /* call the optimizer */
916 plan = planner(querytree, query_string, cursorOptions, boundParams, es);
917
919 ShowUsage("PLANNER STATISTICS");
920
921#ifdef DEBUG_NODE_TESTS_ENABLED
922
923 /* Optional debugging check: pass plan tree through copyObject() */
925 {
927
928 /*
929 * equal() currently does not have routines to compare Plan nodes, so
930 * don't try to test equality here. Perhaps fix someday?
931 */
932#ifdef NOT_USED
933 /* This checks both copyObject() and the equal() routines... */
934 if (!equal(new_plan, plan))
935 elog(WARNING, "copyObject() failed to produce an equal plan tree");
936 else
937#endif
938 plan = new_plan;
939 }
940
941 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
943 {
944 char *str;
946
949 pfree(str);
950
951 /*
952 * equal() currently does not have routines to compare Plan nodes, so
953 * don't try to test equality here. Perhaps fix someday?
954 */
955#ifdef NOT_USED
956 /* This checks both outfuncs/readfuncs and the equal() routines... */
957 if (!equal(new_plan, plan))
958 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
959 else
960#endif
961 plan = new_plan;
962 }
963
964#endif /* DEBUG_NODE_TESTS_ENABLED */
965
966 /*
967 * Print plan if debugging.
968 */
971
973
974 return plan;
975}
Datum querytree(PG_FUNCTION_ARGS)
Definition _int_bool.c:665
#define Assert(condition)
Definition c.h:943
bool Debug_print_plan
Definition guc_tables.c:536
bool log_planner_stats
Definition guc_tables.c:549
#define plan(x)
Definition pg_regress.c:164
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition planner.c:315
bool ActiveSnapshotSet(void)
Definition snapmgr.c:812

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

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

◆ pg_rewrite_query()

List * pg_rewrite_query ( Query query)
extern

Definition at line 814 of file postgres.c.

815{
817
819 elog_node_display(LOG, "parse tree", query,
821
823 ResetUsage();
824
825 if (query->commandType == CMD_UTILITY)
826 {
827 /* don't rewrite utilities, just dump 'em into result list */
828 querytree_list = list_make1(query);
829 }
830 else
831 {
832 /* rewrite regular queries */
834 }
835
837 ShowUsage("REWRITER STATISTICS");
838
839#ifdef DEBUG_NODE_TESTS_ENABLED
840
841 /* Optional debugging check: pass querytree through copyObject() */
843 {
844 List *new_list;
845
847 /* This checks both copyObject() and the equal() routines... */
849 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
850 else
852 }
853
854 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
856 {
857 List *new_list = NIL;
858 ListCell *lc;
859
860 foreach(lc, querytree_list)
861 {
865
866 /*
867 * queryId is not saved in stored rules, but we must preserve it
868 * here to avoid breaking pg_stat_statements.
869 */
870 new_query->queryId = curr_query->queryId;
871
873 pfree(str);
874 }
875
876 /* This checks both outfuncs/readfuncs and the equal() routines... */
878 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
879 else
881 }
882
883#endif /* DEBUG_NODE_TESTS_ENABLED */
884
886 elog_node_display(LOG, "rewritten parse tree", querytree_list,
888
889 return querytree_list;
890}
bool Debug_print_rewritten
Definition guc_tables.c:539
bool Debug_print_parse
Definition guc_tables.c:537
#define list_make1(x1)
Definition pg_list.h:244
List * QueryRewrite(Query *parsetree)

References CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), fb(), 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(), inline_sql_function_in_from(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), pg_analyze_and_rewrite_withcb(), prepare_next_query(), and RevalidateCachedQuery().

◆ PostgresMain()

pg_noreturn void PostgresMain ( const char dbname,
const char username 
)
extern

Definition at line 4273 of file postgres.c.

4274{
4276
4277 /* these must be volatile to ensure state is preserved across longjmp: */
4278 volatile bool send_ready_for_query = true;
4279 volatile bool idle_in_transaction_timeout_enabled = false;
4280 volatile bool idle_session_timeout_enabled = false;
4281
4282 Assert(dbname != NULL);
4283 Assert(username != NULL);
4284
4286
4287 /*
4288 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4289 * has already set up BlockSig and made that the active signal mask.)
4290 *
4291 * Note that postmaster blocked all signals before forking child process,
4292 * so there is no race condition whereby we might receive a signal before
4293 * we have set up the handler.
4294 *
4295 * Also note: it's best not to use any signals that are SIG_IGNored in the
4296 * postmaster. If such a signal arrives before we are able to change the
4297 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4298 * handler in the postmaster to reserve the signal. (Of course, this isn't
4299 * an issue for signals that are locally generated, such as SIGALRM and
4300 * SIGPIPE.)
4301 */
4302 if (am_walsender)
4303 WalSndSignals();
4304 else
4305 {
4307 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4308 pqsignal(SIGTERM, die); /* cancel current query and exit */
4309
4310 /*
4311 * In a postmaster child backend, replace SignalHandlerForCrashExit
4312 * with quickdie, so we can tell the client we're dying.
4313 *
4314 * In a standalone backend, SIGQUIT can be generated from the keyboard
4315 * easily, while SIGTERM cannot, so we make both signals do die()
4316 * rather than quickdie().
4317 */
4319 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4320 else
4321 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4322 InitializeTimeouts(); /* establishes SIGALRM handler */
4323
4324 /*
4325 * Ignore failure to write to frontend. Note: if frontend closes
4326 * connection, we will notice it and exit cleanly when control next
4327 * returns to outer loop. This seems safer than forcing exit in the
4328 * midst of output during who-knows-what operation...
4329 */
4334
4335 /*
4336 * Reset some signals that are accepted by postmaster but not by
4337 * backend
4338 */
4339 pqsignal(SIGCHLD, PG_SIG_DFL); /* system() requires this on some
4340 * platforms */
4341 }
4342
4343 /* Early initialization */
4344 BaseInit();
4345
4346 /* We need to allow SIGINT, etc during the initial transaction */
4348
4349 /*
4350 * Generate a random cancel key, if this is a backend serving a
4351 * connection. InitPostgres() will advertise it in shared memory.
4352 */
4355 {
4356 int len;
4357
4358 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4361 {
4362 ereport(ERROR,
4364 errmsg("could not generate random cancel key")));
4365 }
4367 }
4368
4369 /*
4370 * General initialization.
4371 *
4372 * NOTE: if you are tempted to add code in this vicinity, consider putting
4373 * it inside InitPostgres() instead. In particular, anything that
4374 * involves database access should be there, not here.
4375 *
4376 * Honor session_preload_libraries if not dealing with a WAL sender.
4377 */
4378 InitPostgres(dbname, InvalidOid, /* database to connect to */
4379 username, InvalidOid, /* role to connect as */
4381 NULL); /* no out_dbname */
4382
4383 /*
4384 * If the PostmasterContext is still around, recycle the space; we don't
4385 * need it anymore after InitPostgres completes.
4386 */
4388 {
4391 }
4392
4394
4395 /*
4396 * Now all GUC states are fully set up. Report them to client if
4397 * appropriate.
4398 */
4400
4401 /*
4402 * Also set up handler to log session end; we have to wait till now to be
4403 * sure Log_disconnections has its final value.
4404 */
4407
4409
4410 /* Perform initialization specific to a WAL sender process. */
4411 if (am_walsender)
4412 InitWalSender();
4413
4414 /*
4415 * Send this backend's cancellation info to the frontend.
4416 */
4418 {
4420
4424
4427 /* Need not flush since ReadyForQuery will do it. */
4428 }
4429
4430 /* Welcome banner for standalone case */
4432 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4433
4434 /*
4435 * Create the memory context we will use in the main loop.
4436 *
4437 * MessageContext is reset once per iteration of the main loop, ie, upon
4438 * completion of processing of each command message from the client.
4439 */
4441 "MessageContext",
4443
4444 /*
4445 * Create memory context and buffer used for RowDescription messages. As
4446 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4447 * frequently executed for every single statement, we don't want to
4448 * allocate a separate buffer every time.
4449 */
4451 "RowDescriptionContext",
4456
4457 /* Fire any defined login event triggers, if appropriate */
4459
4460 /*
4461 * POSTGRES main processing loop begins here
4462 *
4463 * If an exception is encountered, processing resumes here so we abort the
4464 * current transaction and start a new one.
4465 *
4466 * You might wonder why this isn't coded as an infinite loop around a
4467 * PG_TRY construct. The reason is that this is the bottom of the
4468 * exception stack, and so with PG_TRY there would be no exception handler
4469 * in force at all during the CATCH part. By leaving the outermost setjmp
4470 * always active, we have at least some chance of recovering from an error
4471 * during error recovery. (If we get into an infinite loop thereby, it
4472 * will soon be stopped by overflow of elog.c's internal state stack.)
4473 *
4474 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4475 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4476 * is essential in case we longjmp'd out of a signal handler on a platform
4477 * where that leaves the signal blocked. It's not redundant with the
4478 * unblock in AbortTransaction() because the latter is only called if we
4479 * were inside a transaction.
4480 */
4481
4482 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4483 {
4484 /*
4485 * NOTE: if you are tempted to add more code in this if-block,
4486 * consider the high probability that it should be in
4487 * AbortTransaction() instead. The only stuff done directly here
4488 * should be stuff that is guaranteed to apply *only* for outer-level
4489 * error recovery, such as adjusting the FE/BE protocol status.
4490 */
4491
4492 /* Since not using PG_TRY, must reset error stack by hand */
4494
4495 /* Prevent interrupts while cleaning up */
4497
4498 /*
4499 * Forget any pending QueryCancel request, since we're returning to
4500 * the idle loop anyway, and cancel any active timeout requests. (In
4501 * future we might want to allow some timeout requests to survive, but
4502 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4503 * we got here because of a query cancel interrupting the SIGALRM
4504 * interrupt handler.) Note in particular that we must clear the
4505 * statement and lock timeout indicators, to prevent any future plain
4506 * query cancels from being misreported as timeouts in case we're
4507 * forgetting a timeout cancel.
4508 */
4509 disable_all_timeouts(false); /* do first to avoid race condition */
4510 QueryCancelPending = false;
4513
4514 /* Not reading from the client anymore. */
4515 DoingCommandRead = false;
4516
4517 /* Make sure libpq is in a good state */
4518 pq_comm_reset();
4519
4520 /* Report the error to the client and/or server log */
4522
4523 /*
4524 * If Valgrind noticed something during the erroneous query, print the
4525 * query string, assuming we have one.
4526 */
4528
4529 /*
4530 * Make sure debug_query_string gets reset before we possibly clobber
4531 * the storage it points at.
4532 */
4534
4535 /*
4536 * Abort the current transaction in order to recover.
4537 */
4539
4540 if (am_walsender)
4542
4544
4545 /*
4546 * We can't release replication slots inside AbortTransaction() as we
4547 * need to be able to start and abort transactions while having a slot
4548 * acquired. But we never need to hold them across top level errors,
4549 * so releasing here is fine. There also is a before_shmem_exit()
4550 * callback ensuring correct cleanup on FATAL errors.
4551 */
4552 if (MyReplicationSlot != NULL)
4554
4555 /* We also want to cleanup temporary slots on error. */
4557
4559
4560 /*
4561 * Now return to normal top-level context and clear ErrorContext for
4562 * next time.
4563 */
4566
4567 /*
4568 * If we were handling an extended-query-protocol message, initiate
4569 * skip till next Sync. This also causes us not to issue
4570 * ReadyForQuery (until we get Sync).
4571 */
4573 ignore_till_sync = true;
4574
4575 /* We don't have a transaction command open anymore */
4576 xact_started = false;
4577
4578 /*
4579 * If an error occurred while we were reading a message from the
4580 * client, we have potentially lost track of where the previous
4581 * message ends and the next one begins. Even though we have
4582 * otherwise recovered from the error, we cannot safely read any more
4583 * messages from the client, so there isn't much we can do with the
4584 * connection anymore.
4585 */
4586 if (pq_is_reading_msg())
4587 ereport(FATAL,
4589 errmsg("terminating connection because protocol synchronization was lost")));
4590
4591 /* Now we can allow interrupts again */
4593 }
4594
4595 /* We can now handle ereport(ERROR) */
4597
4598 if (!ignore_till_sync)
4599 send_ready_for_query = true; /* initially, or after error */
4600
4601 /*
4602 * Non-error queries loop here.
4603 */
4604
4605 for (;;)
4606 {
4607 int firstchar;
4609
4610 /*
4611 * At top of loop, reset extended-query-message flag, so that any
4612 * errors encountered in "idle" state don't provoke skip.
4613 */
4615
4616 /*
4617 * For valgrind reporting purposes, the "current query" begins here.
4618 */
4619#ifdef USE_VALGRIND
4621#endif
4622
4623 /*
4624 * Release storage left over from prior query cycle, and create a new
4625 * query input buffer in the cleared MessageContext.
4626 */
4629
4631
4632 /*
4633 * Also consider releasing our catalog snapshot if any, so that it's
4634 * not preventing advance of global xmin while we wait for the client.
4635 */
4637
4638 /*
4639 * (1) If we've reached idle state, tell the frontend we're ready for
4640 * a new query.
4641 *
4642 * Note: this includes fflush()'ing the last of the prior output.
4643 *
4644 * This is also a good time to flush out collected statistics to the
4645 * cumulative stats system, and to update the PS stats display. We
4646 * avoid doing those every time through the message loop because it'd
4647 * slow down processing of batched messages, and because we don't want
4648 * to report uncommitted updates (that confuses autovacuum). The
4649 * notification processor wants a call too, if we are not in a
4650 * transaction block.
4651 *
4652 * Also, if an idle timeout is enabled, start the timer for that.
4653 */
4655 {
4657 {
4658 set_ps_display("idle in transaction (aborted)");
4660
4661 /* Start the idle-in-transaction timer */
4664 {
4668 }
4669 }
4671 {
4672 set_ps_display("idle in transaction");
4674
4675 /* Start the idle-in-transaction timer */
4678 {
4682 }
4683 }
4684 else
4685 {
4686 long stats_timeout;
4687
4688 /*
4689 * Process incoming notifies (including self-notifies), if
4690 * any, and send relevant messages to the client. Doing it
4691 * here helps ensure stable behavior in tests: if any notifies
4692 * were received during the just-finished transaction, they'll
4693 * be seen by the client before ReadyForQuery is.
4694 */
4697
4698 /*
4699 * Check if we need to report stats. If pgstat_report_stat()
4700 * decides it's too soon to flush out pending stats / lock
4701 * contention prevented reporting, it'll tell us when we
4702 * should try to report stats again (so that stats updates
4703 * aren't unduly delayed if the connection goes idle for a
4704 * long time). We only enable the timeout if we don't already
4705 * have a timeout in progress, because we don't disable the
4706 * timeout below. enable_timeout_after() needs to determine
4707 * the current timestamp, which can have a negative
4708 * performance impact. That's OK because pgstat_report_stat()
4709 * won't have us wake up sooner than a prior call.
4710 */
4712 if (stats_timeout > 0)
4713 {
4717 }
4718 else
4719 {
4720 /* all stats flushed, no need for the timeout */
4723 }
4724
4725 set_ps_display("idle");
4727
4728 /* Start the idle-session timer */
4729 if (IdleSessionTimeout > 0)
4730 {
4734 }
4735 }
4736
4737 /* Report any recently-changed GUC options */
4739
4740 /*
4741 * The first time this backend is ready for query, log the
4742 * durations of the different components of connection
4743 * establishment and setup.
4744 */
4748 {
4752
4754
4764
4765 ereport(LOG,
4766 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4767 (double) total_duration / NS_PER_US,
4768 (double) fork_duration / NS_PER_US,
4769 (double) auth_duration / NS_PER_US));
4770 }
4771
4773 send_ready_for_query = false;
4774 }
4775
4776 /*
4777 * (2) Allow asynchronous signals to be executed immediately if they
4778 * come in while we are waiting for client input. (This must be
4779 * conditional since we don't want, say, reads on behalf of COPY FROM
4780 * STDIN doing the same thing.)
4781 */
4782 DoingCommandRead = true;
4783
4784 /*
4785 * (3) read a command (loop blocks here)
4786 */
4788
4789 /*
4790 * (4) turn off the idle-in-transaction and idle-session timeouts if
4791 * active. We do this before step (5) so that any last-moment timeout
4792 * is certain to be detected in step (5).
4793 *
4794 * At most one of these timeouts will be active, so there's no need to
4795 * worry about combining the timeout.c calls into one.
4796 */
4798 {
4801 }
4803 {
4806 }
4807
4808 /*
4809 * (5) disable async signal conditions again.
4810 *
4811 * Query cancel is supposed to be a no-op when there is no query in
4812 * progress, so if a query cancel arrived while we were idle, just
4813 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4814 * it's called when DoingCommandRead is set, so check for interrupts
4815 * before resetting DoingCommandRead.
4816 */
4818 DoingCommandRead = false;
4819
4820 /*
4821 * (6) check for any other interesting events that happened while we
4822 * slept.
4823 */
4825 {
4826 ConfigReloadPending = false;
4828 }
4829
4830 /*
4831 * (7) process the command. But ignore it if we're skipping till
4832 * Sync.
4833 */
4834 if (ignore_till_sync && firstchar != EOF)
4835 continue;
4836
4837 switch (firstchar)
4838 {
4839 case PqMsg_Query:
4840 {
4841 const char *query_string;
4842
4843 /* Set statement_timestamp() */
4845
4846 query_string = pq_getmsgstring(&input_message);
4848
4849 if (am_walsender)
4850 {
4851 if (!exec_replication_command(query_string))
4852 exec_simple_query(query_string);
4853 }
4854 else
4855 exec_simple_query(query_string);
4856
4857 valgrind_report_error_query(query_string);
4858
4859 send_ready_for_query = true;
4860 }
4861 break;
4862
4863 case PqMsg_Parse:
4864 {
4865 const char *stmt_name;
4866 const char *query_string;
4867 int numParams;
4868 Oid *paramTypes = NULL;
4869
4871
4872 /* Set statement_timestamp() */
4874
4875 stmt_name = pq_getmsgstring(&input_message);
4876 query_string = pq_getmsgstring(&input_message);
4877 numParams = pq_getmsgint(&input_message, 2);
4878 if (numParams > 0)
4879 {
4880 paramTypes = palloc_array(Oid, numParams);
4881 for (int i = 0; i < numParams; i++)
4882 paramTypes[i] = pq_getmsgint(&input_message, 4);
4883 }
4885
4886 exec_parse_message(query_string, stmt_name,
4887 paramTypes, numParams);
4888
4889 valgrind_report_error_query(query_string);
4890 }
4891 break;
4892
4893 case PqMsg_Bind:
4895
4896 /* Set statement_timestamp() */
4898
4899 /*
4900 * this message is complex enough that it seems best to put
4901 * the field extraction out-of-line
4902 */
4904
4905 /* exec_bind_message does valgrind_report_error_query */
4906 break;
4907
4908 case PqMsg_Execute:
4909 {
4910 const char *portal_name;
4911 int max_rows;
4912
4914
4915 /* Set statement_timestamp() */
4917
4921
4923
4924 /* exec_execute_message does valgrind_report_error_query */
4925 }
4926 break;
4927
4928 case PqMsg_FunctionCall:
4930
4931 /* Set statement_timestamp() */
4933
4934 /* Report query to various monitoring facilities. */
4936 set_ps_display("<FASTPATH>");
4937
4938 /* start an xact for this function invocation */
4940
4941 /*
4942 * Note: we may at this point be inside an aborted
4943 * transaction. We can't throw error for that until we've
4944 * finished reading the function-call message, so
4945 * HandleFunctionRequest() must check for it after doing so.
4946 * Be careful not to do anything that assumes we're inside a
4947 * valid transaction here.
4948 */
4949
4950 /* switch back to message context */
4952
4954
4955 /* commit the function-invocation transaction */
4957
4958 valgrind_report_error_query("fastpath function call");
4959
4960 send_ready_for_query = true;
4961 break;
4962
4963 case PqMsg_Close:
4964 {
4965 int close_type;
4966 const char *close_target;
4967
4969
4973
4974 switch (close_type)
4975 {
4976 case 'S':
4977 if (close_target[0] != '\0')
4979 else
4980 {
4981 /* special-case the unnamed statement */
4983 }
4984 break;
4985 case 'P':
4986 {
4987 Portal portal;
4988
4989 portal = GetPortalByName(close_target);
4990 if (PortalIsValid(portal))
4991 PortalDrop(portal, false);
4992 }
4993 break;
4994 default:
4995 ereport(ERROR,
4997 errmsg("invalid CLOSE message subtype %d",
4998 close_type)));
4999 break;
5000 }
5001
5004
5005 valgrind_report_error_query("CLOSE message");
5006 }
5007 break;
5008
5009 case PqMsg_Describe:
5010 {
5011 int describe_type;
5012 const char *describe_target;
5013
5015
5016 /* Set statement_timestamp() (needed for xact) */
5018
5022
5023 switch (describe_type)
5024 {
5025 case 'S':
5027 break;
5028 case 'P':
5030 break;
5031 default:
5032 ereport(ERROR,
5034 errmsg("invalid DESCRIBE message subtype %d",
5035 describe_type)));
5036 break;
5037 }
5038
5039 valgrind_report_error_query("DESCRIBE message");
5040 }
5041 break;
5042
5043 case PqMsg_Flush:
5046 pq_flush();
5047 break;
5048
5049 case PqMsg_Sync:
5051
5052 /*
5053 * If pipelining was used, we may be in an implicit
5054 * transaction block. Close it before calling
5055 * finish_xact_command.
5056 */
5059 valgrind_report_error_query("SYNC message");
5060 send_ready_for_query = true;
5061 break;
5062
5063 /*
5064 * PqMsg_Terminate means that the frontend is closing down the
5065 * socket. EOF means unexpected loss of frontend connection.
5066 * Either way, perform normal shutdown.
5067 */
5068 case EOF:
5069
5070 /* for the cumulative statistics system */
5072
5074
5075 case PqMsg_Terminate:
5076
5077 /*
5078 * Reset whereToSendOutput to prevent ereport from attempting
5079 * to send any more messages to client.
5080 */
5083
5084 /*
5085 * NOTE: if you are tempted to add more code here, DON'T!
5086 * Whatever you had in mind to do should be set up as an
5087 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5088 * it will fail to be called during other backend-shutdown
5089 * scenarios.
5090 */
5091 proc_exit(0);
5092
5093 case PqMsg_CopyData:
5094 case PqMsg_CopyDone:
5095 case PqMsg_CopyFail:
5096
5097 /*
5098 * Accept but ignore these messages, per protocol spec; we
5099 * probably got here because a COPY failed, and the frontend
5100 * is still sending data.
5101 */
5102 break;
5103
5104 default:
5105 ereport(FATAL,
5107 errmsg("invalid frontend message type %d",
5108 firstchar)));
5109 }
5110 } /* end of input-reading loop */
5111}
void ProcessNotifyInterrupt(bool flush)
Definition async.c:2579
volatile sig_atomic_t notifyInterruptPending
Definition async.c:552
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition prepare.c:521
sigset_t UnBlockSig
Definition pqsignal.c:22
uint32 log_connections
ConnectionTiming conn_timing
@ LOG_CONNECTION_SETUP_DURATIONS
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
int32_t int32
Definition c.h:620
uint64_t uint64
Definition c.h:625
#define pg_fallthrough
Definition c.h:161
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
void ReadyForQuery(CommandDest dest)
Definition dest.c:257
@ DestDebug
Definition dest.h:88
@ DestNone
Definition dest.h:87
void EmitErrorReport(void)
Definition elog.c:1883
ErrorContextCallback * error_context_stack
Definition elog.c:100
void FlushErrorState(void)
Definition elog.c:2063
sigjmp_buf * PG_exception_stack
Definition elog.c:102
#define FATAL
Definition elog.h:42
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition fastpath.c:188
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
#define palloc_array(type, count)
Definition fe_memutils.h:76
int MyCancelKeyLength
Definition globals.c:55
int MyProcPid
Definition globals.c:49
bool IsUnderPostmaster
Definition globals.c:122
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
uint8 MyCancelKey[MAX_CANCEL_KEY_LENGTH]
Definition globals.c:54
struct Port * MyProcPort
Definition globals.c:53
Oid MyDatabaseId
Definition globals.c:96
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
void BeginReportingGUCOptions(void)
Definition guc.c:2453
void ReportChangedGUCOptions(void)
Definition guc.c:2503
@ PGC_SIGHUP
Definition guc.h:75
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:316
void proc_exit(int code)
Definition ipc.c:105
void jit_reset_after_error(void)
Definition jit.c:128
#define pq_flush()
Definition libpq.h:49
#define pq_comm_reset()
Definition libpq.h:48
MemoryContext MessageContext
Definition mcxt.c:170
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
MemoryContext TopMemoryContext
Definition mcxt.c:166
MemoryContext PostmasterContext
Definition mcxt.c:168
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138
@ NormalProcessing
Definition miscadmin.h:490
@ InitProcessing
Definition miscadmin.h:489
#define IsExternalConnectionBackend(backend_type)
Definition miscadmin.h:423
#define GetProcessingMode()
Definition miscadmin.h:499
#define INIT_PG_LOAD_SESSION_LIBS
Definition miscadmin.h:517
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
#define SetProcessingMode(mode)
Definition miscadmin.h:501
BackendType MyBackendType
Definition miscinit.c:65
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
const void size_t len
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define die(msg)
long pgstat_report_stat(bool force)
Definition pgstat.c:722
@ DISCONNECT_CLIENT_EOF
Definition pgstat.h:62
void pgstat_report_connect(Oid dboid)
#define pqsignal
Definition port.h:547
bool pg_strong_random(void *buf, size_t len)
#define PG_SIG_IGN
Definition port.h:551
#define printf(...)
Definition port.h:266
#define PG_SIG_DFL
Definition port.h:550
#define PortalIsValid(p)
Definition portal.h:211
void PortalDrop(Portal portal, bool isTopCommit)
Definition portalmem.c:469
Portal GetPortalByName(const char *name)
Definition portalmem.c:132
void PortalErrorCleanup(void)
Definition portalmem.c:919
static void exec_describe_statement_message(const char *stmt_name)
Definition postgres.c:2640
void quickdie(SIGNAL_ARGS)
Definition postgres.c:2926
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5257
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5121
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2121
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3081
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3064
static bool ignore_till_sync
Definition postgres.c:157
static void finish_xact_command(void)
Definition postgres.c:2822
const char * debug_query_string
Definition postgres.c:94
static void exec_simple_query(const char *query_string)
Definition postgres.c:1028
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1405
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1639
static bool xact_started
Definition postgres.c:143
static MemoryContext row_description_context
Definition postgres.c:172
static StringInfoData row_description_buf
Definition postgres.c:173
static bool doing_extended_query_message
Definition postgres.c:156
static void start_xact_command(void)
Definition postgres.c:2783
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2732
bool Log_disconnections
Definition postgres.c:100
static void drop_unnamed_stmt(void)
Definition postgres.c:2901
#define valgrind_report_error_query(query)
Definition postgres.c:228
static int ReadCommand(StringInfo inBuf)
Definition postgres.c:492
void BaseInit(void)
Definition postinit.c:616
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:719
bool pq_is_reading_msg(void)
Definition pqcomm.c:1182
#define PG_PROTOCOL(m, n)
Definition pqcomm.h:89
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition pqformat.c:414
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition pqformat.c:126
void pq_getmsgend(StringInfo msg)
Definition pqformat.c:634
const char * pq_getmsgstring(StringInfo msg)
Definition pqformat.c:578
void pq_putemptymessage(char msgtype)
Definition pqformat.c:387
void pq_endmessage(StringInfo buf)
Definition pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition pqformat.c:398
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:688
#define MAX_CANCEL_KEY_LENGTH
Definition procsignal.h:67
#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
ReplicationSlot * MyReplicationSlot
Definition slot.c:158
void ReplicationSlotRelease(void)
Definition slot.c:769
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:868
void InvalidateCatalogSnapshotConditionally(void)
Definition snapmgr.c:477
int IdleSessionTimeout
Definition proc.c:67
int IdleInTransactionSessionTimeout
Definition proc.c:65
int TransactionTimeout
Definition proc.c:66
char * dbname
Definition streamutil.c:49
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
TimestampTz ready_for_use
TimestampTz auth_start
TimestampTz socket_create
TimestampTz fork_start
ProtocolVersion proto
Definition libpq-be.h:132
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
static uint64 TimestampDifferenceMicroseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.h:90
#define NS_PER_US
Definition uuid.c:33
void WalSndErrorCleanup(void)
Definition walsender.c:370
bool am_walsender
Definition walsender.c:135
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2058
void InitWalSender(void)
Definition walsender.c:323
void WalSndSignals(void)
Definition walsender.c:3892
#define SIGCHLD
Definition win32_port.h:168
#define SIGHUP
Definition win32_port.h:158
#define SIGPIPE
Definition win32_port.h:163
#define SIGQUIT
Definition win32_port.h:159
#define SIGUSR1
Definition win32_port.h:170
#define SIGUSR2
Definition win32_port.h:171
bool IsTransactionOrTransactionBlock(void)
Definition xact.c:5040
bool IsAbortedTransactionBlockState(void)
Definition xact.c:409
void EndImplicitTransactionBlock(void)
Definition xact.c:4402
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916
void AbortCurrentTransaction(void)
Definition xact.c:3501

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert, ConnectionTiming::auth_end, ConnectionTiming::auth_start, BaseInit(), BeginReportingGUCOptions(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, conn_timing, 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(), EndImplicitTransactionBlock(), ereport, errcode(), ERRCODE_PROTOCOL_VIOLATION, 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, fb(), finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), ConnectionTiming::fork_end, ConnectionTiming::fork_start, get_timeout_active(), GetCurrentTimestamp(), 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(), IsExternalConnectionBackend, IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), len, LOG, LOG_CONNECTION_SETUP_DURATIONS, log_connections, Log_disconnections, log_disconnections(), MAX_CANCEL_KEY_LENGTH, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), MessageContext, MyBackendType, MyCancelKey, MyCancelKeyLength, MyDatabaseId, MyProcPid, MyProcPort, MyReplicationSlot, NormalProcessing, notifyInterruptPending, NS_PER_US, on_proc_exit(), palloc_array, PG_exception_stack, pg_fallthrough, PG_PROTOCOL, PG_SIG_DFL, PG_SIG_IGN, pg_strong_random(), 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_sendbytes(), 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(), Port::proto, QueryCancelPending, quickdie(), ReadCommand(), ConnectionTiming::ready_for_use, ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, row_description_buf, row_description_context, set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, ConnectionTiming::socket_create, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TIMESTAMP_MINUS_INFINITY, TimestampDifferenceMicroseconds(), TopMemoryContext, TransactionTimeout, UnBlockSig, username, valgrind_report_error_query, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendMain(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4130 of file postgres.c.

4132{
4133 const char *dbname = NULL;
4134
4136
4137 /* Initialize startup process environment. */
4138 InitStandaloneProcess(argv[0]);
4139
4140 /*
4141 * Set default values for command-line options.
4142 */
4144
4145 /*
4146 * Parse command-line options.
4147 */
4149
4150 /* Must have gotten a database name, or have a default (the username) */
4151 if (dbname == NULL)
4152 {
4153 dbname = username;
4154 if (dbname == NULL)
4155 ereport(FATAL,
4157 errmsg("%s: no database nor user name specified",
4158 progname)));
4159 }
4160
4161 /* Acquire configuration parameters */
4163 proc_exit(1);
4164
4165 /*
4166 * Validate we have been given a reasonable-looking DataDir and change
4167 * into it.
4168 */
4169 checkDataDir();
4171
4172 /*
4173 * Create lockfile for data directory.
4174 */
4175 CreateDataDirLockFile(false);
4176
4177 /* read control file (error checking and contains config ) */
4179
4180 /* Register the shared memory needs of all core subsystems. */
4182
4183 /*
4184 * process any libraries that should be preloaded at postmaster start
4185 */
4187
4188 /* Initialize MaxBackends */
4190
4191 /*
4192 * We don't need postmaster child slots in single-user mode, but
4193 * initialize them anyway to avoid having special handling.
4194 */
4196
4197 /* Initialize size of fast-path lock cache. */
4199
4200 /*
4201 * Also call any legacy shmem request hooks that might'be been installed
4202 * by preloaded libraries.
4203 *
4204 * Note: this must be done before ShmemCallRequestCallbacks(), because the
4205 * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
4206 * turn affects the size of the LWLock array calculated in lwlock.c.
4207 */
4209
4210 /*
4211 * Before computing the total size needed, give all subsystems, including
4212 * add-ins, a chance to chance to adjust their requested shmem sizes.
4213 */
4215
4216 /*
4217 * Now that loadable modules have had their chance to request additional
4218 * shared memory, determine the value of any runtime-computed GUCs that
4219 * depend on the amount of shared memory required.
4220 */
4222
4223 /*
4224 * Now that modules have been loaded, we can process any custom resource
4225 * managers specified in the wal_consistency_checking GUC.
4226 */
4228
4229 /*
4230 * Create shared memory etc. (Nothing's really "shared" in single-user
4231 * mode, but we must have these data structures anyway.)
4232 */
4234
4235 /*
4236 * Estimate number of openable files. This must happen after setting up
4237 * semaphores, because on some platforms semaphores count as open files.
4238 */
4240
4241 /*
4242 * Remember stand-alone backend startup time,roughly at the same point
4243 * during startup that postmaster does so.
4244 */
4246
4247 /*
4248 * Create a per-backend PGPROC struct in shared memory. We must do this
4249 * before we can use LWLocks.
4250 */
4251 InitProcess();
4252
4253 /*
4254 * Now that sufficient infrastructure has been initialized, PostgresMain()
4255 * can do the rest.
4256 */
4258}
TimestampTz PgStartTime
Definition timestamp.c:45
void set_max_safe_fds(void)
Definition fd.c:1045
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition guc.c:1656
void InitializeGUCOptions(void)
Definition guc.c:1408
@ PGC_POSTMASTER
Definition guc.h:74
void RegisterBuiltinShmemCallbacks(void)
Definition ipci.c:168
void InitializeShmemGUCs(void)
Definition ipci.c:189
void CreateSharedMemoryAndSemaphores(void)
Definition ipci.c:120
const char * progname
Definition main.c:44
void ChangeToDataDir(void)
Definition miscinit.c:410
void process_shmem_requests(void)
Definition miscinit.c:1881
void InitStandaloneProcess(const char *argv0)
Definition miscinit.c:176
void process_shared_preload_libraries(void)
Definition miscinit.c:1853
void checkDataDir(void)
Definition miscinit.c:297
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1465
void InitPostmasterChildSlots(void)
Definition pmchild.c:97
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3874
static const char * userDoption
Definition postgres.c:167
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4273
void InitializeMaxBackends(void)
Definition postinit.c:559
void InitializeFastPathLocks(void)
Definition postinit.c:584
void ShmemCallRequestCallbacks(void)
Definition shmem.c:979
void InitProcess(void)
Definition proc.c:392
void InitializeWalConsistencyChecking(void)
Definition xlog.c:5188
void LocalProcessControlFile(bool reset)
Definition xlog.c:5269

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

Referenced by main().

◆ process_postgres_switches()

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

Definition at line 3874 of file postgres.c.

3876{
3877 bool secure = (ctx == PGC_POSTMASTER);
3878 int errs = 0;
3880 int flag;
3882
3883 if (secure)
3884 {
3885 gucsource = PGC_S_ARGV; /* switches came from command line */
3886
3887 /* Ignore the initial --single argument, if present */
3888 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3889 {
3890 argv++;
3891 argc--;
3892 }
3893 }
3894 else
3895 {
3896 gucsource = PGC_S_CLIENT; /* switches came from client */
3897 }
3898
3899 /*
3900 * Parse command-line options. CAUTION: keep this in sync with
3901 * postmaster/postmaster.c (the option sets should not conflict) and with
3902 * the common help() function in main/main.c.
3903 */
3904 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
3905
3906 /*
3907 * Turn this off because it's either printed to stderr and not the log
3908 * where we'd want it, or argv[0] is now "--single", which would make for
3909 * a weird error message. We print our own error message below.
3910 */
3911 optctx.opterr = 0;
3912
3913 while ((flag = pg_getopt_next(&optctx)) != -1)
3914 {
3915 switch (flag)
3916 {
3917 case 'B':
3918 SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
3919 break;
3920
3921 case 'b':
3922 /* Undocumented flag used for binary upgrades */
3923 if (secure)
3924 IsBinaryUpgrade = true;
3925 break;
3926
3927 case 'C':
3928 /* ignored for consistency with the postmaster */
3929 break;
3930
3931 case '-':
3932
3933 /*
3934 * Error if the user misplaced a special must-be-first option
3935 * for dispatching to a subprogram. parse_dispatch_option()
3936 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3937 * error for anything else.
3938 */
3940 ereport(ERROR,
3942 errmsg("--%s must be first argument", optctx.optarg)));
3943
3945 case 'c':
3946 {
3947 char *name,
3948 *value;
3949
3950 ParseLongOption(optctx.optarg, &name, &value);
3951 if (!value)
3952 {
3953 if (flag == '-')
3954 ereport(ERROR,
3956 errmsg("--%s requires a value",
3957 optctx.optarg)));
3958 else
3959 ereport(ERROR,
3961 errmsg("-c %s requires a value",
3962 optctx.optarg)));
3963 }
3965 pfree(name);
3966 pfree(value);
3967 break;
3968 }
3969
3970 case 'D':
3971 if (secure)
3972 userDoption = strdup(optctx.optarg);
3973 break;
3974
3975 case 'd':
3976 set_debug_options(atoi(optctx.optarg), ctx, gucsource);
3977 break;
3978
3979 case 'E':
3980 if (secure)
3981 EchoQuery = true;
3982 break;
3983
3984 case 'e':
3985 SetConfigOption("datestyle", "euro", ctx, gucsource);
3986 break;
3987
3988 case 'F':
3989 SetConfigOption("fsync", "false", ctx, gucsource);
3990 break;
3991
3992 case 'f':
3993 if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
3994 errs++;
3995 break;
3996
3997 case 'h':
3998 SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
3999 break;
4000
4001 case 'i':
4002 SetConfigOption("listen_addresses", "*", ctx, gucsource);
4003 break;
4004
4005 case 'j':
4006 if (secure)
4007 UseSemiNewlineNewline = true;
4008 break;
4009
4010 case 'k':
4011 SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
4012 break;
4013
4014 case 'l':
4015 SetConfigOption("ssl", "true", ctx, gucsource);
4016 break;
4017
4018 case 'N':
4019 SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
4020 break;
4021
4022 case 'n':
4023 /* ignored for consistency with postmaster */
4024 break;
4025
4026 case 'O':
4027 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4028 break;
4029
4030 case 'P':
4031 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4032 break;
4033
4034 case 'p':
4035 SetConfigOption("port", optctx.optarg, ctx, gucsource);
4036 break;
4037
4038 case 'r':
4039 /* send output (stdout and stderr) to the given file */
4040 if (secure)
4042 break;
4043
4044 case 'S':
4045 SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4046 break;
4047
4048 case 's':
4049 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4050 break;
4051
4052 case 'T':
4053 /* ignored for consistency with the postmaster */
4054 break;
4055
4056 case 't':
4057 {
4058 const char *tmp = get_stats_option_name(optctx.optarg);
4059
4060 if (tmp)
4061 SetConfigOption(tmp, "true", ctx, gucsource);
4062 else
4063 errs++;
4064 break;
4065 }
4066
4067 case 'v':
4068
4069 /*
4070 * -v is no longer used in normal operation, since
4071 * FrontendProtocol is already set before we get here. We keep
4072 * the switch only for possible use in standalone operation,
4073 * in case we ever support using normal FE/BE protocol with a
4074 * standalone backend.
4075 */
4076 if (secure)
4078 break;
4079
4080 case 'W':
4081 SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4082 break;
4083
4084 default:
4085 errs++;
4086 break;
4087 }
4088
4089 if (errs)
4090 break;
4091 }
4092
4093 /*
4094 * Optional database name should be there only if *dbname is NULL.
4095 */
4096 if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
4097 *dbname = strdup(argv[optctx.optind++]);
4098
4099 if (errs || argc != optctx.optind)
4100 {
4101 if (errs)
4102 optctx.optind--; /* complain about the previous argument */
4103
4104 /* spell the error message a bit differently depending on context */
4106 ereport(FATAL,
4108 errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4109 errhint("Try \"%s --help\" for more information.", progname));
4110 else
4111 ereport(FATAL,
4113 errmsg("%s: invalid command-line argument: %s",
4114 progname, argv[optctx.optind]),
4115 errhint("Try \"%s --help\" for more information.", progname));
4116 }
4117}
int errhint(const char *fmt,...) pg_attribute_printf(1
bool IsBinaryUpgrade
Definition globals.c:123
ProtocolVersion FrontendProtocol
Definition globals.c:30
char OutputFileName[MAXPGPATH]
Definition globals.c:81
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
void ParseLongOption(const char *string, char **name, char **value)
Definition guc.c:6243
GucSource
Definition guc.h:112
@ PGC_S_ARGV
Definition guc.h:117
@ PGC_S_CLIENT
Definition guc.h:122
static struct @177 value
DispatchOption parse_dispatch_option(const char *name)
Definition main.c:244
#define MAXPGPATH
int pg_getopt_next(pg_getopt_ctx *ctx)
void pg_getopt_start(pg_getopt_ctx *ctx, int nargc, char *const *nargv, const char *ostr)
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:3760
static bool UseSemiNewlineNewline
Definition postgres.c:169
static bool EchoQuery
Definition postgres.c:168
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3792
const char * get_stats_option_name(const char *arg)
Definition postgres.c:3834
@ DISPATCH_POSTMASTER
Definition postmaster.h:139
uint32 ProtocolVersion
Definition pqcomm.h:132
char * flag(int b)
Definition test-ctype.c:33
const char * name

References dbname, DISPATCH_POSTMASTER, EchoQuery, ereport, errcode(), errhint(), errmsg, ERROR, FATAL, fb(), flag(), FrontendProtocol, get_stats_option_name(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, OutputFileName, parse_dispatch_option(), ParseLongOption(), pfree(), pg_fallthrough, pg_getopt_next(), pg_getopt_start(), 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)
extern

Definition at line 513 of file postgres.c.

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

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)
extern

Definition at line 559 of file postgres.c.

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

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

Referenced by secure_write().

◆ quickdie()

pg_noreturn void quickdie ( SIGNAL_ARGS  )
extern

Definition at line 2926 of file postgres.c.

2927{
2928 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2930
2931 /*
2932 * Prevent interrupts while exiting; though we just blocked signals that
2933 * would queue new interrupts, one may have been pending. We don't want a
2934 * quickdie() downgraded to a mere query cancel.
2935 */
2937
2938 /*
2939 * If we're aborting out of client auth, don't risk trying to send
2940 * anything to the client; we will likely violate the protocol, not to
2941 * mention that we may have interrupted the guts of OpenSSL or some
2942 * authentication library.
2943 */
2946
2947 /*
2948 * Notify the client before exiting, to give a clue on what happened.
2949 *
2950 * It's dubious to call ereport() from a signal handler. It is certainly
2951 * not async-signal safe. But it seems better to try, than to disconnect
2952 * abruptly and leave the client wondering what happened. It's remotely
2953 * possible that we crash or hang while trying to send the message, but
2954 * receiving a SIGQUIT is a sign that something has already gone badly
2955 * wrong, so there's not much to lose. Assuming the postmaster is still
2956 * running, it will SIGKILL us soon if we get stuck for some reason.
2957 *
2958 * One thing we can do to make this a tad safer is to clear the error
2959 * context stack, so that context callbacks are not called. That's a lot
2960 * less code that could be reached here, and the context info is unlikely
2961 * to be very relevant to a SIGQUIT report anyway.
2962 */
2964
2965 /*
2966 * When responding to a postmaster-issued signal, we send the message only
2967 * to the client; sending to the server log just creates log spam, plus
2968 * it's more code that we need to hope will work in a signal handler.
2969 *
2970 * Ideally these should be ereport(FATAL), but then we'd not get control
2971 * back to force the correct type of process exit.
2972 */
2973 switch (GetQuitSignalReason())
2974 {
2975 case PMQUIT_NOT_SENT:
2976 /* Hmm, SIGQUIT arrived out of the blue */
2979 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2980 break;
2981 case PMQUIT_FOR_CRASH:
2982 /* A crash-and-restart cycle is in progress */
2985 errmsg("terminating connection because of crash of another server process"),
2986 errdetail("The postmaster has commanded this server process to roll back"
2987 " the current transaction and exit, because another"
2988 " server process exited abnormally and possibly corrupted"
2989 " shared memory."),
2990 errhint("In a moment you should be able to reconnect to the"
2991 " database and repeat your command.")));
2992 break;
2993 case PMQUIT_FOR_STOP:
2994 /* Immediate-mode stop */
2997 errmsg("terminating connection due to immediate shutdown command")));
2998 break;
2999 }
3000
3001 /*
3002 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
3003 * because shared memory may be corrupted, so we don't want to try to
3004 * clean up our transaction. Just nail the windows shut and get out of
3005 * town. The callbacks wouldn't be safe to run from a signal handler,
3006 * anyway.
3007 *
3008 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
3009 * a system reset cycle if someone sends a manual SIGQUIT to a random
3010 * backend. This is necessary precisely because we don't clean up our
3011 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3012 * should ensure the postmaster sees this as a crash, too, but no harm in
3013 * being doubly sure.)
3014 */
3015 _exit(2);
3016}
sigset_t BlockSig
Definition pqsignal.c:23
#define WARNING_CLIENT_ONLY
Definition elog.h:39
QuitSignalReason GetQuitSignalReason(void)
Definition pmsignal.c:212
@ PMQUIT_FOR_STOP
Definition pmsignal.h:57
@ PMQUIT_FOR_CRASH
Definition pmsignal.h:56
@ PMQUIT_NOT_SENT
Definition pmsignal.h:55
bool ClientAuthInProgress
Definition postmaster.c:374

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

Referenced by PostgresMain().

◆ ResetUsage()

◆ set_debug_options()

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

Definition at line 3760 of file postgres.c.

3761{
3762 if (debug_flag > 0)
3763 {
3764 char debugstr[64];
3765
3766 sprintf(debugstr, "debug%d", debug_flag);
3767 SetConfigOption("log_min_messages", debugstr, context, source);
3768 }
3769 else
3770 SetConfigOption("log_min_messages", "notice", context, source);
3771
3772 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3773 {
3774 SetConfigOption("log_connections", "all", context, source);
3775 SetConfigOption("log_disconnections", "true", context, source);
3776 }
3777 if (debug_flag >= 2)
3778 SetConfigOption("log_statement", "all", context, source);
3779 if (debug_flag >= 3)
3780 {
3781 SetConfigOption("debug_print_raw_parse", "true", context, source);
3782 SetConfigOption("debug_print_parse", "true", context, source);
3783 }
3784 if (debug_flag >= 4)
3785 SetConfigOption("debug_print_plan", "true", context, source);
3786 if (debug_flag >= 5)
3787 SetConfigOption("debug_print_rewritten", "true", context, source);
3788}
static rewind_source * source
Definition pg_rewind.c:89
#define sprintf
Definition port.h:262

References fb(), 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 
)
extern

Definition at line 3792 of file postgres.c.

3793{
3794 const char *tmp = NULL;
3795
3796 switch (arg[0])
3797 {
3798 case 's': /* seqscan */
3799 tmp = "enable_seqscan";
3800 break;
3801 case 'i': /* indexscan */
3802 tmp = "enable_indexscan";
3803 break;
3804 case 'o': /* indexonlyscan */
3805 tmp = "enable_indexonlyscan";
3806 break;
3807 case 'b': /* bitmapscan */
3808 tmp = "enable_bitmapscan";
3809 break;
3810 case 't': /* tidscan */
3811 tmp = "enable_tidscan";
3812 break;
3813 case 'n': /* nestloop */
3814 tmp = "enable_nestloop";
3815 break;
3816 case 'm': /* mergejoin */
3817 tmp = "enable_mergejoin";
3818 break;
3819 case 'h': /* hashjoin */
3820 tmp = "enable_hashjoin";
3821 break;
3822 }
3823 if (tmp)
3824 {
3825 SetConfigOption(tmp, "false", context, source);
3826 return true;
3827 }
3828 else
3829 return false;
3830}

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char title)
extern

Definition at line 5148 of file postgres.c.

5149{
5151 struct timeval user,
5152 sys;
5153 struct timeval elapse_t;
5154 struct rusage r;
5155
5158 memcpy(&user, &r.ru_utime, sizeof(user));
5159 memcpy(&sys, &r.ru_stime, sizeof(sys));
5160 if (elapse_t.tv_usec < Save_t.tv_usec)
5161 {
5162 elapse_t.tv_sec--;
5163 elapse_t.tv_usec += 1000000;
5164 }
5165 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5166 {
5167 r.ru_utime.tv_sec--;
5168 r.ru_utime.tv_usec += 1000000;
5169 }
5170 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5171 {
5172 r.ru_stime.tv_sec--;
5173 r.ru_stime.tv_usec += 1000000;
5174 }
5175
5176 /*
5177 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5178 * some work to interpret them, and most platforms don't fill them in.
5179 */
5181
5182 appendStringInfoString(&str, "! system usage stats:\n");
5184 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5185 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5186 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5187 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5188 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5189 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5190 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5192 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5193 (long) user.tv_sec,
5194 (long) user.tv_usec,
5195 (long) sys.tv_sec,
5196 (long) sys.tv_usec);
5197#ifndef WIN32
5198
5199 /*
5200 * The following rusage fields are not defined by POSIX, but they're
5201 * present on all current Unix-like systems so we use them without any
5202 * special checks. Some of these could be provided in our Windows
5203 * emulation in src/port/win32getrusage.c with more work.
5204 */
5206 "!\t%ld kB max resident size\n",
5208 /* in bytes on macOS */
5209 r.ru_maxrss / 1024
5210#else
5211 /* in kilobytes on most other platforms */
5212 r.ru_maxrss
5213#endif
5214 );
5216 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5217 r.ru_inblock - Save_r.ru_inblock,
5218 /* they only drink coffee at dec */
5219 r.ru_oublock - Save_r.ru_oublock,
5220 r.ru_inblock, r.ru_oublock);
5222 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5223 r.ru_majflt - Save_r.ru_majflt,
5224 r.ru_minflt - Save_r.ru_minflt,
5225 r.ru_majflt, r.ru_minflt,
5226 r.ru_nswap - Save_r.ru_nswap,
5227 r.ru_nswap);
5229 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5230 r.ru_nsignals - Save_r.ru_nsignals,
5231 r.ru_nsignals,
5232 r.ru_msgrcv - Save_r.ru_msgrcv,
5233 r.ru_msgsnd - Save_r.ru_msgsnd,
5234 r.ru_msgrcv, r.ru_msgsnd);
5236 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5237 r.ru_nvcsw - Save_r.ru_nvcsw,
5238 r.ru_nivcsw - Save_r.ru_nivcsw,
5239 r.ru_nvcsw, r.ru_nivcsw);
5240#endif /* !WIN32 */
5241
5242 /* remove trailing newline */
5243 if (str.data[str.len - 1] == '\n')
5244 str.data[--str.len] = '\0';
5245
5246 ereport(LOG,
5247 (errmsg_internal("%s", title),
5248 errdetail_internal("%s", str.data)));
5249
5250 pfree(str.data);
5251}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define __darwin__
Definition darwin.h:3
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
static char * user
Definition pg_regress.c:121
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
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(), fb(), getrusage(), gettimeofday(), initStringInfo(), LOG, memcpy(), 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  )
extern

Definition at line 3064 of file postgres.c.

3065{
3066 /*
3067 * Don't joggle the elbow of proc_exit
3068 */
3070 {
3071 InterruptPending = true;
3072 QueryCancelPending = true;
3073 }
3074
3075 /* If we're still here, waken anything waiting on the process latch */
3077}

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

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

Variable Documentation

◆ client_connection_check_interval

PGDLLIMPORT int client_connection_check_interval
extern

Definition at line 108 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ Log_disconnections

PGDLLIMPORT bool Log_disconnections
extern

Definition at line 100 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 102 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ restrict_nonsystem_relation_kind

◆ whereToSendOutput