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

2426{
2429 {
2430 long secs;
2431 int usecs;
2432 int msecs;
2433 bool exceeded_duration;
2435 bool in_sample = false;
2436
2439 &secs, &usecs);
2440 msecs = usecs / 1000;
2441
2442 /*
2443 * This odd-looking test for log_min_duration_* being exceeded is
2444 * designed to avoid integer overflow with very long durations: don't
2445 * compute secs * 1000 until we've verified it will fit in int.
2446 */
2449 (secs > log_min_duration_statement / 1000 ||
2450 secs * 1000 + msecs >= log_min_duration_statement)));
2451
2454 (secs > log_min_duration_sample / 1000 ||
2455 secs * 1000 + msecs >= log_min_duration_sample)));
2456
2457 /*
2458 * Do not log if log_statement_sample_rate = 0. Log a sample if
2459 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2460 * log_statement_sample_rate = 1.
2461 */
2466
2468 {
2469 snprintf(msec_str, 32, "%ld.%03d",
2470 secs * 1000 + msecs, usecs % 1000);
2472 return 2;
2473 else
2474 return 1;
2475 }
2476 }
2477
2478 return 0;
2479}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1715
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
int log_min_duration_statement
Definition guc_tables.c: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:517
double pg_prng_double(pg_prng_state *state)
Definition pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition pg_prng.c:34
#define snprintf
Definition port.h:260
static int fb(int x)
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition xact.c:881
bool xact_is_sampled
Definition xact.c:298

References fb(), GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_sample, log_min_duration_statement, log_statement_sample_rate, pg_global_prng_state, pg_prng_double(), snprintf, TimestampDifference(), and xact_is_sampled.

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

◆ die()

void die ( SIGNAL_ARGS  )
extern

Definition at line 3012 of file postgres.c.

3013{
3014 /* Don't joggle the elbow of proc_exit */
3016 {
3017 InterruptPending = true;
3018 ProcDiePending = true;
3019 }
3020
3021 /* for the cumulative stats system */
3023
3024 /* If we're still here, waken anything waiting on the process latch */
3026
3027 /*
3028 * If we're in single user mode, we want to quit immediately - we can't
3029 * rely on latches as they wouldn't work when stdin/stdout is a file.
3030 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3031 * effort just for the benefit of single user mode.
3032 */
3035}
@ 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:64
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition postgres.c:94
static bool DoingCommandRead
Definition postgres.c:139
void ProcessInterrupts(void)
Definition postgres.c:3339

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

3060{
3061 /* We're not returning, so no need to save errno */
3062 ereport(ERROR,
3064 errmsg("floating-point exception"),
3065 errdetail("An invalid floating-point operation was signaled. "
3066 "This probably means an out-of-range result or an "
3067 "invalid operation, such as division by zero.")));
3068}
int errcode(int sqlerrcode)
Definition elog.c:874
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:151
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 3794 of file postgres.c.

3795{
3796 switch (arg[0])
3797 {
3798 case 'p':
3799 if (arg[1] == 'a') /* "parser" */
3800 return "log_parser_stats";
3801 else if (arg[1] == 'l') /* "planner" */
3802 return "log_planner_stats";
3803 break;
3804
3805 case 'e': /* "executor" */
3806 return "log_executor_stats";
3807 break;
3808 }
3809
3810 return NULL;
3811}
Datum arg
Definition elog.c:1322

References arg, and fb().

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( void  )
extern

Definition at line 3075 of file postgres.c.

3076{
3078 InterruptPending = true;
3079 /* latch will be set by procsignal_sigusr1_handler */
3080}
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
PGPROC * MyProc
Definition proc.c:69
pg_atomic_uint32 pendingRecoveryConflicts
Definition proc.h:269

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

675{
676 Query *query;
678
680
681 /*
682 * (1) Perform parse analysis.
683 */
685 ResetUsage();
686
687 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
688 queryEnv);
689
691 ShowUsage("PARSE ANALYSIS STATISTICS");
692
693 /*
694 * (2) Rewrite the queries, as necessary
695 */
697
699
700 return querytree_list;
701}
bool log_parser_stats
Definition guc_tables.c:530
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition analyze.c:127
List * pg_rewrite_query(Query *query)
Definition postgres.c:803
void ShowUsage(const char *title)
Definition postgres.c:5094
void ResetUsage(void)
Definition postgres.c:5087
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 709 of file postgres.c.

714{
715 Query *query;
717
719
720 /*
721 * (1) Perform parse analysis.
722 */
724 ResetUsage();
725
726 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
727 queryEnv);
728
729 /*
730 * Check all parameter types got determined.
731 */
732 for (int i = 0; i < *numParams; i++)
733 {
734 Oid ptype = (*paramTypes)[i];
735
736 if (ptype == InvalidOid || ptype == UNKNOWNOID)
739 errmsg("could not determine data type of parameter $%d",
740 i + 1)));
741 }
742
744 ShowUsage("PARSE ANALYSIS STATISTICS");
745
746 /*
747 * (2) Rewrite the queries, as necessary
748 */
750
752
753 return querytree_list;
754}
int i
Definition isn.c:77
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition analyze.c:167
#define InvalidOid
unsigned int Oid

