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 (ProcSignalReason reason)
 
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 2424 of file postgres.c.

2425{
2428 {
2429 long secs;
2430 int usecs;
2431 int msecs;
2432 bool exceeded_duration;
2434 bool in_sample = false;
2435
2438 &secs, &usecs);
2439 msecs = usecs / 1000;
2440
2441 /*
2442 * This odd-looking test for log_min_duration_* being exceeded is
2443 * designed to avoid integer overflow with very long durations: don't
2444 * compute secs * 1000 until we've verified it will fit in int.
2445 */
2448 (secs > log_min_duration_statement / 1000 ||
2449 secs * 1000 + msecs >= log_min_duration_statement)));
2450
2453 (secs > log_min_duration_sample / 1000 ||
2454 secs * 1000 + msecs >= log_min_duration_sample)));
2455
2456 /*
2457 * Do not log if log_statement_sample_rate = 0. Log a sample if
2458 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2459 * log_statement_sample_rate = 1.
2460 */
2465
2467 {
2468 snprintf(msec_str, 32, "%ld.%03d",
2469 secs * 1000 + msecs, usecs % 1000);
2471 return 2;
2472 else
2473 return 1;
2474 }
2475 }
2476
2477 return 0;
2478}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1721
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1645
int log_min_duration_statement
Definition guc_tables.c:552
int log_min_duration_sample
Definition guc_tables.c:551
double log_statement_sample_rate
Definition guc_tables.c:556
bool log_duration
Definition guc_tables.c:516
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:880
bool xact_is_sampled
Definition xact.c:297

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

3012{
3013 /* Don't joggle the elbow of proc_exit */
3015 {
3016 InterruptPending = true;
3017 ProcDiePending = true;
3018 }
3019
3020 /* for the cumulative stats system */
3022
3023 /* If we're still here, waken anything waiting on the process latch */
3025
3026 /*
3027 * If we're in single user mode, we want to quit immediately - we can't
3028 * rely on latches as they wouldn't work when stdin/stdout is a file.
3029 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3030 * effort just for the benefit of single user mode.
3031 */
3034}
@ DestRemote
Definition dest.h:89
volatile sig_atomic_t InterruptPending
Definition globals.c:32
struct Latch * MyLatch
Definition globals.c:63
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:60
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition postgres.c:92
static bool DoingCommandRead
Definition postgres.c:137
void ProcessInterrupts(void)
Definition postgres.c:3283

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

◆ FloatExceptionHandler()

pg_noreturn void FloatExceptionHandler ( SIGNAL_ARGS  )
extern

Definition at line 3058 of file postgres.c.

3059{
3060 /* We're not returning, so no need to save errno */
3061 ereport(ERROR,
3063 errmsg("floating-point exception"),
3064 errdetail("An invalid floating-point operation was signaled. "
3065 "This probably means an out-of-range result or an "
3066 "invalid operation, such as division by zero.")));
3067}
int errdetail(const char *fmt,...)
Definition elog.c:1216
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150

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

3739{
3740 switch (arg[0])
3741 {
3742 case 'p':
3743 if (optarg[1] == 'a') /* "parser" */
3744 return "log_parser_stats";
3745 else if (optarg[1] == 'l') /* "planner" */
3746 return "log_planner_stats";
3747 break;
3748
3749 case 'e': /* "executor" */
3750 return "log_executor_stats";
3751 break;
3752 }
3753
3754 return NULL;
3755}
void * arg
PGDLLIMPORT char * optarg
Definition getopt.c:53

References arg, fb(), and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)
extern

Definition at line 3074 of file postgres.c.

3075{
3076 RecoveryConflictPendingReasons[reason] = true;
3078 InterruptPending = true;
3079 /* latch will be set by procsignal_sigusr1_handler */
3080}
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition postgres.c:160
static volatile sig_atomic_t RecoveryConflictPending
Definition postgres.c:159

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ pg_analyze_and_rewrite_fixedparams()

List * pg_analyze_and_rewrite_fixedparams ( RawStmt parsetree,
const char query_string,
const Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)
extern

Definition at line 669 of file postgres.c.

674{
675 Query *query;
677
679
680 /*
681 * (1) Perform parse analysis.
682 */
684 ResetUsage();
685
686 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
687 queryEnv);
688
690 ShowUsage("PARSE ANALYSIS STATISTICS");
691
692 /*
693 * (2) Rewrite the queries, as necessary
694 */
696
698
699 return querytree_list;
700}
bool log_parser_stats
Definition guc_tables.c:529
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition analyze.c:117
List * pg_rewrite_query(Query *query)
Definition postgres.c:802
void ShowUsage(const char *title)
Definition postgres.c:5047
void ResetUsage(void)
Definition postgres.c:5040
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 708 of file postgres.c.

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

767{
768 Query *query;
770
772
773 /*
774 * (1) Perform parse analysis.
775 */
777 ResetUsage();
778
779 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
780 queryEnv);
781
783 ShowUsage("PARSE ANALYSIS STATISTICS");
784
785 /*
786 * (2) Rewrite the queries, as necessary
787 */
789
791
792 return querytree_list;
793}
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition analyze.c:198

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

