PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE , LOGSTMT_DDL , LOGSTMT_MOD , LOGSTMT_ALL }
 

Functions

Listpg_parse_query (const char *query_string)
 
Listpg_rewrite_query (Query *query)
 
Listpg_analyze_and_rewrite_fixedparams (RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_varparams (RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_withcb (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
PlannedStmtpg_plan_query (Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
void die (SIGNAL_ARGS)
 
void quickdie (SIGNAL_ARGS) pg_attribute_noreturn()
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS) pg_attribute_noreturn()
 
void HandleRecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresSingleUserMain (int argc, char *argv[], const char *username) pg_attribute_noreturn()
 
void PostgresMain (const char *dbname, const char *username) pg_attribute_noreturn()
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 
int check_log_duration (char *msec_str, bool was_logged)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 

Variables

PGDLLIMPORT CommandDest whereToSendOutput
 
PGDLLIMPORT const char * debug_query_string
 
PGDLLIMPORT int 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 44 of file tcopprot.h.

◆ RESTRICT_RELKIND_VIEW

#define RESTRICT_RELKIND_VIEW   0x01

Definition at line 43 of file tcopprot.h.

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 31 of file tcopprot.h.

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

Function Documentation

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2398 of file postgres.c.

2399{
2402 {
2403 long secs;
2404 int usecs;
2405 int msecs;
2406 bool exceeded_duration;
2407 bool exceeded_sample_duration;
2408 bool in_sample = false;
2409
2412 &secs, &usecs);
2413 msecs = usecs / 1000;
2414
2415 /*
2416 * This odd-looking test for log_min_duration_* being exceeded is
2417 * designed to avoid integer overflow with very long durations: don't
2418 * compute secs * 1000 until we've verified it will fit in int.
2419 */
2420 exceeded_duration = (log_min_duration_statement == 0 ||
2422 (secs > log_min_duration_statement / 1000 ||
2423 secs * 1000 + msecs >= log_min_duration_statement)));
2424
2425 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2427 (secs > log_min_duration_sample / 1000 ||
2428 secs * 1000 + msecs >= log_min_duration_sample)));
2429
2430 /*
2431 * Do not log if log_statement_sample_rate = 0. Log a sample if
2432 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2433 * log_statement_sample_rate = 1.
2434 */
2435 if (exceeded_sample_duration)
2436 in_sample = log_statement_sample_rate != 0 &&
2439
2440 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2441 {
2442 snprintf(msec_str, 32, "%ld.%03d",
2443 secs * 1000 + msecs, usecs % 1000);
2444 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2445 return 2;
2446 else
2447 return 1;
2448 }
2449 }
2450
2451 return 0;
2452}
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1720
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
int log_min_duration_statement
Definition: guc_tables.c:525
int log_min_duration_sample
Definition: guc_tables.c:524
double log_statement_sample_rate
Definition: guc_tables.c:529
bool log_duration
Definition: guc_tables.c:490
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:238
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:878
bool xact_is_sampled
Definition: xact.c:295

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

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

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 3001 of file postgres.c.

3002{
3003 /* Don't joggle the elbow of proc_exit */
3005 {
3006 InterruptPending = true;
3007 ProcDiePending = true;
3008 }
3009
3010 /* for the cumulative stats system */
3012
3013 /* If we're still here, waken anything waiting on the process latch */
3015
3016 /*
3017 * If we're in single user mode, we want to quit immediately - we can't
3018 * rely on latches as they wouldn't work when stdin/stdout is a file.
3019 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3020 * effort just for the benefit of single user mode.
3021 */
3024}
@ DestRemote
Definition: dest.h:89
volatile sig_atomic_t InterruptPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:62
volatile sig_atomic_t ProcDiePending
Definition: globals.c:33
bool proc_exit_inprogress
Definition: ipc.c:40
void SetLatch(Latch *latch)
Definition: latch.c:632
@ DISCONNECT_KILLED
Definition: pgstat.h:114
SessionEndType pgStatSessionEndCause
CommandDest whereToSendOutput
Definition: postgres.c:90
static bool DoingCommandRead
Definition: postgres.c:135
void ProcessInterrupts(void)
Definition: postgres.c:3273

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

Referenced by PostgresMain().

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 3048 of file postgres.c.

3049{
3050 /* We're not returning, so no need to save errno */
3051 ereport(ERROR,
3052 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3053 errmsg("floating-point exception"),
3054 errdetail("An invalid floating-point operation was signaled. "
3055 "This probably means an out-of-range result or an "
3056 "invalid operation, such as division by zero.")));
3057}
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149

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

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

◆ get_stats_option_name()

const char * get_stats_option_name ( const char *  arg)

Definition at line 3712 of file postgres.c.

3713{
3714 switch (arg[0])
3715 {
3716 case 'p':
3717 if (optarg[1] == 'a') /* "parser" */
3718 return "log_parser_stats";
3719 else if (optarg[1] == 'l') /* "planner" */
3720 return "log_planner_stats";
3721 break;
3722
3723 case 'e': /* "executor" */
3724 return "log_executor_stats";
3725 break;
3726 }
3727
3728 return NULL;
3729}
void * arg
PGDLLIMPORT char * optarg
Definition: getopt.c:53

References arg, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ HandleRecoveryConflictInterrupt()

void HandleRecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 3064 of file postgres.c.

3065{
3066 RecoveryConflictPendingReasons[reason] = true;
3068 InterruptPending = true;
3069 /* latch will be set by procsignal_sigusr1_handler */
3070}
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:158
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:157

References InterruptPending, RecoveryConflictPending, and RecoveryConflictPendingReasons.

Referenced by procsignal_sigusr1_handler().

◆ pg_analyze_and_rewrite_fixedparams()

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

Definition at line 664 of file postgres.c.

669{
670 Query *query;
671 List *querytree_list;
672
673 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
674
675 /*
676 * (1) Perform parse analysis.
677 */
679 ResetUsage();
680
681 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
682 queryEnv);
683
685 ShowUsage("PARSE ANALYSIS STATISTICS");
686
687 /*
688 * (2) Rewrite the queries, as necessary
689 */
690 querytree_list = pg_rewrite_query(query);
691
692 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
693
694 return querytree_list;
695}
bool log_parser_stats
Definition: guc_tables.c:502
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:105
List * pg_rewrite_query(Query *query)
Definition: postgres.c:797
void ShowUsage(const char *title)
Definition: postgres.c:4984
void ResetUsage(void)
Definition: postgres.c:4977
Definition: pg_list.h:54

