PostgreSQL Source Code  git master
miscadmin.h File Reference
#include <signal.h>
#include "pgtime.h"
Include dependency graph for miscadmin.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define InvalidPid   (-1)
 
#define CHECK_FOR_INTERRUPTS()
 
#define HOLD_INTERRUPTS()   (InterruptHoldoffCount++)
 
#define RESUME_INTERRUPTS()
 
#define HOLD_CANCEL_INTERRUPTS()   (QueryCancelHoldoffCount++)
 
#define RESUME_CANCEL_INTERRUPTS()
 
#define START_CRIT_SECTION()   (CritSectionCount++)
 
#define END_CRIT_SECTION()
 
#define USE_POSTGRES_DATES   0
 
#define USE_ISO_DATES   1
 
#define USE_SQL_DATES   2
 
#define USE_GERMAN_DATES   3
 
#define USE_XSD_DATES   4
 
#define DATEORDER_YMD   0
 
#define DATEORDER_DMY   1
 
#define DATEORDER_MDY   2
 
#define INTSTYLE_POSTGRES   0
 
#define INTSTYLE_POSTGRES_VERBOSE   1
 
#define INTSTYLE_SQL_STANDARD   2
 
#define INTSTYLE_ISO_8601   3
 
#define MAXTZLEN   10 /* max TZ name len, not counting tr. null */
 
#define SECURITY_LOCAL_USERID_CHANGE   0x0001
 
#define SECURITY_RESTRICTED_OPERATION   0x0002
 
#define SECURITY_NOFORCE_RLS   0x0004
 
#define IsBootstrapProcessingMode()   (Mode == BootstrapProcessing)
 
#define IsInitProcessingMode()   (Mode == InitProcessing)
 
#define IsNormalProcessingMode()   (Mode == NormalProcessing)
 
#define GetProcessingMode()   Mode
 
#define SetProcessingMode(mode)
 
#define AmBootstrapProcess()   (MyAuxProcType == BootstrapProcess)
 
#define AmStartupProcess()   (MyAuxProcType == StartupProcess)
 
#define AmBackgroundWriterProcess()   (MyAuxProcType == BgWriterProcess)
 
#define AmCheckpointerProcess()   (MyAuxProcType == CheckpointerProcess)
 
#define AmWalWriterProcess()   (MyAuxProcType == WalWriterProcess)
 
#define AmWalReceiverProcess()   (MyAuxProcType == WalReceiverProcess)
 

Typedefs

typedef char * pg_stack_base_t
 
typedef enum ProcessingMode ProcessingMode
 

Enumerations

enum  ProcessingMode { BootstrapProcessing, InitProcessing, NormalProcessing }
 
enum  AuxProcType {
  NotAnAuxProcess = -1, CheckerProcess = 0, BootstrapProcess, StartupProcess,
  BgWriterProcess, CheckpointerProcess, WalWriterProcess, WalReceiverProcess,
  NUM_AUXPROCTYPES
}
 

Functions

void ProcessInterrupts (void)
 
pg_stack_base_t set_stack_base (void)
 
void restore_stack_base (pg_stack_base_t base)
 
void check_stack_depth (void)
 
bool stack_is_too_deep (void)
 
void PostgresSigHupHandler (SIGNAL_ARGS)
 
void PreventCommandIfReadOnly (const char *cmdname)
 
void PreventCommandIfParallelMode (const char *cmdname)
 
void PreventCommandDuringRecovery (const char *cmdname)
 
int trace_recovery (int trace_level)
 
void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SetDatabasePath (const char *path)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
Oid GetSessionUserId (void)
 
Oid GetAuthenticatedUserId (void)
 
void GetUserIdAndSecContext (Oid *userid, int *sec_context)
 
void SetUserIdAndSecContext (Oid userid, int sec_context)
 
bool InLocalUserIdChange (void)
 
bool InSecurityRestrictedOperation (void)
 
bool InNoForceRLSOperation (void)
 
void GetUserIdAndContext (Oid *userid, bool *sec_def_context)
 
void SetUserIdAndContext (Oid userid, bool sec_def_context)
 