References ereport, errcode(), errmsg, ERROR, fb(), i, InvalidOid, log_parser_stats, parse_analyze_varparams(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by exec_parse_message(), and PrepareQuery().

◆ pg_analyze_and_rewrite_withcb()

List * pg_analyze_and_rewrite_withcb ( RawStmt parsetree,
const char query_string,
ParserSetupHook  parserSetup,
void parserSetupArg,
QueryEnvironment queryEnv 
)
extern

Definition at line 763 of file postgres.c.

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

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

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

◆ pg_parse_query()

List * pg_parse_query ( const char query_string)
extern

Definition at line 604 of file postgres.c.

605{
607
609
611 ResetUsage();
612
614
616 ShowUsage("PARSER STATISTICS");
617
618#ifdef DEBUG_NODE_TESTS_ENABLED
619
620 /* Optional debugging check: pass raw parsetrees through copyObject() */
622 {
624
625 /* This checks both copyObject() and the equal() routines... */
627 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
628 else
630 }
631
632 /*
633 * Optional debugging check: pass raw parsetrees through
634 * outfuncs/readfuncs
635 */
637 {
640
641 pfree(str);
642 /* This checks both outfuncs/readfuncs and the equal() routines... */
644 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
645 else
647 }
648
649#endif /* DEBUG_NODE_TESTS_ENABLED */
650
652
654 elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
656
657 return raw_parsetree_list;
658}
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:227
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
bool Debug_print_raw_parse
Definition guc_tables.c:520
bool Debug_pretty_print
Definition guc_tables.c:522
const char * str
static List * new_list(NodeTag type, int min_size)
Definition list.c:91
void pfree(void *pointer)
Definition mcxt.c:1616
#define copyObject(obj)
Definition nodes.h:232
char * nodeToStringWithLocations(const void *obj)
Definition outfuncs.c:817
@ RAW_PARSE_DEFAULT
Definition parser.h:39

References copyObject, Debug_pretty_print, Debug_print_raw_parse, elog, elog_node_display(), equal(), fb(), LOG, log_parser_stats, new_list(), nodeToStringWithLocations(), pfree(), RAW_PARSE_DEFAULT, raw_parser(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), inline_function(), inline_sql_function_in_from(), sql_compile_callback(), and test_inline_in_from_support_func().

◆ pg_plan_queries()

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

Definition at line 975 of file postgres.c.

977{
978 List *stmt_list = NIL;
979 ListCell *query_list;
980
981 foreach(query_list, querytrees)
982 {
983 Query *query = lfirst_node(Query, query_list);
985
986 if (query->commandType == CMD_UTILITY)
987 {
988 /* Utility commands require no planning. */
990 stmt->commandType = CMD_UTILITY;
991 stmt->canSetTag = query->canSetTag;
992 stmt->utilityStmt = query->utilityStmt;
993 stmt->stmt_location = query->stmt_location;
994 stmt->stmt_len = query->stmt_len;
995 stmt->queryId = query->queryId;
996 stmt->planOrigin = PLAN_STMT_INTERNAL;
997 }
998 else
999 {
1000 stmt = pg_plan_query(query, query_string, cursorOptions,
1001 boundParams, NULL);
1002 }
1003
1004 stmt_list = lappend(stmt_list, stmt);
1005 }
1006
1007 return stmt_list;
1008}
#define stmt
List * lappend(List *list, void *datum)
Definition list.c:339
@ CMD_UTILITY
Definition nodes.h:280
#define makeNode(_type_)
Definition nodes.h:161
#define lfirst_node(type, lc)
Definition pg_list.h:176
#define NIL
Definition pg_list.h:68
@ PLAN_STMT_INTERNAL
Definition plannodes.h:38
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition postgres.c:887
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
ParseLoc stmt_location
Definition parsenodes.h:258

References CMD_UTILITY, Query::commandType, fb(), lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PLAN_STMT_INTERNAL, stmt, Query::stmt_location, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

◆ pg_plan_query()

PlannedStmt * pg_plan_query ( Query querytree,
const char query_string,
int  cursorOptions,
ParamListInfo  boundParams,
ExplainState es 
)
extern

Definition at line 887 of file postgres.c.

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

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

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

◆ pg_rewrite_query()

List * pg_rewrite_query ( Query query)
extern

Definition at line 803 of file postgres.c.

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

4220{
4222
4223 /* these must be volatile to ensure state is preserved across longjmp: */
4224 volatile bool send_ready_for_query = true;
4225 volatile bool idle_in_transaction_timeout_enabled = false;
4226 volatile bool idle_session_timeout_enabled = false;
4227
4228 Assert(dbname != NULL);
4229 Assert(username != NULL);
4230
4232
4233 /*
4234 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4235 * has already set up BlockSig and made that the active signal mask.)
4236 *
4237 * Note that postmaster blocked all signals before forking child process,
4238 * so there is no race condition whereby we might receive a signal before
4239 * we have set up the handler.
4240 *
4241 * Also note: it's best not to use any signals that are SIG_IGNored in the
4242 * postmaster. If such a signal arrives before we are able to change the
4243 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4244 * handler in the postmaster to reserve the signal. (Of course, this isn't
4245 * an issue for signals that are locally generated, such as SIGALRM and
4246 * SIGPIPE.)
4247 */
4248 if (am_walsender)
4249 WalSndSignals();
4250 else
4251 {
4253 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4254 pqsignal(SIGTERM, die); /* cancel current query and exit */
4255
4256 /*
4257 * In a postmaster child backend, replace SignalHandlerForCrashExit
4258 * with quickdie, so we can tell the client we're dying.
4259 *
4260 * In a standalone backend, SIGQUIT can be generated from the keyboard
4261 * easily, while SIGTERM cannot, so we make both signals do die()
4262 * rather than quickdie().
4263 */
4265 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4266 else
4267 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4268 InitializeTimeouts(); /* establishes SIGALRM handler */
4269
4270 /*
4271 * Ignore failure to write to frontend. Note: if frontend closes
4272 * connection, we will notice it and exit cleanly when control next
4273 * returns to outer loop. This seems safer than forcing exit in the
4274 * midst of output during who-knows-what operation...
4275 */
4280
4281 /*
4282 * Reset some signals that are accepted by postmaster but not by
4283 * backend
4284 */
4285 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4286 * platforms */
4287 }
4288
4289 /* Early initialization */
4290 BaseInit();
4291
4292 /* We need to allow SIGINT, etc during the initial transaction */
4294
4295 /*
4296 * Generate a random cancel key, if this is a backend serving a
4297 * connection. InitPostgres() will advertise it in shared memory.
4298 */
4301 {
4302 int len;
4303
4304 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4307 {
4308 ereport(ERROR,
4310 errmsg("could not generate random cancel key")));
4311 }
4313 }
4314
4315 /*
4316 * General initialization.
4317 *
4318 * NOTE: if you are tempted to add code in this vicinity, consider putting
4319 * it inside InitPostgres() instead. In particular, anything that
4320 * involves database access should be there, not here.
4321 *
4322 * Honor session_preload_libraries if not dealing with a WAL sender.
4323 */
4324 InitPostgres(dbname, InvalidOid, /* database to connect to */
4325 username, InvalidOid, /* role to connect as */
4327 NULL); /* no out_dbname */
4328
4329 /*
4330 * If the PostmasterContext is still around, recycle the space; we don't
4331 * need it anymore after InitPostgres completes.
4332 */
4334 {
4337 }
4338
4340
4341 /*
4342 * Now all GUC states are fully set up. Report them to client if
4343 * appropriate.
4344 */
4346
4347 /*
4348 * Also set up handler to log session end; we have to wait till now to be
4349 * sure Log_disconnections has its final value.
4350 */
4353
4355
4356 /* Perform initialization specific to a WAL sender process. */
4357 if (am_walsender)
4358 InitWalSender();
4359
4360 /*
4361 * Send this backend's cancellation info to the frontend.
4362 */
4364 {
4366
4370
4373 /* Need not flush since ReadyForQuery will do it. */
4374 }
4375
4376 /* Welcome banner for standalone case */
4378 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4379
4380 /*
4381 * Create the memory context we will use in the main loop.
4382 *
4383 * MessageContext is reset once per iteration of the main loop, ie, upon
4384 * completion of processing of each command message from the client.
4385 */
4387 "MessageContext",
4389
4390 /*
4391 * Create memory context and buffer used for RowDescription messages. As
4392 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4393 * frequently executed for every single statement, we don't want to
4394 * allocate a separate buffer every time.
4395 */
4397 "RowDescriptionContext",
4402
4403 /* Fire any defined login event triggers, if appropriate */
4405
4406 /*
4407 * POSTGRES main processing loop begins here
4408 *
4409 * If an exception is encountered, processing resumes here so we abort the
4410 * current transaction and start a new one.
4411 *
4412 * You might wonder why this isn't coded as an infinite loop around a
4413 * PG_TRY construct. The reason is that this is the bottom of the
4414 * exception stack, and so with PG_TRY there would be no exception handler
4415 * in force at all during the CATCH part. By leaving the outermost setjmp
4416 * always active, we have at least some chance of recovering from an error
4417 * during error recovery. (If we get into an infinite loop thereby, it
4418 * will soon be stopped by overflow of elog.c's internal state stack.)
4419 *
4420 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4421 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4422 * is essential in case we longjmp'd out of a signal handler on a platform
4423 * where that leaves the signal blocked. It's not redundant with the
4424 * unblock in AbortTransaction() because the latter is only called if we
4425 * were inside a transaction.
4426 */
4427
4428 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4429 {
4430 /*
4431 * NOTE: if you are tempted to add more code in this if-block,
4432 * consider the high probability that it should be in
4433 * AbortTransaction() instead. The only stuff done directly here
4434 * should be stuff that is guaranteed to apply *only* for outer-level
4435 * error recovery, such as adjusting the FE/BE protocol status.
4436 */
4437
4438 /* Since not using PG_TRY, must reset error stack by hand */
4440
4441 /* Prevent interrupts while cleaning up */
4443
4444 /*
4445 * Forget any pending QueryCancel request, since we're returning to
4446 * the idle loop anyway, and cancel any active timeout requests. (In
4447 * future we might want to allow some timeout requests to survive, but
4448 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4449 * we got here because of a query cancel interrupting the SIGALRM
4450 * interrupt handler.) Note in particular that we must clear the
4451 * statement and lock timeout indicators, to prevent any future plain
4452 * query cancels from being misreported as timeouts in case we're
4453 * forgetting a timeout cancel.
4454 */
4455 disable_all_timeouts(false); /* do first to avoid race condition */
4456 QueryCancelPending = false;
4459
4460 /* Not reading from the client anymore. */
4461 DoingCommandRead = false;
4462
4463 /* Make sure libpq is in a good state */
4464 pq_comm_reset();
4465
4466 /* Report the error to the client and/or server log */
4468
4469 /*
4470 * If Valgrind noticed something during the erroneous query, print the
4471 * query string, assuming we have one.
4472 */
4474
4475 /*
4476 * Make sure debug_query_string gets reset before we possibly clobber
4477 * the storage it points at.
4478 */
4480
4481 /*
4482 * Abort the current transaction in order to recover.
4483 */
4485
4486 if (am_walsender)
4488
4490
4491 /*
4492 * We can't release replication slots inside AbortTransaction() as we
4493 * need to be able to start and abort transactions while having a slot
4494 * acquired. But we never need to hold them across top level errors,
4495 * so releasing here is fine. There also is a before_shmem_exit()
4496 * callback ensuring correct cleanup on FATAL errors.
4497 */
4498 if (MyReplicationSlot != NULL)
4500
4501 /* We also want to cleanup temporary slots on error. */
4503
4505
4506 /*
4507 * Now return to normal top-level context and clear ErrorContext for
4508 * next time.
4509 */
4512
4513 /*
4514 * If we were handling an extended-query-protocol message, initiate
4515 * skip till next Sync. This also causes us not to issue
4516 * ReadyForQuery (until we get Sync).
4517 */
4519 ignore_till_sync = true;
4520
4521 /* We don't have a transaction command open anymore */
4522 xact_started = false;
4523
4524 /*
4525 * If an error occurred while we were reading a message from the
4526 * client, we have potentially lost track of where the previous
4527 * message ends and the next one begins. Even though we have
4528 * otherwise recovered from the error, we cannot safely read any more
4529 * messages from the client, so there isn't much we can do with the
4530 * connection anymore.
4531 */
4532 if (pq_is_reading_msg())
4533 ereport(FATAL,
4535 errmsg("terminating connection because protocol synchronization was lost")));
4536
4537 /* Now we can allow interrupts again */
4539 }
4540
4541 /* We can now handle ereport(ERROR) */
4543
4544 if (!ignore_till_sync)
4545 send_ready_for_query = true; /* initially, or after error */
4546
4547 /*
4548 * Non-error queries loop here.
4549 */
4550
4551 for (;;)
4552 {
4553 int firstchar;
4555
4556 /*
4557 * At top of loop, reset extended-query-message flag, so that any
4558 * errors encountered in "idle" state don't provoke skip.
4559 */
4561
4562 /*
4563 * For valgrind reporting purposes, the "current query" begins here.
4564 */
4565#ifdef USE_VALGRIND
4567#endif
4568
4569 /*
4570 * Release storage left over from prior query cycle, and create a new
4571 * query input buffer in the cleared MessageContext.
4572 */
4575
4577
4578 /*
4579 * Also consider releasing our catalog snapshot if any, so that it's
4580 * not preventing advance of global xmin while we wait for the client.
4581 */
4583
4584 /*
4585 * (1) If we've reached idle state, tell the frontend we're ready for
4586 * a new query.
4587 *
4588 * Note: this includes fflush()'ing the last of the prior output.
4589 *
4590 * This is also a good time to flush out collected statistics to the
4591 * cumulative stats system, and to update the PS stats display. We
4592 * avoid doing those every time through the message loop because it'd
4593 * slow down processing of batched messages, and because we don't want
4594 * to report uncommitted updates (that confuses autovacuum). The
4595 * notification processor wants a call too, if we are not in a
4596 * transaction block.
4597 *
4598 * Also, if an idle timeout is enabled, start the timer for that.
4599 */
4601 {
4603 {
4604 set_ps_display("idle in transaction (aborted)");
4606
4607 /* Start the idle-in-transaction timer */
4610 {
4614 }
4615 }
4617 {
4618 set_ps_display("idle in transaction");
4620
4621 /* Start the idle-in-transaction timer */
4624 {
4628 }
4629 }
4630 else
4631 {
4632 long stats_timeout;
4633
4634 /*
4635 * Process incoming notifies (including self-notifies), if
4636 * any, and send relevant messages to the client. Doing it
4637 * here helps ensure stable behavior in tests: if any notifies
4638 * were received during the just-finished transaction, they'll
4639 * be seen by the client before ReadyForQuery is.
4640 */
4643
4644 /*
4645 * Check if we need to report stats. If pgstat_report_stat()
4646 * decides it's too soon to flush out pending stats / lock
4647 * contention prevented reporting, it'll tell us when we
4648 * should try to report stats again (so that stats updates
4649 * aren't unduly delayed if the connection goes idle for a
4650 * long time). We only enable the timeout if we don't already
4651 * have a timeout in progress, because we don't disable the
4652 * timeout below. enable_timeout_after() needs to determine
4653 * the current timestamp, which can have a negative
4654 * performance impact. That's OK because pgstat_report_stat()
4655 * won't have us wake up sooner than a prior call.
4656 */
4658 if (stats_timeout > 0)
4659 {
4663 }
4664 else
4665 {
4666 /* all stats flushed, no need for the timeout */
4669 }
4670
4671 set_ps_display("idle");
4673
4674 /* Start the idle-session timer */
4675 if (IdleSessionTimeout > 0)
4676 {
4680 }
4681 }
4682
4683 /* Report any recently-changed GUC options */
4685
4686 /*
4687 * The first time this backend is ready for query, log the
4688 * durations of the different components of connection
4689 * establishment and setup.
4690 */
4694 {
4698
4700
4710
4711 ereport(LOG,
4712 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4713 (double) total_duration / NS_PER_US,
4714 (double) fork_duration / NS_PER_US,
4715 (double) auth_duration / NS_PER_US));
4716 }
4717
4719 send_ready_for_query = false;
4720 }
4721
4722 /*
4723 * (2) Allow asynchronous signals to be executed immediately if they
4724 * come in while we are waiting for client input. (This must be
4725 * conditional since we don't want, say, reads on behalf of COPY FROM
4726 * STDIN doing the same thing.)
4727 */
4728 DoingCommandRead = true;
4729
4730 /*
4731 * (3) read a command (loop blocks here)
4732 */
4734
4735 /*
4736 * (4) turn off the idle-in-transaction and idle-session timeouts if
4737 * active. We do this before step (5) so that any last-moment timeout
4738 * is certain to be detected in step (5).
4739 *
4740 * At most one of these timeouts will be active, so there's no need to
4741 * worry about combining the timeout.c calls into one.
4742 */
4744 {
4747 }
4749 {
4752 }
4753
4754 /*
4755 * (5) disable async signal conditions again.
4756 *
4757 * Query cancel is supposed to be a no-op when there is no query in
4758 * progress, so if a query cancel arrived while we were idle, just
4759 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4760 * it's called when DoingCommandRead is set, so check for interrupts
4761 * before resetting DoingCommandRead.
4762 */
4764 DoingCommandRead = false;
4765
4766 /*
4767 * (6) check for any other interesting events that happened while we
4768 * slept.
4769 */
4771 {
4772 ConfigReloadPending = false;
4774 }
4775
4776 /*
4777 * (7) process the command. But ignore it if we're skipping till
4778 * Sync.
4779 */
4780 if (ignore_till_sync && firstchar != EOF)
4781 continue;
4782
4783 switch (firstchar)
4784 {
4785 case PqMsg_Query:
4786 {
4787 const char *query_string;
4788
4789 /* Set statement_timestamp() */
4791
4792 query_string = pq_getmsgstring(&input_message);
4794
4795 if (am_walsender)
4796 {
4797 if (!exec_replication_command(query_string))
4798 exec_simple_query(query_string);
4799 }
4800 else
4801 exec_simple_query(query_string);
4802
4803 valgrind_report_error_query(query_string);
4804
4805 send_ready_for_query = true;
4806 }
4807 break;
4808
4809 case PqMsg_Parse:
4810 {
4811 const char *stmt_name;
4812 const char *query_string;
4813 int numParams;
4814 Oid *paramTypes = NULL;
4815
4817
4818 /* Set statement_timestamp() */
4820
4821 stmt_name = pq_getmsgstring(&input_message);
4822 query_string = pq_getmsgstring(&input_message);
4823 numParams = pq_getmsgint(&input_message, 2);
4824 if (numParams > 0)
4825 {
4826 paramTypes = palloc_array(Oid, numParams);
4827 for (int i = 0; i < numParams; i++)
4828 paramTypes[i] = pq_getmsgint(&input_message, 4);
4829 }
4831
4832 exec_parse_message(query_string, stmt_name,
4833 paramTypes, numParams);
4834
4835 valgrind_report_error_query(query_string);
4836 }
4837 break;
4838
4839 case PqMsg_Bind:
4841
4842 /* Set statement_timestamp() */
4844
4845 /*
4846 * this message is complex enough that it seems best to put
4847 * the field extraction out-of-line
4848 */
4850
4851 /* exec_bind_message does valgrind_report_error_query */
4852 break;
4853
4854 case PqMsg_Execute:
4855 {
4856 const char *portal_name;
4857 int max_rows;
4858
4860
4861 /* Set statement_timestamp() */
4863
4867
4869
4870 /* exec_execute_message does valgrind_report_error_query */
4871 }
4872 break;
4873
4874 case PqMsg_FunctionCall:
4876
4877 /* Set statement_timestamp() */
4879
4880 /* Report query to various monitoring facilities. */
4882 set_ps_display("<FASTPATH>");
4883
4884 /* start an xact for this function invocation */
4886
4887 /*
4888 * Note: we may at this point be inside an aborted
4889 * transaction. We can't throw error for that until we've
4890 * finished reading the function-call message, so
4891 * HandleFunctionRequest() must check for it after doing so.
4892 * Be careful not to do anything that assumes we're inside a
4893 * valid transaction here.
4894 */
4895
4896 /* switch back to message context */
4898
4900
4901 /* commit the function-invocation transaction */
4903
4904 valgrind_report_error_query("fastpath function call");
4905
4906 send_ready_for_query = true;
4907 break;
4908
4909 case PqMsg_Close:
4910 {
4911 int close_type;
4912 const char *close_target;
4913
4915
4919
4920 switch (close_type)
4921 {
4922 case 'S':
4923 if (close_target[0] != '\0')
4925 else
4926 {
4927 /* special-case the unnamed statement */
4929 }
4930 break;
4931 case 'P':
4932 {
4933 Portal portal;
4934
4935 portal = GetPortalByName(close_target);
4936 if (PortalIsValid(portal))
4937 PortalDrop(portal, false);
4938 }
4939 break;
4940 default:
4941 ereport(ERROR,
4943 errmsg("invalid CLOSE message subtype %d",
4944 close_type)));
4945 break;
4946 }
4947
4950
4951 valgrind_report_error_query("CLOSE message");
4952 }
4953 break;
4954
4955 case PqMsg_Describe:
4956 {
4957 int describe_type;
4958 const char *describe_target;
4959
4961
4962 /* Set statement_timestamp() (needed for xact) */
4964
4968
4969 switch (describe_type)
4970 {
4971 case 'S':
4973 break;
4974 case 'P':
4976 break;
4977 default:
4978 ereport(ERROR,
4980 errmsg("invalid DESCRIBE message subtype %d",
4981 describe_type)));
4982 break;
4983 }
4984
4985 valgrind_report_error_query("DESCRIBE message");
4986 }
4987 break;
4988
4989 case PqMsg_Flush:
4992 pq_flush();
4993 break;
4994
4995 case PqMsg_Sync:
4997
4998 /*
4999 * If pipelining was used, we may be in an implicit
5000 * transaction block. Close it before calling
5001 * finish_xact_command.
5002 */
5005 valgrind_report_error_query("SYNC message");
5006 send_ready_for_query = true;
5007 break;
5008
5009 /*
5010 * PqMsg_Terminate means that the frontend is closing down the
5011 * socket. EOF means unexpected loss of frontend connection.
5012 * Either way, perform normal shutdown.
5013 */
5014 case EOF:
5015
5016 /* for the cumulative statistics system */
5018
5020
5021 case PqMsg_Terminate:
5022
5023 /*
5024 * Reset whereToSendOutput to prevent ereport from attempting
5025 * to send any more messages to client.
5026 */
5029
5030 /*
5031 * NOTE: if you are tempted to add more code here, DON'T!
5032 * Whatever you had in mind to do should be set up as an
5033 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5034 * it will fail to be called during other backend-shutdown
5035 * scenarios.
5036 */
5037 proc_exit(0);
5038
5039 case PqMsg_CopyData:
5040 case PqMsg_CopyDone:
5041 case PqMsg_CopyFail:
5042
5043 /*
5044 * Accept but ignore these messages, per protocol spec; we
5045 * probably got here because a COPY failed, and the frontend
5046 * is still sending data.
5047 */
5048 break;
5049
5050 default:
5051 ereport(FATAL,
5053 errmsg("invalid frontend message type %d",
5054 firstchar)));
5055 }
5056 } /* end of input-reading loop */
5057}
void ProcessNotifyInterrupt(bool flush)
Definition async.c:2582
volatile sig_atomic_t notifyInterruptPending
Definition async.c:538
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition prepare.c:521
sigset_t UnBlockSig
Definition pqsignal.c:22
uint32 log_connections
ConnectionTiming conn_timing
@ LOG_CONNECTION_SETUP_DURATIONS
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
int32_t int32
Definition c.h:620
uint64_t uint64
Definition c.h:625
#define pg_fallthrough
Definition c.h:161
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
void ReadyForQuery(CommandDest dest)
Definition dest.c:257
@ DestDebug
Definition dest.h:88
@ DestNone
Definition dest.h:87
void EmitErrorReport(void)
Definition elog.c:1882
ErrorContextCallback * error_context_stack
Definition elog.c:99
void FlushErrorState(void)
Definition elog.c:2062
sigjmp_buf * PG_exception_stack
Definition elog.c:101
#define FATAL
Definition elog.h:41
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition fastpath.c:188
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
#define palloc_array(type, count)
Definition fe_memutils.h:76
int MyCancelKeyLength
Definition globals.c: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:2453
void ReportChangedGUCOptions(void)
Definition guc.c:2503
@ PGC_SIGHUP
Definition guc.h:75
static char * username
Definition initdb.c:153
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:316
void proc_exit(int code)
Definition ipc.c:105
void jit_reset_after_error(void)
Definition jit.c:128
#define pq_flush()
Definition libpq.h:49
#define pq_comm_reset()
Definition libpq.h:48
MemoryContext MessageContext
Definition mcxt.c:170
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
MemoryContext TopMemoryContext
Definition mcxt.c:166
MemoryContext PostmasterContext
Definition mcxt.c:168
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h: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:65
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
const void size_t len
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define die(msg)
long pgstat_report_stat(bool force)
Definition pgstat.c:722
@ DISCONNECT_CLIENT_EOF
Definition pgstat.h:62
void pgstat_report_connect(Oid dboid)
#define pqsignal
Definition port.h:547
bool pg_strong_random(void *buf, size_t len)
#define printf(...)
Definition port.h:266
#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:2629
void quickdie(SIGNAL_ARGS)
Definition postgres.c:2915
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5203
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5067
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2110
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3059
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3042
static bool ignore_till_sync
Definition postgres.c:146
static void finish_xact_command(void)
Definition postgres.c:2811
const char * debug_query_string
Definition postgres.c:91
static void exec_simple_query(const char *query_string)
Definition postgres.c:1017
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1394
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1628
static bool xact_started
Definition postgres.c:132
static MemoryContext row_description_context
Definition postgres.c:161
static StringInfoData row_description_buf
Definition postgres.c:162
static bool doing_extended_query_message
Definition postgres.c:145
static void start_xact_command(void)
Definition postgres.c:2772
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2721
bool Log_disconnections
Definition postgres.c:97
static void drop_unnamed_stmt(void)
Definition postgres.c:2890
#define valgrind_report_error_query(query)
Definition postgres.c:217
static int ReadCommand(StringInfo inBuf)
Definition postgres.c:481
void BaseInit(void)
Definition postinit.c:616
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:719
bool pq_is_reading_msg(void)
Definition pqcomm.c:1182
#define PG_PROTOCOL(m, n)
Definition pqcomm.h:89
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition pqformat.c:414
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition pqformat.c:126
void pq_getmsgend(StringInfo msg)
Definition pqformat.c:634
const char * pq_getmsgstring(StringInfo msg)
Definition pqformat.c:578
void pq_putemptymessage(char msgtype)
Definition pqformat.c:387
void pq_endmessage(StringInfo buf)
Definition pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition pqformat.c:398
void pq_beginmessage(StringInfo buf, char msgtype)
Definition pqformat.c:88
static void pq_sendint32(StringInfo buf, uint32 i)
Definition pqformat.h:144
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:680
#define MAX_CANCEL_KEY_LENGTH
Definition procsignal.h:61
#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:149
void ReplicationSlotRelease(void)
Definition slot.c:762
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:861
void InvalidateCatalogSnapshotConditionally(void)
Definition snapmgr.c:477
int IdleSessionTimeout
Definition proc.c:65
int IdleInTransactionSessionTimeout
Definition proc.c:63
int TransactionTimeout
Definition proc.c:64
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:349
bool am_walsender
Definition walsender.c:124
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2022
void InitWalSender(void)
Definition walsender.c:302
void WalSndSignals(void)
Definition walsender.c:3751
#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:5012
bool IsAbortedTransactionBlockState(void)
Definition xact.c:409
void EndImplicitTransactionBlock(void)
Definition xact.c:4374
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916
void AbortCurrentTransaction(void)
Definition xact.c:3473

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