References log_parser_stats, parse_analyze_fixedparams(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopyTo(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

◆ pg_analyze_and_rewrite_varparams()

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

Definition at line 703 of file postgres.c.

708{
709 Query *query;
710 List *querytree_list;
711
712 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
713
714 /*
715 * (1) Perform parse analysis.
716 */
718 ResetUsage();
719
720 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
721 queryEnv);
722
723 /*
724 * Check all parameter types got determined.
725 */
726 for (int i = 0; i < *numParams; i++)
727 {
728 Oid ptype = (*paramTypes)[i];
729
730 if (ptype == InvalidOid || ptype == UNKNOWNOID)
732 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
733 errmsg("could not determine data type of parameter $%d",
734 i + 1)));
735 }
736
738 ShowUsage("PARSE ANALYSIS STATISTICS");
739
740 /*
741 * (2) Rewrite the queries, as necessary
742 */
743 querytree_list = pg_rewrite_query(query);
744
745 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
746
747 return querytree_list;
748}
int i
Definition: isn.c:72
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:145
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31

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

Referenced by exec_parse_message(), and PrepareQuery().

◆ pg_analyze_and_rewrite_withcb()

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

Definition at line 757 of file postgres.c.

762{
763 Query *query;
764 List *querytree_list;
765
766 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
767
768 /*
769 * (1) Perform parse analysis.
770 */
772 ResetUsage();
773
774 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
775 queryEnv);
776
778 ShowUsage("PARSE ANALYSIS STATISTICS");
779
780 /*
781 * (2) Rewrite the queries, as necessary
782 */
783 querytree_list = pg_rewrite_query(query);
784
785 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
786
787 return querytree_list;
788}
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:186

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

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

◆ pg_parse_query()

List * pg_parse_query ( const char *  query_string)

Definition at line 602 of file postgres.c.

603{
604 List *raw_parsetree_list;
605
606 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
607
609 ResetUsage();
610
611 raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
612
614 ShowUsage("PARSER STATISTICS");
615
616#ifdef DEBUG_NODE_TESTS_ENABLED
617
618 /* Optional debugging check: pass raw parsetrees through copyObject() */
619 if (Debug_copy_parse_plan_trees)
620 {
621 List *new_list = copyObject(raw_parsetree_list);
622
623 /* This checks both copyObject() and the equal() routines... */
624 if (!equal(new_list, raw_parsetree_list))
625 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
626 else
627 raw_parsetree_list = new_list;
628 }
629
630 /*
631 * Optional debugging check: pass raw parsetrees through
632 * outfuncs/readfuncs
633 */
634 if (Debug_write_read_parse_plan_trees)
635 {
636 char *str = nodeToStringWithLocations(raw_parsetree_list);
637 List *new_list = stringToNodeWithLocations(str);
638
639 pfree(str);
640 /* This checks both outfuncs/readfuncs and the equal() routines... */
641 if (!equal(new_list, raw_parsetree_list))
642 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
643 else
644 raw_parsetree_list = new_list;
645 }
646
647#endif /* DEBUG_NODE_TESTS_ENABLED */
648
649 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
650
651 return raw_parsetree_list;
652}
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:225
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
const char * str
static List * new_list(NodeTag type, int min_size)
Definition: list.c:91
void pfree(void *pointer)
Definition: mcxt.c:1521
#define copyObject(obj)
Definition: nodes.h:224
char * nodeToStringWithLocations(const void *obj)
Definition: outfuncs.c:800
@ RAW_PARSE_DEFAULT
Definition: parser.h:39

References copyObject, elog, equal(), 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(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

◆ pg_plan_queries()

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

Definition at line 969 of file postgres.c.

971{
972 List *stmt_list = NIL;
973 ListCell *query_list;
974
975 foreach(query_list, querytrees)
976 {
977 Query *query = lfirst_node(Query, query_list);
979
980 if (query->commandType == CMD_UTILITY)
981 {
982 /* Utility commands require no planning. */
984 stmt->commandType = CMD_UTILITY;
985 stmt->canSetTag = query->canSetTag;
986 stmt->utilityStmt = query->utilityStmt;
987 stmt->stmt_location = query->stmt_location;
988 stmt->stmt_len = query->stmt_len;
989 stmt->queryId = query->queryId;
990 }
991 else
992 {
993 stmt = pg_plan_query(query, query_string, cursorOptions,
994 boundParams);
995 }
996
997 stmt_list = lappend(stmt_list, stmt);
998 }
999
1000 return stmt_list;
1001}
#define stmt
Definition: indent_codes.h:59
List * lappend(List *list, void *datum)
Definition: list.c:339
@ CMD_UTILITY
Definition: nodes.h:270
#define makeNode(_type_)
Definition: nodes.h:155
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:881
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
ParseLoc stmt_location
Definition: parsenodes.h:240

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

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

◆ pg_plan_query()

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

Definition at line 881 of file postgres.c.

883{
885
886 /* Utility commands have no plans. */
887 if (querytree->commandType == CMD_UTILITY)
888 return NULL;
889
890 /* Planner must have a snapshot in case it calls user-defined functions. */
892
893 TRACE_POSTGRESQL_QUERY_PLAN_START();
894
896 ResetUsage();
897
898 /* call the optimizer */
899 plan = planner(querytree, query_string, cursorOptions, boundParams);
900
902 ShowUsage("PLANNER STATISTICS");
903
904#ifdef DEBUG_NODE_TESTS_ENABLED
905
906 /* Optional debugging check: pass plan tree through copyObject() */
907 if (Debug_copy_parse_plan_trees)
908 {
909 PlannedStmt *new_plan = copyObject(plan);
910
911 /*
912 * equal() currently does not have routines to compare Plan nodes, so
913 * don't try to test equality here. Perhaps fix someday?
914 */
915#ifdef NOT_USED
916 /* This checks both copyObject() and the equal() routines... */
917 if (!equal(new_plan, plan))
918 elog(WARNING, "copyObject() failed to produce an equal plan tree");
919 else
920#endif
921 plan = new_plan;
922 }
923
924 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
925 if (Debug_write_read_parse_plan_trees)
926 {
927 char *str;
928 PlannedStmt *new_plan;
929
931 new_plan = stringToNodeWithLocations(str);
932 pfree(str);
933
934 /*
935 * equal() currently does not have routines to compare Plan nodes, so
936 * don't try to test equality here. Perhaps fix someday?
937 */
938#ifdef NOT_USED
939 /* This checks both outfuncs/readfuncs and the equal() routines... */
940 if (!equal(new_plan, plan))
941 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
942 else
943#endif
944 plan = new_plan;
945 }
946
947#endif /* DEBUG_NODE_TESTS_ENABLED */
948
949 /*
950 * Print plan if debugging.
951 */
954
955 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
956
957 return plan;
958}
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:665
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:72
#define Assert(condition)
Definition: c.h:812
#define LOG
Definition: elog.h:31
bool Debug_print_plan
Definition: guc_tables.c:491
bool Debug_pretty_print
Definition: guc_tables.c:494
bool log_planner_stats
Definition: guc_tables.c:503
#define plan(x)
Definition: pg_regress.c:161
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:284
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:740

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

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

◆ pg_rewrite_query()

List * pg_rewrite_query ( Query query)

Definition at line 797 of file postgres.c.

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

References CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_parse, Debug_print_rewritten, elog, elog_node_display(), equal(), lappend(), lfirst_node, list_make1, LOG, log_parser_stats, new_list(), NIL, nodeToStringWithLocations(), pfree(), QueryRewrite(), ResetUsage(), ShowUsage(), str, and WARNING.

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), and pg_analyze_and_rewrite_withcb().

