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

2479{
2482 {
2483 long secs;
2484 int usecs;
2485 int msecs;
2486 bool exceeded_duration;
2488 bool in_sample = false;
2489
2492 &secs, &usecs);
2493 msecs = usecs / 1000;
2494
2495 /*
2496 * This odd-looking test for log_min_duration_* being exceeded is
2497 * designed to avoid integer overflow with very long durations: don't
2498 * compute secs * 1000 until we've verified it will fit in int.
2499 */
2502 (secs > log_min_duration_statement / 1000 ||
2503 secs * 1000 + msecs >= log_min_duration_statement)));
2504
2507 (secs > log_min_duration_sample / 1000 ||
2508 secs * 1000 + msecs >= log_min_duration_sample)));
2509
2510 /*
2511 * Do not log if log_statement_sample_rate = 0. Log a sample if
2512 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2513 * log_statement_sample_rate = 1.
2514 */
2519
2521 {
2522 snprintf(msec_str, 32, "%ld.%03d",
2523 secs * 1000 + msecs, usecs % 1000);
2525 return 2;
2526 else
2527 return 1;
2528 }
2529 }
2530
2531 return 0;
2532}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1729
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
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:575
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:261
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 3114 of file postgres.c.

3115{
3116 /* Don't joggle the elbow of proc_exit */
3118 {
3119 InterruptPending = true;
3120 ProcDiePending = true;
3121
3122 /*
3123 * Record who sent the signal. Will be 0 on platforms without
3124 * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
3125 * Only set on the first SIGTERM so we report the original sender.
3126 */
3127 if (ProcDieSenderPid == 0)
3128 {
3131 }
3132 }
3133
3134 /* for the cumulative stats system */
3136
3137 /* If we're still here, waken anything waiting on the process latch */
3139
3140 /*
3141 * If we're in single user mode, we want to quit immediately - we can't
3142 * rely on latches as they wouldn't work when stdin/stdout is a file.
3143 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3144 * effort just for the benefit of single user mode.
3145 */
3148}
@ 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:151
void ProcessInterrupts(void)
Definition postgres.c:3452

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

3173{
3174 /* We're not returning, so no need to save errno */
3175 ereport(ERROR,
3177 errmsg("floating-point exception"),
3178 errdetail("An invalid floating-point operation was signaled. "
3179 "This probably means an out-of-range result or an "
3180 "invalid operation, such as division by zero.")));
3181}
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 3925 of file postgres.c.

3926{
3927 switch (arg[0])
3928 {
3929 case 'p':
3930 if (arg[1] == 'a') /* "parser" */
3931 return "log_parser_stats";
3932 else if (arg[1] == 'l') /* "planner" */
3933 return "log_planner_stats";
3934 break;
3935
3936 case 'e': /* "executor" */
3937 return "log_executor_stats";
3938 break;
3939 }
3940
3941 return NULL;
3942}
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 3188 of file postgres.c.

3189{
3191 InterruptPending = true;
3192 /* latch will be set by procsignal_sigusr1_handler */
3193}
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:232
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 683 of file postgres.c.

688{
689 Query *query;
691
693
694 /*
695 * (1) Perform parse analysis.
696 */
698 ResetUsage();
699
700 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
701 queryEnv);
702
704 ShowUsage("PARSE ANALYSIS STATISTICS");
705
706 /*
707 * (2) Rewrite the queries, as necessary
708 */
710
712
713 return querytree_list;
714}
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:128
List * pg_rewrite_query(Query *query)
Definition postgres.c:816
void ShowUsage(const char *title)
Definition postgres.c:5239
void ResetUsage(void)
Definition postgres.c:5232
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 722 of file postgres.c.

727{
728 Query *query;
730
732
733 /*
734 * (1) Perform parse analysis.
735 */
737 ResetUsage();
738
739 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
740 queryEnv);
741
742 /*
743 * Check all parameter types got determined.
744 */
745 for (int i = 0; i < *numParams; i++)
746 {
747 Oid ptype = (*paramTypes)[i];
748
749 if (ptype == InvalidOid || ptype == UNKNOWNOID)
752 errmsg("could not determine data type of parameter $%d",
753 i + 1)));
754 }
755
757 ShowUsage("PARSE ANALYSIS STATISTICS");
758
759 /*
760 * (2) Rewrite the queries, as necessary
761 */
763
765
766 return querytree_list;
767}
int i
Definition isn.c:77
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition analyze.c:168
#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 776 of file postgres.c.

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

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

618{
620
622
624 ResetUsage();
625
627
629 ShowUsage("PARSER STATISTICS");
630
631#ifdef DEBUG_NODE_TESTS_ENABLED
632
633 /* Optional debugging check: pass raw parsetrees through copyObject() */
635 {
637
638 /* This checks both copyObject() and the equal() routines... */
640 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
641 else
643 }
644
645 /*
646 * Optional debugging check: pass raw parsetrees through
647 * outfuncs/readfuncs
648 */
650 {
653
654 pfree(str);
655 /* This checks both outfuncs/readfuncs and the equal() routines... */
657 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
658 else
660 }
661
662#endif /* DEBUG_NODE_TESTS_ENABLED */
663
665
667 elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
669
670 return raw_parsetree_list;
671}
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:1619
#define copyObject(obj)
Definition nodes.h:230
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 988 of file postgres.c.

990{
991 List *stmt_list = NIL;
992 ListCell *query_list;
993
994 foreach(query_list, querytrees)
995 {
996 Query *query = lfirst_node(Query, query_list);
998
999 if (query->commandType == CMD_UTILITY)
1000 {
1001 /* Utility commands require no planning. */
1003 stmt->commandType = CMD_UTILITY;
1004 stmt->canSetTag = query->canSetTag;
1005 stmt->utilityStmt = query->utilityStmt;
1006 stmt->stmt_location = query->stmt_location;
1007 stmt->stmt_len = query->stmt_len;
1008 stmt->queryId = query->queryId;
1009 stmt->planOrigin = PLAN_STMT_INTERNAL;
1010 }
1011 else
1012 {
1013 stmt = pg_plan_query(query, query_string, cursorOptions,
1014 boundParams, NULL);
1015 }
1016
1017 stmt_list = lappend(stmt_list, stmt);
1018 }
1019
1020 return stmt_list;
1021}
#define stmt
List * lappend(List *list, void *datum)
Definition list.c:339
@ CMD_UTILITY
Definition nodes.h:278
#define makeNode(_type_)
Definition nodes.h:159
#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:900
CmdType commandType
Definition parsenodes.h:124
Node * utilityStmt
Definition parsenodes.h:144
ParseLoc stmt_location
Definition parsenodes.h:259

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