604{
606
608
610 ResetUsage();
611
613
615 ShowUsage("PARSER STATISTICS");
616
617#ifdef DEBUG_NODE_TESTS_ENABLED
618
619 /* Optional debugging check: pass raw parsetrees through copyObject() */
621 {
623
624 /* This checks both copyObject() and the equal() routines... */
626 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
627 else
629 }
630
631 /*
632 * Optional debugging check: pass raw parsetrees through
633 * outfuncs/readfuncs
634 */
636 {
639
640 pfree(str);
641 /* This checks both outfuncs/readfuncs and the equal() routines... */
643 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
644 else
646 }
647
648#endif /* DEBUG_NODE_TESTS_ENABLED */
649
651
653 elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
655
656 return raw_parsetree_list;
657}
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:31
#define WARNING
Definition elog.h:36
#define elog(elevel,...)
Definition elog.h:226
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
bool Debug_print_raw_parse
Definition guc_tables.c:519
bool Debug_pretty_print
Definition guc_tables.c:521
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:808
@ 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 974 of file postgres.c.

976{
977 List *stmt_list = NIL;
978 ListCell *query_list;
979
980 foreach(query_list, querytrees)
981 {
982 Query *query = lfirst_node(Query, query_list);
984
985 if (query->commandType == CMD_UTILITY)
986 {
987 /* Utility commands require no planning. */
989 stmt->commandType = CMD_UTILITY;
990 stmt->canSetTag = query->canSetTag;
991 stmt->utilityStmt = query->utilityStmt;
992 stmt->stmt_location = query->stmt_location;
993 stmt->stmt_len = query->stmt_len;
994 stmt->queryId = query->queryId;
995 stmt->planOrigin = PLAN_STMT_INTERNAL;
996 }
997 else
998 {
999 stmt = pg_plan_query(query, query_string, cursorOptions,
1000 boundParams, NULL);
1001 }
1002
1003 stmt_list = lappend(stmt_list, stmt);
1004 }
1005
1006 return stmt_list;
1007}
#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:40
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition postgres.c:886
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
ParseLoc stmt_location
Definition parsenodes.h:255

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

888{
890
891 /* Utility commands have no plans. */
892 if (querytree->commandType == CMD_UTILITY)
893 return NULL;
894
895 /* Planner must have a snapshot in case it calls user-defined functions. */
897
899
901 ResetUsage();
902
903 /* call the optimizer */
904 plan = planner(querytree, query_string, cursorOptions, boundParams, es);
905
907 ShowUsage("PLANNER STATISTICS");
908
909#ifdef DEBUG_NODE_TESTS_ENABLED
910
911 /* Optional debugging check: pass plan tree through copyObject() */
913 {
915
916 /*
917 * equal() currently does not have routines to compare Plan nodes, so
918 * don't try to test equality here. Perhaps fix someday?
919 */
920#ifdef NOT_USED
921 /* This checks both copyObject() and the equal() routines... */
922 if (!equal(new_plan, plan))
923 elog(WARNING, "copyObject() failed to produce an equal plan tree");
924 else
925#endif
926 plan = new_plan;
927 }
928
929 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
931 {
932 char *str;
934
937 pfree(str);
938
939 /*
940 * equal() currently does not have routines to compare Plan nodes, so
941 * don't try to test equality here. Perhaps fix someday?
942 */
943#ifdef NOT_USED
944 /* This checks both outfuncs/readfuncs and the equal() routines... */
945 if (!equal(new_plan, plan))
946 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
947 else
948#endif
949 plan = new_plan;
950 }
951
952#endif /* DEBUG_NODE_TESTS_ENABLED */
953
954 /*
955 * Print plan if debugging.
956 */
959
961
962 return plan;
963}
Datum querytree(PG_FUNCTION_ARGS)
Definition _int_bool.c:665
#define Assert(condition)
Definition c.h:873
bool Debug_print_plan
Definition guc_tables.c:517
bool log_planner_stats
Definition guc_tables.c:530
#define plan(x)
Definition pg_regress.c:161
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 802 of file postgres.c.