◆ PostgresMain()

void PostgresMain ( const char *  dbname,
const char *  username 
)

Definition at line 4146 of file postgres.c.

4147{
4148 sigjmp_buf local_sigjmp_buf;
4149
4150 /* these must be volatile to ensure state is preserved across longjmp: */
4151 volatile bool send_ready_for_query = true;
4152 volatile bool idle_in_transaction_timeout_enabled = false;
4153 volatile bool idle_session_timeout_enabled = false;
4154
4155 Assert(dbname != NULL);
4156 Assert(username != NULL);
4157
4159
4160 /*
4161 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4162 * has already set up BlockSig and made that the active signal mask.)
4163 *
4164 * Note that postmaster blocked all signals before forking child process,
4165 * so there is no race condition whereby we might receive a signal before
4166 * we have set up the handler.
4167 *
4168 * Also note: it's best not to use any signals that are SIG_IGNored in the
4169 * postmaster. If such a signal arrives before we are able to change the
4170 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4171 * handler in the postmaster to reserve the signal. (Of course, this isn't
4172 * an issue for signals that are locally generated, such as SIGALRM and
4173 * SIGPIPE.)
4174 */
4175 if (am_walsender)
4176 WalSndSignals();
4177 else
4178 {
4180 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4181 pqsignal(SIGTERM, die); /* cancel current query and exit */
4182
4183 /*
4184 * In a postmaster child backend, replace SignalHandlerForCrashExit
4185 * with quickdie, so we can tell the client we're dying.
4186 *
4187 * In a standalone backend, SIGQUIT can be generated from the keyboard
4188 * easily, while SIGTERM cannot, so we make both signals do die()
4189 * rather than quickdie().
4190 */
4192 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4193 else
4194 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4195 InitializeTimeouts(); /* establishes SIGALRM handler */
4196
4197 /*
4198 * Ignore failure to write to frontend. Note: if frontend closes
4199 * connection, we will notice it and exit cleanly when control next
4200 * returns to outer loop. This seems safer than forcing exit in the
4201 * midst of output during who-knows-what operation...
4202 */
4207
4208 /*
4209 * Reset some signals that are accepted by postmaster but not by
4210 * backend
4211 */
4212 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4213 * platforms */
4214 }
4215
4216 /* Early initialization */
4217 BaseInit();
4218
4219 /* We need to allow SIGINT, etc during the initial transaction */
4220 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4221
4222 /*
4223 * Generate a random cancel key, if this is a backend serving a
4224 * connection. InitPostgres() will advertise it in shared memory.
4225 */
4228 {
4229 if (!pg_strong_random(&MyCancelKey, sizeof(int32)))
4230 {
4231 ereport(ERROR,
4232 (errcode(ERRCODE_INTERNAL_ERROR),
4233 errmsg("could not generate random cancel key")));
4234 }
4235 MyCancelKeyValid = true;
4236 }
4237
4238 /*
4239 * General initialization.
4240 *
4241 * NOTE: if you are tempted to add code in this vicinity, consider putting
4242 * it inside InitPostgres() instead. In particular, anything that
4243 * involves database access should be there, not here.
4244 *
4245 * Honor session_preload_libraries if not dealing with a WAL sender.
4246 */
4247 InitPostgres(dbname, InvalidOid, /* database to connect to */
4248 username, InvalidOid, /* role to connect as */
4250 NULL); /* no out_dbname */
4251
4252 /*
4253 * If the PostmasterContext is still around, recycle the space; we don't
4254 * need it anymore after InitPostgres completes.
4255 */
4257 {
4259 PostmasterContext = NULL;
4260 }
4261
4263
4264 /*
4265 * Now all GUC states are fully set up. Report them to client if
4266 * appropriate.
4267 */
4269
4270 /*
4271 * Also set up handler to log session end; we have to wait till now to be
4272 * sure Log_disconnections has its final value.
4273 */
4276
4278
4279 /* Perform initialization specific to a WAL sender process. */
4280 if (am_walsender)
4281 InitWalSender();
4282
4283 /*
4284 * Send this backend's cancellation info to the frontend.
4285 */
4287 {
4289
4295 /* Need not flush since ReadyForQuery will do it. */
4296 }
4297
4298 /* Welcome banner for standalone case */
4300 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4301
4302 /*
4303 * Create the memory context we will use in the main loop.
4304 *
4305 * MessageContext is reset once per iteration of the main loop, ie, upon
4306 * completion of processing of each command message from the client.
4307 */
4309 "MessageContext",
4311
4312 /*
4313 * Create memory context and buffer used for RowDescription messages. As
4314 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4315 * frequently executed for ever single statement, we don't want to
4316 * allocate a separate buffer every time.
4317 */
4319 "RowDescriptionContext",
4324
4325 /* Fire any defined login event triggers, if appropriate */
4327
4328 /*
4329 * POSTGRES main processing loop begins here
4330 *
4331 * If an exception is encountered, processing resumes here so we abort the
4332 * current transaction and start a new one.
4333 *
4334 * You might wonder why this isn't coded as an infinite loop around a
4335 * PG_TRY construct. The reason is that this is the bottom of the
4336 * exception stack, and so with PG_TRY there would be no exception handler
4337 * in force at all during the CATCH part. By leaving the outermost setjmp
4338 * always active, we have at least some chance of recovering from an error
4339 * during error recovery. (If we get into an infinite loop thereby, it
4340 * will soon be stopped by overflow of elog.c's internal state stack.)
4341 *
4342 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4343 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4344 * is essential in case we longjmp'd out of a signal handler on a platform
4345 * where that leaves the signal blocked. It's not redundant with the
4346 * unblock in AbortTransaction() because the latter is only called if we
4347 * were inside a transaction.
4348 */
4349
4350 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4351 {
4352 /*
4353 * NOTE: if you are tempted to add more code in this if-block,
4354 * consider the high probability that it should be in
4355 * AbortTransaction() instead. The only stuff done directly here
4356 * should be stuff that is guaranteed to apply *only* for outer-level
4357 * error recovery, such as adjusting the FE/BE protocol status.
4358 */
4359
4360 /* Since not using PG_TRY, must reset error stack by hand */
4361 error_context_stack = NULL;
4362
4363 /* Prevent interrupts while cleaning up */
4365
4366 /*
4367 * Forget any pending QueryCancel request, since we're returning to
4368 * the idle loop anyway, and cancel any active timeout requests. (In
4369 * future we might want to allow some timeout requests to survive, but
4370 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4371 * we got here because of a query cancel interrupting the SIGALRM
4372 * interrupt handler.) Note in particular that we must clear the
4373 * statement and lock timeout indicators, to prevent any future plain
4374 * query cancels from being misreported as timeouts in case we're
4375 * forgetting a timeout cancel.
4376 */
4377 disable_all_timeouts(false); /* do first to avoid race condition */
4378 QueryCancelPending = false;
4379 idle_in_transaction_timeout_enabled = false;
4380 idle_session_timeout_enabled = false;
4381
4382 /* Not reading from the client anymore. */
4383 DoingCommandRead = false;
4384
4385 /* Make sure libpq is in a good state */
4386 pq_comm_reset();
4387
4388 /* Report the error to the client and/or server log */
4390
4391 /*
4392 * If Valgrind noticed something during the erroneous query, print the
4393 * query string, assuming we have one.
4394 */
4396
4397 /*
4398 * Make sure debug_query_string gets reset before we possibly clobber
4399 * the storage it points at.
4400 */
4401 debug_query_string = NULL;
4402
4403 /*
4404 * Abort the current transaction in order to recover.
4405 */
4407
4408 if (am_walsender)
4410
4412
4413 /*
4414 * We can't release replication slots inside AbortTransaction() as we
4415 * need to be able to start and abort transactions while having a slot
4416 * acquired. But we never need to hold them across top level errors,
4417 * so releasing here is fine. There also is a before_shmem_exit()
4418 * callback ensuring correct cleanup on FATAL errors.
4419 */
4420 if (MyReplicationSlot != NULL)
4422
4423 /* We also want to cleanup temporary slots on error. */
4425
4427
4428 /*
4429 * Now return to normal top-level context and clear ErrorContext for
4430 * next time.
4431 */
4434
4435 /*
4436 * If we were handling an extended-query-protocol message, initiate
4437 * skip till next Sync. This also causes us not to issue
4438 * ReadyForQuery (until we get Sync).
4439 */
4441 ignore_till_sync = true;
4442
4443 /* We don't have a transaction command open anymore */
4444 xact_started = false;
4445
4446 /*
4447 * If an error occurred while we were reading a message from the
4448 * client, we have potentially lost track of where the previous
4449 * message ends and the next one begins. Even though we have
4450 * otherwise recovered from the error, we cannot safely read any more
4451 * messages from the client, so there isn't much we can do with the
4452 * connection anymore.
4453 */
4454 if (pq_is_reading_msg())
4455 ereport(FATAL,
4456 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4457 errmsg("terminating connection because protocol synchronization was lost")));
4458
4459 /* Now we can allow interrupts again */
4461 }
4462
4463 /* We can now handle ereport(ERROR) */
4464 PG_exception_stack = &local_sigjmp_buf;
4465
4466 if (!ignore_till_sync)
4467 send_ready_for_query = true; /* initially, or after error */
4468
4469 /*
4470 * Non-error queries loop here.
4471 */
4472
4473 for (;;)
4474 {
4475 int firstchar;
4476 StringInfoData input_message;
4477
4478 /*
4479 * At top of loop, reset extended-query-message flag, so that any
4480 * errors encountered in "idle" state don't provoke skip.
4481 */
4483
4484 /*
4485 * For valgrind reporting purposes, the "current query" begins here.
4486 */
4487#ifdef USE_VALGRIND
4488 old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4489#endif
4490
4491 /*
4492 * Release storage left over from prior query cycle, and create a new
4493 * query input buffer in the cleared MessageContext.
4494 */
4497
4498 initStringInfo(&input_message);
4499
4500 /*
4501 * Also consider releasing our catalog snapshot if any, so that it's
4502 * not preventing advance of global xmin while we wait for the client.
4503 */
4505
4506 /*
4507 * (1) If we've reached idle state, tell the frontend we're ready for
4508 * a new query.
4509 *
4510 * Note: this includes fflush()'ing the last of the prior output.
4511 *
4512 * This is also a good time to flush out collected statistics to the
4513 * cumulative stats system, and to update the PS stats display. We
4514 * avoid doing those every time through the message loop because it'd
4515 * slow down processing of batched messages, and because we don't want
4516 * to report uncommitted updates (that confuses autovacuum). The
4517 * notification processor wants a call too, if we are not in a
4518 * transaction block.
4519 *
4520 * Also, if an idle timeout is enabled, start the timer for that.
4521 */
4522 if (send_ready_for_query)
4523 {
4525 {
4526 set_ps_display("idle in transaction (aborted)");
4528
4529 /* Start the idle-in-transaction timer */
4532 {
4533 idle_in_transaction_timeout_enabled = true;
4536 }
4537 }
4539 {
4540 set_ps_display("idle in transaction");
4542
4543 /* Start the idle-in-transaction timer */
4546 {
4547 idle_in_transaction_timeout_enabled = true;
4550 }
4551 }
4552 else
4553 {
4554 long stats_timeout;
4555
4556 /*
4557 * Process incoming notifies (including self-notifies), if
4558 * any, and send relevant messages to the client. Doing it
4559 * here helps ensure stable behavior in tests: if any notifies
4560 * were received during the just-finished transaction, they'll
4561 * be seen by the client before ReadyForQuery is.
4562 */
4565
4566 /*
4567 * Check if we need to report stats. If pgstat_report_stat()
4568 * decides it's too soon to flush out pending stats / lock
4569 * contention prevented reporting, it'll tell us when we
4570 * should try to report stats again (so that stats updates
4571 * aren't unduly delayed if the connection goes idle for a
4572 * long time). We only enable the timeout if we don't already
4573 * have a timeout in progress, because we don't disable the
4574 * timeout below. enable_timeout_after() needs to determine
4575 * the current timestamp, which can have a negative
4576 * performance impact. That's OK because pgstat_report_stat()
4577 * won't have us wake up sooner than a prior call.
4578 */
4579 stats_timeout = pgstat_report_stat(false);
4580 if (stats_timeout > 0)
4581 {
4584 stats_timeout);
4585 }
4586 else
4587 {
4588 /* all stats flushed, no need for the timeout */
4591 }
4592
4593 set_ps_display("idle");
4595
4596 /* Start the idle-session timer */
4597 if (IdleSessionTimeout > 0)
4598 {
4599 idle_session_timeout_enabled = true;
4602 }
4603 }
4604
4605 /* Report any recently-changed GUC options */
4607
4609 send_ready_for_query = false;
4610 }
4611
4612 /*
4613 * (2) Allow asynchronous signals to be executed immediately if they
4614 * come in while we are waiting for client input. (This must be
4615 * conditional since we don't want, say, reads on behalf of COPY FROM
4616 * STDIN doing the same thing.)
4617 */
4618 DoingCommandRead = true;
4619
4620 /*
4621 * (3) read a command (loop blocks here)
4622 */
4623 firstchar = ReadCommand(&input_message);
4624
4625 /*
4626 * (4) turn off the idle-in-transaction and idle-session timeouts if
4627 * active. We do this before step (5) so that any last-moment timeout
4628 * is certain to be detected in step (5).
4629 *
4630 * At most one of these timeouts will be active, so there's no need to
4631 * worry about combining the timeout.c calls into one.
4632 */
4633 if (idle_in_transaction_timeout_enabled)
4634 {
4636 idle_in_transaction_timeout_enabled = false;
4637 }
4638 if (idle_session_timeout_enabled)
4639 {
4641 idle_session_timeout_enabled = false;
4642 }
4643
4644 /*
4645 * (5) disable async signal conditions again.
4646 *
4647 * Query cancel is supposed to be a no-op when there is no query in
4648 * progress, so if a query cancel arrived while we were idle, just
4649 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4650 * it's called when DoingCommandRead is set, so check for interrupts
4651 * before resetting DoingCommandRead.
4652 */
4654 DoingCommandRead = false;
4655
4656 /*
4657 * (6) check for any other interesting events that happened while we
4658 * slept.
4659 */
4661 {
4662 ConfigReloadPending = false;
4664 }
4665
4666 /*
4667 * (7) process the command. But ignore it if we're skipping till
4668 * Sync.
4669 */
4670 if (ignore_till_sync && firstchar != EOF)
4671 continue;
4672
4673 switch (firstchar)
4674 {
4675 case PqMsg_Query:
4676 {
4677 const char *query_string;
4678
4679 /* Set statement_timestamp() */
4681
4682 query_string = pq_getmsgstring(&input_message);
4683 pq_getmsgend(&input_message);
4684
4685 if (am_walsender)
4686 {
4687 if (!exec_replication_command(query_string))
4688 exec_simple_query(query_string);
4689 }
4690 else
4691 exec_simple_query(query_string);
4692
4693 valgrind_report_error_query(query_string);
4694
4695 send_ready_for_query = true;
4696 }
4697 break;
4698
4699 case PqMsg_Parse:
4700 {
4701 const char *stmt_name;
4702 const char *query_string;
4703 int numParams;
4704 Oid *paramTypes = NULL;
4705
4706 forbidden_in_wal_sender(firstchar);
4707
4708 /* Set statement_timestamp() */
4710
4711 stmt_name = pq_getmsgstring(&input_message);
4712 query_string = pq_getmsgstring(&input_message);
4713 numParams = pq_getmsgint(&input_message, 2);
4714 if (numParams > 0)
4715 {
4716 paramTypes = palloc_array(Oid, numParams);
4717 for (int i = 0; i < numParams; i++)
4718 paramTypes[i] = pq_getmsgint(&input_message, 4);
4719 }
4720 pq_getmsgend(&input_message);
4721
4722 exec_parse_message(query_string, stmt_name,
4723 paramTypes, numParams);
4724
4725 valgrind_report_error_query(query_string);
4726 }
4727 break;
4728
4729 case PqMsg_Bind:
4730 forbidden_in_wal_sender(firstchar);
4731
4732 /* Set statement_timestamp() */
4734
4735 /*
4736 * this message is complex enough that it seems best to put
4737 * the field extraction out-of-line
4738 */
4739 exec_bind_message(&input_message);
4740
4741 /* exec_bind_message does valgrind_report_error_query */
4742 break;
4743
4744 case PqMsg_Execute:
4745 {
4746 const char *portal_name;
4747 int max_rows;
4748
4749 forbidden_in_wal_sender(firstchar);
4750
4751 /* Set statement_timestamp() */
4753
4754 portal_name = pq_getmsgstring(&input_message);
4755 max_rows = pq_getmsgint(&input_message, 4);
4756 pq_getmsgend(&input_message);
4757
4758 exec_execute_message(portal_name, max_rows);
4759
4760 /* exec_execute_message does valgrind_report_error_query */
4761 }
4762 break;
4763
4764 case PqMsg_FunctionCall:
4765 forbidden_in_wal_sender(firstchar);
4766
4767 /* Set statement_timestamp() */
4769
4770 /* Report query to various monitoring facilities. */
4772 set_ps_display("<FASTPATH>");
4773
4774 /* start an xact for this function invocation */
4776
4777 /*
4778 * Note: we may at this point be inside an aborted
4779 * transaction. We can't throw error for that until we've
4780 * finished reading the function-call message, so
4781 * HandleFunctionRequest() must check for it after doing so.
4782 * Be careful not to do anything that assumes we're inside a
4783 * valid transaction here.
4784 */
4785
4786 /* switch back to message context */
4788
4789 HandleFunctionRequest(&input_message);
4790
4791 /* commit the function-invocation transaction */
4793
4794 valgrind_report_error_query("fastpath function call");
4795
4796 send_ready_for_query = true;
4797 break;
4798
4799 case PqMsg_Close:
4800 {
4801 int close_type;
4802 const char *close_target;
4803
4804 forbidden_in_wal_sender(firstchar);
4805
4806 close_type = pq_getmsgbyte(&input_message);
4807 close_target = pq_getmsgstring(&input_message);
4808 pq_getmsgend(&input_message);
4809
4810 switch (close_type)
4811 {
4812 case 'S':
4813 if (close_target[0] != '\0')
4814 DropPreparedStatement(close_target, false);
4815 else
4816 {
4817 /* special-case the unnamed statement */
4819 }
4820 break;
4821 case 'P':
4822 {
4823 Portal portal;
4824
4825 portal = GetPortalByName(close_target);
4826 if (PortalIsValid(portal))
4827 PortalDrop(portal, false);
4828 }
4829 break;
4830 default:
4831 ereport(ERROR,
4832 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4833 errmsg("invalid CLOSE message subtype %d",
4834 close_type)));
4835 break;
4836 }
4837
4840
4841 valgrind_report_error_query("CLOSE message");
4842 }
4843 break;
4844
4845 case PqMsg_Describe:
4846 {
4847 int describe_type;
4848 const char *describe_target;
4849
4850 forbidden_in_wal_sender(firstchar);
4851
4852 /* Set statement_timestamp() (needed for xact) */
4854
4855 describe_type = pq_getmsgbyte(&input_message);
4856 describe_target = pq_getmsgstring(&input_message);
4857 pq_getmsgend(&input_message);
4858
4859 switch (describe_type)
4860 {
4861 case 'S':
4862 exec_describe_statement_message(describe_target);
4863 break;
4864 case 'P':
4865 exec_describe_portal_message(describe_target);
4866 break;
4867 default:
4868 ereport(ERROR,
4869 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4870 errmsg("invalid DESCRIBE message subtype %d",
4871 describe_type)));
4872 break;
4873 }
4874
4875 valgrind_report_error_query("DESCRIBE message");
4876 }
4877 break;
4878
4879 case PqMsg_Flush:
4880 pq_getmsgend(&input_message);
4882 pq_flush();
4883 break;
4884
4885 case PqMsg_Sync:
4886 pq_getmsgend(&input_message);
4887
4888 /*
4889 * If pipelining was used, we may be in an implicit
4890 * transaction block. Close it before calling
4891 * finish_xact_command.
4892 */
4895 valgrind_report_error_query("SYNC message");
4896 send_ready_for_query = true;
4897 break;
4898
4899 /*
4900 * 'X' means that the frontend is closing down the socket. EOF
4901 * means unexpected loss of frontend connection. Either way,
4902 * perform normal shutdown.
4903 */
4904 case EOF:
4905
4906 /* for the cumulative statistics system */
4908
4909 /* FALLTHROUGH */
4910
4911 case PqMsg_Terminate:
4912
4913 /*
4914 * Reset whereToSendOutput to prevent ereport from attempting
4915 * to send any more messages to client.
4916 */
4919
4920 /*
4921 * NOTE: if you are tempted to add more code here, DON'T!
4922 * Whatever you had in mind to do should be set up as an
4923 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4924 * it will fail to be called during other backend-shutdown
4925 * scenarios.
4926 */
4927 proc_exit(0);
4928
4929 case PqMsg_CopyData:
4930 case PqMsg_CopyDone:
4931 case PqMsg_CopyFail:
4932
4933 /*
4934 * Accept but ignore these messages, per protocol spec; we
4935 * probably got here because a COPY failed, and the frontend
4936 * is still sending data.
4937 */
4938 break;
4939
4940 default:
4941 ereport(FATAL,
4942 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4943 errmsg("invalid frontend message type %d",
4944 firstchar)));
4945 }
4946 } /* end of input-reading loop */
4947}
void ProcessNotifyInterrupt(bool flush)
Definition: async.c:1834
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:413
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:516
sigset_t UnBlockSig
Definition: pqsignal.c:22
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_FASTPATH
int32_t int32
Definition: c.h:481
void ReadyForQuery(CommandDest dest)
Definition: dest.c:256
@ DestDebug
Definition: dest.h:88
@ DestNone
Definition: dest.h:87
void EmitErrorReport(void)
Definition: elog.c:1687
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void FlushErrorState(void)
Definition: elog.c:1867
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
#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
int32 MyCancelKey
Definition: globals.c:52
int MyProcPid
Definition: globals.c:46
bool IsUnderPostmaster
Definition: globals.c:119
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:32
bool MyCancelKeyValid
Definition: globals.c:51
Oid MyDatabaseId
Definition: globals.c:93
void ProcessConfigFile(GucContext context)
Definition: guc-file.l:120
void BeginReportingGUCOptions(void)
Definition: guc.c:2546
void ReportChangedGUCOptions(void)
Definition: guc.c:2596
@ PGC_SIGHUP
Definition: guc.h:71
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:309
void proc_exit(int code)
Definition: ipc.c:104
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:153
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
MemoryContext TopMemoryContext
Definition: mcxt.c:149
MemoryContext PostmasterContext
Definition: mcxt.c:151
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:461
@ InitProcessing
Definition: miscadmin.h:460
#define GetProcessingMode()
Definition: miscadmin.h:470
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:488
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:472
static char * buf
Definition: pg_test_fsync.c:72
long pgstat_report_stat(bool force)
Definition: pgstat.c:692
@ DISCONNECT_CLIENT_EOF
Definition: pgstat.h:112
void pgstat_report_connect(Oid dboid)
bool pg_strong_random(void *buf, size_t len)
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define printf(...)
Definition: port.h:244
#define PortalIsValid(p)
Definition: portal.h:211
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:468
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:2616
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2904
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:5093
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4957
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2093
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3048
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3031
static bool ignore_till_sync
Definition: postgres.c:142
static void finish_xact_command(void)
Definition: postgres.c:2800
const char * debug_query_string
Definition: postgres.c:87
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1010
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1387
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1622
void die(SIGNAL_ARGS)
Definition: postgres.c:3001
static bool xact_started
Definition: postgres.c:128
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:141
static void start_xact_command(void)
Definition: postgres.c:2761
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2709
bool Log_disconnections
Definition: postgres.c:93
static void drop_unnamed_stmt(void)
Definition: postgres.c:2879
#define valgrind_report_error_query(query)
Definition: postgres.c:215
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:479
void BaseInit(void)
Definition: postinit.c:606
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:700
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1181
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:415
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:635
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:579
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:388
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:399
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:671
#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
MemoryContextSwitchTo(old_ctx)
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotRelease(void)
Definition: slot.c:652
void ReplicationSlotCleanup(bool synced_only)
Definition: slot.c:745
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:405
int IdleSessionTimeout
Definition: proc.c:62
int IdleInTransactionSessionTimeout
Definition: proc.c:60
int TransactionTimeout
Definition: proc.c:61
char * dbname
Definition: streamutil.c:50
void initStringInfo(StringInfo str)
Definition: stringinfo.c:56
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
bool get_timeout_active(TimeoutId id)
Definition: timeout.c:780
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:751
void InitializeTimeouts(void)
Definition: timeout.c:470
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:36
void WalSndErrorCleanup(void)
Definition: walsender.c:325
bool am_walsender
Definition: walsender.c:115
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1952
void WalSndSignals(void)
Definition: walsender.c:3563
void InitWalSender(void)
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define SIGPIPE
Definition: win32_port.h:173
#define SIGQUIT
Definition: win32_port.h:169
#define SIGUSR1
Definition: win32_port.h:180
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4981
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:406
void EndImplicitTransactionBlock(void)
Definition: xact.c:4343
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:913
void AbortCurrentTransaction(void)
Definition: xact.c:3443

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), buf, CHECK_FOR_INTERRUPTS, ConfigReloadPending, dbname, debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), DISCONNECT_CLIENT_EOF, doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), 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, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), get_timeout_active(), 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(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, jit_reset_after_error(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyCancelKeyValid, MyDatabaseId, MyProcPid, MyReplicationSlot, NormalProcessing, notifyInterruptPending, on_proc_exit(), palloc_array, PG_exception_stack, 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_sendint32(), PqMsg_BackendKeyData, PqMsg_Bind, PqMsg_Close, PqMsg_CloseComplete, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyFail, PqMsg_Describe, PqMsg_Execute, PqMsg_Flush, PqMsg_FunctionCall, PqMsg_Parse, PqMsg_Query, PqMsg_Sync, PqMsg_Terminate, pqsignal(), printf, proc_exit(), ProcessConfigFile(), ProcessNotifyInterrupt(), procsignal_sigusr1_handler(), QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), ReportChangedGUCOptions(), RESUME_INTERRUPTS, row_description_buf, row_description_context, set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, TransactionTimeout, UnBlockSig, username, valgrind_report_error_query, WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendMain(), and PostgresSingleUserMain().

◆ PostgresSingleUserMain()

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

Definition at line 4017 of file postgres.c.

4019{
4020 const char *dbname = NULL;
4021
4023
4024 /* Initialize startup process environment. */
4025 InitStandaloneProcess(argv[0]);
4026
4027 /*
4028 * Set default values for command-line options.
4029 */
4031
4032 /*
4033 * Parse command-line options.
4034 */
4036
4037 /* Must have gotten a database name, or have a default (the username) */
4038 if (dbname == NULL)
4039 {
4040 dbname = username;
4041 if (dbname == NULL)
4042 ereport(FATAL,
4043 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4044 errmsg("%s: no database nor user name specified",
4045 progname)));
4046 }
4047
4048 /* Acquire configuration parameters */
4050 proc_exit(1);
4051
4052 /*
4053 * Validate we have been given a reasonable-looking DataDir and change
4054 * into it.
4055 */
4056 checkDataDir();
4058
4059 /*
4060 * Create lockfile for data directory.
4061 */
4062 CreateDataDirLockFile(false);
4063
4064 /* read control file (error checking and contains config ) */
4066
4067 /*
4068 * process any libraries that should be preloaded at postmaster start
4069 */
4071
4072 /* Initialize MaxBackends */
4074
4075 /*
4076 * We don't need postmaster child slots in single-user mode, but
4077 * initialize them anyway to avoid having special handling.
4078 */
4080
4081 /* Initialize size of fast-path lock cache. */
4083
4084 /*
4085 * Give preloaded libraries a chance to request additional shared memory.
4086 */
4088
4089 /*
4090 * Now that loadable modules have had their chance to request additional
4091 * shared memory, determine the value of any runtime-computed GUCs that
4092 * depend on the amount of shared memory required.
4093 */
4095
4096 /*
4097 * Now that modules have been loaded, we can process any custom resource
4098 * managers specified in the wal_consistency_checking GUC.
4099 */
4101
4102 /*
4103 * Create shared memory etc. (Nothing's really "shared" in single-user
4104 * mode, but we must have these data structures anyway.)
4105 */
4107
4108 /*
4109 * Estimate number of openable files. This must happen after setting up
4110 * semaphores, because on some platforms semaphores count as open files.
4111 */
4113
4114 /*
4115 * Remember stand-alone backend startup time,roughly at the same point
4116 * during startup that postmaster does so.
4117 */
4119
4120 /*
4121 * Create a per-backend PGPROC struct in shared memory. We must do this
4122 * before we can use LWLocks.
4123 */
4124 InitProcess();
4125
4126 /*
4127 * Now that sufficient infrastructure has been initialized, PostgresMain()
4128 * can do the rest.
4129 */
4131}
TimestampTz PgStartTime
Definition: timestamp.c:53
void set_max_safe_fds(void)
Definition: fd.c:1043
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1784
void InitializeGUCOptions(void)
Definition: guc.c:1530
@ PGC_POSTMASTER
Definition: guc.h:70
void InitializeShmemGUCs(void)
Definition: ipci.c:352
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:198
const char * progname
Definition: main.c:44
void ChangeToDataDir(void)
Definition: miscinit.c:457
void process_shmem_requests(void)
Definition: miscinit.c:1927
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:175
void process_shared_preload_libraries(void)
Definition: miscinit.c:1899
void checkDataDir(void)
Definition: miscinit.c:344
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1511
void InitPostmasterChildSlots(void)
Definition: pmchild.c:86
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3752
static const char * userDoption
Definition: postgres.c:152
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4146
void InitializeMaxBackends(void)
Definition: postinit.c:545
void InitializeFastPathLocks(void)
Definition: postinit.c:577
void InitProcess(void)
Definition: proc.c:341
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4784
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4846