902{
904
905 /* Utility commands have no plans. */
906 if (querytree->commandType == CMD_UTILITY)
907 return NULL;
908
909 /* Planner must have a snapshot in case it calls user-defined functions. */
911
913
915 ResetUsage();
916
917 /* call the optimizer */
918 plan = planner(querytree, query_string, cursorOptions, boundParams, es);
919
921 ShowUsage("PLANNER STATISTICS");
922
923#ifdef DEBUG_NODE_TESTS_ENABLED
924
925 /* Optional debugging check: pass plan tree through copyObject() */
927 {
929
930 /*
931 * equal() currently does not have routines to compare Plan nodes, so
932 * don't try to test equality here. Perhaps fix someday?
933 */
934#ifdef NOT_USED
935 /* This checks both copyObject() and the equal() routines... */
936 if (!equal(new_plan, plan))
937 elog(WARNING, "copyObject() failed to produce an equal plan tree");
938 else
939#endif
940 plan = new_plan;
941 }
942
943 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
945 {
946 char *str;
948
951 pfree(str);
952
953 /*
954 * equal() currently does not have routines to compare Plan nodes, so
955 * don't try to test equality here. Perhaps fix someday?
956 */
957#ifdef NOT_USED
958 /* This checks both outfuncs/readfuncs and the equal() routines... */
959 if (!equal(new_plan, plan))
960 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
961 else
962#endif
963 plan = new_plan;
964 }
965
966#endif /* DEBUG_NODE_TESTS_ENABLED */
967
968 /*
969 * Print plan if debugging.
970 */
973
975
976 return plan;
977}
Datum querytree(PG_FUNCTION_ARGS)
Definition _int_bool.c:711
#define Assert(condition)
Definition c.h:1002
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:328
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 816 of file postgres.c.

