PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
miscadmin.h File Reference
#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 PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"
#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_ROW_LEVEL_DISABLED   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)
#define LOCK_FILE_LINE_PID   1
#define LOCK_FILE_LINE_DATA_DIR   2
#define LOCK_FILE_LINE_START_TIME   3
#define LOCK_FILE_LINE_PORT   4
#define LOCK_FILE_LINE_SOCKET_DIR   5
#define LOCK_FILE_LINE_LISTEN_ADDR   6
#define LOCK_FILE_LINE_SHMEM_KEY   7

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)
void PreventCommandIfReadOnly (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)
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)
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, 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)
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
volatile bool ClientConnectionLost
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
PGDLLIMPORT volatile uint32 CritSectionCount
pid_t PostmasterPid
bool IsPostmasterEnvironment
PGDLLIMPORT bool IsUnderPostmaster
bool IsBackgroundWorker
PGDLLIMPORT bool IsBinaryUpgrade
bool ExitOnAnyError
PGDLLIMPORT char * DataDir
PGDLLIMPORT int NBuffers
int MaxBackends
int MaxConnections
int max_worker_processes
PGDLLIMPORT int MyProcPid
PGDLLIMPORT pg_time_t MyStartTime
PGDLLIMPORT struct PortMyProcPort
PGDLLIMPORT struct LatchMyLatch
long 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
bool allowSystemTableMods
PGDLLIMPORT int work_mem
PGDLLIMPORT int maintenance_work_mem
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

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 398 of file miscadmin.h.

Referenced by ForwardFsyncRequest().

#define AmBootstrapProcess ( )    (MyAuxProcType == BootstrapProcess)

Definition at line 396 of file miscadmin.h.

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)
#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 397 of file miscadmin.h.

Referenced by HotStandbyActiveInReplay(), mdinit(), and TruncateMultiXact().

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 401 of file miscadmin.h.

Referenced by get_sync_bit().

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 400 of file miscadmin.h.

#define CHECK_FOR_INTERRUPTS ( )
Value:
do { \
ProcessInterrupts(); \
} while(0)

Definition at line 96 of file miscadmin.h.