References Assert, ChangeToDataDir(), checkDataDir(), CreateDataDirLockFile(), CreateSharedMemoryAndSemaphores(), dbname, ereport, errcode(), errmsg(), FATAL, 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 
)

Definition at line 3752 of file postgres.c.

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

References dbname, DISPATCH_POSTMASTER, EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, 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)

Definition at line 500 of file postgres.c.

501{
502 int save_errno = errno;
503
505 {
506 /* Check for general interrupts that arrived before/while reading */
508
509 /* Process sinval catchup interrupts, if any */
512
513 /* Process notify interrupts, if any */
516 }
517 else if (ProcDiePending)
518 {
519 /*
520 * We're dying. If there is no data available to read, then it's safe
521 * (and sane) to handle that now. If we haven't tried to read yet,
522 * make sure the process latch is set, so that if there is no data
523 * then we'll come back here and die. If we're done reading, also
524 * make sure the process latch is set, as we might've undesirably
525 * cleared it while reading.
526 */
527 if (blocked)
529 else
531 }
532
533 errno = save_errno;
534}
void ProcessCatchupInterrupt(void)
Definition: sinval.c:174
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:39

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

Referenced by interactive_getc(), and secure_read().

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 546 of file postgres.c.

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

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

Referenced by secure_write().

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2904 of file postgres.c.

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

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