817{
819
821 elog_node_display(LOG, "parse tree", query,
823
825 ResetUsage();
826
827 if (query->commandType == CMD_UTILITY)
828 {
829 /* don't rewrite utilities, just dump 'em into result list */
830 querytree_list = list_make1(query);
831 }
832 else
833 {
834 /* rewrite regular queries */
836 }
837
839 ShowUsage("REWRITER STATISTICS");
840
841#ifdef DEBUG_NODE_TESTS_ENABLED
842
843 /* Optional debugging check: pass querytree through copyObject() */
845 {
846 List *new_list;
847
849 /* This checks both copyObject() and the equal() routines... */
851 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
852 else
854 }
855
856 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
858 {
859 List *new_list = NIL;
860 ListCell *lc;
861
862 foreach(lc, querytree_list)
863 {
867
868 /*
869 * queryId is not saved in stored rules, but we must preserve it
870 * here to avoid breaking pg_stat_statements.
871 */
872 new_query->queryId = curr_query->queryId;
873
875 pfree(str);
876 }
877
878 /* This checks both outfuncs/readfuncs and the equal() routines... */
880 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
881 else
883 }
884
885#endif /* DEBUG_NODE_TESTS_ENABLED */
886
888 elog_node_display(LOG, "rewritten parse tree", querytree_list,
890
891 return querytree_list;
892}
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 4364 of file postgres.c.

4365{
4367
4368 /* these must be volatile to ensure state is preserved across longjmp: */
4369 volatile bool send_ready_for_query = true;
4370 volatile bool idle_in_transaction_timeout_enabled = false;
4371 volatile bool idle_session_timeout_enabled = false;
4372
4373 Assert(dbname != NULL);
4374 Assert(username != NULL);
4375
4377
4378 /*
4379 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4380 * has already set up BlockSig and made that the active signal mask.)
4381 *
4382 * Note that postmaster blocked all signals before forking child process,
4383 * so there is no race condition whereby we might receive a signal before
4384 * we have set up the handler.
4385 *
4386 * Also note: it's best not to use any signals that are SIG_IGNored in the
4387 * postmaster. If such a signal arrives before we are able to change the
4388 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4389 * handler in the postmaster to reserve the signal. (Of course, this isn't
4390 * an issue for signals that are locally generated, such as SIGALRM and
4391 * SIGPIPE.)
4392 */
4393 if (am_walsender)
4394 WalSndSignals();
4395 else
4396 {
4398 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4399 pqsignal(SIGTERM, die); /* cancel current query and exit */
4400
4401 /*
4402 * In a postmaster child backend, replace SignalHandlerForCrashExit
4403 * with quickdie, so we can tell the client we're dying.
4404 *
4405 * In a standalone backend, SIGQUIT can be generated from the keyboard
4406 * easily, while SIGTERM cannot, so we make both signals do die()
4407 * rather than quickdie().
4408 */
4410 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4411 else
4412 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4413 InitializeTimeouts(); /* establishes SIGALRM handler */
4414
4415 /*
4416 * Ignore failure to write to frontend. Note: if frontend closes
4417 * connection, we will notice it and exit cleanly when control next
4418 * returns to outer loop. This seems safer than forcing exit in the
4419 * midst of output during who-knows-what operation...
4420 */
4425
4426 /*
4427 * Reset some signals that are accepted by postmaster but not by
4428 * backend
4429 */
4430 pqsignal(SIGCHLD, PG_SIG_DFL); /* system() requires this on some
4431 * platforms */
4432 }
4433
4434 /* Early initialization */
4435 BaseInit();
4436
4437 /* We need to allow SIGINT, etc during the initial transaction */
4439
4440 /*
4441 * Generate a random cancel key, if this is a backend serving a
4442 * connection. InitPostgres() will advertise it in shared memory.
4443 */
4446 {
4447 int len;
4448
4449 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4452 {
4453 ereport(ERROR,
4455 errmsg("could not generate random cancel key")));
4456 }
4458 }
4459
4460 /*
4461 * General initialization.
4462 *
4463 * NOTE: if you are tempted to add code in this vicinity, consider putting
4464 * it inside InitPostgres() instead. In particular, anything that
4465 * involves database access should be there, not here.
4466 *
4467 * Honor session_preload_libraries if not dealing with a WAL sender.
4468 */
4469 InitPostgres(dbname, InvalidOid, /* database to connect to */
4470 username, InvalidOid, /* role to connect as */
4472 NULL); /* no out_dbname */
4473
4474 /*
4475 * If the PostmasterContext is still around, recycle the space; we don't
4476 * need it anymore after InitPostgres completes.
4477 */
4479 {
4482 }
4483
4485
4486 /*
4487 * Now all GUC states are fully set up. Report them to client if
4488 * appropriate.
4489 */
4491
4492 /*
4493 * Also set up handler to log session end; we have to wait till now to be
4494 * sure Log_disconnections has its final value.
4495 */
4498
4500
4501 /* Perform initialization specific to a WAL sender process. */
4502 if (am_walsender)
4503 InitWalSender();
4504
4505 /*
4506 * Send this backend's cancellation info to the frontend.
4507 */
4509 {
4511
4515
4518 /* Need not flush since ReadyForQuery will do it. */
4519 }
4520
4521 /* Welcome banner for standalone case */
4523 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4524
4525 /*
4526 * Create the memory context we will use in the main loop.
4527 *
4528 * MessageContext is reset once per iteration of the main loop, ie, upon
4529 * completion of processing of each command message from the client.
4530 */
4532 "MessageContext",
4534
4535 /*
4536 * Create memory context and buffer used for RowDescription messages. As
4537 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4538 * frequently executed for every single statement, we don't want to
4539 * allocate a separate buffer every time.
4540 */
4542 "RowDescriptionContext",
4547
4548 /* Fire any defined login event triggers, if appropriate */
4550
4551 /*
4552 * POSTGRES main processing loop begins here
4553 *
4554 * If an exception is encountered, processing resumes here so we abort the
4555 * current transaction and start a new one.
4556 *
4557 * You might wonder why this isn't coded as an infinite loop around a
4558 * PG_TRY construct. The reason is that this is the bottom of the
4559 * exception stack, and so with PG_TRY there would be no exception handler
4560 * in force at all during the CATCH part. By leaving the outermost setjmp
4561 * always active, we have at least some chance of recovering from an error
4562 * during error recovery. (If we get into an infinite loop thereby, it
4563 * will soon be stopped by overflow of elog.c's internal state stack.)
4564 *
4565 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4566 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4567 * is essential in case we longjmp'd out of a signal handler on a platform
4568 * where that leaves the signal blocked. It's not redundant with the
4569 * unblock in AbortTransaction() because the latter is only called if we
4570 * were inside a transaction.
4571 */
4572
4573 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4574 {
4575 /*
4576 * NOTE: if you are tempted to add more code in this if-block,
4577 * consider the high probability that it should be in
4578 * AbortTransaction() instead. The only stuff done directly here
4579 * should be stuff that is guaranteed to apply *only* for outer-level
4580 * error recovery, such as adjusting the FE/BE protocol status.
4581 */
4582
4583 /* Since not using PG_TRY, must reset error stack by hand */
4585
4586 /* Prevent interrupts while cleaning up */
4588
4589 /*
4590 * Forget any pending QueryCancel request, since we're returning to
4591 * the idle loop anyway, and cancel any active timeout requests. (In
4592 * future we might want to allow some timeout requests to survive, but
4593 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4594 * we got here because of a query cancel interrupting the SIGALRM
4595 * interrupt handler.) Note in particular that we must clear the
4596 * statement and lock timeout indicators, to prevent any future plain
4597 * query cancels from being misreported as timeouts in case we're
4598 * forgetting a timeout cancel.
4599 */
4600 disable_all_timeouts(false); /* do first to avoid race condition */
4601 QueryCancelPending = false;
4604
4605 /* Not reading from the client anymore. */
4606 DoingCommandRead = false;
4607
4608 /* Make sure libpq is in a good state */
4609 pq_comm_reset();
4610
4611 /* Report the error to the client and/or server log */
4613
4614 /*
4615 * If Valgrind noticed something during the erroneous query, print the
4616 * query string, assuming we have one.
4617 */
4619
4620 /*
4621 * Make sure debug_query_string gets reset before we possibly clobber
4622 * the storage it points at.
4623 */
4625
4626 /*
4627 * Abort the current transaction in order to recover.
4628 */
4630
4631 if (am_walsender)
4633
4635
4636 /*
4637 * We can't release replication slots inside AbortTransaction() as we
4638 * need to be able to start and abort transactions while having a slot
4639 * acquired. But we never need to hold them across top level errors,
4640 * so releasing here is fine. There also is a before_shmem_exit()
4641 * callback ensuring correct cleanup on FATAL errors.
4642 */
4643 if (MyReplicationSlot != NULL)
4645
4646 /* We also want to cleanup temporary slots on error. */
4648
4650
4651 /*
4652 * Now return to normal top-level context and clear ErrorContext for
4653 * next time.
4654 */
4657
4658 /*
4659 * If we were handling an extended-query-protocol message, initiate
4660 * skip till next Sync. This also causes us not to issue
4661 * ReadyForQuery (until we get Sync).
4662 */
4664 ignore_till_sync = true;
4665
4666 /* We don't have a transaction command open anymore */
4667 xact_started = false;
4668
4669 /*
4670 * If an error occurred while we were reading a message from the
4671 * client, we have potentially lost track of where the previous
4672 * message ends and the next one begins. Even though we have
4673 * otherwise recovered from the error, we cannot safely read any more
4674 * messages from the client, so there isn't much we can do with the
4675 * connection anymore.
4676 */
4677 if (pq_is_reading_msg())
4678 ereport(FATAL,
4680 errmsg("terminating connection because protocol synchronization was lost")));
4681
4682 /* Now we can allow interrupts again */
4684 }
4685
4686 /* We can now handle ereport(ERROR) */
4688
4689 if (!ignore_till_sync)
4690 send_ready_for_query = true; /* initially, or after error */
4691
4692 /*
4693 * Non-error queries loop here.
4694 */
4695
4696 for (;;)
4697 {
4698 int firstchar;
4700
4701 /*
4702 * At top of loop, reset extended-query-message flag, so that any
4703 * errors encountered in "idle" state don't provoke skip.
4704 */
4706
4707 /*
4708 * For valgrind reporting purposes, the "current query" begins here.
4709 */
4710#ifdef USE_VALGRIND
4712#endif
4713
4714 /*
4715 * Release storage left over from prior query cycle, and create a new
4716 * query input buffer in the cleared MessageContext.
4717 */
4720
4722
4723 /*
4724 * Also consider releasing our catalog snapshot if any, so that it's
4725 * not preventing advance of global xmin while we wait for the client.
4726 */
4728
4729 /*
4730 * (1) If we've reached idle state, tell the frontend we're ready for
4731 * a new query.
4732 *
4733 * Note: this includes fflush()'ing the last of the prior output.
4734 *
4735 * This is also a good time to flush out collected statistics to the
4736 * cumulative stats system, and to update the PS stats display. We
4737 * avoid doing those every time through the message loop because it'd
4738 * slow down processing of batched messages, and because we don't want
4739 * to report uncommitted updates (that confuses autovacuum). The
4740 * notification processor wants a call too, if we are not in a
4741 * transaction block.
4742 *
4743 * Also, if an idle timeout is enabled, start the timer for that.
4744 */
4746 {
4748 {
4749 set_ps_display("idle in transaction (aborted)");
4751
4752 /* Start the idle-in-transaction timer */
4755 {
4759 }
4760 }
4762 {
4763 set_ps_display("idle in transaction");
4765
4766 /* Start the idle-in-transaction timer */
4769 {
4773 }
4774 }
4775 else
4776 {
4777 long stats_timeout;
4778
4779 /*
4780 * Process incoming notifies (including self-notifies), if
4781 * any, and send relevant messages to the client. Doing it
4782 * here helps ensure stable behavior in tests: if any notifies
4783 * were received during the just-finished transaction, they'll
4784 * be seen by the client before ReadyForQuery is.
4785 */
4788
4789 /*
4790 * Check if we need to report stats. If pgstat_report_stat()
4791 * decides it's too soon to flush out pending stats / lock
4792 * contention prevented reporting, it'll tell us when we
4793 * should try to report stats again (so that stats updates
4794 * aren't unduly delayed if the connection goes idle for a
4795 * long time). We only enable the timeout if we don't already
4796 * have a timeout in progress, because we don't disable the
4797 * timeout below. enable_timeout_after() needs to determine
4798 * the current timestamp, which can have a negative
4799 * performance impact. That's OK because pgstat_report_stat()
4800 * won't have us wake up sooner than a prior call.
4801 */
4803 if (stats_timeout > 0)
4804 {
4808 }
4809 else
4810 {
4811 /* all stats flushed, no need for the timeout */
4814 }
4815
4816 set_ps_display("idle");
4818
4819 /* Start the idle-session timer */
4820 if (IdleSessionTimeout > 0)
4821 {
4825 }
4826 }
4827
4828 /* Report any recently-changed GUC options */
4830
4831 /*
4832 * The first time this backend is ready for query, log the
4833 * durations of the different components of connection
4834 * establishment and setup.
4835 */
4839 {
4843
4845
4855
4856 ereport(LOG,
4857 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4858 (double) total_duration / NS_PER_US,
4859 (double) fork_duration / NS_PER_US,
4860 (double) auth_duration / NS_PER_US));
4861 }
4862
4864 send_ready_for_query = false;
4865 }
4866
4867 /*
4868 * (2) Allow asynchronous signals to be executed immediately if they
4869 * come in while we are waiting for client input. (This must be
4870 * conditional since we don't want, say, reads on behalf of COPY FROM
4871 * STDIN doing the same thing.)
4872 */
4873 DoingCommandRead = true;
4874
4875 /*
4876 * (3) read a command (loop blocks here)
4877 */
4879
4880 /*
4881 * (4) turn off the idle-in-transaction and idle-session timeouts if
4882 * active. We do this before step (5) so that any last-moment timeout
4883 * is certain to be detected in step (5).
4884 *
4885 * At most one of these timeouts will be active, so there's no need to
4886 * worry about combining the timeout.c calls into one.
4887 */
4889 {
4892 }
4894 {
4897 }
4898
4899 /*
4900 * (5) disable async signal conditions again.
4901 *
4902 * Query cancel is supposed to be a no-op when there is no query in
4903 * progress, so if a query cancel arrived while we were idle, just
4904 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4905 * it's called when DoingCommandRead is set, so check for interrupts
4906 * before resetting DoingCommandRead.
4907 */
4909 DoingCommandRead = false;
4910
4911 /*
4912 * (6) check for any other interesting events that happened while we
4913 * slept.
4914 */
4916 {
4917 ConfigReloadPending = false;
4919 }
4920
4921 /*
4922 * (7) process the command. But ignore it if we're skipping till
4923 * Sync.
4924 */
4925 if (ignore_till_sync && firstchar != EOF)
4926 continue;
4927
4928 switch (firstchar)
4929 {
4930 case PqMsg_Query:
4931 {
4932 const char *query_string;
4933
4934 /* Set statement_timestamp() */
4936
4937 query_string = pq_getmsgstring(&input_message);
4939
4940 if (am_walsender)
4941 {
4942 if (!exec_replication_command(query_string))
4943 exec_simple_query(query_string);
4944 }
4945 else
4946 exec_simple_query(query_string);
4947
4948 valgrind_report_error_query(query_string);
4949
4950 send_ready_for_query = true;
4951 }
4952 break;
4953
4954 case PqMsg_Parse:
4955 {
4956 const char *stmt_name;
4957 const char *query_string;
4958 int numParams;
4959 Oid *paramTypes = NULL;
4960
4962
4963 /* Set statement_timestamp() */
4965
4966 stmt_name = pq_getmsgstring(&input_message);
4967 query_string = pq_getmsgstring(&input_message);
4968 numParams = pq_getmsgint(&input_message, 2);
4969 if (numParams > 0)
4970 {
4971 paramTypes = palloc_array(Oid, numParams);
4972 for (int i = 0; i < numParams; i++)
4973 paramTypes[i] = pq_getmsgint(&input_message, 4);
4974 }
4976
4977 exec_parse_message(query_string, stmt_name,
4978 paramTypes, numParams);
4979
4980 valgrind_report_error_query(query_string);
4981 }
4982 break;
4983
4984 case PqMsg_Bind:
4986
4987 /* Set statement_timestamp() */
4989
4990 /*
4991 * this message is complex enough that it seems best to put
4992 * the field extraction out-of-line
4993 */
4995
4996 /* exec_bind_message does valgrind_report_error_query */
4997 break;
4998
4999 case PqMsg_Execute:
5000 {
5001 const char *portal_name;
5002 int max_rows;
5003
5005
5006 /* Set statement_timestamp() */
5008
5012
5014
5015 /* exec_execute_message does valgrind_report_error_query */
5016 }
5017 break;
5018
5019 case PqMsg_FunctionCall:
5021
5022 /* Set statement_timestamp() */
5024
5025 /* Report query to various monitoring facilities. */
5027 set_ps_display("<FASTPATH>");
5028
5029 /* start an xact for this function invocation */
5031
5032 /*
5033 * Note: we may at this point be inside an aborted
5034 * transaction. We can't throw error for that until we've
5035 * finished reading the function-call message, so
5036 * HandleFunctionRequest() must check for it after doing so.
5037 * Be careful not to do anything that assumes we're inside a
5038 * valid transaction here.
5039 */
5040
5041 /* switch back to message context */
5043
5045
5046 /* commit the function-invocation transaction */
5048
5049 valgrind_report_error_query("fastpath function call");
5050
5051 send_ready_for_query = true;
5052 break;
5053
5054 case PqMsg_Close:
5055 {
5056 int close_type;
5057 const char *close_target;
5058
5060
5064
5065 switch (close_type)
5066 {
5067 case 'S':
5068 if (close_target[0] != '\0')
5070 else
5071 {
5072 /* special-case the unnamed statement */
5074 }
5075 break;
5076 case 'P':
5077 {
5078 Portal portal;
5079
5080 portal = GetPortalByName(close_target);
5081 if (PortalIsValid(portal))
5082 PortalDrop(portal, false);
5083 }
5084 break;
5085 default:
5086 ereport(ERROR,
5088 errmsg("invalid CLOSE message subtype %d",
5089 close_type)));
5090 break;
5091 }
5092
5095
5096 valgrind_report_error_query("CLOSE message");
5097 }
5098 break;
5099
5100 case PqMsg_Describe:
5101 {
5102 int describe_type;
5103 const char *describe_target;
5104
5106
5107 /* Set statement_timestamp() (needed for xact) */
5109
5113
5114 switch (describe_type)
5115 {
5116 case 'S':
5118 break;
5119 case 'P':
5121 break;
5122 default:
5123 ereport(ERROR,
5125 errmsg("invalid DESCRIBE message subtype %d",
5126 describe_type)));
5127 break;
5128 }
5129
5130 valgrind_report_error_query("DESCRIBE message");
5131 }
5132 break;
5133
5134 case PqMsg_Flush:
5137 pq_flush();
5138 break;
5139
5140 case PqMsg_Sync:
5142
5143 /*
5144 * If pipelining was used, we may be in an implicit
5145 * transaction block. Close it before calling
5146 * finish_xact_command.
5147 */
5150 valgrind_report_error_query("SYNC message");
5151 send_ready_for_query = true;
5152 break;
5153
5154 /*
5155 * PqMsg_Terminate means that the frontend is closing down the
5156 * socket. EOF means unexpected loss of frontend connection.
5157 * Either way, perform normal shutdown.
5158 */
5159 case EOF:
5160
5161 /* for the cumulative statistics system */
5163
5165
5166 case PqMsg_Terminate:
5167
5168 /*
5169 * Reset whereToSendOutput to prevent ereport from attempting
5170 * to send any more messages to client.
5171 */
5174
5175 /*
5176 * NOTE: if you are tempted to add more code here, DON'T!
5177 * Whatever you had in mind to do should be set up as an
5178 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5179 * it will fail to be called during other backend-shutdown
5180 * scenarios.
5181 */
5182 proc_exit(0);
5183
5184 case PqMsg_CopyData:
5185 case PqMsg_CopyDone:
5186 case PqMsg_CopyFail:
5187
5188 /*
5189 * Accept but ignore these messages, per protocol spec; we
5190 * probably got here because a COPY failed, and the frontend
5191 * is still sending data.
5192 */
5193 break;
5194
5195 default:
5196 ereport(FATAL,
5198 errmsg("invalid frontend message type %d",
5199 firstchar)));
5200 }
5201 } /* end of input-reading loop */
5202}
void ProcessNotifyInterrupt(bool flush)
Definition async.c:2581
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:679
uint64_t uint64
Definition c.h:684
#define pg_fallthrough
Definition c.h:220
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
void ReadyForQuery(CommandDest dest)
Definition dest.c:268
@ 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:91
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:171
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
MemoryContext TopMemoryContext
Definition mcxt.c:167
MemoryContext PostmasterContext
Definition mcxt.c:169
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
#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:481
@ InitProcessing
Definition miscadmin.h:480
#define IsExternalConnectionBackend(backend_type)
Definition miscadmin.h:414
#define GetProcessingMode()
Definition miscadmin.h:490
#define INIT_PG_LOAD_SESSION_LIBS
Definition miscadmin.h:508
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
#define SetProcessingMode(mode)
Definition miscadmin.h:492
BackendType MyBackendType
Definition miscinit.c:65
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
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:548
bool pg_strong_random(void *buf, size_t len)
#define PG_SIG_IGN
Definition port.h:552
#define printf(...)
Definition port.h:267
#define PG_SIG_DFL
Definition port.h:551
#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:2731
void quickdie(SIGNAL_ARGS)
Definition postgres.c:3017
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5348
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5212
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2151
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3172
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3155
static bool ignore_till_sync
Definition postgres.c:158
static void finish_xact_command(void)
Definition postgres.c:2913
const char * debug_query_string
Definition postgres.c:94
static void exec_simple_query(const char *query_string)
Definition postgres.c:1030
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1421
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1662
static bool xact_started
Definition postgres.c:144
static MemoryContext row_description_context
Definition postgres.c:173
static StringInfoData row_description_buf
Definition postgres.c:174
static bool doing_extended_query_message
Definition postgres.c:157
static void start_xact_command(void)
Definition postgres.c:2874
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2823
bool Log_disconnections
Definition postgres.c:100
static void drop_unnamed_stmt(void)
Definition postgres.c:2992
#define valgrind_report_error_query(query)
Definition postgres.c:230
static int ReadCommand(StringInfo inBuf)
Definition postgres.c:494
void BaseInit(void)
Definition postinit.c:622
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:722
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:696
#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:861
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:377
bool am_walsender
Definition walsender.c:135
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2103
void InitWalSender(void)
Definition walsender.c:330
void WalSndSignals(void)
Definition walsender.c:3984
#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:5043
bool IsAbortedTransactionBlockState(void)
Definition xact.c:409
void EndImplicitTransactionBlock(void)
Definition xact.c:4405
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916
void AbortCurrentTransaction(void)
Definition xact.c:3504

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