803{
805
807 elog_node_display(LOG, "parse tree", query,
809
811 ResetUsage();
812
813 if (query->commandType == CMD_UTILITY)
814 {
815 /* don't rewrite utilities, just dump 'em into result list */
816 querytree_list = list_make1(query);
817 }
818 else
819 {
820 /* rewrite regular queries */
822 }
823
825 ShowUsage("REWRITER STATISTICS");
826
827#ifdef DEBUG_NODE_TESTS_ENABLED
828
829 /* Optional debugging check: pass querytree through copyObject() */
831 {
832 List *new_list;
833
835 /* This checks both copyObject() and the equal() routines... */
837 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
838 else
840 }
841
842 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
844 {
845 List *new_list = NIL;
846 ListCell *lc;
847
848 foreach(lc, querytree_list)
849 {
853
854 /*
855 * queryId is not saved in stored rules, but we must preserve it
856 * here to avoid breaking pg_stat_statements.
857 */
858 new_query->queryId = curr_query->queryId;
859
861 pfree(str);
862 }
863
864 /* This checks both outfuncs/readfuncs and the equal() routines... */
866 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
867 else
869 }
870
871#endif /* DEBUG_NODE_TESTS_ENABLED */
872
874 elog_node_display(LOG, "rewritten parse tree", querytree_list,
876
877 return querytree_list;
878}
bool Debug_print_rewritten
Definition guc_tables.c:520
bool Debug_print_parse
Definition guc_tables.c:518
#define list_make1(x1)
Definition pg_list.h:212
List * QueryRewrite(Query *parsetree)

References CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), 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 4172 of file postgres.c.

4173{
4175
4176 /* these must be volatile to ensure state is preserved across longjmp: */
4177 volatile bool send_ready_for_query = true;
4178 volatile bool idle_in_transaction_timeout_enabled = false;
4179 volatile bool idle_session_timeout_enabled = false;
4180
4181 Assert(dbname != NULL);
4182 Assert(username != NULL);
4183
4185
4186 /*
4187 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4188 * has already set up BlockSig and made that the active signal mask.)
4189 *
4190 * Note that postmaster blocked all signals before forking child process,
4191 * so there is no race condition whereby we might receive a signal before
4192 * we have set up the handler.
4193 *
4194 * Also note: it's best not to use any signals that are SIG_IGNored in the
4195 * postmaster. If such a signal arrives before we are able to change the
4196 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4197 * handler in the postmaster to reserve the signal. (Of course, this isn't
4198 * an issue for signals that are locally generated, such as SIGALRM and
4199 * SIGPIPE.)
4200 */
4201 if (am_walsender)
4202 WalSndSignals();
4203 else
4204 {
4206 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4207 pqsignal(SIGTERM, die); /* cancel current query and exit */
4208
4209 /*
4210 * In a postmaster child backend, replace SignalHandlerForCrashExit
4211 * with quickdie, so we can tell the client we're dying.
4212 *
4213 * In a standalone backend, SIGQUIT can be generated from the keyboard
4214 * easily, while SIGTERM cannot, so we make both signals do die()
4215 * rather than quickdie().
4216 */
4218 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4219 else
4220 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4221 InitializeTimeouts(); /* establishes SIGALRM handler */
4222
4223 /*
4224 * Ignore failure to write to frontend. Note: if frontend closes
4225 * connection, we will notice it and exit cleanly when control next
4226 * returns to outer loop. This seems safer than forcing exit in the
4227 * midst of output during who-knows-what operation...
4228 */
4233
4234 /*
4235 * Reset some signals that are accepted by postmaster but not by
4236 * backend
4237 */
4238 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4239 * platforms */
4240 }
4241
4242 /* Early initialization */
4243 BaseInit();
4244
4245 /* We need to allow SIGINT, etc during the initial transaction */
4247
4248 /*
4249 * Generate a random cancel key, if this is a backend serving a
4250 * connection. InitPostgres() will advertise it in shared memory.
4251 */
4254 {
4255 int len;
4256
4257 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4260 {
4261 ereport(ERROR,
4263 errmsg("could not generate random cancel key")));
4264 }
4266 }
4267
4268 /*
4269 * General initialization.
4270 *
4271 * NOTE: if you are tempted to add code in this vicinity, consider putting
4272 * it inside InitPostgres() instead. In particular, anything that
4273 * involves database access should be there, not here.
4274 *
4275 * Honor session_preload_libraries if not dealing with a WAL sender.
4276 */
4277 InitPostgres(dbname, InvalidOid, /* database to connect to */
4278 username, InvalidOid, /* role to connect as */
4280 NULL); /* no out_dbname */
4281
4282 /*
4283 * If the PostmasterContext is still around, recycle the space; we don't
4284 * need it anymore after InitPostgres completes.
4285 */
4287 {
4290 }
4291
4293
4294 /*
4295 * Now all GUC states are fully set up. Report them to client if
4296 * appropriate.
4297 */
4299
4300 /*
4301 * Also set up handler to log session end; we have to wait till now to be
4302 * sure Log_disconnections has its final value.
4303 */
4306
4308
4309 /* Perform initialization specific to a WAL sender process. */
4310 if (am_walsender)
4311 InitWalSender();
4312
4313 /*
4314 * Send this backend's cancellation info to the frontend.
4315 */
4317 {
4319
4323
4326 /* Need not flush since ReadyForQuery will do it. */
4327 }
4328
4329 /* Welcome banner for standalone case */
4331 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4332
4333 /*
4334 * Create the memory context we will use in the main loop.
4335 *
4336 * MessageContext is reset once per iteration of the main loop, ie, upon
4337 * completion of processing of each command message from the client.
4338 */
4340 "MessageContext",
4342
4343 /*
4344 * Create memory context and buffer used for RowDescription messages. As
4345 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4346 * frequently executed for every single statement, we don't want to
4347 * allocate a separate buffer every time.
4348 */
4350 "RowDescriptionContext",
4355
4356 /* Fire any defined login event triggers, if appropriate */
4358
4359 /*
4360 * POSTGRES main processing loop begins here
4361 *
4362 * If an exception is encountered, processing resumes here so we abort the
4363 * current transaction and start a new one.
4364 *
4365 * You might wonder why this isn't coded as an infinite loop around a
4366 * PG_TRY construct. The reason is that this is the bottom of the
4367 * exception stack, and so with PG_TRY there would be no exception handler
4368 * in force at all during the CATCH part. By leaving the outermost setjmp
4369 * always active, we have at least some chance of recovering from an error
4370 * during error recovery. (If we get into an infinite loop thereby, it
4371 * will soon be stopped by overflow of elog.c's internal state stack.)
4372 *
4373 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4374 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4375 * is essential in case we longjmp'd out of a signal handler on a platform
4376 * where that leaves the signal blocked. It's not redundant with the
4377 * unblock in AbortTransaction() because the latter is only called if we
4378 * were inside a transaction.
4379 */
4380
4381 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4382 {
4383 /*
4384 * NOTE: if you are tempted to add more code in this if-block,
4385 * consider the high probability that it should be in
4386 * AbortTransaction() instead. The only stuff done directly here
4387 * should be stuff that is guaranteed to apply *only* for outer-level
4388 * error recovery, such as adjusting the FE/BE protocol status.
4389 */
4390
4391 /* Since not using PG_TRY, must reset error stack by hand */
4393
4394 /* Prevent interrupts while cleaning up */
4396
4397 /*
4398 * Forget any pending QueryCancel request, since we're returning to
4399 * the idle loop anyway, and cancel any active timeout requests. (In
4400 * future we might want to allow some timeout requests to survive, but
4401 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4402 * we got here because of a query cancel interrupting the SIGALRM
4403 * interrupt handler.) Note in particular that we must clear the
4404 * statement and lock timeout indicators, to prevent any future plain
4405 * query cancels from being misreported as timeouts in case we're
4406 * forgetting a timeout cancel.
4407 */
4408 disable_all_timeouts(false); /* do first to avoid race condition */
4409 QueryCancelPending = false;
4412
4413 /* Not reading from the client anymore. */
4414 DoingCommandRead = false;
4415
4416 /* Make sure libpq is in a good state */
4417 pq_comm_reset();
4418
4419 /* Report the error to the client and/or server log */
4421
4422 /*
4423 * If Valgrind noticed something during the erroneous query, print the
4424 * query string, assuming we have one.
4425 */
4427
4428 /*
4429 * Make sure debug_query_string gets reset before we possibly clobber
4430 * the storage it points at.
4431 */
4433
4434 /*
4435 * Abort the current transaction in order to recover.
4436 */
4438
4439 if (am_walsender)
4441
4443
4444 /*
4445 * We can't release replication slots inside AbortTransaction() as we
4446 * need to be able to start and abort transactions while having a slot
4447 * acquired. But we never need to hold them across top level errors,
4448 * so releasing here is fine. There also is a before_shmem_exit()
4449 * callback ensuring correct cleanup on FATAL errors.
4450 */
4451 if (MyReplicationSlot != NULL)
4453
4454 /* We also want to cleanup temporary slots on error. */
4456
4458
4459 /*
4460 * Now return to normal top-level context and clear ErrorContext for
4461 * next time.
4462 */
4465
4466 /*
4467 * If we were handling an extended-query-protocol message, initiate
4468 * skip till next Sync. This also causes us not to issue
4469 * ReadyForQuery (until we get Sync).
4470 */
4472 ignore_till_sync = true;
4473
4474 /* We don't have a transaction command open anymore */
4475 xact_started = false;
4476
4477 /*
4478 * If an error occurred while we were reading a message from the
4479 * client, we have potentially lost track of where the previous
4480 * message ends and the next one begins. Even though we have
4481 * otherwise recovered from the error, we cannot safely read any more
4482 * messages from the client, so there isn't much we can do with the
4483 * connection anymore.
4484 */
4485 if (pq_is_reading_msg())
4486 ereport(FATAL,
4488 errmsg("terminating connection because protocol synchronization was lost")));
4489
4490 /* Now we can allow interrupts again */
4492 }
4493
4494 /* We can now handle ereport(ERROR) */
4496
4497 if (!ignore_till_sync)
4498 send_ready_for_query = true; /* initially, or after error */
4499
4500 /*
4501 * Non-error queries loop here.
4502 */
4503
4504 for (;;)
4505 {
4506 int firstchar;
4508
4509 /*
4510 * At top of loop, reset extended-query-message flag, so that any
4511 * errors encountered in "idle" state don't provoke skip.
4512 */
4514
4515 /*
4516 * For valgrind reporting purposes, the "current query" begins here.
4517 */
4518#ifdef USE_VALGRIND
4520#endif
4521
4522 /*
4523 * Release storage left over from prior query cycle, and create a new
4524 * query input buffer in the cleared MessageContext.
4525 */
4528
4530
4531 /*
4532 * Also consider releasing our catalog snapshot if any, so that it's
4533 * not preventing advance of global xmin while we wait for the client.
4534 */
4536
4537 /*
4538 * (1) If we've reached idle state, tell the frontend we're ready for
4539 * a new query.
4540 *
4541 * Note: this includes fflush()'ing the last of the prior output.
4542 *
4543 * This is also a good time to flush out collected statistics to the
4544 * cumulative stats system, and to update the PS stats display. We
4545 * avoid doing those every time through the message loop because it'd
4546 * slow down processing of batched messages, and because we don't want
4547 * to report uncommitted updates (that confuses autovacuum). The
4548 * notification processor wants a call too, if we are not in a
4549 * transaction block.
4550 *
4551 * Also, if an idle timeout is enabled, start the timer for that.
4552 */
4554 {
4556 {
4557 set_ps_display("idle in transaction (aborted)");
4559
4560 /* Start the idle-in-transaction timer */
4563 {
4567 }
4568 }
4570 {
4571 set_ps_display("idle in transaction");
4573
4574 /* Start the idle-in-transaction timer */
4577 {
4581 }
4582 }
4583 else
4584 {
4585 long stats_timeout;
4586
4587 /*
4588 * Process incoming notifies (including self-notifies), if
4589 * any, and send relevant messages to the client. Doing it
4590 * here helps ensure stable behavior in tests: if any notifies
4591 * were received during the just-finished transaction, they'll
4592 * be seen by the client before ReadyForQuery is.
4593 */
4596
4597 /*
4598 * Check if we need to report stats. If pgstat_report_stat()
4599 * decides it's too soon to flush out pending stats / lock
4600 * contention prevented reporting, it'll tell us when we
4601 * should try to report stats again (so that stats updates
4602 * aren't unduly delayed if the connection goes idle for a
4603 * long time). We only enable the timeout if we don't already
4604 * have a timeout in progress, because we don't disable the
4605 * timeout below. enable_timeout_after() needs to determine
4606 * the current timestamp, which can have a negative
4607 * performance impact. That's OK because pgstat_report_stat()
4608 * won't have us wake up sooner than a prior call.
4609 */
4611 if (stats_timeout > 0)
4612 {
4616 }
4617 else
4618 {
4619 /* all stats flushed, no need for the timeout */
4622 }
4623
4624 set_ps_display("idle");
4626
4627 /* Start the idle-session timer */
4628 if (IdleSessionTimeout > 0)
4629 {
4633 }
4634 }
4635
4636 /* Report any recently-changed GUC options */
4638
4639 /*
4640 * The first time this backend is ready for query, log the
4641 * durations of the different components of connection
4642 * establishment and setup.
4643 */
4647 {
4651
4653
4663
4664 ereport(LOG,
4665 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4666 (double) total_duration / NS_PER_US,
4667 (double) fork_duration / NS_PER_US,
4668 (double) auth_duration / NS_PER_US));
4669 }
4670
4672 send_ready_for_query = false;
4673 }
4674
4675 /*
4676 * (2) Allow asynchronous signals to be executed immediately if they
4677 * come in while we are waiting for client input. (This must be
4678 * conditional since we don't want, say, reads on behalf of COPY FROM
4679 * STDIN doing the same thing.)
4680 */
4681 DoingCommandRead = true;
4682
4683 /*
4684 * (3) read a command (loop blocks here)
4685 */
4687
4688 /*
4689 * (4) turn off the idle-in-transaction and idle-session timeouts if
4690 * active. We do this before step (5) so that any last-moment timeout
4691 * is certain to be detected in step (5).
4692 *
4693 * At most one of these timeouts will be active, so there's no need to
4694 * worry about combining the timeout.c calls into one.
4695 */
4697 {
4700 }
4702 {
4705 }
4706
4707 /*
4708 * (5) disable async signal conditions again.
4709 *
4710 * Query cancel is supposed to be a no-op when there is no query in
4711 * progress, so if a query cancel arrived while we were idle, just
4712 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4713 * it's called when DoingCommandRead is set, so check for interrupts
4714 * before resetting DoingCommandRead.
4715 */
4717 DoingCommandRead = false;
4718
4719 /*
4720 * (6) check for any other interesting events that happened while we
4721 * slept.
4722 */
4724 {
4725 ConfigReloadPending = false;
4727 }
4728
4729 /*
4730 * (7) process the command. But ignore it if we're skipping till
4731 * Sync.
4732 */
4733 if (ignore_till_sync && firstchar != EOF)
4734 continue;
4735
4736 switch (firstchar)
4737 {
4738 case PqMsg_Query:
4739 {
4740 const char *query_string;
4741
4742 /* Set statement_timestamp() */
4744
4745 query_string = pq_getmsgstring(&input_message);
4747
4748 if (am_walsender)
4749 {
4750 if (!exec_replication_command(query_string))
4751 exec_simple_query(query_string);
4752 }
4753 else
4754 exec_simple_query(query_string);
4755
4756 valgrind_report_error_query(query_string);
4757
4758 send_ready_for_query = true;
4759 }
4760 break;
4761
4762 case PqMsg_Parse:
4763 {
4764 const char *stmt_name;
4765 const char *query_string;
4766 int numParams;
4767 Oid *paramTypes = NULL;
4768
4770
4771 /* Set statement_timestamp() */
4773
4774 stmt_name = pq_getmsgstring(&input_message);
4775 query_string = pq_getmsgstring(&input_message);
4776 numParams = pq_getmsgint(&input_message, 2);
4777 if (numParams > 0)
4778 {
4779 paramTypes = palloc_array(Oid, numParams);
4780 for (int i = 0; i < numParams; i++)
4781 paramTypes[i] = pq_getmsgint(&input_message, 4);
4782 }
4784
4785 exec_parse_message(query_string, stmt_name,
4786 paramTypes, numParams);
4787
4788 valgrind_report_error_query(query_string);
4789 }
4790 break;
4791
4792 case PqMsg_Bind:
4794
4795 /* Set statement_timestamp() */
4797
4798 /*
4799 * this message is complex enough that it seems best to put
4800 * the field extraction out-of-line
4801 */
4803
4804 /* exec_bind_message does valgrind_report_error_query */
4805 break;
4806
4807 case PqMsg_Execute:
4808 {
4809 const char *portal_name;
4810 int max_rows;
4811
4813
4814 /* Set statement_timestamp() */
4816
4820
4822
4823 /* exec_execute_message does valgrind_report_error_query */
4824 }
4825 break;
4826
4827 case PqMsg_FunctionCall:
4829
4830 /* Set statement_timestamp() */
4832
4833 /* Report query to various monitoring facilities. */
4835 set_ps_display("<FASTPATH>");
4836
4837 /* start an xact for this function invocation */
4839
4840 /*
4841 * Note: we may at this point be inside an aborted
4842 * transaction. We can't throw error for that until we've
4843 * finished reading the function-call message, so
4844 * HandleFunctionRequest() must check for it after doing so.
4845 * Be careful not to do anything that assumes we're inside a
4846 * valid transaction here.
4847 */
4848
4849 /* switch back to message context */
4851
4853
4854 /* commit the function-invocation transaction */
4856
4857 valgrind_report_error_query("fastpath function call");
4858
4859 send_ready_for_query = true;
4860 break;
4861
4862 case PqMsg_Close:
4863 {
4864 int close_type;
4865 const char *close_target;
4866
4868
4872
4873 switch (close_type)
4874 {
4875 case 'S':
4876 if (close_target[0] != '\0')
4878 else
4879 {
4880 /* special-case the unnamed statement */
4882 }
4883 break;
4884 case 'P':
4885 {
4886 Portal portal;
4887
4888 portal = GetPortalByName(close_target);
4889 if (PortalIsValid(portal))
4890 PortalDrop(portal, false);
4891 }
4892 break;
4893 default:
4894 ereport(ERROR,
4896 errmsg("invalid CLOSE message subtype %d",
4897 close_type)));
4898 break;
4899 }
4900
4903
4904 valgrind_report_error_query("CLOSE message");
4905 }
4906 break;
4907
4908 case PqMsg_Describe:
4909 {
4910 int describe_type;
4911 const char *describe_target;
4912
4914
4915 /* Set statement_timestamp() (needed for xact) */
4917
4921
4922 switch (describe_type)
4923 {
4924 case 'S':
4926 break;
4927 case 'P':
4929 break;
4930 default:
4931 ereport(ERROR,
4933 errmsg("invalid DESCRIBE message subtype %d",
4934 describe_type)));
4935 break;
4936 }
4937
4938 valgrind_report_error_query("DESCRIBE message");
4939 }
4940 break;
4941
4942 case PqMsg_Flush:
4945 pq_flush();
4946 break;
4947
4948 case PqMsg_Sync:
4950
4951 /*
4952 * If pipelining was used, we may be in an implicit
4953 * transaction block. Close it before calling
4954 * finish_xact_command.
4955 */
4958 valgrind_report_error_query("SYNC message");
4959 send_ready_for_query = true;
4960 break;
4961
4962 /*
4963 * PqMsg_Terminate means that the frontend is closing down the
4964 * socket. EOF means unexpected loss of frontend connection.
4965 * Either way, perform normal shutdown.
4966 */
4967 case EOF:
4968
4969 /* for the cumulative statistics system */
4971
4972 /* FALLTHROUGH */
4973
4974 case PqMsg_Terminate:
4975
4976 /*
4977 * Reset whereToSendOutput to prevent ereport from attempting
4978 * to send any more messages to client.
4979 */
4982
4983 /*
4984 * NOTE: if you are tempted to add more code here, DON'T!
4985 * Whatever you had in mind to do should be set up as an
4986 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4987 * it will fail to be called during other backend-shutdown
4988 * scenarios.
4989 */
4990 proc_exit(0);
4991
4992 case PqMsg_CopyData:
4993 case PqMsg_CopyDone:
4994 case PqMsg_CopyFail:
4995
4996 /*
4997 * Accept but ignore these messages, per protocol spec; we
4998 * probably got here because a COPY failed, and the frontend
4999 * is still sending data.
5000 */
5001 break;
5002
5003 default:
5004 ereport(FATAL,
5006 errmsg("invalid frontend message type %d",
5007 firstchar)));
5008 }
5009 } /* end of input-reading loop */
5010}
void ProcessNotifyInterrupt(bool flush)
Definition async.c:2572
volatile sig_atomic_t notifyInterruptPending
Definition async.c:537
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition prepare.c:519
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:542
uint64_t uint64
Definition c.h:547
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
void ReadyForQuery(CommandDest dest)
Definition dest.c:256
@ DestDebug
Definition dest.h:88
@ DestNone
Definition dest.h:87
void EmitErrorReport(void)
Definition elog.c:1704
ErrorContextCallback * error_context_stack
Definition elog.c:95
void FlushErrorState(void)
Definition elog.c:1884
sigjmp_buf * PG_exception_stack
Definition elog.c:97
#define FATAL
Definition elog.h:41
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition fastpath.c:188
#define palloc_array(type, count)
Definition fe_memutils.h:76
int MyCancelKeyLength
Definition globals.c:53
int MyProcPid
Definition globals.c:47
bool IsUnderPostmaster
Definition globals.c:120
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
uint8 MyCancelKey[MAX_CANCEL_KEY_LENGTH]
Definition globals.c:52
struct Port * MyProcPort
Definition globals.c:51
Oid MyDatabaseId
Definition globals.c:94
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
void BeginReportingGUCOptions(void)
Definition guc.c:2421
void ReportChangedGUCOptions(void)
Definition guc.c:2471
@ 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:127
#define pq_flush()
Definition libpq.h:46
#define pq_comm_reset()
Definition libpq.h:45
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:136
@ NormalProcessing
Definition miscadmin.h:472
@ InitProcessing
Definition miscadmin.h:471
#define IsExternalConnectionBackend(backend_type)
Definition miscadmin.h:405
#define GetProcessingMode()
Definition miscadmin.h:481
#define INIT_PG_LOAD_SESSION_LIBS
Definition miscadmin.h:499
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
#define SetProcessingMode(mode)
Definition miscadmin.h:483
BackendType MyBackendType
Definition miscinit.c:64
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:704
@ DISCONNECT_CLIENT_EOF
Definition pgstat.h:58
void pgstat_report_connect(Oid dboid)
#define pqsignal
Definition port.h:547
bool pg_strong_random(void *buf, size_t len)
#define printf(...)
Definition port.h:266
#define PortalIsValid(p)
Definition portal.h:211
void PortalDrop(Portal portal, bool isTopCommit)
Definition portalmem.c:467
Portal GetPortalByName(const char *name)
Definition portalmem.c:130
void PortalErrorCleanup(void)
Definition portalmem.c:917
static void exec_describe_statement_message(const char *stmt_name)
Definition postgres.c:2628
void quickdie(SIGNAL_ARGS)
Definition postgres.c:2914
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5156
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5020
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2109
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3058
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3041
static bool ignore_till_sync
Definition postgres.c:144
static void finish_xact_command(void)
Definition postgres.c:2810
const char * debug_query_string
Definition postgres.c:89
static void exec_simple_query(const char *query_string)
Definition postgres.c:1016
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1393
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1627
static bool xact_started
Definition postgres.c:130
static MemoryContext row_description_context
Definition postgres.c:163
static StringInfoData row_description_buf
Definition postgres.c:164
static bool doing_extended_query_message
Definition postgres.c:143
static void start_xact_command(void)
Definition postgres.c:2771
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2720
bool Log_disconnections
Definition postgres.c:95
static void drop_unnamed_stmt(void)
Definition postgres.c:2889
#define valgrind_report_error_query(query)
Definition postgres.c:216
static int ReadCommand(StringInfo inBuf)
Definition postgres.c:480
void BaseInit(void)
Definition postinit.c:607
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:710
bool pq_is_reading_msg(void)
Definition pqcomm.c:1181
#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:677
#define MAX_CANCEL_KEY_LENGTH
Definition procsignal.h:69
#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:148
void ReplicationSlotRelease(void)
Definition slot.c:758
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:857
void InvalidateCatalogSnapshotConditionally(void)
Definition snapmgr.c:477
int IdleSessionTimeout
Definition proc.c:63
int IdleInTransactionSessionTimeout
Definition proc.c:61
int TransactionTimeout
Definition proc.c:62
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:348
bool am_walsender
Definition walsender.c:123
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2010
void InitWalSender(void)
Definition walsender.c:301
void WalSndSignals(void)
Definition walsender.c:3734
#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:5011
bool IsAbortedTransactionBlockState(void)
Definition xact.c:408
void EndImplicitTransactionBlock(void)
Definition xact.c:4373
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:915
void AbortCurrentTransaction(void)
Definition xact.c:3472

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(), 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_PROTOCOL, 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 4043 of file postgres.c.