Referenced by PostgresMain().

◆ ResetUsage()

void ResetUsage ( void  )

◆ set_debug_options()

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

Definition at line 3641 of file postgres.c.

3642{
3643 if (debug_flag > 0)
3644 {
3645 char debugstr[64];
3646
3647 sprintf(debugstr, "debug%d", debug_flag);
3648 SetConfigOption("log_min_messages", debugstr, context, source);
3649 }
3650 else
3651 SetConfigOption("log_min_messages", "notice", context, source);
3652
3653 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3654 {
3655 SetConfigOption("log_connections", "true", context, source);
3656 SetConfigOption("log_disconnections", "true", context, source);
3657 }
3658 if (debug_flag >= 2)
3659 SetConfigOption("log_statement", "all", context, source);
3660 if (debug_flag >= 3)
3661 SetConfigOption("debug_print_parse", "true", context, source);
3662 if (debug_flag >= 4)
3663 SetConfigOption("debug_print_plan", "true", context, source);
3664 if (debug_flag >= 5)
3665 SetConfigOption("debug_print_rewritten", "true", context, source);
3666}
static rewind_source * source
Definition: pg_rewind.c:89
#define sprintf
Definition: port.h:240
tree context
Definition: radixtree.h:1837

References context, PGC_POSTMASTER, SetConfigOption(), source, and sprintf.