Referenced by _bt_buildadd(), _bt_steppage(), _bt_walk_left(), _hash_metapinit(), _hash_readnext(), _hash_readprev(), add_path(), analyze_rel(), ATRewriteTable(), backend_read_statsfile(), brin_evacuate_page(), brin_getinsertbuffer(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinsummarize(), btree_xlog_delete_get_latestRemovedXid(), calculate_database_size(), calculate_relation_size(), calculate_tablespace_size(), ClientAuthentication(), cluster_rel(), copy_file(), copy_heap_data(), copy_messages(), copy_relation_data(), copydir(), CopyFrom(), CopyTo(), count_nondeletable_pages(), CountOtherDBBackends(), db_dir_size(), DecodingContextFindStartpoint(), do_autovacuum(), do_pg_stop_backup(), errfinish(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), exec_stmt(), exec_stmts(), ExecHashJoin(), ExecMakeTableFunctionResult(), ExecProcNode(), ExecScan(), fsm_vacuum_page(), get_query_def(), get_rule_expr(), get_setop_query(), GetMultiXactIdMembers(), GetNewOidWithIndex(), GetNewRelFileNode(), getNextNearest(), ginbuild(), ginBuildCallback(), gingetbitmap(), ginInsertCleanup(), gistgetbitmap(), gistgettuple(), gistProcessItup(), HandleFunctionRequest(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heapgetpage(), hypothetical_dense_rank_final(), hypothetical_rank_common(), ident_inet(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), interactive_getc(), lazy_truncate_heap(), logical_read_local_xlog_page(), make_bounded_heap(), md5_crypt_verify(), mode_final(), MultiExecBitmapIndexScan(), MultiExecProcNode(), numeric_fac(), pg_logical_slot_get_changes_guts(), pg_prewarm(), pg_sleep(), PGSemaphoreLock(), pgstat_collect_oids(), pgstat_get_backend_current_activity(), pgstat_heap(), pgstat_index(), pgstat_read_current_status(), pgstat_vacuum_stat(), pgstatindex_impl(), plperl_spi_prepare(), PortalRunMulti(), postgresAcquireSampleRowsFunc(), PostgresMain(), predicate_implied_by_simple_clause(), predicate_refuted_by_simple_clause(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessWalRcvInterrupts(), ProcSleep(), ProcWaitForSignal(), puttuple_common(), RE_compile_and_cache(), RE_wchar_execute(), refresh_matview_datafill(), regexp_fixed_prefix(), replace_text(), replace_text_regexp(), RequestCheckpoint(), revmap_extend_and_get_blkno(), sendAuthRequest(), sendDir(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), spgdoinsert(), spgWalk(), storeQueryResult(), summarize_range(), test_shm_mq_pipelined(), text_to_array_internal(), throttle(), toast_save_datum(), tuplesort_heap_insert(), tuplesort_heap_siftup(), tuplesort_skiptuples(), tuplestore_skiptuples(), vacuum_delay_point(), vacuum_rel(), validate_index_heapscan(), wait_for_workers_to_become_ready(), wait_pid(), WaitForBackgroundWorkerStartup(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

#define DATEORDER_DMY   1
#define DATEORDER_MDY   2

Definition at line 216 of file miscadmin.h.

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

#define DATEORDER_YMD   0

Definition at line 214 of file miscadmin.h.

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

#define END_CRIT_SECTION ( )
Value:
do { \
Assert(CritSectionCount > 0); \
CritSectionCount--; \
} while(0)

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_expandtable(), AbsorbFsyncRequests(), addLeafTuple(), AlterSequence(), brin_doinsert(), brin_doupdate(), brinbuildempty(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), heap_delete(), 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(), ReplicationSlotDropAcquired(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

#define GetProcessingMode ( )    Mode

Definition at line 363 of file miscadmin.h.

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 121 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

#define INTSTYLE_ISO_8601   3

Definition at line 231 of file miscadmin.h.

Referenced by EncodeInterval().

#define INTSTYLE_POSTGRES   0

Definition at line 228 of file miscadmin.h.

Referenced by EncodeInterval(), and set_transmission_modes().

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 229 of file miscadmin.h.

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

#define INTSTYLE_SQL_STANDARD   2

Definition at line 230 of file miscadmin.h.

Referenced by DecodeInterval(), and EncodeInterval().

#define IsInitProcessingMode ( )    (Mode == InitProcessing)
#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)
#define LOCK_FILE_LINE_DATA_DIR   2

Definition at line 441 of file miscadmin.h.

#define LOCK_FILE_LINE_LISTEN_ADDR   6

Definition at line 445 of file miscadmin.h.

Referenced by PostmasterMain(), and test_postmaster_connection().

#define LOCK_FILE_LINE_PID   1

Definition at line 440 of file miscadmin.h.

Referenced by test_postmaster_connection().

#define LOCK_FILE_LINE_PORT   4

Definition at line 443 of file miscadmin.h.

Referenced by get_sock_dir(), and test_postmaster_connection().

#define LOCK_FILE_LINE_SHMEM_KEY   7

Definition at line 446 of file miscadmin.h.

Referenced by CreateLockFile(), and InternalIpcMemoryCreate().

#define LOCK_FILE_LINE_SOCKET_DIR   5

Definition at line 444 of file miscadmin.h.

Referenced by get_sock_dir(), PostmasterMain(), and test_postmaster_connection().

#define LOCK_FILE_LINE_START_TIME   3

Definition at line 442 of file miscadmin.h.

Referenced by test_postmaster_connection().

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

Definition at line 235 of file miscadmin.h.

Referenced by abstime2tm(), and EncodeDateTime().

#define PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"

Definition at line 29 of file miscadmin.h.

Referenced by adjust_data_dir(), do_start(), getInstallationPaths(), and setup_bin_paths().

#define RESUME_CANCEL_INTERRUPTS ( )
Value:
do { \
Assert(QueryCancelHoldoffCount > 0); \
QueryCancelHoldoffCount--; \
} while(0)

Definition at line 123 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

#define SECURITY_RESTRICTED_OPERATION   0x0002
#define SECURITY_ROW_LEVEL_DISABLED   0x0004

Definition at line 288 of file miscadmin.h.

Referenced by CreateCachedPlan(), get_row_security_policies(), and ri_PlanCheck().

#define SetProcessingMode (   mode)
#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 129 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_expandtable(), AbsorbFsyncRequests(), addLeafTuple(), AlterSequence(), brin_doinsert(), brin_doupdate(), brinbuildempty(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), createPostingTree(), CreateSlotOnDisk(), dataPlaceToPageInternal(), dataPlaceToPageLeaf(), do_setval(), doPickSplit(), EndPrepare(), entryPlaceToPage(), fill_seq_with_data(), GetNewMultiXactId(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), heap_delete(), 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(), ReplicationSlotDropAcquired(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

#define USE_GERMAN_DATES   3

Definition at line 210 of file miscadmin.h.

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

#define USE_ISO_DATES   1
#define USE_POSTGRES_DATES   0

Definition at line 207 of file miscadmin.h.

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

#define USE_SQL_DATES   2

Definition at line 209 of file miscadmin.h.

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

#define USE_XSD_DATES   4

Typedef Documentation

Definition at line 265 of file miscadmin.h.

Enumeration Type Documentation

Enumerator:
NotAnAuxProcess 
CheckerProcess 
BootstrapProcess 
StartupProcess 
BgWriterProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 380 of file miscadmin.h.

Enumerator:
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 350 of file miscadmin.h.

{
BootstrapProcessing, /* bootstrap creation of template database */
InitProcessing, /* initializing system */
NormalProcessing /* normal processing */

Function Documentation

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1092 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, elog, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, NULL, PG_BINARY, pg_fsync(), read, snprintf(), and write.

Referenced by InternalIpcMemoryCreate(), and PostmasterMain().

{
int fd;
int len;
int lineno;
char *srcptr;
char *destptr;
char srcbuffer[BLCKSZ];
char destbuffer[BLCKSZ];
fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
if (fd < 0)
{
errmsg("could not open file \"%s\": %m",
return;
}
len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
if (len < 0)
{
errmsg("could not read from file \"%s\": %m",
close(fd);
return;
}
srcbuffer[len] = '\0';
/*
* Advance over lines we are not supposed to rewrite, then copy them to
* destbuffer.
*/
srcptr = srcbuffer;
for (lineno = 1; lineno < target_line; lineno++)
{
if ((srcptr = strchr(srcptr, '\n')) == NULL)
{
elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
DIRECTORY_LOCK_FILE, lineno - 1, target_line);
close(fd);
return;
}
srcptr++;
}
memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
destptr = destbuffer + (srcptr - srcbuffer);
/*
* Write or rewrite the target line.
*/
snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
destptr += strlen(destptr);
/*
* If there are more lines in the old file, append them to destbuffer.
*/
if ((srcptr = strchr(srcptr, '\n')) != NULL)
{
srcptr++;
snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
srcptr);
}
/*
* And rewrite the data. Since we write in a single kernel call, this
* update should appear atomic to onlookers.
*/
len = strlen(destbuffer);
errno = 0;
if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
(int) write(fd, destbuffer, len) != len)
{
/* if write didn't set errno, assume problem is no disk space */
if (errno == 0)
errno = ENOSPC;
errmsg("could not write to file \"%s\": %m",
close(fd);
return;
}
if (pg_fsync(fd) != 0)
{
errmsg("could not write to file \"%s\": %m",
}
if (close(fd) != 0)
{
errmsg("could not write to file \"%s\": %m",
}
}
bool BackupInProgress ( void  )

Definition at line 10403 of file xlog.c.

References BACKUP_LABEL_FILE.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

{
struct stat stat_buf;
return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
}
void BaseInit ( void  )

Definition at line 501 of file postinit.c.

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

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

{
/*
* Attach to shared memory and semaphores, and initialize our
* input/output/debugging file descriptors.
*/
/* Do local initialization of file, storage and buffer managers */
}
void CancelBackup ( void  )

Definition at line 10418 of file xlog.c.

References BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, ereport, errcode_for_file_access(), errdetail(), errmsg(), LOG, unlink(), and WARNING.

Referenced by PostmasterStateMachine().

{
struct stat stat_buf;
/* if the file is not there, return */
if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
return;
/* remove leftover file from previously canceled backup if it exists */
{
(errmsg("online backup mode canceled"),
errdetail("\"%s\" was renamed to \"%s\".",
}
else
{
errmsg("online backup mode was not canceled"),
errdetail("Could not rename \"%s\" to \"%s\": %m.",
}
}
void ChangeToDataDir ( void  )

Definition at line 113 of file miscinit.c.

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

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

{
if (chdir(DataDir) < 0)
errmsg("could not change directory to \"%s\": %m",
DataDir)));
}
void check_stack_depth ( void  )

Definition at line 3087 of file postgres.c.

References ereport, errcode(), errhint(), errmsg(), ERROR, max_stack_depth, max_stack_depth_bytes, NULL, and stack_base_ptr.

Referenced by addone(), clean_fakeval_intree(), clean_NOT_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObject(), Cover(), dofindsubquery(), EventTriggerInvoke(), ExecInitExpr(), ExecMakeFunctionResult(), ExecMakeFunctionResultNoSets(), execute(), expression_tree_mutator(), expression_tree_walker(), fillQT(), findoprnd(), findoprnd_recurse(), freetree(), get_query_def(), get_rule_expr(), get_setop_query(), gistSplit(), infix(), inline_set_returning_function(), JsonbDeepContains(), JumbleExpr(), makepol(), plainnode(), plperl_hash_from_tuple(), plperl_sv_to_datum(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), raw_expression_tree_walker(), split_array(), transformExprRecurse(), transformSetOperationTree(), TS_execute(), TS_execute_ternary(), tsquery_opr_selec(), and tsquery_requires_match().

{
char stack_top_loc;
long stack_depth;
/*
* Compute distance from reference point to my local variables
*/
stack_depth = (long) (stack_base_ptr - &stack_top_loc);
/*
* Take abs value, since stacks grow up on some machines, down on others
*/
if (stack_depth < 0)
stack_depth = -stack_depth;
/*
* Trouble?
*
* The test on stack_base_ptr prevents us from erroring out if called
* during process setup or in a non-backend process. Logically it should
* be done first, but putting it here avoids wasting cycles during normal
* cases.
*/
if (stack_depth > max_stack_depth_bytes &&
{
(errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
errmsg("stack depth limit exceeded"),
errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
"after ensuring the platform's stack depth limit is adequate.",
}
/*
* On IA64 there is a separate "register" stack that requires its own
* independent check. For this, we have to measure the change in the
* "BSP" pointer from PostgresMain to here. Logic is just as above,
* except that we know IA64's register stack grows up.
*
* Note we assume that the same max_stack_depth applies to both stacks.
*/
#if defined(__ia64__) || defined(__ia64)
stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
if (stack_depth > max_stack_depth_bytes &&
register_stack_base_ptr != NULL)
{
(errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
errmsg("stack depth limit exceeded"),
errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
"after ensuring the platform's stack depth limit is adequate.",
}
#endif /* IA64 */
}
void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1016 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

{
CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
}
void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1025 of file miscinit.c.

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

{
char lockfile[MAXPGPATH];
snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
}
Oid GetAuthenticatedUserId ( void  )
Oid GetCurrentRoleId ( void  )

Definition at line 599 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by show_role().

{
return OuterUserId;
else
return InvalidOid;
}
Oid GetOuterUserId ( void  )

Definition at line 284 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

Oid GetUserId ( void  )

Definition at line 273 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOpFamilyAdd(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterSequence(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), analyze_rel(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetStatistics(), ATPrepSetTableSpace(), ATSimplePermissions(), binary_upgrade_create_empty_extension(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), compute_return_type(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtension(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreateRole(), CreateTableSpace(), 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(), DropTableSpace(), EnableDisableRule(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecEvalArrayCoerceExpr(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitWindowAgg(), ExecSecLabelStmt(), 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(), 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_fcache(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), LargeObjectCreate(), lastval(), lo_get_fragment_internal(), lo_read(), lo_truncate_internal(), lo_unlink(), lo_write(), LockTableAclCheck(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_prewarm(), pg_sequence_parameters(), pg_signal_backend(), pg_start_backup(), 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_waiting(), pg_stat_get_backend_xact_start(), pg_stat_statements_internal(), pg_stop_backup(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginForeignModify(), postgresBeginForeignScan(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), and vacuum_rel().

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 411 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

{
*userid = CurrentUserId;
*sec_def_context = InLocalUserIdChange();
}
char* GetUserNameFromId ( Oid  roleid)

Definition at line 654 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(), session_user(), and timetravel().

{
HeapTuple tuple;
char *result;
if (!HeapTupleIsValid(tuple))
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("invalid role OID: %u", roleid)));
result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
return result;
}
bool has_rolreplication ( Oid  roleid)

Definition at line 438 of file miscinit.c.

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

Referenced by check_permissions(), InitPostgres(), pg_start_backup(), and pg_stop_backup().

{
bool result = false;
HeapTuple utup;
if (HeapTupleIsValid(utup))
{
result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
}
return result;
}
void InitializeMaxBackends ( void  )

Definition at line 479 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().

{
/* the extra unit accounts for the autovacuum launcher */
/* internal error because the values were all checked previously */
elog(ERROR, "too many backends configured");
}
void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 456 of file miscinit.c.

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

Referenced by InitPostgres().

{
HeapTuple roleTup;
/*
* Don't do scans if we're bootstrapping, none of the system catalogs
* exist yet, and they should be owned by postgres anyway.
*/
/* call only once */
if (rolename != NULL)
roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
else
if (!HeapTupleIsValid(roleTup))
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("role \"%s\" does not exist", rolename)));
rform = (Form_pg_authid) GETSTRUCT(roleTup);
roleid = HeapTupleGetOid(roleTup);
AuthenticatedUserIsSuperuser = rform->rolsuper;
/* This sets OuterUserId/CurrentUserId too */
/* Also mark our PGPROC entry with the authenticated user id */
/* (We assume this is an atomic store so no lock is needed) */
MyProc->roleId = roleid;
/*
* These next checks are not enforced when in standalone mode, so that
* there is a way to recover from sillinesses like "UPDATE pg_authid SET
* rolcanlogin = false;".
*/
{
/*
* Is role allowed to login at all?
*/
if (!rform->rolcanlogin)
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("role \"%s\" is not permitted to log in",
rolename)));
/*
* Check connection limit for this role.
*
* There is a race condition here --- we create our PGPROC before
* checking for other PGPROCs. If two backends did this at about the
* same time, they might both think they were over the limit, while
* ideally one should succeed and one fail. Getting that to work
* exactly seems more trouble than it is worth, however; instead we
* just document that the connection limit is approximate.
*/
if (rform->rolconnlimit >= 0 &&
CountUserBackends(roleid) > rform->rolconnlimit)
(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
errmsg("too many connections for role \"%s\"",
rolename)));
}
/* Record username and superuser status as GUC settings too */
SetConfigOption("session_authorization", rolename,
SetConfigOption("is_superuser",
ReleaseSysCache(roleTup);
}
void InitializeSessionUserIdStandalone ( void  )
void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
char *  out_dbname 
)

Definition at line 542 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, InitBufferPoolBackend(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, NULL, 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().

{
bool bootstrap = IsBootstrapProcessingMode();
bool am_superuser;
char *fullpath;
elog(DEBUG3, "InitPostgres");
/*
* Add my PGPROC struct to the ProcArray.
*
* Once I have done this, I am visible to other backends!
*/
/*
* Initialize my entry in the shared-invalidation manager's array of
* per-backend data.
*
* Sets up MyBackendId, a unique backend identifier.
*/
elog(FATAL, "bad backend ID: %d", MyBackendId);
/* Now that we have a BackendId, we can participate in ProcSignal */
/*
* Also set up timeout handlers needed for backend operation. We need
* these in every case except bootstrap.
*/
if (!bootstrap)
{
}
/*
* bufmgr needs another initialization call too
*/
/*
* Initialize local process's access to XLOG.
*/
{
/*
* The postmaster already started the XLOG machinery, but we need to
* call InitXLOGAccess(), if the system isn't in hot-standby mode.
* This is handled by calling RecoveryInProgress and ignoring the
* result.
*/
}
else
{
/*
* We are either a bootstrap process or a standalone backend. Either
* way, start up the XLOG machinery, and register to have it closed
* down at exit.
*/
}
/*
* Initialize the relation cache and the system catalog caches. Note that
* no catalog access happens here; we only set up the hashtable structure.
* We must do this before starting a transaction because transaction abort
* would try to touch these hashtables.
*/
/* Initialize portal manager */
/* Initialize stats collection --- must happen before first xact */
if (!bootstrap)
/*
* Load relcache entries for the shared system catalogs. This must create
* at least entries for pg_database and catalogs used for authentication.
*/
/*
* Set up process-exit callback to do pre-shutdown cleanup. This is the
* first before_shmem_exit callback we register; thus, this will be the
* last thing we do before low-level modules like the buffer manager begin
* to close down. We need to have this in place before we begin our first
* transaction --- if we fail during the initialization transaction, as is
* entirely possible, we need the AbortTransaction call to clean up.
*/
/* The autovacuum launcher is done here */
return;
/*
* Start a new transaction here before first access to db, and get a
* snapshot. We don't have a use for the snapshot itself, but we're
* interested in the secondary effect that it sets RecentGlobalXmin. (This
* is critical for anything that reads heap pages, because HOT may decide
* to prune them even if the process doesn't attempt to modify any
* tuples.)
*/
if (!bootstrap)
{
/* statement_timestamp must be set for timeouts to work correctly */
/*
* transaction_isolation will have been set to the default by the
* above. If the default is "serializable", and we are in hot
* standby, we will fail if we don't change it to something lower.
* Fortunately, "read committed" is plenty good enough.
*/
}
/*
* Perform client authentication if necessary, then figure out our
* postgres user ID, and see if we are a superuser.
*
* In standalone mode and in autovacuum worker processes, we use a fixed
* ID, otherwise we figure it out from the authenticated user name.
*/
if (bootstrap || IsAutoVacuumWorkerProcess())
{
am_superuser = true;
}
else if (!IsUnderPostmaster)
{
am_superuser = true;
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("no roles are defined in this database system"),
errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
username != NULL ? username : "postgres")));
}
{
if (username == NULL && !OidIsValid(useroid))
{
am_superuser = true;
}
else
{
am_superuser = superuser();
}
}
else
{
/* normal multiuser case */
am_superuser = superuser();
}
/*
* If we're trying to shut down, only superusers can connect, and new
* replication connections are not allowed.
*/
if ((!am_superuser || am_walsender) &&
{
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("new replication connections are not allowed during database shutdown")));
else
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to connect during database shutdown")));
}
/*
* Binary upgrades only allowed super-user connections
*/
if (IsBinaryUpgrade && !am_superuser)
{
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to connect in binary upgrade mode")));
}
/*
* The last few connections slots are reserved for superusers. Although
* replication connections currently require superuser privileges, we
* don't allow them to consume the reserved slots, which are intended for
* interactive use.
*/
if ((!am_superuser || am_walsender) &&
(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
errmsg("remaining connection slots are reserved for non-replication superuser connections")));
/* Check replication permissions needed for walsender processes. */
{
Assert(!bootstrap);
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser or replication role to start walsender")));
}
/*
* If this is a plain walsender only supporting physical replication, we
* don't want to connect to any particular database. Just finish the
* backend startup by processing any options from the startup packet, and
* we're done.
*/
{
/* process any options passed in the startup packet */
if (MyProcPort != NULL)
/* Apply PostAuthDelay as soon as we've read all options */
if (PostAuthDelay > 0)
pg_usleep(PostAuthDelay * 1000000L);
/* initialize client encoding */
/* report this backend in the PgBackendStatus array */
/* close the transaction we started above */
return;
}
/*
* Set up the global variables holding database id and default tablespace.
* But note we won't actually try to touch the database just yet.
*
* We take a shortcut in the bootstrap case, otherwise we have to look up
* the db's entry in pg_database.
*/
if (bootstrap)
{
}
else if (in_dbname != NULL)
{
HeapTuple tuple;
tuple = GetDatabaseTuple(in_dbname);
if (!HeapTupleIsValid(tuple))
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist", in_dbname)));
dbform = (Form_pg_database) GETSTRUCT(tuple);
MyDatabaseTableSpace = dbform->dattablespace;
/* take database name from the caller, just for paranoia */
strlcpy(dbname, in_dbname, sizeof(dbname));
}
else
{
/* caller specified database by OID */
HeapTuple tuple;
tuple = GetDatabaseTupleByOid(dboid);
if (!HeapTupleIsValid(tuple))
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database %u does not exist", dboid)));
dbform = (Form_pg_database) GETSTRUCT(tuple);
MyDatabaseTableSpace = dbform->dattablespace;
Assert(MyDatabaseId == dboid);
strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
/* pass the database name back to the caller */
if (out_dbname)
strcpy(out_dbname, dbname);
}
/* Now we can mark our PGPROC entry with the database ID */
/* (We assume this is an atomic store so no lock is needed) */
/*
* We established a catalog snapshot while reading pg_authid and/or
* pg_database; but until we have set up MyDatabaseId, we won't react to
* incoming sinval messages for unshared catalogs, so we won't realize it
* if the snapshot has been invalidated. Assume it's no good anymore.
*/
/*
* Now, take a writer's lock on the database we are trying to connect to.
* If there is a concurrently running DROP DATABASE on that database, this
* will block us until it finishes (and has committed its update of
* pg_database).
*
* Note that the lock is not held long, only until the end of this startup
* transaction. This is OK since we are already advertising our use of
* the database in the PGPROC array; anyone trying a DROP DATABASE after
* this point will see us there.
*
* Note: use of RowExclusiveLock here is reasonable because we envision
* our session as being a concurrent writer of the database. If we had a
* way of declaring a session as being guaranteed-read-only, we could use
* AccessShareLock for such sessions and thereby not conflict against
* CREATE DATABASE.
*/
if (!bootstrap)
/*
* Recheck pg_database to make sure the target database hasn't gone away.
* If there was a concurrent DROP DATABASE, this ensures we will die
* cleanly without creating a mess.
*/
if (!bootstrap)
{
HeapTuple tuple;
tuple = GetDatabaseTuple(dbname);
if (!HeapTupleIsValid(tuple) ||
MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist", dbname),
errdetail("It seems to have just been dropped or renamed.")));
}
/*
* Now we should be able to access the database directory safely. Verify
* it's there and looks reasonable.
*/
if (!bootstrap)
{
if (access(fullpath, F_OK) == -1)
{
if (errno == ENOENT)
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist",
dbname),
errdetail("The database subdirectory \"%s\" is missing.",
fullpath)));
else
errmsg("could not access directory \"%s\": %m",
fullpath)));
}
ValidatePgVersion(fullpath);
}
SetDatabasePath(fullpath);
/*
* It's now possible to do real access to the system catalogs.
*
* Load relcache entries for the system catalogs. This must create at
* least the minimum set of "nailed-in" cache entries.
*/
/* set up ACL framework (so CheckMyDatabase can check permissions) */
/*
* Re-read the pg_database row for our database, check permissions and set
* up database-specific GUC settings. We can't do this until all the
* database-access infrastructure is up. (Also, it wants to know if the
* user is a superuser, so the above stuff has to happen first.)
*/
if (!bootstrap)
CheckMyDatabase(dbname, am_superuser);
/*
* Now process any command-line switches and any additional GUC variable
* settings passed in the startup packet. We couldn't do this before
* because we didn't know if client is a superuser.
*/
if (MyProcPort != NULL)
/* Process pg_db_role_setting options */
/* Apply PostAuthDelay as soon as we've read all options */
if (PostAuthDelay > 0)
pg_usleep(PostAuthDelay * 1000000L);
/*
* Initialize various default states that can't be set up until we've
* selected the active user and gotten the right GUC settings.
*/
/* set default namespace search path */
/* initialize client encoding */
/* report this backend in the PgBackendStatus array */
if (!bootstrap)
/* close the transaction we started above */
if (!bootstrap)
}
void InitPostmasterChild ( void  )

Definition at line 173 of file miscinit.c.

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

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

{
IsUnderPostmaster = true; /* we are a postmaster subprocess now */
MyProcPid = getpid(); /* reset MyProcPid */
MyStartTime = time(NULL); /* set our start time in case we call elog */
/*
* make sure stderr is in binary mode before anything can possibly be
* written to it, in case it's actually the syslogger pipe, so the pipe
* chunking protocol isn't disturbed. Non-logpipe data gets translated on
* redirection (e.g. via pg_ctl -l) anyway.
*/
#ifdef WIN32
_setmode(fileno(stderr), _O_BINARY);
#endif
/* We don't want the postmaster's proc_exit() handlers */
/* Initialize process-local latch support */
/*
* If possible, make this process a group leader, so that the postmaster
* can signal any child processes too. Not all processes will have
* children, but for consistency we , but for consistency we make all
* postmaster child processes do this.
*/
#ifdef HAVE_SETSID
if (setsid() < 0)
elog(FATAL, "setsid() failed: %m");
#endif
}
void InitStandaloneProcess ( const char *  argv0)

Definition at line 217 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), and PostgresMain().

{
MyProcPid = getpid(); /* reset MyProcPid */
MyStartTime = time(NULL); /* set our start time in case we call elog */
/* Initialize process-local latch support */
/* Compute paths, no postmaster to inherit from */
if (my_exec_path[0] == '\0')
{
elog(FATAL, "%s: could not locate my own executable path",
}
if (pkglib_path[0] == '\0')
}
bool InLocalUserIdChange ( void  )
void pg_bindtextdomain ( const char *  domain)

Definition at line 1362 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

{
#ifdef ENABLE_NLS
if (my_exec_path[0] != '\0')
{
char locale_path[MAXPGPATH];
bindtextdomain(domain, locale_path);
pg_bind_textdomain_codeset(domain);
}
#endif
}
void pg_split_opts ( char **  argv,
int *  argcp,
char *  optstr 
)

Definition at line 421 of file postinit.c.

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

Referenced by BackendRun(), and process_startup_options().

{
while (*optstr)
{
bool last_was_escape = false;
/* skip over leading space */
while (isspace((unsigned char) *optstr))
optstr++;
if (*optstr == '\0')
break;
/*
* Parse a single option + value, stopping at the first space, unless
* it's escaped.
*/
while (*optstr)
{
if (isspace((unsigned char) *optstr) && !last_was_escape)
break;
if (!last_was_escape && *optstr == '\\')
last_was_escape = true;
else
{
last_was_escape = false;
appendStringInfoChar(&s, *optstr);
}
optstr++;
}
/* now store the option */
argv[(*argcp)++] = pstrdup(s.data);
}
}
void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 243 of file utility.c.

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

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

{
(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
/* translator: %s is name of a SQL command, eg CREATE */
errmsg("cannot execute %s during recovery",
cmdname)));
}
void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 224 of file utility.c.

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

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

{
(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
/* translator: %s is name of a SQL command, eg CREATE */
errmsg("cannot execute %s in a read-only transaction",
cmdname)));
}
void process_session_preload_libraries ( void  )

Definition at line 1351 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

{
"session_preload_libraries",
false);
"local_preload_libraries",
true);
}
void process_shared_preload_libraries ( void  )
void ProcessInterrupts ( void  )

Definition at line 2843 of file postgres.c.

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

Referenced by die().

{
/* OK to accept any interrupts now? */
return;
{
ProcDiePending = false;
QueryCancelPending = false; /* ProcDie trumps QueryCancel */
/* As in quickdie, don't risk sending to client during auth */
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling authentication due to timeout")));
(errcode(ERRCODE_ADMIN_SHUTDOWN),
errmsg("terminating autovacuum process due to administrator command")));
{
(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
errmsg("terminating connection due to conflict with recovery"),
}
{
/* Currently there is only one non-retryable recovery conflict */
(errcode(ERRCODE_DATABASE_DROPPED),
errmsg("terminating connection due to conflict with recovery"),
}
else
(errcode(ERRCODE_ADMIN_SHUTDOWN),
errmsg("terminating connection due to administrator command")));
}
{
QueryCancelPending = false; /* lost connection trumps QueryCancel */
/* don't send to client, we already know the connection to be dead. */
(errcode(ERRCODE_CONNECTION_FAILURE),
errmsg("connection to client lost")));
}
/*
* If a recovery conflict happens while we are waiting for input from the
* client, the client is presumably just sitting idle in a transaction,
* preventing recovery from making progress. Terminate the connection to
* dislodge it.
*/
{
QueryCancelPending = false; /* this trumps QueryCancel */
(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
errmsg("terminating connection due to conflict with recovery"),
errhint("In a moment you should be able to reconnect to the"
" database and repeat your command.")));
}
{
/*
* Don't allow query cancel interrupts while reading input from the
* client, because we might lose sync in the FE/BE protocol. (Die
* interrupts are OK, because we won't read any further messages from
* the client in that case.)
*/
{
/*
* Re-arm InterruptPending so that we process the cancel request
* as soon as we're done reading the message.
*/
return;
}
/*
* If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
* prefer to report the former; but be sure to clear both.
*/
{
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("canceling statement due to lock timeout")));
}
{
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling statement due to statement timeout")));
}
{
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling autovacuum task")));
}
{
(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
errmsg("canceling statement due to conflict with recovery"),
}
/*
* If we are reading a command from the client, just ignore the cancel
* request --- sending an extra error message won't accomplish
* anything. Otherwise, go ahead and throw the error.
*/
{
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling statement due to user request")));
}
}
/* If we get here, do nothing (probably, QueryCancelPending was reset) */
}
void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3068 of file postgres.c.