4092{
4093 const char *dbname = NULL;
4094
4096
4097 /* Initialize startup process environment. */
4098 InitStandaloneProcess(argv[0]);
4099
4100 /*
4101 * Set default values for command-line options.
4102 */
4104
4105 /*
4106 * Parse command-line options.
4107 */
4109
4110 /* Must have gotten a database name, or have a default (the username) */
4111 if (dbname == NULL)
4112 {
4113 dbname = username;
4114 if (dbname == NULL)
4115 ereport(FATAL,
4117 errmsg("%s: no database nor user name specified",
4118 progname)));
4119 }
4120
4121 /* Acquire configuration parameters */
4123 proc_exit(1);
4124
4125 /*
4126 * Validate we have been given a reasonable-looking DataDir and change
4127 * into it.
4128 */
4129 checkDataDir();
4131
4132 /*
4133 * Create lockfile for data directory.
4134 */
4135 CreateDataDirLockFile(false);
4136
4137 /* read control file (error checking and contains config ) */
4139
4140 /*
4141 * process any libraries that should be preloaded at postmaster start
4142 */
4144
4145 /* Initialize MaxBackends */
4147
4148 /*
4149 * We don't need postmaster child slots in single-user mode, but
4150 * initialize them anyway to avoid having special handling.
4151 */
4153
4154 /* Initialize size of fast-path lock cache. */
4156
4157 /*
4158 * Give preloaded libraries a chance to request additional shared memory.
4159 */
4161
4162 /*
4163 * Now that loadable modules have had their chance to request additional
4164 * shared memory, determine the value of any runtime-computed GUCs that
4165 * depend on the amount of shared memory required.
4166 */
4168
4169 /*
4170 * Now that modules have been loaded, we can process any custom resource
4171 * managers specified in the wal_consistency_checking GUC.
4172 */
4174
4175 /*
4176 * Create shared memory etc. (Nothing's really "shared" in single-user
4177 * mode, but we must have these data structures anyway.)
4178 */
4180
4181 /*
4182 * Estimate number of openable files. This must happen after setting up
4183 * semaphores, because on some platforms semaphores count as open files.
4184 */
4186
4187 /*
4188 * Remember stand-alone backend startup time,roughly at the same point
4189 * during startup that postmaster does so.
4190 */
4192
4193 /*
4194 * Create a per-backend PGPROC struct in shared memory. We must do this
4195 * before we can use LWLocks.
4196 */
4197 InitProcess();
4198
4199 /*
4200 * Now that sufficient infrastructure has been initialized, PostgresMain()
4201 * can do the rest.
4202 */
4204}
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 InitializeShmemGUCs(void)
Definition ipci.c:335
void CreateSharedMemoryAndSemaphores(void)
Definition ipci.c:192
const char * progname
Definition main.c:44
void ChangeToDataDir(void)
Definition miscinit.c:410
void process_shmem_requests(void)
Definition miscinit.c:1880
void InitStandaloneProcess(const char *argv0)
Definition miscinit.c:176
void process_shared_preload_libraries(void)
Definition miscinit.c:1852
void checkDataDir(void)
Definition miscinit.c:297
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1464
void InitPostmasterChildSlots(void)
Definition pmchild.c:97
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3834
static const char * userDoption
Definition postgres.c:156
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4219
void InitializeMaxBackends(void)
Definition postinit.c:559
void InitializeFastPathLocks(void)
Definition postinit.c:584
void InitProcess(void)
Definition proc.c:381
void InitializeWalConsistencyChecking(void)
Definition xlog.c:4842
void LocalProcessControlFile(bool reset)
Definition xlog.c:4923

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