Referenced by PostmasterMain(), and process_postgres_switches().

◆ set_plan_disabling_options()

bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3670 of file postgres.c.

3671{
3672 const char *tmp = NULL;
3673
3674 switch (arg[0])
3675 {
3676 case 's': /* seqscan */
3677 tmp = "enable_seqscan";
3678 break;
3679 case 'i': /* indexscan */
3680 tmp = "enable_indexscan";
3681 break;
3682 case 'o': /* indexonlyscan */
3683 tmp = "enable_indexonlyscan";
3684 break;
3685 case 'b': /* bitmapscan */
3686 tmp = "enable_bitmapscan";
3687 break;
3688 case 't': /* tidscan */
3689 tmp = "enable_tidscan";
3690 break;
3691 case 'n': /* nestloop */
3692 tmp = "enable_nestloop";
3693 break;
3694 case 'm': /* mergejoin */
3695 tmp = "enable_mergejoin";
3696 break;
3697 case 'h': /* hashjoin */
3698 tmp = "enable_hashjoin";
3699 break;
3700 }
3701 if (tmp)
3702 {
3703 SetConfigOption(tmp, "false", context, source);
3704 return true;
3705 }
3706 else
3707 return false;
3708}

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

Referenced by PostmasterMain(), and process_postgres_switches().

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4984 of file postgres.c.