void InitializeSessionUserId (const char *rolename, Oid useroid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
bool superuser (void)
 
bool superuser_arg (Oid roleid)
 
void pg_split_opts (char **argv, int *argcp, const char *optstr)
 
void InitializeMaxBackends (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
 
void BaseInit (void)
 
void CreateDataDirLockFile (bool amPostmaster)
 
void CreateSocketLockFile (const char *socketfile, bool amPostmaster, const char *socketDir)
 
void TouchSocketLockFiles (void)
 
void AddToDataDirLockFile (int target_line, const char *str)
 
bool RecheckDataDirLockFile (void)
 
void ValidatePgVersion (const char *path)
 
void process_shared_preload_libraries (void)
 
void process_session_preload_libraries (void)
 
void pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
bool BackupInProgress (void)
 
void CancelBackup (void)
 

Variables

PGDLLIMPORT volatile bool InterruptPending
 
PGDLLIMPORT volatile bool QueryCancelPending
 
PGDLLIMPORT volatile bool ProcDiePending
 
PGDLLIMPORT volatile bool IdleInTransactionSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t ConfigReloadPending
 
volatile bool ClientConnectionLost
 
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
 
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
 
PGDLLIMPORT volatile uint32 CritSectionCount
 
PGDLLIMPORT pid_t PostmasterPid
 
PGDLLIMPORT bool IsPostmasterEnvironment
 
PGDLLIMPORT bool IsUnderPostmaster
 
PGDLLIMPORT bool IsBackgroundWorker
 
PGDLLIMPORT bool IsBinaryUpgrade
 
PGDLLIMPORT bool ExitOnAnyError
 
PGDLLIMPORT char * DataDir
 
PGDLLIMPORT int NBuffers
 
PGDLLIMPORT int MaxBackends
 
PGDLLIMPORT int MaxConnections
 
PGDLLIMPORT int max_worker_processes
 
PGDLLIMPORT int max_parallel_workers
 
PGDLLIMPORT int MyProcPid
 
PGDLLIMPORT pg_time_t MyStartTime
 
PGDLLIMPORT struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
int32 MyCancelKey
 
int MyPMChildSlot
 
char OutputFileName []
 
PGDLLIMPORT char my_exec_path []
 
char pkglib_path []
 
PGDLLIMPORT Oid MyDatabaseId
 
PGDLLIMPORT Oid MyDatabaseTableSpace
 
PGDLLIMPORT int DateStyle
 
PGDLLIMPORT int DateOrder
 
PGDLLIMPORT int IntervalStyle
 
bool enableFsync
 
PGDLLIMPORT bool allowSystemTableMods
 
PGDLLIMPORT int work_mem
 
PGDLLIMPORT int maintenance_work_mem
 
PGDLLIMPORT int max_parallel_maintenance_workers
 
int VacuumCostPageHit
 
int VacuumCostPageMiss
 
int VacuumCostPageDirty
 
int VacuumCostLimit
 
int VacuumCostDelay
 
int VacuumPageHit
 
int VacuumPageMiss
 
int VacuumPageDirty
 
int VacuumCostBalance
 
bool VacuumCostActive
 
int trace_recovery_messages
 
char * DatabasePath
 
ProcessingMode Mode
 
AuxProcType MyAuxProcType
 
bool IgnoreSystemIndexes
 
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
 
char * session_preload_libraries_string
 
char * shared_preload_libraries_string
 
char * local_preload_libraries_string
 

Macro Definition Documentation

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 407 of file miscadmin.h.

Referenced by ForwardFsyncRequest().

◆ AmBootstrapProcess

#define AmBootstrapProcess ( )    (MyAuxProcType == BootstrapProcess)

Definition at line 405 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 406 of file miscadmin.h.

Referenced by HotStandbyActiveInReplay(), and mdinit().

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 410 of file miscadmin.h.

Referenced by get_sync_bit().

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 409 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

#define CHECK_FOR_INTERRUPTS ( )
Value:
do { \
ProcessInterrupts(); \
} while(0)
PGDLLIMPORT volatile bool InterruptPending
Definition: globals.c:29

Definition at line 98 of file miscadmin.h.

Referenced by _bt_buildadd(), _bt_readnextpage(), _bt_walk_left(), _crypt_blowfish_rn(), _hash_init(), _hash_readnext(), _hash_readprev(), add_partial_path(), add_path(), agg_retrieve_hash_table(), analyze_rel(), ApplyLauncherMain(), apw_dump_now(), ATRewriteTable(), autoprewarm_database_main(), backend_read_statsfile(), BipartiteMatch(), BitmapHeapNext(), blgetbitmap(), bloomBuildCallback(), brin_evacuate_page(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinsummarize(), bt_check_level_from_leftmost(), bt_right_page_check_scankey(), bt_target_page_check(), btree_xlog_delete_get_latestRemovedXid(), BufFileDeleteShared(), BufFileOpenShared(), calculate_database_size(), calculate_relation_size(), calculate_tablespace_size(), check_default_allows_bound(), CheckSCRAMAuth(), ClientAuthentication(), cluster_rel(), collect_corrupt_items(), collect_visibility_data(), ConditionVariableSleep(), copy_file(), copy_heap_data(), copy_messages(), copy_read_data(), copy_relation_data(), copydir(), CopyFrom(), CopyTo(), count_nondeletable_pages(), CountOtherDBBackends(), db_dir_size(), DecodingContextFindStartpoint(), do_autovacuum(), do_des(), do_pg_stop_backup(), dofindsubquery(), errfinish(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), exec_stmt(), exec_stmts(), ExecAgg(), ExecAppend(), ExecCustomScan(), ExecGather(), ExecGatherMerge(), ExecGroup(), ExecHashIncreaseNumBatches(), ExecHashIncreaseNumBuckets(), ExecHashJoinGetSavedTuple(), ExecHashJoinImpl(), ExecHashRemoveNextSkewBucket(), ExecLimit(), ExecLockRows(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecMergeAppend(), ExecMergeJoin(), ExecModifyTable(), ExecNestLoop(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashJoinPartitionOuter(), ExecParallelHashRepartitionFirst(), ExecParallelHashRepartitionRest(), ExecProjectSet(), ExecRecursiveUnion(), ExecResult(), ExecScanFetch(), ExecScanHashTableForUnmatched(), ExecSetOp(), ExecSort(), ExecSubPlan(), ExecUnique(), ExecWindowAgg(), fetch_input_tuple(), findPartialMatch(), fsm_vacuum_page(), gather_getnext(), gather_merge_init(), gather_readnext(), get_query_def(), get_rule_expr(), get_setop_query(), GetMultiXactIdMembers(), GetNewOidWithIndex(), GetNewRelFileNode(), getNextNearest(), ginbuild(), ginBuildCallback(), gingetbitmap(), gistgetbitmap(), gistgettuple(), gistProcessItup(), gm_readnext_tuple(), HandleFunctionRequest(), hash_xlog_vacuum_get_latestRemovedXid(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heapgetpage(), hypothetical_dense_rank_final(), hypothetical_rank_common(), ident_inet(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), IndexNext(), IndexNextWithReorder(), IndexOnlyNext(), initialize_worker_spi(), interactive_getc(), lazy_truncate_heap(), libpqrcv_connect(), libpqrcv_PQexec(), libpqrcv_processTuples(), logicalrep_worker_stop(), LogicalRepApplyLoop(), lseg_inside_poly(), make_bounded_heap(), mode_final(), mq_putmessage(), MultiExecBitmapIndexScan(), MultiExecProcNode(), numeric_fac(), OpenTableList(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), pg_prewarm(), pg_sleep(), pg_visibility_map_summary(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PGSemaphoreLock(), pgstat_collect_oids(), pgstat_get_backend_current_activity(), pgstat_heap(), pgstat_index(), pgstat_read_current_status(), pgstat_vacuum_stat(), pgstathashindex(), pgstatindex_impl(), plperl_spi_prepare(), PortalRunMulti(), postgresAcquireSampleRowsFunc(), PostgresMain(), predicate_implied_by_simple_clause(), predicate_refuted_by_simple_clause(), process_ordered_aggregate_multi(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessWalRcvInterrupts(), ProcSleep(), ProcWaitForSignal(), puttuple_common(), random_relative_prime(), RE_compile_and_cache(), RE_wchar_execute(), read_local_xlog_page(), refresh_matview_datafill(), regexp_fixed_prefix(), replace_text(), replace_text_regexp(), replorigin_create(), RequestCheckpoint(), revmap_extend_and_get_blkno(), sendAuthRequest(), sendDir(), set_rtable_names(), setop_retrieve_hash_table(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), spgdoinsert(), spgWalk(), statapprox_heap(), storeQueryResult(), summarize_range(), tablesample_getnext(), test_shm_mq_pipelined(), text_to_array_internal(), tfuncLoadRows(), throttle(), TidNext(), toast_save_datum(), tuplesort_heap_insert(), tuplesort_heap_replace_top(), tuplesort_skiptuples(), tuplestore_skiptuples(), vacuum_delay_point(), vacuum_rel(), validate_index_heapscan(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), wait_pid(), WaitExceedsMaxStandbyDelay(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), walkdir(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), and window_gettupleslot().

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 219 of file miscadmin.h.

Referenced by check_datestyle(), locale_date_order(), and setup_config().

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 217 of file miscadmin.h.

Referenced by check_datestyle(), DecodeNumber(), locale_date_order(), and setup_config().

◆ END_CRIT_SECTION

#define END_CRIT_SECTION ( )
Value:
do { \
Assert(CritSectionCount > 0); \
CritSectionCount--; \
} while(0)
PGDLLIMPORT volatile uint32 CritSectionCount
Definition: globals.c:37

Definition at line 133 of file miscadmin.h.

Referenced by _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), AbsorbFsyncRequests(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), brinRevmapDesummarizeRange(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), GenericXLogFinish(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), lazy_scan_heap(), lazy_vacuum_page(), moveLeafs(), MultiXactIdCreateFromMembers(), nextval_internal(), PostPrepare_Locks(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), RecordTransactionCommitPrepared(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), visibilitymap_truncate(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 372 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 123 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

◆ HOLD_INTERRUPTS

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 234 of file miscadmin.h.

Referenced by EncodeInterval().

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 231 of file miscadmin.h.

Referenced by EncodeInterval(), and set_transmission_modes().

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 232 of file miscadmin.h.

Referenced by DecodeInterval(), EncodeInterval(), and PGTYPESinterval_to_asc().

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 233 of file miscadmin.h.

Referenced by DecodeInterval(), and EncodeInterval().

◆ InvalidPid

◆ IsBootstrapProcessingMode

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

◆ MAXTZLEN

#define MAXTZLEN   10 /* max TZ name len, not counting tr. null */

Definition at line 238 of file miscadmin.h.

Referenced by abstime2tm(), and EncodeDateTime().

◆ RESUME_CANCEL_INTERRUPTS

#define RESUME_CANCEL_INTERRUPTS ( )
Value:
do { \
Assert(QueryCancelHoldoffCount > 0); \
QueryCancelHoldoffCount--; \
} while(0)
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:36

Definition at line 125 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

◆ RESUME_INTERRUPTS

◆ SECURITY_LOCAL_USERID_CHANGE

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 296 of file miscadmin.h.

Referenced by InNoForceRLSOperation(), ri_PerformCheck(), and ri_PlanCheck().

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

◆ SetProcessingMode

#define SetProcessingMode (   mode)

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 131 of file miscadmin.h.

Referenced by _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), AbsorbFsyncRequests(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), brinRevmapDesummarizeRange(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), GenericXLogFinish(), GetNewMultiXactId(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), lazy_scan_heap(), lazy_vacuum_page(), moveLeafs(), nextval_internal(), PostPrepare_Locks(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), RecordTransactionCommitPrepared(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), visibilitymap_truncate(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 213 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 210 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 212 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Typedef Documentation

◆ pg_stack_base_t

Definition at line 269 of file miscadmin.h.

◆ ProcessingMode

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
CheckerProcess 
BootstrapProcess 
StartupProcess 
BgWriterProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 389 of file miscadmin.h.

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 359 of file miscadmin.h.

360 {
361  BootstrapProcessing, /* bootstrap creation of template database */
362  InitProcessing, /* initializing system */
363  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:359

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1158 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf(), WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE, and write.

Referenced by InternalIpcMemoryCreate(), pmdie(), PostmasterMain(), reaper(), and sigusr1_handler().

1159 {
1160  int fd;
1161  int len;
1162  int lineno;
1163  char *srcptr;
1164  char *destptr;
1165  char srcbuffer[BLCKSZ];
1166  char destbuffer[BLCKSZ];
1167 
1168  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1169  if (fd < 0)
1170  {
1171  ereport(LOG,
1173  errmsg("could not open file \"%s\": %m",
1175  return;
1176  }
1178  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1180  if (len < 0)
1181  {
1182  ereport(LOG,
1184  errmsg("could not read from file \"%s\": %m",
1186  close(fd);
1187  return;
1188  }
1189  srcbuffer[len] = '\0';
1190 
1191  /*
1192  * Advance over lines we are not supposed to rewrite, then copy them to
1193  * destbuffer.
1194  */
1195  srcptr = srcbuffer;
1196  for (lineno = 1; lineno < target_line; lineno++)
1197  {
1198  char *eol = strchr(srcptr, '\n');
1199 
1200  if (eol == NULL)
1201  break; /* not enough lines in file yet */
1202  srcptr = eol + 1;
1203  }
1204  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1205  destptr = destbuffer + (srcptr - srcbuffer);
1206 
1207  /*
1208  * Fill in any missing lines before the target line, in case lines are
1209  * added to the file out of order.
1210  */
1211  for (; lineno < target_line; lineno++)
1212  {
1213  if (destptr < destbuffer + sizeof(destbuffer))
1214  *destptr++ = '\n';
1215  }
1216 
1217  /*
1218  * Write or rewrite the target line.
1219  */
1220  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1221  destptr += strlen(destptr);
1222 
1223  /*
1224  * If there are more lines in the old file, append them to destbuffer.
1225  */
1226  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1227  {
1228  srcptr++;
1229  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1230  srcptr);
1231  }
1232 
1233  /*
1234  * And rewrite the data. Since we write in a single kernel call, this
1235  * update should appear atomic to onlookers.
1236  */
1237  len = strlen(destbuffer);
1238  errno = 0;
1240  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1241  (int) write(fd, destbuffer, len) != len)
1242  {
1244  /* if write didn't set errno, assume problem is no disk space */
1245  if (errno == 0)
1246  errno = ENOSPC;
1247  ereport(LOG,
1249  errmsg("could not write to file \"%s\": %m",
1251  close(fd);
1252  return;
1253  }
1256  if (pg_fsync(fd) != 0)
1257  {
1258  ereport(LOG,
1260  errmsg("could not write to file \"%s\": %m",
1262  }
1264  if (close(fd) != 0)
1265  {
1266  ereport(LOG,
1268  errmsg("could not write to file \"%s\": %m",
1270  }
1271 }
#define write(a, b, c)
Definition: win32.h:14
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:55
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1069
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
#define ereport(elevel, rest)
Definition: elog.h:122
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1236
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:348
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ BackupInProgress()

bool BackupInProgress ( void  )

Definition at line 11450 of file xlog.c.

References BACKUP_LABEL_FILE, and stat.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

11451 {
11452  struct stat stat_buf;
11453 
11454  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
11455 }
struct stat stat_buf
Definition: pg_standby.c:103
#define stat(a, b)
Definition: win32_port.h:266
#define BACKUP_LABEL_FILE
Definition: xlog.h:322

◆ BaseInit()

void BaseInit ( void  )

Definition at line 524 of file postinit.c.

References DebugFileOpen(), InitBufferPoolAccess(), InitCommunication(), InitFileAccess(), and smgrinit().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), PostgresMain(), and StartBackgroundWorker().

525 {
526  /*
527  * Attach to shared memory and semaphores, and initialize our
528  * input/output/debugging file descriptors.
529  */
531  DebugFileOpen();
532 
533  /* Do local initialization of file, storage and buffer managers */
534  InitFileAccess();
535  smgrinit();
537 }
static void InitCommunication(void)
Definition: postinit.c:416
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2437
void DebugFileOpen(void)
Definition: elog.c:1863
void smgrinit(void)
Definition: smgr.c:102
void InitFileAccess(void)
Definition: fd.c:779

◆ CancelBackup()

void CancelBackup ( void  )

Definition at line 11470 of file xlog.c.

References BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errdetail(), errmsg(), LOG, stat, TABLESPACE_MAP, TABLESPACE_MAP_OLD, and WARNING.

Referenced by PostmasterStateMachine().

11471 {
11472  struct stat stat_buf;
11473 
11474  /* if the backup_label file is not there, return */
11475  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
11476  return;
11477 
11478  /* remove leftover file from previously canceled backup if it exists */
11479  unlink(BACKUP_LABEL_OLD);
11480 
11482  {
11483  ereport(WARNING,
11485  errmsg("online backup mode was not canceled"),
11486  errdetail("File \"%s\" could not be renamed to \"%s\": %m.",
11488  return;
11489  }
11490 
11491  /* if the tablespace_map file is not there, return */
11492  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
11493  {
11494  ereport(LOG,
11495  (errmsg("online backup mode canceled"),
11496  errdetail("File \"%s\" was renamed to \"%s\".",
11498  return;
11499  }
11500 
11501  /* remove leftover file from previously canceled backup if it exists */
11502  unlink(TABLESPACE_MAP_OLD);
11503 
11505  {
11506  ereport(LOG,
11507  (errmsg("online backup mode canceled"),
11508  errdetail("Files \"%s\" and \"%s\" were renamed to "
11509  "\"%s\" and \"%s\", respectively.",
11512  }
11513  else
11514  {
11515  ereport(WARNING,
11517  errmsg("online backup mode canceled"),
11518  errdetail("File \"%s\" was renamed to \"%s\", but "
11519  "file \"%s\" could not be renamed to \"%s\": %m.",
11522  }
11523 }
#define DEBUG1
Definition: elog.h:25
#define LOG
Definition: elog.h:26
#define BACKUP_LABEL_OLD
Definition: xlog.h:323
#define TABLESPACE_MAP
Definition: xlog.h:325
struct stat stat_buf
Definition: pg_standby.c:103
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:608
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:266
#define TABLESPACE_MAP_OLD
Definition: xlog.h:326
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BACKUP_LABEL_FILE
Definition: xlog.h:322

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 116 of file miscinit.c.

References AssertState, DataDir, ereport, errcode_for_file_access(), errmsg(), and FATAL.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

117 {
119 
120  if (chdir(DataDir) < 0)
121  ereport(FATAL,
123  errmsg("could not change directory to \"%s\": %m",
124  DataDir)));
125 }
#define AssertState(condition)
Definition: c.h:691
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:60

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3154 of file postgres.c.

References ereport, errcode(), errhint(), errmsg(), ERROR, max_stack_depth, and stack_is_too_deep().

Referenced by clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), EventTriggerInvoke(), ExecEndNode(), ExecEvalAlternativeSubPlan(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode(), execute(), expand_partitioned_rtentry(), expression_tree_mutator(), expression_tree_walker(), fillQT(), find_composite_type_dependencies(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_partition_dispatch_recurse(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), gistSplit(), hash_range(), hash_range_extended(), hk_depth_search(), infix(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), parse_array(), parse_object(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), set_append_rel_size(), setPath(), split_array(), transformExprRecurse(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute(), TS_execute_ternary(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3155 {
3156  if (stack_is_too_deep())
3157  {
3158  ereport(ERROR,
3159  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3160  errmsg("stack depth limit exceeded"),
3161  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3162  "after ensuring the platform's stack depth limit is adequate.",
3163  max_stack_depth)));
3164  }
3165 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int max_stack_depth
Definition: postgres.c:96
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool stack_is_too_deep(void)
Definition: postgres.c:3168

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1081 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

1082 {
1083  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1084 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:55
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:769
char * DataDir
Definition: globals.c:60

◆ CreateSocketLockFile()

void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1090 of file miscinit.c.

References CreateLockFile(), MAXPGPATH, and snprintf().

Referenced by StreamServerPort().

1092 {
1093  char lockfile[MAXPGPATH];
1094 
1095  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1096  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1097 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:769
#define MAXPGPATH

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 343 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

344 {
346  return AuthenticatedUserId;
347 }
#define AssertState(condition)
Definition: c.h:691
#define OidIsValid(objectId)
Definition: c.h:594
static Oid AuthenticatedUserId
Definition: miscinit.c:156

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 636 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

637 {
638  if (SetRoleIsActive)
639  return OuterUserId;
640  else
641  return InvalidOid;
642 }
static Oid OuterUserId
Definition: miscinit.c:158
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:168

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 295 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

296 {
298  return OuterUserId;
299 }
#define AssertState(condition)
Definition: c.h:691
static Oid OuterUserId
Definition: miscinit.c:158
#define OidIsValid(objectId)
Definition: c.h:594

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 318 of file miscinit.c.

References AssertState, OidIsValid, and SessionUserId.

Referenced by check_role(), DropRole(), get_rolespec_oid(), get_rolespec_tuple(), InitPostgres(), is_admin_of_role(), pgstat_bestart(), RenameRole(), and session_user().

319 {
321  return SessionUserId;
322 }
#define AssertState(condition)
Definition: c.h:691
static Oid SessionUserId
Definition: miscinit.c:157
#define OidIsValid(objectId)
Definition: c.h:594

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 284 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), analyze_rel(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetStatistics(), ATPrepSetTableSpace(), ATSimplePermissions(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), brin_summarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTrigger(), current_user(), currtid_byrelname(), currtid_byreloid(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), DelRoleMems(), do_setval(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecBuildGroupingEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecSecLabelStmt(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteTruncate(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockTableAclCheck(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_activity(), pg_stat_get_backend_activity(), pg_stat_get_backend_activity_start(), pg_stat_get_backend_client_addr(), pg_stat_get_backend_client_port(), pg_stat_get_backend_start(), pg_stat_get_backend_wait_event(), pg_stat_get_backend_wait_event_type(), pg_stat_get_backend_xact_start(), pg_stat_get_progress_info(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignModify(), postgresBeginForeignScan(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), RemoveRoleFromObjectPolicy(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_foreign_rel_properties(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_rel(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

285 {
287  return CurrentUserId;
288 }
#define AssertState(condition)
Definition: c.h:691
#define OidIsValid(objectId)
Definition: c.h:594
static Oid CurrentUserId
Definition: miscinit.c:159

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 438 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

439 {
440  *userid = CurrentUserId;
441  *sec_def_context = InLocalUserIdChange();
442 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:407
static Oid CurrentUserId
Definition: miscinit.c:159

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 692 of file miscinit.c.

References AUTHOID, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by check_is_member_of_role(), current_user(), getObjectDescription(), getObjectIdentityParts(), insert_username(), regroleout(), RemoveRoleFromObjectPolicy(), session_user(), and timetravel().

693 {
694  HeapTuple tuple;
695  char *result;
696 
697  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
698  if (!HeapTupleIsValid(tuple))
699  {
700  if (!noerr)
701  ereport(ERROR,
702  (errcode(ERRCODE_UNDEFINED_OBJECT),
703  errmsg("invalid role OID: %u", roleid)));
704  result = NULL;
705  }
706  else
707  {
708  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
709  ReleaseSysCache(tuple);
710  }
711  return result;
712 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
char * pstrdup(const char *in)
Definition: mcxt.c:1063
int errcode(int sqlerrcode)
Definition: elog.c:575
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:565

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 465 of file miscinit.c.

References AUTHOID, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum, ReleaseSysCache(), and SearchSysCache1().

Referenced by check_permissions(), and InitPostgres().

466 {
467  bool result = false;
468  HeapTuple utup;
469 
470  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
471  if (HeapTupleIsValid(utup))
472  {
473  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
474  ReleaseSysCache(utup);
475  }
476  return result;
477 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 502 of file postinit.c.

References Assert, autovacuum_max_workers, elog, ERROR, MAX_BACKENDS, max_worker_processes, MaxBackends, and MaxConnections.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

503 {
504  Assert(MaxBackends == 0);
505 
506  /* the extra unit accounts for the autovacuum launcher */
509 
510  /* internal error because the values were all checked previously */
512  elog(ERROR, "too many backends configured");
513 }
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
int MaxBackends
Definition: globals.c:127
int MaxConnections
Definition: globals.c:124
int autovacuum_max_workers
Definition: autovacuum.c:114
#define Assert(condition)
Definition: c.h:688
int max_worker_processes
Definition: globals.c:125
#define elog
Definition: elog.h:219

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 483 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, HeapTupleGetOid, HeapTupleIsValid, IsBootstrapProcessingMode, IsUnderPostmaster, MyProc, NameStr, ObjectIdGetDatum, OidIsValid, PGC_BACKEND, PGC_INTERNAL, PGC_S_OVERRIDE, PointerGetDatum, ReleaseSysCache(), PGPROC::roleId, SearchSysCache1(), SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

484 {
485  HeapTuple roleTup;
486  Form_pg_authid rform;
487  char *rname;
488 
489  /*
490  * Don't do scans if we're bootstrapping, none of the system catalogs
491  * exist yet, and they should be owned by postgres anyway.
492  */
494 
495  /* call only once */
497 
498  if (rolename != NULL)
499  {
500  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
501  if (!HeapTupleIsValid(roleTup))
502  ereport(FATAL,
503  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
504  errmsg("role \"%s\" does not exist", rolename)));
505  }
506  else
507  {
508  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
509  if (!HeapTupleIsValid(roleTup))
510  ereport(FATAL,
511  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
512  errmsg("role with OID %u does not exist", roleid)));
513  }
514 
515  rform = (Form_pg_authid) GETSTRUCT(roleTup);
516  roleid = HeapTupleGetOid(roleTup);
517  rname = NameStr(rform->rolname);
518 
519  AuthenticatedUserId = roleid;
520  AuthenticatedUserIsSuperuser = rform->rolsuper;
521 
522  /* This sets OuterUserId/CurrentUserId too */
524 
525  /* Also mark our PGPROC entry with the authenticated user id */
526  /* (We assume this is an atomic store so no lock is needed) */
527  MyProc->roleId = roleid;
528 
529  /*
530  * These next checks are not enforced when in standalone mode, so that
531  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
532  * rolcanlogin = false;".
533  */
534  if (IsUnderPostmaster)
535  {
536  /*
537  * Is role allowed to login at all?
538  */
539  if (!rform->rolcanlogin)
540  ereport(FATAL,
541  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
542  errmsg("role \"%s\" is not permitted to log in",
543  rname)));
544 
545  /*
546  * Check connection limit for this role.
547  *
548  * There is a race condition here --- we create our PGPROC before
549  * checking for other PGPROCs. If two backends did this at about the
550  * same time, they might both think they were over the limit, while
551  * ideally one should succeed and one fail. Getting that to work
552  * exactly seems more trouble than it is worth, however; instead we
553  * just document that the connection limit is approximate.
554  */
555  if (rform->rolconnlimit >= 0 &&
557  CountUserBackends(roleid) > rform->rolconnlimit)
558  ereport(FATAL,
559  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
560  errmsg("too many connections for role \"%s\"",
561  rname)));
562  }
563 
564  /* Record username and superuser status as GUC settings too */
565  SetConfigOption("session_authorization", rname,
567  SetConfigOption("is_superuser",
568  AuthenticatedUserIsSuperuser ? "on" : "off",
570 
571  ReleaseSysCache(roleTup);
572 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define AssertState(condition)
Definition: c.h:691
PGPROC * MyProc
Definition: proc.c:67
#define PointerGetDatum(X)
Definition: postgres.h:539
Oid roleId
Definition: proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:594
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
#define FATAL
Definition: elog.h:52
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6720
bool IsUnderPostmaster
Definition: globals.c:101
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:162
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int CountUserBackends(Oid roleid)
Definition: procarray.c:2840
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:368
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:565
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:326
static Oid AuthenticatedUserId
Definition: miscinit.c:156

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 579 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, BOOTSTRAP_SUPERUSERID, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsUnderPostmaster, OidIsValid, and SetSessionUserId().

Referenced by InitPostgres().

580 {
581  /*
582  * This function should only be called in single-user mode, in autovacuum
583  * workers, and in background workers.
584  */
586 
587  /* call only once */
589 
592 
594 }
#define AssertState(condition)
Definition: c.h:691
#define OidIsValid(objectId)
Definition: c.h:594
bool IsBackgroundWorker
Definition: globals.c:103
bool IsUnderPostmaster
Definition: globals.c:101
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:162
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:102
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:326
static Oid AuthenticatedUserId
Definition: miscinit.c:156

◆ InitPostgres()

void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
char *  out_dbname 
)

Definition at line 565 of file postinit.c.

References am_db_walsender, am_walsender, Assert, before_shmem_exit(), CAC_WAITBACKUP, Port::canAcceptConnections, CheckDeadLockAlert(), CheckMyDatabase(), CommitTransactionCommand(), PGPROC::databaseId, DatabaseRelationId, dbname, DEADLOCK_TIMEOUT, DEBUG3, DEFAULTTABLESPACE_OID, elog, EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_rolreplication(), HaveNFreeProcs(), HeapTupleGetOid, HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), InitBufferPoolBackend(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, OidIsValid, on_shmem_exit(), PerformAuthentication(), pg_usleep(), pgstat_bestart(), pgstat_initialize(), PostAuthDelay, process_settings(), process_startup_options(), ProcSignalInit(), RecoveryInProgress(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), TemplateDbOid, ThereIsAtLeastOneRole(), ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), BackgroundWorkerInitializeConnection(), BackgroundWorkerInitializeConnectionByOid(), BootstrapModeMain(), and PostgresMain().

567 {
568  bool bootstrap = IsBootstrapProcessingMode();
569  bool am_superuser;
570  char *fullpath;
571  char dbname[NAMEDATALEN];
572 
573  elog(DEBUG3, "InitPostgres");
574 
575  /*
576  * Add my PGPROC struct to the ProcArray.
577  *
578  * Once I have done this, I am visible to other backends!
579  */
581 
582  /*
583  * Initialize my entry in the shared-invalidation manager's array of
584  * per-backend data.
585  *
586  * Sets up MyBackendId, a unique backend identifier.
587  */
589 
590  SharedInvalBackendInit(false);
591 
592  if (MyBackendId > MaxBackends || MyBackendId <= 0)
593  elog(FATAL, "bad backend ID: %d", MyBackendId);
594 
595  /* Now that we have a BackendId, we can participate in ProcSignal */
597 
598  /*
599  * Also set up timeout handlers needed for backend operation. We need
600  * these in every case except bootstrap.
601  */
602  if (!bootstrap)
603  {
609  }
610 
611  /*
612  * bufmgr needs another initialization call too
613  */
615 
616  /*
617  * Initialize local process's access to XLOG.
618  */
619  if (IsUnderPostmaster)
620  {
621  /*
622  * The postmaster already started the XLOG machinery, but we need to
623  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
624  * This is handled by calling RecoveryInProgress and ignoring the
625  * result.
626  */
627  (void) RecoveryInProgress();
628  }
629  else
630  {
631  /*
632  * We are either a bootstrap process or a standalone backend. Either
633  * way, start up the XLOG machinery, and register to have it closed
634  * down at exit.
635  */
636  StartupXLOG();
638  }
639 
640  /*
641  * Initialize the relation cache and the system catalog caches. Note that
642  * no catalog access happens here; we only set up the hashtable structure.
643  * We must do this before starting a transaction because transaction abort
644  * would try to touch these hashtables.
645  */
648  InitPlanCache();
649 
650  /* Initialize portal manager */
652 
653  /* Initialize stats collection --- must happen before first xact */
654  if (!bootstrap)
656 
657  /*
658  * Load relcache entries for the shared system catalogs. This must create
659  * at least entries for pg_database and catalogs used for authentication.
660  */
662 
663  /*
664  * Set up process-exit callback to do pre-shutdown cleanup. This is the
665  * first before_shmem_exit callback we register; thus, this will be the
666  * last thing we do before low-level modules like the buffer manager begin
667  * to close down. We need to have this in place before we begin our first
668  * transaction --- if we fail during the initialization transaction, as is
669  * entirely possible, we need the AbortTransaction call to clean up.
670  */
672 
673  /* The autovacuum launcher is done here */
675  {
676  /* report this backend in the PgBackendStatus array */
677  pgstat_bestart();
678 
679  return;
680  }
681 
682  /*
683  * Start a new transaction here before first access to db, and get a
684  * snapshot. We don't have a use for the snapshot itself, but we're
685  * interested in the secondary effect that it sets RecentGlobalXmin. (This
686  * is critical for anything that reads heap pages, because HOT may decide
687  * to prune them even if the process doesn't attempt to modify any
688  * tuples.)
689  */
690  if (!bootstrap)
691  {
692  /* statement_timestamp must be set for timeouts to work correctly */
695 
696  /*
697  * transaction_isolation will have been set to the default by the
698  * above. If the default is "serializable", and we are in hot
699  * standby, we will fail if we don't change it to something lower.
700  * Fortunately, "read committed" is plenty good enough.
701  */
703 
704  (void) GetTransactionSnapshot();
705  }
706 
707  /*
708  * Perform client authentication if necessary, then figure out our
709  * postgres user ID, and see if we are a superuser.
710  *
711  * In standalone mode and in autovacuum worker processes, we use a fixed
712  * ID, otherwise we figure it out from the authenticated user name.
713  */
714  if (bootstrap || IsAutoVacuumWorkerProcess())
715  {
717  am_superuser = true;
718  }
719  else if (!IsUnderPostmaster)
720  {
722  am_superuser = true;
723  if (!ThereIsAtLeastOneRole())
725  (errcode(ERRCODE_UNDEFINED_OBJECT),
726  errmsg("no roles are defined in this database system"),
727  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
728  username != NULL ? username : "postgres")));
729  }
730  else if (IsBackgroundWorker)
731  {
732  if (username == NULL && !OidIsValid(useroid))
733  {
735  am_superuser = true;
736  }
737  else
738  {
740  am_superuser = superuser();
741  }
742  }
743  else
744  {
745  /* normal multiuser case */
746  Assert(MyProcPort != NULL);
749  am_superuser = superuser();
750  }
751 
752  /*
753  * If we're trying to shut down, only superusers can connect, and new
754  * replication connections are not allowed.
755  */
756  if ((!am_superuser || am_walsender) &&
757  MyProcPort != NULL &&
759  {
760  if (am_walsender)
761  ereport(FATAL,
762  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
763  errmsg("new replication connections are not allowed during database shutdown")));
764  else
765  ereport(FATAL,
766  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
767  errmsg("must be superuser to connect during database shutdown")));
768  }
769 
770  /*
771  * Binary upgrades only allowed super-user connections
772  */
773  if (IsBinaryUpgrade && !am_superuser)
774  {
775  ereport(FATAL,
776  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
777  errmsg("must be superuser to connect in binary upgrade mode")));
778  }
779 
780  /*
781  * The last few connections slots are reserved for superusers. Although
782  * replication connections currently require superuser privileges, we
783  * don't allow them to consume the reserved slots, which are intended for
784  * interactive use.
785  */
786  if ((!am_superuser || am_walsender) &&
787  ReservedBackends > 0 &&
789  ereport(FATAL,
790  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
791  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
792 
793  /* Check replication permissions needed for walsender processes. */
794  if (am_walsender)
795  {
796  Assert(!bootstrap);
797 
798  if (!superuser() && !has_rolreplication(GetUserId()))
799  ereport(FATAL,
800  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
801  errmsg("must be superuser or replication role to start walsender")));
802  }
803 
804  /*
805  * If this is a plain walsender only supporting physical replication, we
806  * don't want to connect to any particular database. Just finish the
807  * backend startup by processing any options from the startup packet, and
808  * we're done.
809  */
811  {
812  /* process any options passed in the startup packet */
813  if (MyProcPort != NULL)
814  process_startup_options(MyProcPort, am_superuser);
815 
816  /* Apply PostAuthDelay as soon as we've read all options */
817  if (PostAuthDelay > 0)
818  pg_usleep(PostAuthDelay * 1000000L);
819 
820  /* initialize client encoding */
822 
823  /* report this backend in the PgBackendStatus array */
824  pgstat_bestart();
825 
826  /* close the transaction we started above */
828 
829  return;
830  }
831 
832  /*
833  * Set up the global variables holding database id and default tablespace.
834  * But note we won't actually try to touch the database just yet.
835  *
836  * We take a shortcut in the bootstrap case, otherwise we have to look up
837  * the db's entry in pg_database.
838  */
839  if (bootstrap)
840  {
843  }
844  else if (in_dbname != NULL)
845  {
846  HeapTuple tuple;
847  Form_pg_database dbform;
848 
849  tuple = GetDatabaseTuple(in_dbname);
850  if (!HeapTupleIsValid(tuple))
851  ereport(FATAL,
852  (errcode(ERRCODE_UNDEFINED_DATABASE),
853  errmsg("database \"%s\" does not exist", in_dbname)));
854  dbform = (Form_pg_database) GETSTRUCT(tuple);
855  MyDatabaseId = HeapTupleGetOid(tuple);
856  MyDatabaseTableSpace = dbform->dattablespace;
857  /* take database name from the caller, just for paranoia */
858  strlcpy(dbname, in_dbname, sizeof(dbname));
859  }
860  else if (OidIsValid(dboid))
861  {
862  /* caller specified database by OID */
863  HeapTuple tuple;
864  Form_pg_database dbform;
865 
866  tuple = GetDatabaseTupleByOid(dboid);
867  if (!HeapTupleIsValid(tuple))
868  ereport(FATAL,
869  (errcode(ERRCODE_UNDEFINED_DATABASE),
870  errmsg("database %u does not exist", dboid)));
871  dbform = (Form_pg_database) GETSTRUCT(tuple);
872  MyDatabaseId = HeapTupleGetOid(tuple);
873  MyDatabaseTableSpace = dbform->dattablespace;
874  Assert(MyDatabaseId == dboid);
875  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
876  /* pass the database name back to the caller */
877  if (out_dbname)
878  strcpy(out_dbname, dbname);
879  }
880  else
881  {
882  /*
883  * If this is a background worker not bound to any particular
884  * database, we're done now. Everything that follows only makes sense
885  * if we are bound to a specific database. We do need to close the
886  * transaction we started before returning.
887  */
888  if (!bootstrap)
889  {
890  pgstat_bestart();
892  }
893  return;
894  }
895 
896  /*
897  * Now, take a writer's lock on the database we are trying to connect to.
898  * If there is a concurrently running DROP DATABASE on that database, this
899  * will block us until it finishes (and has committed its update of
900  * pg_database).
901  *
902  * Note that the lock is not held long, only until the end of this startup
903  * transaction. This is OK since we will advertise our use of the
904  * database in the ProcArray before dropping the lock (in fact, that's the
905  * next thing to do). Anyone trying a DROP DATABASE after this point will
906  * see us in the array once they have the lock. Ordering is important for
907  * this because we don't want to advertise ourselves as being in this
908  * database until we have the lock; otherwise we create what amounts to a
909  * deadlock with CountOtherDBBackends().
910  *
911  * Note: use of RowExclusiveLock here is reasonable because we envision
912  * our session as being a concurrent writer of the database. If we had a
913  * way of declaring a session as being guaranteed-read-only, we could use
914  * AccessShareLock for such sessions and thereby not conflict against
915  * CREATE DATABASE.
916  */
917  if (!bootstrap)
920 
921  /*
922  * Now we can mark our PGPROC entry with the database ID.
923  *
924  * We assume this is an atomic store so no lock is needed; though actually
925  * things would work fine even if it weren't atomic. Anyone searching the
926  * ProcArray for this database's ID should hold the database lock, so they
927  * would not be executing concurrently with this store. A process looking
928  * for another database's ID could in theory see a chance match if it read
929  * a partially-updated databaseId value; but as long as all such searches
930  * wait and retry, as in CountOtherDBBackends(), they will certainly see
931  * the correct value on their next try.
932  */
934 
935  /*
936  * We established a catalog snapshot while reading pg_authid and/or
937  * pg_database; but until we have set up MyDatabaseId, we won't react to
938  * incoming sinval messages for unshared catalogs, so we won't realize it
939  * if the snapshot has been invalidated. Assume it's no good anymore.
940  */
942 
943  /*
944  * Recheck pg_database to make sure the target database hasn't gone away.
945  * If there was a concurrent DROP DATABASE, this ensures we will die
946  * cleanly without creating a mess.
947  */
948  if (!bootstrap)
949  {
950  HeapTuple tuple;
951 
952  tuple = GetDatabaseTuple(dbname);
953  if (!HeapTupleIsValid(tuple) ||
954  MyDatabaseId != HeapTupleGetOid(tuple) ||
955  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
956  ereport(FATAL,
957  (errcode(ERRCODE_UNDEFINED_DATABASE),
958  errmsg("database \"%s\" does not exist", dbname),
959  errdetail("It seems to have just been dropped or renamed.")));
960  }
961 
962  /*
963  * Now we should be able to access the database directory safely. Verify
964  * it's there and looks reasonable.
965  */
967 
968  if (!bootstrap)
969  {
970  if (access(fullpath, F_OK) == -1)
971  {
972  if (errno == ENOENT)
973  ereport(FATAL,
974  (errcode(ERRCODE_UNDEFINED_DATABASE),
975  errmsg("database \"%s\" does not exist",
976  dbname),
977  errdetail("The database subdirectory \"%s\" is missing.",
978  fullpath)));
979  else
980  ereport(FATAL,
982  errmsg("could not access directory \"%s\": %m",
983  fullpath)));
984  }
985 
986  ValidatePgVersion(fullpath);
987  }
988 
989  SetDatabasePath(fullpath);
990 
991  /*
992  * It's now possible to do real access to the system catalogs.
993  *
994  * Load relcache entries for the system catalogs. This must create at
995  * least the minimum set of "nailed-in" cache entries.
996  */
998 
999  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1000  initialize_acl();
1001 
1002  /*
1003  * Re-read the pg_database row for our database, check permissions and set
1004  * up database-specific GUC settings. We can't do this until all the
1005  * database-access infrastructure is up. (Also, it wants to know if the
1006  * user is a superuser, so the above stuff has to happen first.)
1007  */
1008  if (!bootstrap)
1009  CheckMyDatabase(dbname, am_superuser);
1010 
1011  /*
1012  * Now process any command-line switches and any additional GUC variable
1013  * settings passed in the startup packet. We couldn't do this before
1014  * because we didn't know if client is a superuser.
1015  */
1016  if (MyProcPort != NULL)
1017  process_startup_options(MyProcPort, am_superuser);
1018 
1019  /* Process pg_db_role_setting options */
1021 
1022  /* Apply PostAuthDelay as soon as we've read all options */
1023  if (PostAuthDelay > 0)
1024  pg_usleep(PostAuthDelay * 1000000L);
1025 
1026  /*
1027  * Initialize various default states that can't be set up until we've
1028  * selected the active user and gotten the right GUC settings.
1029  */
1030 
1031  /* set default namespace search path */
1033 
1034  /* initialize client encoding */
1036 
1037  /* Initialize this backend's session state. */
1039 
1040  /* report this backend in the PgBackendStatus array */
1041  if (!bootstrap)
1042  pgstat_bestart();
1043 
1044  /* close the transaction we started above */
1045  if (!bootstrap)
1047 }
int errhint(const char *fmt,...)
Definition: elog.c:987
BackendId MyBackendId
Definition: globals.c:73
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
struct Port * MyProcPort
Definition: globals.c:41
CAC_state canAcceptConnections
Definition: libpq-be.h:129
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:258
#define DEBUG3
Definition: elog.h:23
Oid GetUserId(void)
Definition: miscinit.c:284
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
PGPROC * MyProc
Definition: proc.c:67
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:95
#define DatabaseRelationId
Definition: pg_database.h:29
void CommitTransactionCommand(void)
Definition: xact.c:2745
void InitializeSession(void)
Definition: session.c:54
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1358
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3548
static void PerformAuthentication(Port *port)
Definition: postinit.c:184
static void LockTimeoutHandler(void)
Definition: postinit.c:1192
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
static void CheckMyDatabase(const char *name, bool am_superuser)
Definition: postinit.c:293
void initialize_acl(void)
Definition: acl.c:4614
bool RecoveryInProgress(void)
Definition: xlog.c:7919
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define OidIsValid(objectId)
Definition: c.h:594
Oid GetSessionUserId(void)
Definition: miscinit.c:318
bool HaveNFreeProcs(int n)
Definition: proc.c:646
bool IsBinaryUpgrade
Definition: globals.c:102
Oid MyDatabaseTableSpace
Definition: globals.c:79
bool IsBackgroundWorker
Definition: globals.c:103
void RelationCacheInitializePhase3(void)
Definition: relcache.c:3607
#define NAMEDATALEN
bool am_walsender
Definition: walsender.c:115
void pg_usleep(long microsec)
Definition: signal.c:53
int ReservedBackends
Definition: postmaster.c:212
#define FATAL
Definition: elog.h:52
void InitializeSearchPath(void)
Definition: namespace.c:4110
int MaxBackends
Definition: globals.c:127
#define TemplateDbOid
Definition: pg_database.h:80
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:355
bool IsUnderPostmaster
Definition: globals.c:101
#define RowExclusiveLock
Definition: lockdefs.h:38
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1202
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:327
Oid databaseId
Definition: proc.h:114
void pgstat_initialize(void)
Definition: pgstat.c:2745
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1213
void StartupXLOG(void)
Definition: xlog.c:6257
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define ereport(elevel, rest)
Definition: elog.h:122
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:510
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:108
void SetDatabasePath(const char *path)
Definition: miscinit.c:83
#define WARNING
Definition: elog.h:40
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8350
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:138
#define InvalidBackendId
Definition: backendid.h:23
bool am_db_walsender
Definition: walsender.c:118
Oid MyDatabaseId
Definition: globals.c:77
int PostAuthDelay
Definition: postgres.c:99
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:897
void EnablePortalManager(void)
Definition: portalmem.c:104
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1153
static char * username
Definition: initdb.c:132
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:373
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3249
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:688
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:579
void StartTransactionCommand(void)
Definition: xact.c:2674
#define XACT_READ_COMMITTED
Definition: xact.h:29
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:483
char * dbname
Definition: streamutil.c:42
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1054
int XactIsoLevel
Definition: xact.c:74
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:465
void InitializeClientEncoding(void)
Definition: mbutils.c:282
void InitPlanCache(void)
Definition: plancache.c:116
void InitProcessPhase2(void)
Definition: proc.c:456
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:368
void RelationCacheInitialize(void)
Definition: relcache.c:3511
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:105
void InitCatalogCache(void)
Definition: syscache.c:998
static void StatementTimeoutHandler(void)
Definition: postinit.c:1170
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:733
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pgstat_bestart(void)
Definition: pgstat.c:2785
#define NameStr(name)
Definition: c.h:565
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1119
void CheckDeadLockAlert(void)
Definition: proc.c:1752
void InitBufferPoolBackend(void)
Definition: bufmgr.c:2461
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 176 of file miscinit.c.

References elog, FATAL, InitializeLatchSupport(), InitLatch(), IsUnderPostmaster, LocalLatchData, MyLatch, MyProcPid, MyStartTime, and on_exit_reset().

Referenced by BackendRun(), BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacLauncher(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

177 {
178  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
179 
180  MyProcPid = getpid(); /* reset MyProcPid */
181 
182  MyStartTime = time(NULL); /* set our start time in case we call elog */
183 
184  /*
185  * make sure stderr is in binary mode before anything can possibly be
186  * written to it, in case it's actually the syslogger pipe, so the pipe
187  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
188  * redirection (e.g. via pg_ctl -l) anyway.
189  */
190 #ifdef WIN32
191  _setmode(fileno(stderr), _O_BINARY);
192 #endif
193 
194  /* We don't want the postmaster's proc_exit() handlers */
195  on_exit_reset();
196 
197  /* Initialize process-local latch support */
201 
202  /*
203  * If possible, make this process a group leader, so that the postmaster
204  * can signal any child processes too. Not all processes will have
205  * children, but for consistency we make all postmaster child processes do
206  * this.
207  */
208 #ifdef HAVE_SETSID
209  if (setsid() < 0)
210  elog(FATAL, "setsid() failed: %m");
211 #endif
212 }
int MyProcPid
Definition: globals.c:39
pg_time_t MyStartTime
Definition: globals.c:40
void on_exit_reset(void)
Definition: ipc.c:403
static Latch LocalLatchData
Definition: miscinit.c:62
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:101
void InitializeLatchSupport(void)
Definition: latch.c:147
void InitLatch(volatile Latch *latch)
Definition: latch.c:220
struct Latch * MyLatch
Definition: globals.c:52
#define elog
Definition: elog.h:219

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 220 of file miscinit.c.

References Assert, elog, FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitLatch(), IsPostmasterEnvironment, LocalLatchData, my_exec_path, MyLatch, MyProcPid, MyStartTime, and pkglib_path.

Referenced by AuxiliaryProcessMain(), and PostgresMain().

221 {
223 
224  MyProcPid = getpid(); /* reset MyProcPid */
225 
226  MyStartTime = time(NULL); /* set our start time in case we call elog */
227 
228  /* Initialize process-local latch support */
232 
233  /* Compute paths, no postmaster to inherit from */
234  if (my_exec_path[0] == '\0')
235  {
236  if (find_my_exec(argv0, my_exec_path) < 0)
237  elog(FATAL, "%s: could not locate my own executable path",
238  argv0);
239  }
240 
241  if (pkglib_path[0] == '\0')
243 }
bool IsPostmasterEnvironment
Definition: globals.c:100
static char * argv0
Definition: pg_ctl.c:93
int MyProcPid
Definition: globals.c:39
pg_time_t MyStartTime
Definition: globals.c:40
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:62
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
char my_exec_path[MAXPGPATH]
Definition: globals.c:64
void InitializeLatchSupport(void)
Definition: latch.c:147
#define Assert(condition)
Definition: c.h:688
void InitLatch(volatile Latch *latch)
Definition: latch.c:220
struct Latch * MyLatch
Definition: globals.c:52
#define elog
Definition: elog.h:219
char pkglib_path[MAXPGPATH]
Definition: globals.c:65

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 407 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), is_admin_of_role(), and set_config_option().

408 {
410 }
static int SecurityRestrictionContext
Definition: miscinit.c:165
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:294

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 425 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

426 {
428 }
static int SecurityRestrictionContext
Definition: miscinit.c:165
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:296

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

Definition at line 416 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

Referenced by CheckRestrictedOperation(), DefineRelation(), is_admin_of_role(), set_config_option(), and SetUserIdAndContext().

417 {
419 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:295
static int SecurityRestrictionContext
Definition: miscinit.c:165

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1511 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1512 {
1513 #ifdef ENABLE_NLS
1514  if (my_exec_path[0] != '\0')
1515  {
1516  char locale_path[MAXPGPATH];
1517 
1518  get_locale_path(my_exec_path, locale_path);
1519  bindtextdomain(domain, locale_path);
1520  pg_bind_textdomain_codeset(domain);
1521  }
1522 #endif
1523 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:64
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767

◆ pg_split_opts()

void pg_split_opts ( char **  argv,
int *  argcp,
const char *  optstr 
)

Definition at line 443 of file postinit.c.

References appendStringInfoChar(), StringInfoData::data, initStringInfo(), pfree(), pstrdup(), and resetStringInfo().

Referenced by BackendRun(), and process_startup_options().

444 {
445  StringInfoData s;
446 
447  initStringInfo(&s);
448 
449  while (*optstr)
450  {
451  bool last_was_escape = false;
452 
453  resetStringInfo(&s);
454 
455  /* skip over leading space */
456  while (isspace((unsigned char) *optstr))
457  optstr++;
458 
459  if (*optstr == '\0')
460  break;
461 
462  /*
463  * Parse a single option, stopping at the first space, unless it's
464  * escaped.
465  */
466  while (*optstr)
467  {
468  if (isspace((unsigned char) *optstr) && !last_was_escape)
469  break;
470 
471  if (!last_was_escape && *optstr == '\\')
472  last_was_escape = true;
473  else
474  {
475  last_was_escape = false;
476  appendStringInfoChar(&s, *optstr);
477  }
478 
479  optstr++;
480  }
481 
482  /* now store the option in the next argv[] position */
483  argv[(*argcp)++] = pstrdup(s.data);
484  }
485 
486  pfree(s.data);
487 }
char * pstrdup(const char *in)
Definition: mcxt.c:1063
void pfree(void *pointer)
Definition: mcxt.c:936
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46

◆ PostgresSigHupHandler()

void PostgresSigHupHandler ( SIGNAL_ARGS  )

Definition at line 2727 of file postgres.c.

References ConfigReloadPending, MyLatch, and SetLatch().

Referenced by PostgresMain(), and WalSndSignals().

2728 {
2729  int save_errno = errno;
2730 
2731  ConfigReloadPending = true;
2732  SetLatch(MyLatch);
2733 
2734  errno = save_errno;
2735 }
volatile sig_atomic_t ConfigReloadPending
Definition: globals.c:34
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 274 of file utility.c.

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

Referenced by LockTableCommand(), pg_notify(), standard_ProcessUtility(), and txid_current().

275 {
276  if (RecoveryInProgress())
277  ereport(ERROR,
278  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
279  /* translator: %s is name of a SQL command, eg CREATE */
280  errmsg("cannot execute %s during recovery",
281  cmdname)));
282 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool RecoveryInProgress(void)
Definition: xlog.c:7919
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 255 of file utility.c.

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

Referenced by _SPI_execute_plan(), check_xact_readonly(), do_setval(), DoCopy(), ExecCheckXactReadOnly(), init_execution_state(), nextval_internal(), and SPI_cursor_open_internal().

256 {
257  if (IsInParallelMode())
258  ereport(ERROR,
259  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
260  /* translator: %s is name of a SQL command, eg CREATE */
261  errmsg("cannot execute %s during a parallel operation",
262  cmdname)));
263 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsInParallelMode(void)
Definition: xact.c:906
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 237 of file utility.c.

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

Referenced by check_xact_readonly(), do_setval(), DoCopy(), ExecCheckXactReadOnly(), and nextval_internal().

238 {
239  if (XactReadOnly)
240  ereport(ERROR,
241  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
242  /* translator: %s is name of a SQL command, eg CREATE */
243  errmsg("cannot execute %s in a read-only transaction",
244  cmdname)));
245 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
bool XactReadOnly
Definition: xact.c:77
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1500 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1501 {
1503  "session_preload_libraries",
1504  false);
1506  "local_preload_libraries",
1507  true);
1508 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1435
char * local_preload_libraries_string
Definition: miscinit.c:1423
char * session_preload_libraries_string
Definition: miscinit.c:1421

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1487 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1488 {
1491  "shared_preload_libraries",
1492  false);
1494 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1426
char * shared_preload_libraries_string
Definition: miscinit.c:1422
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1435

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 2864 of file postgres.c.

References Assert, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, ereport, errcode(), errdetail_recovery_conflict(), errhint(), errmsg(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsLogicalLauncher(), IsLogicalWorker(), LOCK_TIMEOUT, LockErrorCleanup(), ParallelMessagePending, pgstat_report_recovery_conflict(), proc_exit(), ProcDiePending, PROCSIG_RECOVERY_CONFLICT_DATABASE, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

2865 {
2866  /* OK to accept any interrupts now? */
2867  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2868  return;
2869  InterruptPending = false;
2870 
2871  if (ProcDiePending)
2872  {
2873  ProcDiePending = false;
2874  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2875  LockErrorCleanup();
2876  /* As in quickdie, don't risk sending to client during auth */
2880  ereport(FATAL,
2881  (errcode(ERRCODE_QUERY_CANCELED),
2882  errmsg("canceling authentication due to timeout")));
2883  else if (IsAutoVacuumWorkerProcess())
2884  ereport(FATAL,
2885  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2886  errmsg("terminating autovacuum process due to administrator command")));
2887  else if (IsLogicalWorker())
2888  ereport(FATAL,
2889  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2890  errmsg("terminating logical replication worker due to administrator command")));
2891  else if (IsLogicalLauncher())
2892  {
2893  ereport(DEBUG1,
2894  (errmsg("logical replication launcher shutting down")));
2895 
2896  /*
2897  * The logical replication launcher can be stopped at any time.
2898  * Use exit status 1 so the background worker is restarted.
2899  */
2900  proc_exit(1);
2901  }
2903  {
2905  ereport(FATAL,
2906  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2907  errmsg("terminating connection due to conflict with recovery"),
2909  }
2910  else if (RecoveryConflictPending)
2911  {
2912  /* Currently there is only one non-retryable recovery conflict */
2915  ereport(FATAL,
2916  (errcode(ERRCODE_DATABASE_DROPPED),
2917  errmsg("terminating connection due to conflict with recovery"),
2919  }
2920  else
2921  ereport(FATAL,
2922  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2923  errmsg("terminating connection due to administrator command")));
2924  }
2926  {
2927  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2928  LockErrorCleanup();
2929  /* don't send to client, we already know the connection to be dead. */
2931  ereport(FATAL,
2932  (errcode(ERRCODE_CONNECTION_FAILURE),
2933  errmsg("connection to client lost")));
2934  }
2935 
2936  /*
2937  * If a recovery conflict happens while we are waiting for input from the
2938  * client, the client is presumably just sitting idle in a transaction,
2939  * preventing recovery from making progress. Terminate the connection to
2940  * dislodge it.
2941  */
2943  {
2944  QueryCancelPending = false; /* this trumps QueryCancel */
2945  RecoveryConflictPending = false;
2946  LockErrorCleanup();
2948  ereport(FATAL,
2949  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2950  errmsg("terminating connection due to conflict with recovery"),
2952  errhint("In a moment you should be able to reconnect to the"
2953  " database and repeat your command.")));
2954  }
2955 
2956  /*
2957  * Don't allow query cancel interrupts while reading input from the
2958  * client, because we might lose sync in the FE/BE protocol. (Die
2959  * interrupts are OK, because we won't read any further messages from the
2960  * client in that case.)
2961  */
2963  {
2964  /*
2965  * Re-arm InterruptPending so that we process the cancel request as
2966  * soon as we're done reading the message.
2967  */
2968  InterruptPending = true;
2969  }
2970  else if (QueryCancelPending)
2971  {
2972  bool lock_timeout_occurred;
2973  bool stmt_timeout_occurred;
2974 
2975  QueryCancelPending = false;
2976 
2977  /*
2978  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2979  * need to clear both, so always fetch both.
2980  */
2981  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2982  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2983 
2984  /*
2985  * If both were set, we want to report whichever timeout completed
2986  * earlier; this ensures consistent behavior if the machine is slow
2987  * enough that the second timeout triggers before we get here. A tie
2988  * is arbitrarily broken in favor of reporting a lock timeout.
2989  */
2990  if (lock_timeout_occurred && stmt_timeout_occurred &&
2992  lock_timeout_occurred = false; /* report stmt timeout */
2993 
2994  if (lock_timeout_occurred)
2995  {
2996  LockErrorCleanup();
2997  ereport(ERROR,
2998  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2999  errmsg("canceling statement due to lock timeout")));
3000  }
3001  if (stmt_timeout_occurred)
3002  {
3003  LockErrorCleanup();
3004  ereport(ERROR,
3005  (errcode(ERRCODE_QUERY_CANCELED),
3006  errmsg("canceling statement due to statement timeout")));
3007  }
3009  {
3010  LockErrorCleanup();
3011  ereport(ERROR,
3012  (errcode(ERRCODE_QUERY_CANCELED),
3013  errmsg("canceling autovacuum task")));
3014  }
3016  {
3017  RecoveryConflictPending = false;
3018  LockErrorCleanup();
3020  ereport(ERROR,
3021  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3022  errmsg("canceling statement due to conflict with recovery"),
3024  }
3025 
3026  /*
3027  * If we are reading a command from the client, just ignore the cancel
3028  * request --- sending an extra error message won't accomplish
3029  * anything. Otherwise, go ahead and throw the error.
3030  */
3031  if (!DoingCommandRead)
3032  {
3033  LockErrorCleanup();
3034  ereport(ERROR,
3035  (errcode(ERRCODE_QUERY_CANCELED),
3036  errmsg("canceling statement due to user request")));
3037  }
3038  }
3039 
3041  {
3042  /* Has the timeout setting changed since last we looked? */
3044  ereport(FATAL,
3045  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3046  errmsg("terminating connection due to idle-in-transaction timeout")));
3047  else
3049 
3050  }
3051 
3054 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:35
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:667
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1486
volatile bool IdleInTransactionSessionTimeoutPending
Definition: globals.c:33
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:36
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
volatile bool QueryCancelPending
Definition: globals.c:30
bool IsLogicalWorker(void)
Definition: worker.c:1661
volatile bool ClientConnectionLost
Definition: globals.c:32
volatile bool ParallelMessagePending
Definition: parallel.c:106
bool ClientAuthInProgress
Definition: postmaster.c:350
#define ERROR
Definition: elog.h:43
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:52
void HandleParallelMessages(void)
Definition: parallel.c:960
Definition: dest.h:88
volatile uint32 CritSectionCount
Definition: globals.c:37
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define ereport(elevel, rest)
Definition: elog.h:122
void LockErrorCleanup(void)
Definition: proc.c:686
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static bool RecoveryConflictPending
Definition: postgres.c:164
static bool RecoveryConflictRetryable
Definition: postgres.c:165
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:633
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2287
volatile bool InterruptPending
Definition: globals.c:29
#define Assert(condition)
Definition: c.h:688
static bool DoingCommandRead
Definition: postgres.c:137
volatile bool ProcDiePending
Definition: globals.c:31
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool IsLogicalLauncher(void)
Definition: launcher.c:1003
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1286 of file miscinit.c.

References buffer, close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), read, and WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ.

Referenced by ServerLoop().

1287 {
1288  int fd;
1289  int len;
1290  long file_pid;
1291  char buffer[BLCKSZ];
1292 
1293  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1294  if (fd < 0)
1295  {
1296  /*
1297  * There are many foreseeable false-positive error conditions. For
1298  * safety, fail only on enumerated clearly-something-is-wrong
1299  * conditions.
1300  */
1301  switch (errno)
1302  {
1303  case ENOENT:
1304  case ENOTDIR:
1305  /* disaster */
1306  ereport(LOG,
1308  errmsg("could not open file \"%s\": %m",
1310  return false;
1311  default:
1312  /* non-fatal, at least for now */
1313  ereport(LOG,
1315  errmsg("could not open file \"%s\": %m; continuing anyway",
1317  return true;
1318  }
1319  }
1321  len = read(fd, buffer, sizeof(buffer) - 1);
1323  if (len < 0)
1324  {
1325  ereport(LOG,
1327  errmsg("could not read from file \"%s\": %m",
1329  close(fd);
1330  return true; /* treat read failure as nonfatal */
1331  }
1332  buffer[len] = '\0';
1333  close(fd);
1334  file_pid = atol(buffer);
1335  if (file_pid == getpid())
1336  return true; /* all is well */
1337 
1338  /* Trouble: someone's overwritten the lock file */
1339  ereport(LOG,
1340  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1341  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1342  return false;
1343 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:55
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1069
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
#define ereport(elevel, rest)
Definition: elog.h:122
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1236
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3132 of file postgres.c.

References stack_base_ptr.

3133 {
3134 #if defined(__ia64__) || defined(__ia64)
3135  stack_base_ptr = base.stack_base_ptr;
3136  register_stack_base_ptr = base.register_stack_base_ptr;
3137 #else
3138  stack_base_ptr = base;
3139 #endif
3140 }
char * stack_base_ptr
Definition: postgres.c:117

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )

Definition at line 3101 of file postgres.c.

References stack_base_ptr.

Referenced by BackendRun(), and PostmasterMain().

3102 {
3103  char stack_base;
3104  pg_stack_base_t old;
3105 
3106 #if defined(__ia64__) || defined(__ia64)
3107  old.stack_base_ptr = stack_base_ptr;
3108  old.register_stack_base_ptr = register_stack_base_ptr;
3109 #else
3110  old = stack_base_ptr;
3111 #endif
3112 
3113  /* Set up reference point for stack depth checking */
3114  stack_base_ptr = &stack_base;
3115 #if defined(__ia64__) || defined(__ia64)
3116  register_stack_base_ptr = ia64_get_bsp();
3117 #endif
3118 
3119  return old;
3120 }
char * stack_base_ptr
Definition: postgres.c:117
char * pg_stack_base_t
Definition: miscadmin.h:269

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 657 of file miscinit.c.

References OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SessionUserId, SessionUserIsSuperuser, SetConfigOption(), SetOuterUserId(), and SetRoleIsActive.

Referenced by assign_role(), and ParallelWorkerMain().

658 {
659  /*
660  * Get correct info if it's SET ROLE NONE
661  *
662  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
663  * SetSessionUserId call will fix everything. This is needed since we
664  * will get called during GUC initialization.
665  */
666  if (!OidIsValid(roleid))
667  {
669  return;
670 
671  roleid = SessionUserId;
673 
674  SetRoleIsActive = false;
675  }
676  else
677  SetRoleIsActive = true;
678 
679  SetOuterUserId(roleid);
680 
681  SetConfigOption("is_superuser",
682  is_superuser ? "on" : "off",
684 }
static Oid SessionUserId
Definition: miscinit.c:157
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:303
#define OidIsValid(objectId)
Definition: c.h:594
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6720
static bool SetRoleIsActive
Definition: miscinit.c:168
static bool SessionUserIsSuperuser
Definition: miscinit.c:163
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:3976

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 83 of file miscinit.c.

References Assert, DatabasePath, MemoryContextStrdup(), and TopMemoryContext.

Referenced by InitPostgres().

84 {
85  /* This should happen only once per process */
88 }
MemoryContext TopMemoryContext
Definition: mcxt.c:43
char * DatabasePath
Definition: globals.c:85
#define Assert(condition)
Definition: c.h:688
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1050

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 95 of file miscinit.c.

References AssertArg, DataDir, free, and make_absolute_path().

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

96 {
97  char *new;
98 
99  AssertArg(dir);
100 
101  /* If presented path is relative, convert to absolute */
102  new = make_absolute_path(dir);
103 
104  if (DataDir)
105  free(DataDir);
106  DataDir = new;
107 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:690
#define free(a)
Definition: header.h:65
char * DataDir
Definition: globals.c:60

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 611 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), errmsg(), ERROR, OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

612 {
613  /* Must have authenticated already, else can't make permission check */
615 
616  if (userid != AuthenticatedUserId &&
618  ereport(ERROR,
619  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
620  errmsg("permission denied to set session authorization")));
621 
623 
624  SetConfigOption("is_superuser",
625  is_superuser ? "on" : "off",
627 }
#define AssertState(condition)
Definition: c.h:691
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:594
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6720
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:162
#define ereport(elevel, rest)
Definition: elog.h:122
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:3976
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:326
static Oid AuthenticatedUserId
Definition: miscinit.c:156

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 445 of file miscinit.c.

References CurrentUserId, ereport, errcode(), errmsg(), ERROR, InSecurityRestrictedOperation(), SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

446 {
447  /* We throw the same error SET ROLE would. */
449  ereport(ERROR,
450  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
451  errmsg("cannot set parameter \"%s\" within security-restricted operation",
452  "role")));
453  CurrentUserId = userid;
454  if (sec_def_context)
456  else
458 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:165
#define ereport(elevel, rest)
Definition: elog.h:122
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:294
static Oid CurrentUserId
Definition: miscinit.c:159
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:416
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )

Definition at line 3168 of file postgres.c.

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

3169 {
3170  char stack_top_loc;
3171  long stack_depth;
3172 
3173  /*
3174  * Compute distance from reference point to my local variables
3175  */
3176  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3177 
3178  /*
3179  * Take abs value, since stacks grow up on some machines, down on others
3180  */
3181  if (stack_depth < 0)
3182  stack_depth = -stack_depth;
3183 
3184  /*
3185  * Trouble?
3186  *
3187  * The test on stack_base_ptr prevents us from erroring out if called
3188  * during process setup or in a non-backend process. Logically it should
3189  * be done first, but putting it here avoids wasting cycles during normal
3190  * cases.
3191  */
3192  if (stack_depth > max_stack_depth_bytes &&
3193  stack_base_ptr != NULL)
3194  return true;
3195 
3196  /*
3197  * On IA64 there is a separate "register" stack that requires its own
3198  * independent check. For this, we have to measure the change in the
3199  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3200  * except that we know IA64's register stack grows up.
3201  *
3202  * Note we assume that the same max_stack_depth applies to both stacks.
3203  */
3204 #if defined(__ia64__) || defined(__ia64)
3205  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3206 
3207  if (stack_depth > max_stack_depth_bytes &&
3208  register_stack_base_ptr != NULL)
3209  return true;
3210 #endif /* IA64 */
3211 
3212  return false;
3213 }
static long max_stack_depth_bytes
Definition: postgres.c:109
char * stack_base_ptr
Definition: postgres.c:117

◆ superuser()

bool superuser ( void  )

Definition at line 47 of file superuser.c.

References GetUserId(), and superuser_arg().

Referenced by AddRoleMems(), AlterForeignDataWrapper(), AlterForeignDataWrapperOwner_internal(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOpFamily(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSystemSetConfigFile(), AlterTypeOwner(), ATExecChangeOwner(), brin_metapage_info(), brin_page_items(), brin_page_type(), brin_revmap_data(), bt_metap(), bt_page_items(), bt_page_items_bytea(), bt_page_stats(), check_encoding_locale_matches(), check_permissions(), CreateAccessMethod(), CreateCast(), CreateEventTrigger(), CreateForeignDataWrapper(), CreateFunction(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateSubscription(), CreateTableSpace(), dblink_connstr_check(), dblink_security_check(), DefineAggregate(), DefineOpClass(), DefineOpFamily(), DefineTSParser(), DefineTSTemplate(), DefineType(), DelRoleMems(), DoCopy(), DropRole(), dummy_object_relabel(), EnableDisableTrigger(), ExecSetVariableStmt(), ExecuteDoStmt(), file_fdw_validator(), fmgr_security_definer(), fsm_page_contents(), get_raw_page_internal(), GetConfigOptionByNum(), gin_leafpage_items(), gin_metapage_info(), gin_page_opaque_info(), GUCArrayReset(), hash_bitmap_info(), hash_metapage_info(), hash_page_items(), hash_page_stats(), hash_page_type(), have_createdb_privilege(), heap_page_items(), InitPostgres(), main(), page_checksum(), page_header(), pg_import_system_collations(), pg_logdir_ls(), pg_ls_dir(), pg_read_binary_file(), pg_read_file(), pg_relpages(), pg_relpagesbyid(), pg_signal_backend(), pg_stat_file(), pgstat_get_backend_current_activity(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuple_approx(), pgstattuplebyid(), ProcedureCreate(), regress_putenv(), RemoveAccessMethodById(), RenameRole(), replorigin_check_prerequisites(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), ShowAllGUCConfig(), standard_ProcessUtility(), tuple_data_split(), validate_option_array_item(), and wait_pid().

48 {
49  return superuser_arg(GetUserId());
50 }
Oid GetUserId(void)
Definition: miscinit.c:284
bool superuser_arg(Oid roleid)
Definition: superuser.c:57

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)

Definition at line 57 of file superuser.c.

References AUTHOID, BOOTSTRAP_SUPERUSERID, CacheRegisterSyscacheCallback(), GETSTRUCT, HeapTupleIsValid, IsUnderPostmaster, last_roleid, last_roleid_is_super, ObjectIdGetDatum, OidIsValid, ReleaseSysCache(), roleid_callback_registered, RoleidCallback(), and SearchSysCache1().

Referenced by AddRoleMems(), AlterEventTriggerOwner_internal(), AlterForeignDataWrapperOwner_internal(), AlterPublicationOwner_internal(), AlterSubscriptionOwner_internal(), check_conn_params(), check_object_ownership(), connect_pg_server(), DelRoleMems(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), is_admin_of_role(), is_member_of_role(), LockGXact(), pg_class_aclmask(), pg_class_ownercheck(), pg_collation_ownercheck(), pg_conversion_ownercheck(), pg_database_aclmask(), pg_database_ownercheck(), pg_event_trigger_ownercheck(), pg_extension_ownercheck(), pg_foreign_data_wrapper_aclmask(), pg_foreign_data_wrapper_ownercheck(), pg_foreign_server_aclmask(), pg_foreign_server_ownercheck(), pg_language_aclmask(), pg_language_ownercheck(), pg_largeobject_aclmask_snapshot(), pg_largeobject_ownercheck(), pg_namespace_aclmask(), pg_namespace_ownercheck(), pg_opclass_ownercheck(), pg_oper_ownercheck(), pg_opfamily_ownercheck(), pg_proc_aclmask(), pg_proc_ownercheck(), pg_publication_ownercheck(), pg_signal_backend(), pg_statistics_object_ownercheck(), pg_subscription_ownercheck(), pg_tablespace_aclmask(), pg_tablespace_ownercheck(), pg_ts_config_ownercheck(), pg_ts_dict_ownercheck(), pg_type_aclmask(), pg_type_ownercheck(), select_best_grantor(), and superuser().

58 {
59  bool result;
60  HeapTuple rtup;
61 
62  /* Quick out for cache hit */
63  if (OidIsValid(last_roleid) && last_roleid == roleid)
64  return last_roleid_is_super;
65 
66  /* Special escape path in case you deleted all your users. */
67  if (!IsUnderPostmaster && roleid == BOOTSTRAP_SUPERUSERID)
68  return true;
69 
70  /* OK, look up the information in pg_authid */
71  rtup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
72  if (HeapTupleIsValid(rtup))
73  {
74  result = ((Form_pg_authid) GETSTRUCT(rtup))->rolsuper;
75  ReleaseSysCache(rtup);
76  }
77  else
78  {
79  /* Report "not superuser" for invalid roleids */
80  result = false;
81  }
82 
83  /* If first time through, set up callback for cache flushes */
85  {
88  (Datum) 0);
90  }
91 
92  /* Cache the result for next time */
93  last_roleid = roleid;
94  last_roleid_is_super = result;
95 
96  return result;
97 }
static Oid last_roleid
Definition: superuser.c:36
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define OidIsValid(objectId)
Definition: c.h:594
static void RoleidCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: superuser.c:104
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
static bool last_roleid_is_super
Definition: superuser.c:37
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
bool IsUnderPostmaster
Definition: globals.c:101
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1389
uintptr_t Datum
Definition: postgres.h:365
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:102
static bool roleid_callback_registered
Definition: superuser.c:38

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 265 of file miscinit.c.

References Assert, FeBeWaitSet, LocalLatchData, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by AuxiliaryProcKill(), and ProcKill().

266 {
268  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
269 
271 
272  if (FeBeWaitSet)
274 
275  SetLatch(MyLatch);
276 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:736
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:62
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:688
struct Latch * MyLatch
Definition: globals.c:52
#define WL_LATCH_SET
Definition: latch.h:124

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 246 of file miscinit.c.

References Assert, FeBeWaitSet, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by InitAuxiliaryProcess(), and InitProcess().

247 {
249  Assert(MyProc != NULL);
250 
252 
253  if (FeBeWaitSet)
255 
256  /*
257  * Set the shared latch as the local one might have been set. This
258  * shouldn't normally be necessary as code is supposed to check the
259  * condition before waiting for the latch, but a bit care can't hurt.
260  */
261  SetLatch(MyLatch);
262 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:736
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:62
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:688
struct Latch * MyLatch
Definition: globals.c:52
#define WL_LATCH_SET
Definition: latch.h:124

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1108 of file miscinit.c.

References buffer, close, DIRECTORY_LOCK_FILE, fd(), lfirst, PG_BINARY, and read.

Referenced by ServerLoop().

1109 {
1110  ListCell *l;
1111 
1112  foreach(l, lock_files)
1113  {
1114  char *socketLockFile = (char *) lfirst(l);
1115 
1116  /* No need to touch the data directory lock file, we trust */
1117  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1118  continue;
1119 
1120  /*
1121  * utime() is POSIX standard, utimes() is a common alternative; if we
1122  * have neither, fall back to actually reading the file (which only
1123  * sets the access time not mod time, but that should be enough in
1124  * most cases). In all paths, we ignore errors.
1125  */
1126 #ifdef HAVE_UTIME
1127  utime(socketLockFile, NULL);
1128 #else /* !HAVE_UTIME */
1129 #ifdef HAVE_UTIMES
1130  utimes(socketLockFile, NULL);
1131 #else /* !HAVE_UTIMES */
1132  int fd;
1133  char buffer[1];
1134 
1135  fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1136  if (fd >= 0)
1137  {
1138  read(fd, buffer, sizeof(buffer));
1139  close(fd);
1140  }
1141 #endif /* HAVE_UTIMES */
1142 #endif /* HAVE_UTIME */
1143  }
1144 }
static List * lock_files
Definition: miscinit.c:60
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:55
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1069
#define lfirst(lc)
Definition: pg_list.h:106
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ trace_recovery()

int trace_recovery ( int  trace_level)

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1358 of file miscinit.c.

References AllocateFile(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, FreeFile(), MAXPGPATH, and snprintf().

Referenced by AuxiliaryProcessMain(), checkDataDir(), InitPostgres(), and PostgresMain().

1359 {
1360  char full_path[MAXPGPATH];
1361  FILE *file;
1362  int ret;
1363  long file_major;
1364  long my_major;
1365  char *endptr;
1366  char file_version_string[64];
1367  const char *my_version_string = PG_VERSION;
1368 
1369  my_major = strtol(my_version_string, &endptr, 10);
1370 
1371  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1372 
1373  file = AllocateFile(full_path, "r");
1374  if (!file)
1375  {
1376  if (errno == ENOENT)
1377  ereport(FATAL,
1378  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1379  errmsg("\"%s\" is not a valid data directory",
1380  path),
1381  errdetail("File \"%s\" is missing.", full_path)));
1382  else
1383  ereport(FATAL,
1385  errmsg("could not open file \"%s\": %m", full_path)));
1386  }
1387 
1388  file_version_string[0] = '\0';
1389  ret = fscanf(file, "%63s", file_version_string);
1390  file_major = strtol(file_version_string, &endptr, 10);
1391 
1392  if (ret != 1 || endptr == file_version_string)
1393  ereport(FATAL,
1394  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1395  errmsg("\"%s\" is not a valid data directory",
1396  path),
1397  errdetail("File \"%s\" does not contain valid data.",
1398  full_path),
1399  errhint("You might need to initdb.")));
1400 
1401  FreeFile(file);
1402 
1403  if (my_major != file_major)
1404  ereport(FATAL,
1405  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1406  errmsg("database files are incompatible with server"),
1407  errdetail("The data directory was initialized by PostgreSQL version %s, "
1408  "which is not compatible with this version %s.",
1409  file_version_string, my_version_string)));
1410 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2353
#define ereport(elevel, rest)
Definition: elog.h:122
int FreeFile(FILE *file)
Definition: fd.c:2545
int errmsg(const char *fmt,...)
Definition: elog.c:797

Variable Documentation

◆ allowSystemTableMods

◆ ClientConnectionLost

volatile bool ClientConnectionLost

Definition at line 32 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

◆ ConfigReloadPending

PGDLLIMPORT volatile sig_atomic_t ConfigReloadPending

◆ CritSectionCount

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError

Definition at line 105 of file globals.c.

Referenced by BackgroundWriterMain(), CheckpointerMain(), and errstart().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile bool IdleInTransactionSessionTimeoutPending

Definition at line 33 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

bool IgnoreSystemIndexes

◆ InterruptHoldoffCount

PGDLLIMPORT volatile uint32 InterruptHoldoffCount

Definition at line 35 of file globals.c.

Referenced by errfinish(), proc_exit_prepare(), and ProcessInterrupts().

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle

◆ IsBackgroundWorker

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster

Definition at line 101 of file globals.c.

Referenced by _PG_init(), AutoVacuumShmemInit(), AuxiliaryProcessMain(), BackendRandomShmemInit(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), CreateLWLocks(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), dsm_attach(), dsm_create(), dsm_postmaster_startup(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForgetDatabaseFsyncRequests(), ForgetRelationFsyncRequests(), ForwardFsyncRequest(), GetNewMultiXactId(), GetNewTransactionId(), HandleStartupProcInterrupts(), heap_create_with_catalog(), init_ps_display(), InitCommunication(), InitializeLatchSupport(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitPredicateLocks(), InitProcess(), LWLockAcquire(), mdinit(), MultiXactShmemInit(), OldSerXidInit(), pg_backend_random(), PGSemaphoreCreate(), PGSharedMemoryCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_startup(), PostgresMain(), process_postgres_switches(), process_settings(), ProcKill(), readRecoveryCommandFile(), register_unlink(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), RequestAddinShmemSpace(), RequestNamedLWLockTranche(), SendPostmasterSignal(), set_config_option(), set_config_sourcefile(), set_ps_display(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), standard_planner(), StartupXLOG(), superuser_arg(), SyncScanShmemInit(), TwoPhaseShmemInit(), verify_dictoptions(), WaitLatchOrSocket(), XLogArchiveNotify(), and XLogWrite().

◆ local_preload_libraries_string

char* local_preload_libraries_string

Definition at line 1423 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers

Definition at line 115 of file globals.c.

Referenced by plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers

Definition at line 126 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 57 of file miscinit.c.

◆ my_exec_path

◆ MyAuxProcType

AuxProcType MyAuxProcType

Definition at line 69 of file bootstrap.c.

Referenced by AuxiliaryProcessMain(), pgstat_bestart(), and pgstat_initialize().

◆ MyCancelKey

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId

Definition at line 77 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner(), analyze_rel(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), AutoVacuumRequestWork(), backend_read_statsfile(), CacheInvalidateCatalog(), CacheInvalidateHeapTuple(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), classIdGetDbId(), CreateDecodingContext(), CreateInitDecodingContext(), CreateProceduralLanguage(), CreatePublication(), CreateSchemaCommand(), CreateSubscription(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), DropSubscription(), Exec_ListenPreCommit(), exec_object_restorecon(), exec_replication_command(), ExpandColumnRefStar(), ExportSnapshot(), get_subscription_oid(), GetCurrentVirtualXIDs(), GetNewRelFileNode(), GetOldestXmin(), IdentifySystem(), ImportSnapshot(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), lazy_vacuum_rel(), libpqrcv_exec(), LocalExecuteInvalidationMessage(), LockDatabaseObject(), LockGXact(), logical_heap_rewrite_flush_mappings(), logical_rewrite_log_mapping(), LogLogicalMessage(), LogStandbyInvalidations(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), movedb(), perform_relmap_update(), perform_work_item(), pg_namespace_aclmask(), pg_relation_filepath(), pgss_store(), pgstat_beshutdown_hook(), pgstat_bestart(), pgstat_drop_database(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry(), pgstat_report_analyze(), pgstat_report_deadlock(), pgstat_report_recovery_conflict(), pgstat_report_stat(), pgstat_report_tempfile(), pgstat_report_vacuum(), pgstat_reset_counters(), pgstat_reset_single_counter(), pgstat_send_funcstats(), pgstat_vacuum_stat(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), ReindexMultipleTables(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationMapFinishBootstrap(), RenameDatabase(), RenameSchema(), ReplicationSlotCreate(), ScanPgRelation(), sepgsql_schema_post_create(), SetLocktagRelationOid(), shdepDropOwned(), shdepReassignOwned(), table_recheck_autovac(), transformColumnRef(), UnlockDatabaseObject(), UpdateLogicalMappings(), vac_truncate_clog(), vac_update_datfrozenxid(), vacuum_rel(), and XactLogCommitRecord().

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch

Definition at line 52 of file globals.c.

Referenced by ApplyLauncherMain(), ArchSigHupHandler(), ArchSigTermHandler(), AutoVacLauncherMain(), av_sighup_handler(), avl_sigterm_handler(), avl_sigusr2_handler(), BackgroundWriterMain(), be_tls_open_server(), BgSigHupHandler(), CheckDeadLockAlert(), CheckpointerMain(), ChkptSigHupHandler(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), copy_read_data(), die(), gather_readnext(), handle_sig_alarm(), handle_sigterm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), initialize_worker_spi(), InitPostmasterChild(), InitStandaloneProcess(), libpqrcv_connect(), libpqrcv_PQexec(), logicalrep_launcher_sighup(), logicalrep_worker_sighup(), logicalrep_worker_stop(), LogicalRepApplyLoop(), mq_putmessage(), pg_sleep(), pgarch_MainLoop(), pgarch_waken(), pgarch_waken_stop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pgstat_exit(), pgstat_sighup_handler(), PgstatCollectorMain(), PostgresSigHupHandler(), pq_init(), procsignal_sigusr1_handler(), ProcSleep(), ProcWaitForSignal(), RecoveryConflictInterrupt(), ReqCheckpointHandler(), ReqShutdownHandler(), secure_read(), secure_write(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), sigHupHandler(), sigUsr1Handler(), StatementCancelHandler(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WalShutdownHandler(), WalSigHupHandler(), WalSndLastCycleHandler(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), WalWriterMain(), worker_spi_sighup(), worker_spi_sigterm(), and write_syslogger_file().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid

Definition at line 39 of file globals.c.

Referenced by AddWaitEventToSet(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), apw_start_database_worker(), apw_start_master_worker(), Async_Listen(), Async_Unlisten(), Async_UnlistenAll(), asyncQueueNotificationToEntry(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), autoprewarm_main(), AutoVacLauncherMain(), BackendRun(), CheckpointerMain(), CleanupProcSignalState(), DisownLatch(), Exec_ListenPreCommit(), Exec_UnlistenAllCommit(), Exec_UnlistenCommit(), ExportSnapshot(), GetSerializableTransactionSnapshotInt(), HandleWalSndInitStopping(), InitAuxiliaryProcess(), InitializeLatchSupport(), InitializeParallelDSM(), InitLatch(), InitPostmasterChild(), InitPostmasterDeathWatchHandle(), InitProcess(), InitStandaloneProcess(), InitWalSenderSlot(), IsLogicalLauncher(), LaunchParallelWorkers(), LockBufferForCleanup(), LockTimeoutHandler(), log_line_prefix(), logicalrep_worker_launch(), OpenTemporaryFileInTablespace(), OwnLatch(), ParallelWorkerMain(), pg_backend_pid(), pgstat_bestart(), PostgresMain(), PostmasterMain(), ProcSignalInit(), ProcSleep(), PublishStartupProcessInformation(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotsDropDBSlots(), replorigin_session_setup(), ResetLatch(), ServerLoop(), set_ps_display(), SetLatch(), setup_background_workers(), SharedFileSetInit(), SharedInvalBackendInit(), SignalBackends(), SnapBuildSerialize(), StatementTimeoutHandler(), UnlockBuffers(), WalRcvDie(), WalReceiverMain(), worker_spi_launch(), write_csvlog(), write_pipe_chunks(), and write_relcache_init_file().

◆ MyProcPort

◆ MyStartTime

◆ NBuffers

PGDLLIMPORT int NBuffers

Definition at line 123 of file globals.c.

◆ OutputFileName

char OutputFileName[]

Definition at line 62 of file globals.c.

Referenced by AuxiliaryProcessMain(), DebugFileOpen(), and process_postgres_switches().

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ process_shared_preload_libraries_in_progress

PGDLLIMPORT bool process_shared_preload_libraries_in_progress

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount

Definition at line 36 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

◆ QueryCancelPending

◆ session_preload_libraries_string

char* session_preload_libraries_string

Definition at line 1421 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

char* shared_preload_libraries_string

Definition at line 1422 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ trace_recovery_messages

int trace_recovery_messages

Definition at line 456 of file guc.c.

Referenced by StartupXLOG(), and trace_recovery().

◆ VacuumCostActive

bool VacuumCostActive

◆ VacuumCostBalance

int VacuumCostBalance

◆ VacuumCostDelay

◆ VacuumCostLimit

int VacuumCostLimit

◆ VacuumCostPageDirty

int VacuumCostPageDirty

Definition at line 131 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

int VacuumCostPageHit

Definition at line 129 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

int VacuumCostPageMiss

Definition at line 130 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumPageDirty

int VacuumPageDirty

Definition at line 137 of file globals.c.

Referenced by lazy_vacuum_rel(), MarkBufferDirty(), MarkBufferDirtyHint(), and vacuum().

◆ VacuumPageHit

int VacuumPageHit

Definition at line 135 of file globals.c.

Referenced by lazy_vacuum_rel(), ReadBuffer_common(), and vacuum().

◆ VacuumPageMiss

int VacuumPageMiss

Definition at line 136 of file globals.c.

Referenced by lazy_vacuum_rel(), ReadBuffer_common(), and vacuum().

◆ work_mem

PGDLLIMPORT int work_mem

Definition at line 113 of file globals.c.

Referenced by _bt_parallel_scan_and_sort(), _bt_spools_heapscan(), add_partial_paths_to_grouping_rel(), add_paths_to_grouping_rel(), begin_partition(), brin_page_items(), BuildTupleHashTable(), choose_hashed_setop(), collectMatchBitmap(), compute_bitmap_pages(), connectby(), consider_groupingsets_paths(), cost_material(), cost_rescan(), create_distinct_paths(), create_gather_merge_path(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), crosstab(), dblink_get_notify(), deflist_to_tuplestore(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), exec_init_tuple_store(), ExecChooseHashTableSize(), ExecInitCteScan(), ExecInitRecursiveUnion(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecParallelHashIncreaseNumBatches(), ExecRecursiveUnion(), ExecSort(), final_cost_hashjoin(), final_cost_mergejoin(), fmgr_sql(), get_crosstab_tuplestore(), GetCurrentFDWTuplestore(), ginInsertCleanup(), initial_cost_mergejoin(), initialize_aggregate(), initialize_phase(), label_sort_with_costsize(), libpqrcv_processTuples(), MakeTransitionCaptureState(), materializeQueryResult(), materializeResult(), MultiExecBitmapIndexScan(), MultiExecBitmapOr(), ordered_set_startup(), pg_available_extension_versions(), pg_available_extensions(), pg_config(), pg_cursor(), pg_event_trigger_ddl_commands(), pg_event_trigger_dropped_objects(), pg_extension_update_paths(), pg_get_replication_slots(), pg_hba_file_rules(), pg_logical_slot_get_changes_guts(), pg_prepared_statement(), pg_show_replication_origin_status(), pg_stat_get_activity(), pg_stat_get_progress_info(), pg_stat_get_subscription(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pg_stop_backup_v2(), plperl_return_next_internal(), pltcl_init_tuple_store(), populate_recordset_worker(), PortalCreateHoldStore(), show_all_file_settings(), storeRow(), subplan_is_hashable(), tfuncFetchRows(), and xpath_table().