4045{
4046 const char *dbname = NULL;
4047
4049
4050 /* Initialize startup process environment. */
4051 InitStandaloneProcess(argv[0]);
4052
4053 /*
4054 * Set default values for command-line options.
4055 */
4057
4058 /*
4059 * Parse command-line options.
4060 */
4062
4063 /* Must have gotten a database name, or have a default (the username) */
4064 if (dbname == NULL)
4065 {
4066 dbname = username;
4067 if (dbname == NULL)
4068 ereport(FATAL,
4070 errmsg("%s: no database nor user name specified",
4071 progname)));
4072 }
4073
4074 /* Acquire configuration parameters */
4076 proc_exit(1);
4077
4078 /*
4079 * Validate we have been given a reasonable-looking DataDir and change
4080 * into it.
4081 */
4082 checkDataDir();
4084
4085 /*
4086 * Create lockfile for data directory.
4087 */
4088 CreateDataDirLockFile(false);
4089
4090 /* read control file (error checking and contains config ) */
4092
4093 /*
4094 * process any libraries that should be preloaded at postmaster start
4095 */
4097
4098 /* Initialize MaxBackends */
4100
4101 /*
4102 * We don't need postmaster child slots in single-user mode, but
4103 * initialize them anyway to avoid having special handling.
4104 */
4106
4107 /* Initialize size of fast-path lock cache. */
4109
4110 /*
4111 * Give preloaded libraries a chance to request additional shared memory.
4112 */
4114
4115 /*
4116 * Now that loadable modules have had their chance to request additional
4117 * shared memory, determine the value of any runtime-computed GUCs that
4118 * depend on the amount of shared memory required.
4119 */
4121
4122 /*
4123 * Now that modules have been loaded, we can process any custom resource
4124 * managers specified in the wal_consistency_checking GUC.
4125 */
4127
4128 /*
4129 * Create shared memory etc. (Nothing's really "shared" in single-user
4130 * mode, but we must have these data structures anyway.)
4131 */
4133
4134 /*
4135 * Estimate number of openable files. This must happen after setting up
4136 * semaphores, because on some platforms semaphores count as open files.
4137 */
4139
4140 /*
4141 * Remember stand-alone backend startup time,roughly at the same point
4142 * during startup that postmaster does so.
4143 */
4145
4146 /*
4147 * Create a per-backend PGPROC struct in shared memory. We must do this
4148 * before we can use LWLocks.
4149 */
4150 InitProcess();
4151
4152 /*
4153 * Now that sufficient infrastructure has been initialized, PostgresMain()
4154 * can do the rest.
4155 */
4157}
TimestampTz PgStartTime
Definition timestamp.c:54
void set_max_safe_fds(void)
Definition fd.c:1044
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition guc.c:1655
void InitializeGUCOptions(void)
Definition guc.c:1407
@ PGC_POSTMASTER
Definition guc.h:74
void InitializeShmemGUCs(void)
Definition ipci.c:340
void CreateSharedMemoryAndSemaphores(void)
Definition ipci.c:191
const char * progname
Definition main.c:44
void ChangeToDataDir(void)
Definition miscinit.c:409
void process_shmem_requests(void)
Definition miscinit.c:1879
void InitStandaloneProcess(const char *argv0)
Definition miscinit.c:175
void process_shared_preload_libraries(void)
Definition miscinit.c:1851
void checkDataDir(void)
Definition miscinit.c:296
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1463
void InitPostmasterChildSlots(void)
Definition pmchild.c:97
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3778
static const char * userDoption
Definition postgres.c:154
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4172
void InitializeMaxBackends(void)
Definition postinit.c:550
void InitializeFastPathLocks(void)
Definition postinit.c:575
void InitProcess(void)
Definition proc.c:395
void InitializeWalConsistencyChecking(void)
Definition xlog.c:4858
void LocalProcessControlFile(bool reset)
Definition xlog.c:4939

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, SelectConfigFiles(), set_max_safe_fds(), 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 3778 of file postgres.c.

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