4223{
4224 const char *dbname = NULL;
4225
4227
4228 /* Initialize startup process environment. */
4229 InitStandaloneProcess(argv[0]);
4230
4231 /*
4232 * Set default values for command-line options.
4233 */
4235
4236 /*
4237 * Parse command-line options.
4238 */
4240
4241 /* Must have gotten a database name, or have a default (the username) */
4242 if (dbname == NULL)
4243 {
4244 dbname = username;
4245 if (dbname == NULL)
4246 ereport(FATAL,
4248 errmsg("%s: no database nor user name specified",
4249 progname)));
4250 }
4251
4252 /* Acquire configuration parameters */
4254 proc_exit(1);
4255
4256 /*
4257 * Validate we have been given a reasonable-looking DataDir and change
4258 * into it.
4259 */
4260 checkDataDir();
4262
4263 /*
4264 * Create lockfile for data directory.
4265 */
4266 CreateDataDirLockFile(false);
4267
4268 /* read control file (error checking and contains config ) */
4270
4271 /* Register the shared memory needs of all core subsystems. */
4273
4274 /*
4275 * process any libraries that should be preloaded at postmaster start
4276 */
4278
4279 /* Initialize MaxBackends */
4281
4282 /*
4283 * We don't need postmaster child slots in single-user mode, but
4284 * initialize them anyway to avoid having special handling.
4285 */
4287
4288 /* Initialize size of fast-path lock cache. */
4290
4291 /*
4292 * Also call any legacy shmem request hooks that might'be been installed
4293 * by preloaded libraries.
4294 *
4295 * Note: this must be done before ShmemCallRequestCallbacks(), because the
4296 * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
4297 * turn affects the size of the LWLock array calculated in lwlock.c.
4298 */
4300
4301 /*
4302 * Before computing the total size needed, give all subsystems, including
4303 * add-ins, a chance to chance to adjust their requested shmem sizes.
4304 */
4306
4307 /*
4308 * Now that loadable modules have had their chance to request additional
4309 * shared memory, determine the value of any runtime-computed GUCs that
4310 * depend on the amount of shared memory required.
4311 */
4313
4314 /*
4315 * Now that modules have been loaded, we can process any custom resource
4316 * managers specified in the wal_consistency_checking GUC.
4317 */
4319
4320 /*
4321 * Create shared memory etc. (Nothing's really "shared" in single-user
4322 * mode, but we must have these data structures anyway.)
4323 */
4325
4326 /*
4327 * Estimate number of openable files. This must happen after setting up
4328 * semaphores, because on some platforms semaphores count as open files.
4329 */
4331
4332 /*
4333 * Remember stand-alone backend startup time,roughly at the same point
4334 * during startup that postmaster does so.
4335 */
4337
4338 /*
4339 * Create a per-backend PGPROC struct in shared memory. We must do this
4340 * before we can use LWLocks.
4341 */
4342 InitProcess();
4343
4344 /*
4345 * Now that sufficient infrastructure has been initialized, PostgresMain()
4346 * can do the rest.
4347 */
4349}
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:1883
void InitStandaloneProcess(const char *argv0)
Definition miscinit.c:176
void process_shared_preload_libraries(void)
Definition miscinit.c:1855
void checkDataDir(void)
Definition miscinit.c:297
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1466
void InitPostmasterChildSlots(void)
Definition pmchild.c:97
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3965
static const char * userDoption
Definition postgres.c:168
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4364
void InitializeMaxBackends(void)
Definition postinit.c:565
void InitializeFastPathLocks(void)
Definition postinit.c:590
void ShmemCallRequestCallbacks(void)
Definition shmem.c:981
void InitProcess(void)
Definition proc.c:393
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 3965 of file postgres.c.