References stack_base_ptr.

{
#if defined(__ia64__) || defined(__ia64)
stack_base_ptr = base.stack_base_ptr;
register_stack_base_ptr = base.register_stack_base_ptr;
#else
#endif
}
pg_stack_base_t set_stack_base ( void  )

Definition at line 3037 of file postgres.c.

References stack_base_ptr.

Referenced by PostmasterMain().

{
char stack_base;
#if defined(__ia64__) || defined(__ia64)
old.stack_base_ptr = stack_base_ptr;
old.register_stack_base_ptr = register_stack_base_ptr;
#else
#endif
/* Set up reference point for stack depth checking */
stack_base_ptr = &stack_base;
#if defined(__ia64__) || defined(__ia64)
register_stack_base_ptr = ia64_get_bsp();
#endif
return old;
}
void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 620 of file miscinit.c.

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

Referenced by assign_role().

{
/*
* Get correct info if it's SET ROLE NONE
*
* If SessionUserId hasn't been set yet, just do nothing --- the eventual
* SetSessionUserId call will fix everything. This is needed since we
* will get called during GUC initialization.
*/
if (!OidIsValid(roleid))
{
return;
roleid = SessionUserId;
SetRoleIsActive = false;
}
else
SetOuterUserId(roleid);
SetConfigOption("is_superuser",
is_superuser ? "on" : "off",
}
void SetDatabasePath ( const char *  path)

Definition at line 80 of file miscinit.c.

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

Referenced by InitPostgres().

{
/* This should happen only once per process */
}
void SetDataDir ( const char *  dir)

Definition at line 92 of file miscinit.c.

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

Referenced by SelectConfigFiles().

{
char *new;
AssertArg(dir);
/* If presented path is relative, convert to absolute */
new = make_absolute_path(dir);
if (DataDir)
DataDir = new;
}
void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 574 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().

{
/* Must have authenticated already, else can't make permission check */
if (userid != AuthenticatedUserId &&
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied to set session authorization")));
SetConfigOption("is_superuser",
is_superuser ? "on" : "off",
}
void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 418 of file miscinit.c.

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

{
/* We throw the same error SET ROLE would. */
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("cannot set parameter \"%s\" within security-restricted operation",
"role")));
CurrentUserId = userid;
if (sec_def_context)
else
}
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(), AlterRole(), AlterRoleSet(), AlterSystemSetConfigFile(), AlterTypeOwner(), ATExecChangeOwner(), brin_page_items(), brin_revmap_data(), bt_metap(), bt_page_items(), bt_page_stats(), check_conn_params(), check_encoding_locale_matches(), check_permissions(), connect_pg_server(), CreateCast(), CreateEventTrigger(), CreateForeignDataWrapper(), CreateFunction(), CreateProceduralLanguage(), CreateRole(), CreateTableSpace(), dblink_connstr_check(), dblink_security_check(), DefineAggregate(), DefineOpClass(), DefineOpFamily(), DefineTSParser(), DefineTSTemplate(), DefineType(), DelRoleMems(), DoCopy(), DropRole(), dummy_object_relabel(), EnableDisableTrigger(), ExecSetVariableStmt(), execute_extension_script(), ExecuteDoStmt(), file_fdw_validator(), fmgr_security_definer(), fsm_page_contents(), get_raw_page_internal(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), gin_leafpage_items(), gin_metapage_info(), gin_page_opaque_info(), GUCArrayReset(), have_createdb_privilege(), heap_page_items(), InitPostgres(), lo_export(), lo_import_internal(), main(), page_header(), pg_create_restore_point(), pg_logdir_ls(), pg_ls_dir(), pg_read_binary_file(), pg_read_binary_file_all(), pg_read_file(), pg_read_file_all(), pg_reload_conf(), pg_relpages(), pg_relpagesbyid(), pg_rotate_logfile(), pg_signal_backend(), pg_start_backup(), pg_stat_file(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pg_stop_backup(), pg_switch_xlog(), pg_xlog_replay_pause(), pg_xlog_replay_resume(), pgstat_get_backend_current_activity(), pgstat_reset_counters(), pgstat_reset_shared_counters(), pgstat_reset_single_counter(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuplebyid(), ProcedureCreate(), regress_putenv(), RenameRole(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), ShowAllGUCConfig(), standard_ProcessUtility(), validate_option_array_item(), and wait_pid().

{
}
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(), check_object_ownership(), 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_signal_backend(), pg_tablespace_aclmask(), pg_tablespace_ownercheck(), pg_ts_config_ownercheck(), pg_ts_dict_ownercheck(), pg_type_aclmask(), pg_type_ownercheck(), pltcl_init_load_unknown(), select_best_grantor(), and superuser().

{
bool result;
HeapTuple rtup;
/* Quick out for cache hit */
if (OidIsValid(last_roleid) && last_roleid == roleid)
/* Special escape path in case you deleted all your users. */
return true;
/* OK, look up the information in pg_authid */
if (HeapTupleIsValid(rtup))
{
result = ((Form_pg_authid) GETSTRUCT(rtup))->rolsuper;
}
else
{
/* Report "not superuser" for invalid roleids */
result = false;
}
/* If first time through, set up callback for cache flushes */
{
(Datum) 0);
}
/* Cache the result for next time */
last_roleid = roleid;
return result;
}
void SwitchBackToLocalLatch ( void  )
void SwitchToSharedLatch ( void  )

Definition at line 243 of file miscinit.c.

References Assert, MyLatch, MyProc, NULL, PGPROC::procLatch, and SetLatch().

Referenced by InitAuxiliaryProcess(), and InitProcess().

{
/*
* Set the shared latch as the local one might have been set. This
* shouldn't normally be necessary as code is supposed to check the
* condition before waiting for the latch, but a bit care can't hurt.
*/
}
void TouchSocketLockFiles ( void  )

Definition at line 1043 of file miscinit.c.

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

Referenced by ServerLoop().

{
foreach(l, lock_files)
{
char *socketLockFile = (char *) lfirst(l);
/* No need to touch the data directory lock file, we trust */
if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
continue;
/*
* utime() is POSIX standard, utimes() is a common alternative; if we
* have neither, fall back to actually reading the file (which only
* sets the access time not mod time, but that should be enough in
* most cases). In all paths, we ignore errors.
*/
#ifdef HAVE_UTIME
utime(socketLockFile, NULL);
#else /* !HAVE_UTIME */
#ifdef HAVE_UTIMES
utimes(socketLockFile, NULL);
#else /* !HAVE_UTIMES */
int fd;
char buffer[1];
fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
if (fd >= 0)
{
read(fd, buffer, sizeof(buffer));
close(fd);
}
#endif /* HAVE_UTIMES */
#endif /* HAVE_UTIME */
}
}
void ValidatePgVersion ( const char *  path)

Definition at line 1206 of file miscinit.c.

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

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

{
char full_path[MAXPGPATH];
FILE *file;
int ret;
long file_major,
file_minor;
long my_major = 0,
my_minor = 0;
char *endptr;
const char *version_string = PG_VERSION;
my_major = strtol(version_string, &endptr, 10);
if (*endptr == '.')
my_minor = strtol(endptr + 1, NULL, 10);
snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
file = AllocateFile(full_path, "r");
if (!file)
{
if (errno == ENOENT)
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\"%s\" is not a valid data directory",
path),
errdetail("File \"%s\" is missing.", full_path)));
else
errmsg("could not open file \"%s\": %m", full_path)));
}
ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
if (ret != 2)
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\"%s\" is not a valid data directory",
path),
errdetail("File \"%s\" does not contain valid data.",
full_path),
errhint("You might need to initdb.")));
FreeFile(file);
if (my_major != file_major || my_minor != file_minor)
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("database files are incompatible with server"),
errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
"which is not compatible with this version %s.",
file_major, file_minor, version_string)));
}