3836{
3837 bool secure = (ctx == PGC_POSTMASTER);
3838 int errs = 0;
3840 int flag;
3842
3843 if (secure)
3844 {
3845 gucsource = PGC_S_ARGV; /* switches came from command line */
3846
3847 /* Ignore the initial --single argument, if present */
3848 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3849 {
3850 argv++;
3851 argc--;
3852 }
3853 }
3854 else
3855 {
3856 gucsource = PGC_S_CLIENT; /* switches came from client */
3857 }
3858
3859 /*
3860 * Parse command-line options. CAUTION: keep this in sync with
3861 * postmaster/postmaster.c (the option sets should not conflict) and with
3862 * the common help() function in main/main.c.
3863 */
3864 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
3865
3866 /*
3867 * Turn this off because it's either printed to stderr and not the log
3868 * where we'd want it, or argv[0] is now "--single", which would make for
3869 * a weird error message. We print our own error message below.
3870 */
3871 optctx.opterr = 0;
3872
3873 while ((flag = pg_getopt_next(&optctx)) != -1)
3874 {
3875 switch (flag)
3876 {
3877 case 'B':
3878 SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
3879 break;
3880
3881 case 'b':
3882 /* Undocumented flag used for binary upgrades */
3883 if (secure)
3884 IsBinaryUpgrade = true;
3885 break;
3886
3887 case 'C':
3888 /* ignored for consistency with the postmaster */
3889 break;
3890
3891 case '-':
3892
3893 /*
3894 * Error if the user misplaced a special must-be-first option
3895 * for dispatching to a subprogram. parse_dispatch_option()
3896 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3897 * error for anything else.
3898 */
3900 ereport(ERROR,
3902 errmsg("--%s must be first argument", optctx.optarg)));
3903
3905 case 'c':
3906 {
3907 char *name,
3908 *value;
3909
3910 ParseLongOption(optctx.optarg, &name, &value);
3911 if (!value)
3912 {
3913 if (flag == '-')
3914 ereport(ERROR,
3916 errmsg("--%s requires a value",
3917 optctx.optarg)));
3918 else
3919 ereport(ERROR,
3921 errmsg("-c %s requires a value",
3922 optctx.optarg)));
3923 }
3925 pfree(name);
3926 pfree(value);
3927 break;
3928 }
3929
3930 case 'D':
3931 if (secure)
3932 userDoption = strdup(optctx.optarg);
3933 break;
3934
3935 case 'd':
3936 set_debug_options(atoi(optctx.optarg), ctx, gucsource);
3937 break;
3938
3939 case 'E':
3940 if (secure)
3941 EchoQuery = true;
3942 break;
3943
3944 case 'e':
3945 SetConfigOption("datestyle", "euro", ctx, gucsource);
3946 break;
3947
3948 case 'F':
3949 SetConfigOption("fsync", "false", ctx, gucsource);
3950 break;
3951
3952 case 'f':
3953 if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
3954 errs++;
3955 break;
3956
3957 case 'h':
3958 SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
3959 break;
3960
3961 case 'i':
3962 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3963 break;
3964
3965 case 'j':
3966 if (secure)
3967 UseSemiNewlineNewline = true;
3968 break;
3969
3970 case 'k':
3971 SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
3972 break;
3973
3974 case 'l':
3975 SetConfigOption("ssl", "true", ctx, gucsource);
3976 break;
3977
3978 case 'N':
3979 SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
3980 break;
3981
3982 case 'n':
3983 /* ignored for consistency with postmaster */
3984 break;
3985
3986 case 'O':
3987 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3988 break;
3989
3990 case 'P':
3991 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3992 break;
3993
3994 case 'p':
3995 SetConfigOption("port", optctx.optarg, ctx, gucsource);
3996 break;
3997
3998 case 'r':
3999 /* send output (stdout and stderr) to the given file */
4000 if (secure)
4002 break;
4003
4004 case 'S':
4005 SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4006 break;
4007
4008 case 's':
4009 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4010 break;
4011
4012 case 'T':
4013 /* ignored for consistency with the postmaster */
4014 break;
4015
4016 case 't':
4017 {
4018 const char *tmp = get_stats_option_name(optctx.optarg);
4019
4020 if (tmp)
4021 SetConfigOption(tmp, "true", ctx, gucsource);
4022 else
4023 errs++;
4024 break;
4025 }
4026
4027 case 'v':
4028
4029 /*
4030 * -v is no longer used in normal operation, since
4031 * FrontendProtocol is already set before we get here. We keep
4032 * the switch only for possible use in standalone operation,
4033 * in case we ever support using normal FE/BE protocol with a
4034 * standalone backend.
4035 */
4036 if (secure)
4038 break;
4039
4040 case 'W':
4041 SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4042 break;
4043
4044 default:
4045 errs++;
4046 break;
4047 }
4048
4049 if (errs)
4050 break;
4051 }
4052
4053 /*
4054 * Optional database name should be there only if *dbname is NULL.
4055 */
4056 if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
4057 *dbname = strdup(argv[optctx.optind++]);
4058
4059 if (errs || argc != optctx.optind)
4060 {
4061 if (errs)
4062 optctx.optind--; /* complain about the previous argument */
4063
4064 /* spell the error message a bit differently depending on context */
4066 ereport(FATAL,
4068 errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4069 errhint("Try \"%s --help\" for more information.", progname));
4070 else
4071 ereport(FATAL,
4073 errmsg("%s: invalid command-line argument: %s",
4074 progname, argv[optctx.optind]),
4075 errhint("Try \"%s --help\" for more information.", progname));
4076 }
4077}
int errhint(const char *fmt,...) pg_attribute_printf(1
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:4228
void ParseLongOption(const char *string, char **name, char **value)
Definition guc.c:6237
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:3720
static bool UseSemiNewlineNewline
Definition postgres.c:158
static bool EchoQuery
Definition postgres.c:157
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3752
const char * get_stats_option_name(const char *arg)
Definition postgres.c:3794
@ 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 502 of file postgres.c.

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

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

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

3721{
3722 if (debug_flag > 0)
3723 {
3724 char debugstr[64];
3725
3726 sprintf(debugstr, "debug%d", debug_flag);
3727 SetConfigOption("log_min_messages", debugstr, context, source);
3728 }
3729 else
3730 SetConfigOption("log_min_messages", "notice", context, source);
3731
3732 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3733 {
3734 SetConfigOption("log_connections", "all", context, source);
3735 SetConfigOption("log_disconnections", "true", context, source);
3736 }
3737 if (debug_flag >= 2)
3738 SetConfigOption("log_statement", "all", context, source);
3739 if (debug_flag >= 3)
3740 {
3741 SetConfigOption("debug_print_raw_parse", "true", context, source);
3742 SetConfigOption("debug_print_parse", "true", context, source);
3743 }
3744 if (debug_flag >= 4)
3745 SetConfigOption("debug_print_plan", "true", context, source);
3746 if (debug_flag >= 5)
3747 SetConfigOption("debug_print_rewritten", "true", context, source);
3748}
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 3752 of file postgres.c.

3753{
3754 const char *tmp = NULL;
3755
3756 switch (arg[0])
3757 {
3758 case 's': /* seqscan */
3759 tmp = "enable_seqscan";
3760 break;
3761 case 'i': /* indexscan */
3762 tmp = "enable_indexscan";
3763 break;
3764 case 'o': /* indexonlyscan */
3765 tmp = "enable_indexonlyscan";
3766 break;
3767 case 'b': /* bitmapscan */
3768 tmp = "enable_bitmapscan";
3769 break;
3770 case 't': /* tidscan */
3771 tmp = "enable_tidscan";
3772 break;
3773 case 'n': /* nestloop */
3774 tmp = "enable_nestloop";
3775 break;
3776 case 'm': /* mergejoin */
3777 tmp = "enable_mergejoin";
3778 break;
3779 case 'h': /* hashjoin */
3780 tmp = "enable_hashjoin";
3781 break;
3782 }
3783 if (tmp)
3784 {
3785 SetConfigOption(tmp, "false", context, source);
3786 return true;
3787 }
3788 else
3789 return false;
3790}

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char title)
extern