3967{
3968 bool secure = (ctx == PGC_POSTMASTER);
3969 int errs = 0;
3971 int flag;
3973
3974 if (secure)
3975 {
3976 gucsource = PGC_S_ARGV; /* switches came from command line */
3977
3978 /* Ignore the initial --single argument, if present */
3979 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3980 {
3981 argv++;
3982 argc--;
3983 }
3984 }
3985 else
3986 {
3987 gucsource = PGC_S_CLIENT; /* switches came from client */
3988 }
3989
3990 /*
3991 * Parse command-line options. CAUTION: keep this in sync with
3992 * postmaster/postmaster.c (the option sets should not conflict) and with
3993 * the common help() function in main/main.c.
3994 */
3995 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
3996
3997 /*
3998 * Turn this off because it's either printed to stderr and not the log
3999 * where we'd want it, or argv[0] is now "--single", which would make for
4000 * a weird error message. We print our own error message below.
4001 */
4002 optctx.opterr = 0;
4003
4004 while ((flag = pg_getopt_next(&optctx)) != -1)
4005 {
4006 switch (flag)
4007 {
4008 case 'B':
4009 SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
4010 break;
4011
4012 case 'b':
4013 /* Undocumented flag used for binary upgrades */
4014 if (secure)
4015 IsBinaryUpgrade = true;
4016 break;
4017
4018 case 'C':
4019 /* ignored for consistency with the postmaster */
4020 break;
4021
4022 case '-':
4023
4024 /*
4025 * Error if the user misplaced a special must-be-first option
4026 * for dispatching to a subprogram. parse_dispatch_option()
4027 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
4028 * error for anything else.
4029 */
4031 ereport(ERROR,
4033 errmsg("--%s must be first argument", optctx.optarg)));
4034
4036 case 'c':
4037 {
4038 char *name,
4039 *value;
4040
4041 ParseLongOption(optctx.optarg, &name, &value);
4042 if (!value)
4043 {
4044 if (flag == '-')
4045 ereport(ERROR,
4047 errmsg("--%s requires a value",
4048 optctx.optarg)));
4049 else
4050 ereport(ERROR,
4052 errmsg("-c %s requires a value",
4053 optctx.optarg)));
4054 }
4056 pfree(name);
4057 pfree(value);
4058 break;
4059 }
4060
4061 case 'D':
4062 if (secure)
4063 userDoption = strdup(optctx.optarg);
4064 break;
4065
4066 case 'd':
4067 set_debug_options(atoi(optctx.optarg), ctx, gucsource);
4068 break;
4069
4070 case 'E':
4071 if (secure)
4072 EchoQuery = true;
4073 break;
4074
4075 case 'e':
4076 SetConfigOption("datestyle", "euro", ctx, gucsource);
4077 break;
4078
4079 case 'F':
4080 SetConfigOption("fsync", "false", ctx, gucsource);
4081 break;
4082
4083 case 'f':
4084 if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
4085 errs++;
4086 break;
4087
4088 case 'h':
4089 SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
4090 break;
4091
4092 case 'i':
4093 SetConfigOption("listen_addresses", "*", ctx, gucsource);
4094 break;
4095
4096 case 'j':
4097 if (secure)
4098 UseSemiNewlineNewline = true;
4099 break;
4100
4101 case 'k':
4102 SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
4103 break;
4104
4105 case 'l':
4106 SetConfigOption("ssl", "true", ctx, gucsource);
4107 break;
4108
4109 case 'N':
4110 SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
4111 break;
4112
4113 case 'n':
4114 /* ignored for consistency with postmaster */
4115 break;
4116
4117 case 'O':
4118 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4119 break;
4120
4121 case 'P':
4122 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4123 break;
4124
4125 case 'p':
4126 SetConfigOption("port", optctx.optarg, ctx, gucsource);
4127 break;
4128
4129 case 'r':
4130 /* send output (stdout and stderr) to the given file */
4131 if (secure)
4133 break;
4134
4135 case 'S':
4136 SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4137 break;
4138
4139 case 's':
4140 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4141 break;
4142
4143 case 'T':
4144 /* ignored for consistency with the postmaster */
4145 break;
4146
4147 case 't':
4148 {
4149 const char *tmp = get_stats_option_name(optctx.optarg);
4150
4151 if (tmp)
4152 SetConfigOption(tmp, "true", ctx, gucsource);
4153 else
4154 errs++;
4155 break;
4156 }
4157
4158 case 'v':
4159
4160 /*
4161 * -v is no longer used in normal operation, since
4162 * FrontendProtocol is already set before we get here. We keep
4163 * the switch only for possible use in standalone operation,
4164 * in case we ever support using normal FE/BE protocol with a
4165 * standalone backend.
4166 */
4167 if (secure)
4169 break;
4170
4171 case 'W':
4172 SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4173 break;
4174
4175 default:
4176 errs++;
4177 break;
4178 }
4179
4180 if (errs)
4181 break;
4182 }
4183
4184 /*
4185 * Optional database name should be there only if *dbname is NULL.
4186 */
4187 if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
4188 *dbname = strdup(argv[optctx.optind++]);
4189
4190 if (errs || argc != optctx.optind)
4191 {
4192 if (errs)
4193 optctx.optind--; /* complain about the previous argument */
4194
4195 /* spell the error message a bit differently depending on context */
4197 ereport(FATAL,
4199 errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4200 errhint("Try \"%s --help\" for more information.", progname));
4201 else
4202 ereport(FATAL,
4204 errmsg("%s: invalid command-line argument: %s",
4205 progname, argv[optctx.optind]),
4206 errhint("Try \"%s --help\" for more information.", progname));
4207 }
4208}
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 @175 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:3851
static bool UseSemiNewlineNewline
Definition postgres.c:170
static bool EchoQuery
Definition postgres.c:169
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3883
const char * get_stats_option_name(const char *arg)
Definition postgres.c:3925
@ 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 515 of file postgres.c.

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

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