Referenced by PostgresSingleUserMain(), and process_startup_options().

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)
extern

Definition at line 501 of file postgres.c.

502{
503 int save_errno = errno;
504
506 {
507 /* Check for general interrupts that arrived before/while reading */
509
510 /* Process sinval catchup interrupts, if any */
513
514 /* Process notify interrupts, if any */
517 }
518 else if (ProcDiePending)
519 {
520 /*
521 * We're dying. If there is no data available to read, then it's safe
522 * (and sane) to handle that now. If we haven't tried to read yet,
523 * make sure the process latch is set, so that if there is no data
524 * then we'll come back here and die. If we're done reading, also
525 * make sure the process latch is set, as we might've undesirably
526 * cleared it while reading.
527 */
528 if (blocked)
530 else
532 }
533
535}
void ProcessCatchupInterrupt(void)
Definition sinval.c:174
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 547 of file postgres.c.

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

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

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

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

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

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char title)
extern

Definition at line 5047 of file postgres.c.

5048{
5050 struct timeval user,
5051 sys;
5052 struct timeval elapse_t;
5053 struct rusage r;
5054
5057 memcpy(&user, &r.ru_utime, sizeof(user));
5058 memcpy(&sys, &r.ru_stime, sizeof(sys));
5059 if (elapse_t.tv_usec < Save_t.tv_usec)
5060 {
5061 elapse_t.tv_sec--;
5062 elapse_t.tv_usec += 1000000;
5063 }
5064 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5065 {
5066 r.ru_utime.tv_sec--;
5067 r.ru_utime.tv_usec += 1000000;
5068 }
5069 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5070 {
5071 r.ru_stime.tv_sec--;
5072 r.ru_stime.tv_usec += 1000000;
5073 }
5074
5075 /*
5076 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5077 * some work to interpret them, and most platforms don't fill them in.
5078 */
5080
5081 appendStringInfoString(&str, "! system usage stats:\n");
5083 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5084 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5085 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5086 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5087 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5088 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5089 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5091 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5092 (long) user.tv_sec,
5093 (long) user.tv_usec,
5094 (long) sys.tv_sec,
5095 (long) sys.tv_usec);
5096#ifndef WIN32
5097
5098 /*
5099 * The following rusage fields are not defined by POSIX, but they're
5100 * present on all current Unix-like systems so we use them without any
5101 * special checks. Some of these could be provided in our Windows
5102 * emulation in src/port/win32getrusage.c with more work.
5103 */
5105 "!\t%ld kB max resident size\n",
5107 /* in bytes on macOS */
5108 r.ru_maxrss / 1024
5109#else
5110 /* in kilobytes on most other platforms */
5111 r.ru_maxrss
5112#endif
5113 );
5115 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5116 r.ru_inblock - Save_r.ru_inblock,
5117 /* they only drink coffee at dec */
5118 r.ru_oublock - Save_r.ru_oublock,
5119 r.ru_inblock, r.ru_oublock);
5121 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5122 r.ru_majflt - Save_r.ru_majflt,
5123 r.ru_minflt - Save_r.ru_minflt,
5124 r.ru_majflt, r.ru_minflt,
5125 r.ru_nswap - Save_r.ru_nswap,
5126 r.ru_nswap);
5128 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5129 r.ru_nsignals - Save_r.ru_nsignals,
5130 r.ru_nsignals,
5131 r.ru_msgrcv - Save_r.ru_msgrcv,
5132 r.ru_msgsnd - Save_r.ru_msgsnd,
5133 r.ru_msgrcv, r.ru_msgsnd);
5135 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5136 r.ru_nvcsw - Save_r.ru_nvcsw,
5137 r.ru_nivcsw - Save_r.ru_nivcsw,
5138 r.ru_nvcsw, r.ru_nivcsw);
5139#endif /* !WIN32 */
5140
5141 /* remove trailing newline */
5142 if (str.data[str.len - 1] == '\n')
5143 str.data[--str.len] = '\0';
5144
5145 ereport(LOG,
5146 (errmsg_internal("%s", title),
5147 errdetail_internal("%s", str.data)));
5148
5149 pfree(str.data);
5150}
#define __darwin__
Definition darwin.h:3
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
int errdetail_internal(const char *fmt,...)
Definition elog.c:1243
static char * user
Definition pg_regress.c:119
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, 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 3041 of file postgres.c.

3042{
3043 /*
3044 * Don't joggle the elbow of proc_exit
3045 */
3047 {
3048 InterruptPending = true;
3049 QueryCancelPending = true;
3050 }
3051
3052 /* If we're still here, waken anything waiting on the process latch */
3054}

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

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ Log_disconnections

PGDLLIMPORT bool Log_disconnections
extern

Definition at line 95 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 97 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ restrict_nonsystem_relation_kind

◆ whereToSendOutput