Variable Documentation

volatile bool ClientConnectionLost

Definition at line 32 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

PGDLLIMPORT int DateOrder
bool ExitOnAnyError

Definition at line 101 of file globals.c.

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

bool IgnoreSystemIndexes
PGDLLIMPORT volatile uint32 InterruptHoldoffCount

Definition at line 33 of file globals.c.

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

PGDLLIMPORT int IntervalStyle
bool IsBackgroundWorker
PGDLLIMPORT bool IsUnderPostmaster
char* local_preload_libraries_string

Definition at line 1271 of file miscinit.c.

Referenced by process_session_preload_libraries().

Definition at line 54 of file miscinit.c.

AuxProcType MyAuxProcType

Definition at line 64 of file bootstrap.c.

Referenced by AuxiliaryProcessMain().

long MyCancelKey
PGDLLIMPORT Oid MyDatabaseId

Definition at line 73 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterSchemaOwner_internal(), analyze_rel(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), backend_read_statsfile(), CacheInvalidateCatalog(), CacheInvalidateHeapTuple(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), classIdGetDbId(), CreateDecodingContext(), CreateInitDecodingContext(), CreateProceduralLanguage(), CreateSchemaCommand(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), exec_object_restorecon(), ExpandColumnRefStar(), ExportSnapshot(), GetCurrentVirtualXIDs(), GetNewRelFileNode(), GetOldestXmin(), IdentifySystem(), ImportSnapshot(), InitPostgres(), InitTempTableNamespace(), lazy_vacuum_rel(), LocalExecuteInvalidationMessage(), LockDatabaseObject(), LockGXact(), logical_heap_rewrite_flush_mappings(), logical_rewrite_log_mapping(), 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(), pg_namespace_aclmask(), pg_relation_filepath(), pgss_store(), pgstat_beshutdown_hook(), pgstat_bestart(), 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_vacuum_stat(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), 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().