3018{
3019 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
3021
3022 /*
3023 * Prevent interrupts while exiting; though we just blocked signals that
3024 * would queue new interrupts, one may have been pending. We don't want a
3025 * quickdie() downgraded to a mere query cancel.
3026 */
3028
3029 /*
3030 * If we're aborting out of client auth, don't risk trying to send
3031 * anything to the client; we will likely violate the protocol, not to
3032 * mention that we may have interrupted the guts of OpenSSL or some
3033 * authentication library.
3034 */
3037
3038 /*
3039 * Notify the client before exiting, to give a clue on what happened.
3040 *
3041 * It's dubious to call ereport() from a signal handler. It is certainly
3042 * not async-signal safe. But it seems better to try, than to disconnect
3043 * abruptly and leave the client wondering what happened. It's remotely
3044 * possible that we crash or hang while trying to send the message, but
3045 * receiving a SIGQUIT is a sign that something has already gone badly
3046 * wrong, so there's not much to lose. Assuming the postmaster is still
3047 * running, it will SIGKILL us soon if we get stuck for some reason.
3048 *
3049 * One thing we can do to make this a tad safer is to clear the error
3050 * context stack, so that context callbacks are not called. That's a lot
3051 * less code that could be reached here, and the context info is unlikely
3052 * to be very relevant to a SIGQUIT report anyway.
3053 */
3055
3056 /*
3057 * When responding to a postmaster-issued signal, we send the message only
3058 * to the client; sending to the server log just creates log spam, plus
3059 * it's more code that we need to hope will work in a signal handler.
3060 *
3061 * Ideally these should be ereport(FATAL), but then we'd not get control
3062 * back to force the correct type of process exit.
3063 */
3064 switch (GetQuitSignalReason())
3065 {
3066 case PMQUIT_NOT_SENT:
3067 /* Hmm, SIGQUIT arrived out of the blue */
3070 errmsg("terminating connection because of unexpected SIGQUIT signal")));
3071 break;
3072 case PMQUIT_FOR_CRASH:
3073 /* A crash-and-restart cycle is in progress */
3076 errmsg("terminating connection because of crash of another server process"),
3077 errdetail("The postmaster has commanded this server process to roll back"
3078 " the current transaction and exit, because another"
3079 " server process exited abnormally and possibly corrupted"
3080 " shared memory."),
3081 errhint("In a moment you should be able to reconnect to the"
3082 " database and repeat your command.")));
3083 break;
3084 case PMQUIT_FOR_STOP:
3085 /* Immediate-mode stop */
3088 errmsg("terminating connection due to immediate shutdown command")));
3089 break;
3090 }
3091
3092 /*
3093 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
3094 * because shared memory may be corrupted, so we don't want to try to
3095 * clean up our transaction. Just nail the windows shut and get out of
3096 * town. The callbacks wouldn't be safe to run from a signal handler,
3097 * anyway.
3098 *
3099 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
3100 * a system reset cycle if someone sends a manual SIGQUIT to a random
3101 * backend. This is necessary precisely because we don't clean up our
3102 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3103 * should ensure the postmaster sees this as a crash, too, but no harm in
3104 * being doubly sure.)
3105 */
3106 _exit(2);
3107}
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 3851 of file postgres.c.