Definition at line 5094 of file postgres.c.

5095{
5097 struct timeval user,
5098 sys;
5099 struct timeval elapse_t;
5100 struct rusage r;
5101
5104 memcpy(&user, &r.ru_utime, sizeof(user));
5105 memcpy(&sys, &r.ru_stime, sizeof(sys));
5106 if (elapse_t.tv_usec < Save_t.tv_usec)
5107 {
5108 elapse_t.tv_sec--;
5109 elapse_t.tv_usec += 1000000;
5110 }
5111 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5112 {
5113 r.ru_utime.tv_sec--;
5114 r.ru_utime.tv_usec += 1000000;
5115 }
5116 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5117 {
5118 r.ru_stime.tv_sec--;
5119 r.ru_stime.tv_usec += 1000000;
5120 }
5121
5122 /*
5123 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5124 * some work to interpret them, and most platforms don't fill them in.
5125 */
5127
5128 appendStringInfoString(&str, "! system usage stats:\n");
5130 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5131 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5132 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5133 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5134 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5135 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5136 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5138 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5139 (long) user.tv_sec,
5140 (long) user.tv_usec,
5141 (long) sys.tv_sec,
5142 (long) sys.tv_usec);
5143#ifndef WIN32
5144
5145 /*
5146 * The following rusage fields are not defined by POSIX, but they're
5147 * present on all current Unix-like systems so we use them without any
5148 * special checks. Some of these could be provided in our Windows
5149 * emulation in src/port/win32getrusage.c with more work.
5150 */
5152 "!\t%ld kB max resident size\n",
5154 /* in bytes on macOS */
5155 r.ru_maxrss / 1024
5156#else
5157 /* in kilobytes on most other platforms */
5158 r.ru_maxrss
5159#endif
5160 );
5162 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5163 r.ru_inblock - Save_r.ru_inblock,
5164 /* they only drink coffee at dec */
5165 r.ru_oublock - Save_r.ru_oublock,
5166 r.ru_inblock, r.ru_oublock);
5168 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5169 r.ru_majflt - Save_r.ru_majflt,
5170 r.ru_minflt - Save_r.ru_minflt,
5171 r.ru_majflt, r.ru_minflt,
5172 r.ru_nswap - Save_r.ru_nswap,
5173 r.ru_nswap);
5175 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5176 r.ru_nsignals - Save_r.ru_nsignals,
5177 r.ru_nsignals,
5178 r.ru_msgrcv - Save_r.ru_msgrcv,
5179 r.ru_msgsnd - Save_r.ru_msgsnd,
5180 r.ru_msgrcv, r.ru_msgsnd);
5182 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5183 r.ru_nvcsw - Save_r.ru_nvcsw,
5184 r.ru_nivcsw - Save_r.ru_nivcsw,
5185 r.ru_nvcsw, r.ru_nivcsw);
5186#endif /* !WIN32 */
5187
5188 /* remove trailing newline */
5189 if (str.data[str.len - 1] == '\n')
5190 str.data[--str.len] = '\0';
5191
5192 ereport(LOG,
5193 (errmsg_internal("%s", title),
5194 errdetail_internal("%s", str.data)));
5195
5196 pfree(str.data);
5197}
#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, 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 3042 of file postgres.c.

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

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

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ Log_disconnections

PGDLLIMPORT bool Log_disconnections
extern

Definition at line 97 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 99 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

◆ restrict_nonsystem_relation_kind

◆ whereToSendOutput