PGDLLIMPORT int NBuffers

Definition at line 118 of file globals.c.

char OutputFileName[]

Definition at line 60 of file globals.c.

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

char pkglib_path[]

Definition at line 63 of file globals.c.

Referenced by getInstallationPaths(), InitStandaloneProcess(), and substitute_libpath_macro().

pid_t PostmasterPid
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount

Definition at line 34 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

char* session_preload_libraries_string

Definition at line 1269 of file miscinit.c.

Referenced by process_session_preload_libraries().

char* shared_preload_libraries_string

Definition at line 1270 of file miscinit.c.

Referenced by process_shared_preload_libraries().

int trace_recovery_messages

Definition at line 430 of file guc.c.

Referenced by StartupXLOG(), and trace_recovery().

bool VacuumCostActive
int VacuumCostBalance
int VacuumCostLimit
int VacuumCostPageDirty

Definition at line 125 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

int VacuumCostPageHit

Definition at line 123 of file globals.c.

Referenced by ReadBuffer_common().

int VacuumCostPageMiss

Definition at line 124 of file globals.c.

Referenced by ReadBuffer_common().

int VacuumPageDirty

Definition at line 131 of file globals.c.

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

int VacuumPageHit

Definition at line 129 of file globals.c.

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

int VacuumPageMiss

Definition at line 130 of file globals.c.

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