3852{
3853 if (debug_flag > 0)
3854 {
3855 char debugstr[64];
3856
3857 sprintf(debugstr, "debug%d", debug_flag);
3858 SetConfigOption("log_min_messages", debugstr, context, source);
3859 }
3860 else
3861 SetConfigOption("log_min_messages", "notice", context, source);
3862
3863 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3864 {
3865 SetConfigOption("log_connections", "all", context, source);
3866 SetConfigOption("log_disconnections", "true", context, source);
3867 }
3868 if (debug_flag >= 2)
3869 SetConfigOption("log_statement", "all", context, source);
3870 if (debug_flag >= 3)
3871 {
3872 SetConfigOption("debug_print_raw_parse", "true", context, source);
3873 SetConfigOption("debug_print_parse", "true", context, source);
3874 }
3875 if (debug_flag >= 4)
3876 SetConfigOption("debug_print_plan", "true", context, source);
3877 if (debug_flag >= 5)
3878 SetConfigOption("debug_print_rewritten", "true", context, source);
3879}
static rewind_source * source
Definition pg_rewind.c:89
#define sprintf
Definition port.h:263

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

3884{
3885 const char *tmp = NULL;
3886
3887 switch (arg[0])
3888 {
3889 case 's': /* seqscan */
3890 tmp = "enable_seqscan";
3891 break;
3892 case 'i': /* indexscan */
3893 tmp = "enable_indexscan";
3894 break;
3895 case 'o': /* indexonlyscan */
3896 tmp = "enable_indexonlyscan";
3897 break;
3898 case 'b': /* bitmapscan */
3899 tmp = "enable_bitmapscan";
3900 break;
3901 case 't': /* tidscan */
3902 tmp = "enable_tidscan";
3903 break;
3904 case 'n': /* nestloop */
3905 tmp = "enable_nestloop";
3906 break;
3907 case 'm': /* mergejoin */
3908 tmp = "enable_mergejoin";
3909 break;
3910 case 'h': /* hashjoin */
3911 tmp = "enable_hashjoin";
3912 break;
3913 }
3914 if (tmp)
3915 {
3916 SetConfigOption(tmp, "false", context, source);
3917 return true;
3918 }
3919 else
3920 return false;
3921}

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char title)
extern