4985{
4987 struct timeval user,
4988 sys;
4989 struct timeval elapse_t;
4990 struct rusage r;
4991
4993 gettimeofday(&elapse_t, NULL);
4994 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4995 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4996 if (elapse_t.tv_usec < Save_t.tv_usec)
4997 {
4998 elapse_t.tv_sec--;
4999 elapse_t.tv_usec += 1000000;
5000 }
5001 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5002 {
5003 r.ru_utime.tv_sec--;
5004 r.ru_utime.tv_usec += 1000000;
5005 }
5006 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5007 {
5008 r.ru_stime.tv_sec--;
5009 r.ru_stime.tv_usec += 1000000;
5010 }
5011
5012 /*
5013 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5014 * some work to interpret them, and most platforms don't fill them in.
5015 */
5017
5018 appendStringInfoString(&str, "! system usage stats:\n");
5020 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5021 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5022 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5023 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5024 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5025 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5026 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5028 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5029 (long) user.tv_sec,
5030 (long) user.tv_usec,
5031 (long) sys.tv_sec,
5032 (long) sys.tv_usec);
5033#ifndef WIN32
5034
5035 /*
5036 * The following rusage fields are not defined by POSIX, but they're
5037 * present on all current Unix-like systems so we use them without any
5038 * special checks. Some of these could be provided in our Windows
5039 * emulation in src/port/win32getrusage.c with more work.
5040 */
5042 "!\t%ld kB max resident size\n",
5043#if defined(__darwin__)
5044 /* in bytes on macOS */
5045 r.ru_maxrss / 1024
5046#else
5047 /* in kilobytes on most other platforms */
5048 r.ru_maxrss
5049#endif
5050 );
5052 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5053 r.ru_inblock - Save_r.ru_inblock,
5054 /* they only drink coffee at dec */
5055 r.ru_oublock - Save_r.ru_oublock,
5056 r.ru_inblock, r.ru_oublock);
5058 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5059 r.ru_majflt - Save_r.ru_majflt,
5060 r.ru_minflt - Save_r.ru_minflt,
5061 r.ru_majflt, r.ru_minflt,
5062 r.ru_nswap - Save_r.ru_nswap,
5063 r.ru_nswap);
5065 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5066 r.ru_nsignals - Save_r.ru_nsignals,
5067 r.ru_nsignals,
5068 r.ru_msgrcv - Save_r.ru_msgrcv,
5069 r.ru_msgsnd - Save_r.ru_msgsnd,
5070 r.ru_msgrcv, r.ru_msgsnd);
5072 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5073 r.ru_nvcsw - Save_r.ru_nvcsw,
5074 r.ru_nivcsw - Save_r.ru_nivcsw,
5075 r.ru_nvcsw, r.ru_nivcsw);
5076#endif /* !WIN32 */
5077
5078 /* remove trailing newline */
5079 if (str.data[str.len - 1] == '\n')
5080 str.data[--str.len] = '\0';
5081
5082 ereport(LOG,
5083 (errmsg_internal("%s", title),
5084 errdetail_internal("%s", str.data)));
5085
5086 pfree(str.data);
5087}
#define __darwin__
Definition: darwin.h:3
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
static char * user
Definition: pg_regress.c:119
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:94
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:179
struct timeval ru_utime
Definition: resource.h:14
struct timeval ru_stime
Definition: resource.h:15