Definition at line 5239 of file postgres.c.

5240{
5242 struct timeval user,
5243 sys;
5244 struct timeval elapse_t;
5245 struct rusage r;
5246
5249 memcpy(&user, &r.ru_utime, sizeof(user));
5250 memcpy(&sys, &r.ru_stime, sizeof(sys));
5251 if (elapse_t.tv_usec < Save_t.tv_usec)
5252 {
5253 elapse_t.tv_sec--;
5254 elapse_t.tv_usec += 1000000;
5255 }
5256 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5257 {
5258 r.ru_utime.tv_sec--;
5259 r.ru_utime.tv_usec += 1000000;
5260 }
5261 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5262 {
5263 r.ru_stime.tv_sec--;
5264 r.ru_stime.tv_usec += 1000000;
5265 }
5266
5267 /*
5268 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5269 * some work to interpret them, and most platforms don't fill them in.
5270 */
5272
5273 appendStringInfoString(&str, "! system usage stats:\n");
5275 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5276 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5277 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5278 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5279 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5280 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5281 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5283 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5284 (long) user.tv_sec,
5285 (long) user.tv_usec,
5286 (long) sys.tv_sec,
5287 (long) sys.tv_usec);
5288#ifndef WIN32
5289
5290 /*
5291 * The following rusage fields are not defined by POSIX, but they're
5292 * present on all current Unix-like systems so we use them without any
5293 * special checks. Some of these could be provided in our Windows
5294 * emulation in src/port/win32getrusage.c with more work.
5295 */
5297 "!\t%ld kB max resident size\n",
5299 /* in bytes on macOS */
5300 r.ru_maxrss / 1024
5301#else
5302 /* in kilobytes on most other platforms */
5303 r.ru_maxrss
5304#endif
5305 );
5307 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5308 r.ru_inblock - Save_r.ru_inblock,
5309 /* they only drink coffee at dec */
5310 r.ru_oublock - Save_r.ru_oublock,
5311 r.ru_inblock, r.ru_oublock);
5313 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5314 r.ru_majflt - Save_r.ru_majflt,
5315 r.ru_minflt - Save_r.ru_minflt,
5316 r.ru_majflt, r.ru_minflt,
5317 r.ru_nswap - Save_r.ru_nswap,
5318 r.ru_nswap);
5320 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5321 r.ru_nsignals - Save_r.ru_nsignals,
5322 r.ru_nsignals,
5323 r.ru_msgrcv - Save_r.ru_msgrcv,
5324 r.ru_msgsnd - Save_r.ru_msgsnd,
5325 r.ru_msgrcv, r.ru_msgsnd);
5327 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5328 r.ru_nvcsw - Save_r.ru_nvcsw,
5329 r.ru_nivcsw - Save_r.ru_nivcsw,
5330 r.ru_nvcsw, r.ru_nivcsw);
5331#endif /* !WIN32 */
5332
5333 /* remove trailing newline */
5334 if (str.data[str.len - 1] == '\n')
5335 str.data[--str.len] = '\0';
5336
5337 ereport(LOG,
5338 (errmsg_internal("%s", title),
5339 errdetail_internal("%s", str.data)));
5340
5341 pfree(str.data);
5342}
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 3155 of file postgres.c.

3156{
3157 /*
3158 * Don't joggle the elbow of proc_exit
3159 */
3161 {
3162 InterruptPending = true;
3163 QueryCancelPending = true;
3164 }
3165
3166 /* If we're still here, waken anything waiting on the process latch */
3168}

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