References __darwin__, appendStringInfo(), appendStringInfoString(), ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), LOG, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, Save_t, str, and user.

Referenced by _bt_leader_participate_as_worker(), _bt_leafbuild(), _bt_parallel_build_main(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_varparams(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 3031 of file postgres.c.

3032{
3033 /*
3034 * Don't joggle the elbow of proc_exit
3035 */
3037 {
3038 InterruptPending = true;
3039 QueryCancelPending = true;
3040 }
3041
3042 /* If we're still here, waken anything waiting on the process latch */
3044}

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

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

Variable Documentation

◆ client_connection_check_interval

PGDLLIMPORT int client_connection_check_interval
extern

Definition at line 101 of file postgres.c.

Referenced by ProcessInterrupts(), and start_xact_command().

◆ debug_query_string

◆ Log_disconnections

PGDLLIMPORT bool Log_disconnections
extern

Definition at line 93 of file postgres.c.

Referenced by PostgresMain().

◆ log_statement

PGDLLIMPORT int log_statement
extern

Definition at line 95 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ PostAuthDelay

PGDLLIMPORT int PostAuthDelay
extern

Definition at line 98 of file postgres.c.

Referenced by AutoVacWorkerMain(), BackgroundWorkerMain(), and InitPostgres().

◆ restrict_nonsystem_relation_kind

PGDLLIMPORT int restrict_nonsystem_relation_kind
extern

◆ whereToSendOutput