Movatterモバイル変換


[0]ホーム

URL:


September 25, 2025: PostgreSQL 18 Released!
Supported Versions:Current (18) /17 /16 /15 /14 /13
Development Versions:devel
Unsupported versions:12 /11 /10 /9.6 /9.5 /9.4 /9.3 /9.2 /9.1 /9.0 /8.4 /8.3 /8.2 /8.1 /8.0
This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for thecurrent version, or one of the other supported versions listed above instead.
PostgreSQL 9.3.25 Documentation
PrevUpChapter 9. Functionsand OperatorsNext

9.26. System Administration Functions

The functions described in this section are used to control andmonitor aPostgreSQLinstallation.

9.26.1. Configuration SettingsFunctions

Table9-59 shows the functions available to query and alter run-timeconfiguration parameters.

Table 9-59. Configuration Settings Functions

NameReturn TypeDescription
current_setting(setting_name)textget current value of setting
set_config(setting_name,new_value,is_local)textset parameter and return new value

The functioncurrent_settingyields the current value of the settingsetting_name. It corresponds to theSQL commandSHOW. An example:

SELECT current_setting('datestyle'); current_setting----------------- ISO, MDY(1 row)

set_config sets the parametersetting_name tonew_value. Ifis_localistrue, the new value will only apply tothe current transaction. If you want the new value to apply for thecurrent session, usefalse instead. Thefunction corresponds to the SQL commandSET. An example:

SELECT set_config('log_statement_stats', 'off', false); set_config------------ off(1 row)

9.26.2. Server SignalingFunctions

The functions shown inTable 9-60send control signals to other server processes. Use of thesefunctions is usually restricted to superusers, with notedexceptions.

Table 9-60. Server Signaling Functions

NameReturn TypeDescription
pg_cancel_backend(pidint)booleanCancel a backend's current query. You can execute this againstanother backend that has exactly the same role as the user callingthe function. In all other cases, you must be a superuser.
pg_reload_conf()booleanCause server processes to reload their configuration files
pg_rotate_logfile()booleanRotate server's log file
pg_terminate_backend(pidint)booleanTerminate a backend. You can execute this against anotherbackend that has exactly the same role as the user calling thefunction. In all other cases, you must be a superuser.

Each of these functions returnstrue ifsuccessful andfalse otherwise.

pg_cancel_backend andpg_terminate_backend send signals (SIGINT orSIGTERM respectively) to backend processesidentified by process ID. The process ID of an active backend canbe found from thepid column of thepg_stat_activity view, or by listingthepostgres processes on the server(usingps on Unix or theTask Manager onWindows). The role of an active backend can befound from theusename column of thepg_stat_activity view.

pg_reload_conf sends aSIGHUP signal to the server,causing configuration files to be reloaded by all serverprocesses.

pg_rotate_logfile signals thelog-file manager to switch to a new output file immediately. Thisworks only when the built-in log collector is running, sinceotherwise there is no log-file manager subprocess.

9.26.3. Backup Control Functions

The functions shown inTable 9-61assist in making on-line backups. These functions cannot beexecuted during recovery (exceptpg_is_in_backup,pg_backup_start_time andpg_xlog_location_diff).

Table 9-61. Backup Control Functions

NameReturn TypeDescription
pg_create_restore_point(nametext)textCreate a named point for performing restore (restricted tosuperusers)
pg_current_xlog_insert_location()textGet current transaction log insert location
pg_current_xlog_location()textGet current transaction log write location
pg_start_backup(labeltext [,fastboolean])textPrepare for performing on-line backup (restricted to superusersor replication roles)
pg_stop_backup()textFinish performing on-line backup (restricted to superusers orreplication roles)
pg_is_in_backup()boolTrue if an on-line exclusive backup is still in progress.
pg_backup_start_time()timestamp with time zoneGet start time of an on-line exclusive backup in progress.
pg_switch_xlog()textForce switch to a new transaction log file (restricted tosuperusers)
pg_xlogfile_name(locationtext)textConvert transaction log location string to file name
pg_xlogfile_name_offset(locationtext)text,integerConvert transaction log location string to file name anddecimal byte offset within file
pg_xlog_location_diff(locationtext,locationtext)numericCalculate the difference between two transaction loglocations

pg_start_backup accepts anarbitrary user-defined label for the backup. (Typically this wouldbe the name under which the backup dump file will be stored.) Thefunction writes a backup label file (backup_label) into the database cluster's datadirectory, performs a checkpoint, and then returns the backup'sstarting transaction log location as text. The user can ignore thisresult value, but it is provided in case it is useful.

postgres=# select pg_start_backup('label_goes_here'); pg_start_backup----------------- 0/D4445B8(1 row)

There is an optional second parameter of typeboolean. Iftrue, it specifiesexecutingpg_start_backup as quicklyas possible. This forces an immediate checkpoint which will cause aspike in I/O operations, slowing any concurrently executingqueries.

pg_stop_backup removes the labelfile created bypg_start_backup, andcreates a backup history file in the transaction log archive area.The history file includes the label given topg_start_backup, the starting and endingtransaction log locations for the backup, and the starting andending times of the backup. The return value is the backup's endingtransaction log location (which again can be ignored). Afterrecording the ending location, the current transaction loginsertion point is automatically advanced to the next transactionlog file, so that the ending transaction log file can be archivedimmediately to complete the backup.

pg_switch_xlog moves to the nexttransaction log file, allowing the current file to be archived(assuming you are using continuous archiving). The return value isthe ending transaction log location + 1 within the just-completedtransaction log file. If there has been no transaction log activitysince the last transaction log switch,pg_switch_xlog does nothing and returns the startlocation of the transaction log file currently in use.

pg_create_restore_point creates anamed transaction log record that can be used as recovery target,and returns the corresponding transaction log location. The givenname can then be used withrecovery_target_nameto specify the point up to which recovery will proceed. Avoidcreating multiple restore points with the same name, since recoverywill stop at the first one whose name matches the recoverytarget.

pg_current_xlog_location displaysthe current transaction log write location in the same format usedby the above functions. Similarly,pg_current_xlog_insert_location displays thecurrent transaction log insertion point. The insertion point is the"logical" end of the transaction log atany instant, while the write location is the end of what hasactually been written out from the server's internal buffers. Thewrite location is the end of what can be examined from outside theserver, and is usually what you want if you are interested inarchiving partially-complete transaction log files. The insertionpoint is made available primarily for server debugging purposes.These are both read-only operations and do not require superuserpermissions.

You can usepg_xlogfile_name_offset to extract thecorresponding transaction log file name and byte offset from theresults of any of the above functions. For example:

postgres=# SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup());        file_name         | file_offset --------------------------+------------- 00000001000000000000000D |     4039624(1 row)

Similarly,pg_xlogfile_nameextracts just the transaction log file name. When the giventransaction log location is exactly at a transaction log fileboundary, both these functions return the name of the precedingtransaction log file. This is usually the desired behavior formanaging transaction log archiving behavior, since the precedingfile is the last one that currently needs to be archived.

pg_xlog_location_diff calculatesthe difference in bytes between two transaction log locations. Itcan be used withpg_stat_replication orsome functions shown inTable 9-61to get the replication lag.

For details about proper usage of these functions, seeSection 24.3.

9.26.4. Recovery ControlFunctions

The functions shown inTable 9-62provide information about the current status of the standby. Thesefunctions may be executed both during recovery and in normalrunning.

Table 9-62. Recovery Information Functions

NameReturn TypeDescription
pg_is_in_recovery()boolTrue if recovery is still in progress.
pg_last_xlog_receive_location()textGet last transaction log location received and synced to diskby streaming replication. While streaming replication is inprogress this will increase monotonically. If recovery hascompleted this will remain static at the value of the last WALrecord received and synced to disk during recovery. If streamingreplication is disabled, or if it has not yet started, the functionreturns NULL.
pg_last_xlog_replay_location()textGet last transaction log location replayed during recovery. Ifrecovery is still in progress this will increase monotonically. Ifrecovery has completed then this value will remain static at thevalue of the last WAL record applied during that recovery. When theserver has been started normally without recovery the functionreturns NULL.
pg_last_xact_replay_timestamp()timestamp with time zoneGet time stamp of last transaction replayed during recovery.This is the time at which the commit or abort WAL record for thattransaction was generated on the primary. If no transactions havebeen replayed during recovery, this function returns NULL.Otherwise, if recovery is still in progress this will increasemonotonically. If recovery has completed then this value willremain static at the value of the last transaction applied duringthat recovery. When the server has been started normally withoutrecovery the function returns NULL.

The functions shown inTable9-63 control the progress of recovery. These functions may beexecuted only during recovery.

Table 9-63. Recovery Control Functions

NameReturn TypeDescription
pg_is_xlog_replay_paused()boolTrue if recovery is paused.
pg_xlog_replay_pause()voidPauses recovery immediately.
pg_xlog_replay_resume()voidRestarts recovery if it was paused.

While recovery is paused no further database changes areapplied. If in hot standby, all new queries will see the sameconsistent snapshot of the database, and no further query conflictswill be generated until recovery is resumed.

If streaming replication is disabled, the paused state maycontinue indefinitely without problem. While streaming replicationis in progress WAL records will continue to be received, which willeventually fill available disk space, depending upon the durationof the pause, the rate of WAL generation and available diskspace.

9.26.5. SnapshotSynchronization Functions

PostgreSQL allows databasesessions to synchronize their snapshots. Asnapshot determines which data is visible to thetransaction that is using the snapshot. Synchronized snapshots arenecessary when two or more sessions need to see identical contentin the database. If two sessions just start their transactionsindependently, there is always a possibility that some thirdtransaction commits between the executions of the twoSTART TRANSACTION commands, so that one session seesthe effects of that transaction and the other does not.

To solve this problem,PostgreSQL allows a transaction toexport the snapshot it is using. As long as theexporting transaction remains open, other transactions canimport its snapshot, and thereby beguaranteed that they see exactly the same view of the database thatthe first transaction sees. But note that any database changes madeby any one of these transactions remain invisible to the othertransactions, as is usual for changes made by uncommittedtransactions. So the transactions are synchronized with respect topre-existing data, but act normally for changes they makethemselves.

Snapshots are exported with thepg_export_snapshot function, shown inTable9-64, and imported with theSET TRANSACTION command.

Table 9-64. Snapshot Synchronization Functions

NameReturn TypeDescription
pg_export_snapshot()textSave the current snapshot and return its identifier

The functionpg_export_snapshotsaves the current snapshot and returns atextstring identifying the snapshot. This string must be passed(outside the database) to clients that want to import the snapshot.The snapshot is available for import only until the end of thetransaction that exported it. A transaction can export more thanone snapshot, if needed. Note that doing so is only useful inREAD COMMITTED transactions, since inREPEATABLE READ and higher isolationlevels, transactions use the same snapshot throughout theirlifetime. Once a transaction has exported any snapshots, it cannotbe prepared withPREPARETRANSACTION.

SeeSET TRANSACTION fordetails of how to use an exported snapshot.

9.26.6. Database Object ManagementFunctions

The functions shown inTable 9-65calculate the disk space usage of database objects.

Table 9-65. Database Object Size Functions

NameReturn TypeDescription
pg_column_size(any)intNumber of bytes used to store a particular value (possiblycompressed)
pg_database_size(oid)bigintDisk space used by the database with the specified OID
pg_database_size(name)bigintDisk space used by the database with the specified name
pg_indexes_size(regclass)bigintTotal disk space used by indexes attached to the specifiedtable
pg_relation_size(relationregclass,forktext)bigintDisk space used by the specified fork ('main','fsm','vm', or'init') of thespecified table or index
pg_relation_size(relationregclass)bigintShorthand forpg_relation_size(...,'main')
pg_size_pretty(bigint)textConverts a size in bytes expressed as a 64-bit integer into ahuman-readable format with size units
pg_size_pretty(numeric)textConverts a size in bytes expressed as a numeric value into ahuman-readable format with size units
pg_table_size(regclass)bigintDisk space used by the specified table, excluding indexes (butincluding TOAST, free space map, and visibility map)
pg_tablespace_size(oid)bigintDisk space used by the tablespace with the specified OID
pg_tablespace_size(name)bigintDisk space used by the tablespace with the specified name
pg_total_relation_size(regclass)bigintTotal disk space used by the specified table, including allindexes andTOAST data

pg_column_size shows the spaceused to store any individual data value.

pg_total_relation_size accepts theOID or name of a table or toast table, and returns the totalon-disk space used for that table, including all associatedindexes. This function is equivalent topg_table_size+pg_indexes_size.

pg_table_size accepts the OID orname of a table and returns the disk space needed for that table,exclusive of indexes. (TOAST space, free space map, and visibilitymap are included.)

pg_indexes_size accepts the OID orname of a table and returns the total disk space used by all theindexes attached to that table.

pg_database_size andpg_tablespace_size accept the OID or name of adatabase or tablespace, and return the total disk space usedtherein. To usepg_database_size, youmust haveCONNECT permission on thespecified database (which is granted by default). To usepg_tablespace_size, you must haveCREATE permission on the specifiedtablespace, unless it is the default tablespace for the currentdatabase.

pg_relation_size accepts the OIDor name of a table, index or toast table, and returns the on-disksize in bytes of one fork of that relation. (Note that for mostpurposes it is more convenient to use the higher-level functionspg_total_relation_size orpg_table_size, which sum the sizes ofall forks.) With one argument, it returns the size of the main datafork of the relation. The second argument can be provided tospecify which fork to examine:

  • 'main' returns the size of the maindata fork of the relation.

  • 'fsm' returns the size of the FreeSpace Map (seeSection 58.3)associated with the relation.

  • 'vm' returns the size of the VisibilityMap (seeSection 58.4) associatedwith the relation.

  • 'init' returns the size of theinitialization fork, if any, (seeSection 58.5) associated with therelation.

pg_size_pretty can be used toformat the result of one of the other functions in a human-readableway, using kB, MB, GB or TB as appropriate.

The functions above that operate on tables or indexes accept aregclass argument, which is simply the OID ofthe table or index in thepg_classsystem catalog. You do not have to look up the OID by hand,however, since theregclass data type's inputconverter will do the work for you. Just write the table nameenclosed in single quotes so that it looks like a literal constant.For compatibility with the handling of ordinarySQL names, the string will be converted tolower case unless it contains double quotes around the tablename.

If an OID that does not represent an existing object is passedas argument to one of the above functions, NULL is returned.

The functions shown inTable 9-66assist in identifying the specific disk files associated withdatabase objects.

Table 9-66. Database Object Location Functions

NameReturn TypeDescription
pg_relation_filenode(relationregclass)oidFilenode number of the specified relation
pg_relation_filepath(relationregclass)textFile path name of the specified relation

pg_relation_filenode accepts theOID or name of a table, index, sequence, or toast table, andreturns the"filenode" number currentlyassigned to it. The filenode is the base component of the filename(s) used for the relation (seeSection 58.1 for more information).For most tables the result is the same aspg_class.relfilenode, but for certain system catalogsrelfilenode is zero and this functionmust be used to get the correct value. The function returns NULL ifpassed a relation that does not have storage, such as a view.

pg_relation_filepath is similar topg_relation_filenode, but it returnsthe entire file path name (relative to the database cluster's datadirectoryPGDATA) of the relation.

9.26.7. Generic File AccessFunctions

The functions shown inTable 9-67provide native access to files on the machine hosting the server.Only files within the database cluster directory and thelog_directory can be accessed. Use a relative pathfor files in the cluster directory, and a path matching thelog_directory configuration setting forlog files. Use of these functions is restricted to superusers.

Table 9-67. Generic File Access Functions

NameReturn TypeDescription
pg_ls_dir(dirnametext)setof textList the contents of a directory
pg_read_file(filenametext [,offsetbigint,lengthbigint])textReturn the contents of a text file
pg_read_binary_file(filenametext [,offsetbigint,lengthbigint])byteaReturn the contents of a file
pg_stat_file(filenametext)recordReturn information about a file

pg_ls_dir returns all the names inthe specified directory, except the special entries"." and"..".

pg_read_file returns part of atext file, starting at the givenoffset,returning at mostlength bytes (less ifthe end of file is reached first). Ifoffset is negative, it is relative to the end ofthe file. Ifoffset andlength are omitted, the entire file is returned.The bytes read from the file are interpreted as a string in theserver encoding; an error is thrown if they are not valid in thatencoding.

pg_read_binary_file is similar topg_read_file, except that the resultis abytea value; accordingly, no encodingchecks are performed. In combination with theconvert_from function, this function can be usedto read a file in a specified encoding:

SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');

pg_stat_file returns a recordcontaining the file size, last accessed time stamp, last modifiedtime stamp, last file status change time stamp (Unix platformsonly), file creation time stamp (Windows only), and aboolean indicating if it is a directory. Typical usagesinclude:

SELECT * FROM pg_stat_file('filename');SELECT (pg_stat_file('filename')).modification;

9.26.8. Advisory Lock Functions

The functions shown inTable9-68 manage advisory locks. For details about proper use ofthese functions, seeSection 13.3.4.

Table 9-68. Advisory Lock Functions

NameReturn TypeDescription
pg_advisory_lock(keybigint)voidObtain exclusive session level advisory lock
pg_advisory_lock(key1int,key2int)voidObtain exclusive session level advisory lock
pg_advisory_lock_shared(keybigint)voidObtain shared session level advisory lock
pg_advisory_lock_shared(key1int,key2int)voidObtain shared session level advisory lock
pg_advisory_unlock(keybigint)booleanRelease an exclusive session level advisory lock
pg_advisory_unlock(key1int,key2int)booleanRelease an exclusive session level advisory lock
pg_advisory_unlock_all()voidRelease all session level advisory locks held by the currentsession
pg_advisory_unlock_shared(keybigint)booleanRelease a shared session level advisory lock
pg_advisory_unlock_shared(key1int,key2int)booleanRelease a shared session level advisory lock
pg_advisory_xact_lock(keybigint)voidObtain exclusive transaction level advisory lock
pg_advisory_xact_lock(key1int,key2int)voidObtain exclusive transaction level advisory lock
pg_advisory_xact_lock_shared(keybigint)voidObtain shared transaction level advisory lock
pg_advisory_xact_lock_shared(key1int,key2int)voidObtain shared transaction level advisory lock
pg_try_advisory_lock(keybigint)booleanObtain exclusive session level advisory lock if available
pg_try_advisory_lock(key1int,key2int)booleanObtain exclusive session level advisory lock if available
pg_try_advisory_lock_shared(keybigint)booleanObtain shared session level advisory lock if available
pg_try_advisory_lock_shared(key1int,key2int)booleanObtain shared session level advisory lock if available
pg_try_advisory_xact_lock(keybigint)booleanObtain exclusive transaction level advisory lock ifavailable
pg_try_advisory_xact_lock(key1int,key2int)booleanObtain exclusive transaction level advisory lock ifavailable
pg_try_advisory_xact_lock_shared(keybigint)booleanObtain shared transaction level advisory lock if available
pg_try_advisory_xact_lock_shared(key1int,key2int)booleanObtain shared transaction level advisory lock if available

pg_advisory_lock locks anapplication-defined resource, which can be identified either by asingle 64-bit key value or two 32-bit key values (note that thesetwo key spaces do not overlap). If another session already holds alock on the same resource identifier, this function will wait untilthe resource becomes available. The lock is exclusive. Multiplelock requests stack, so that if the same resource is locked threetimes it must then be unlocked three times to be released for othersessions' use.

pg_advisory_lock_shared works thesame aspg_advisory_lock, except thelock can be shared with other sessions requesting shared locks.Only would-be exclusive lockers are locked out.

pg_try_advisory_lock is similar topg_advisory_lock, except the functionwill not wait for the lock to become available. It will eitherobtain the lock immediately and returntrue, or returnfalse ifthe lock cannot be acquired immediately.

pg_try_advisory_lock_shared worksthe same aspg_try_advisory_lock,except it attempts to acquire a shared rather than an exclusivelock.

pg_advisory_unlock will release apreviously-acquired exclusive session level advisory lock. Itreturnstrue if the lock is successfullyreleased. If the lock was not held, it will returnfalse, and in addition, an SQL warning will bereported by the server.

pg_advisory_unlock_shared worksthe same aspg_advisory_unlock,except it releases a shared session level advisory lock.

pg_advisory_unlock_all willrelease all session level advisory locks held by the currentsession. (This function is implicitly invoked at session end, evenif the client disconnects ungracefully.)

pg_advisory_xact_lock works thesame aspg_advisory_lock, except thelock is automatically released at the end of the currenttransaction and cannot be released explicitly.

pg_advisory_xact_lock_shared worksthe same aspg_advisory_lock_shared,except the lock is automatically released at the end of the currenttransaction and cannot be released explicitly.

pg_try_advisory_xact_lock worksthe same aspg_try_advisory_lock,except the lock, if acquired, is automatically released at the endof the current transaction and cannot be released explicitly.

pg_try_advisory_xact_lock_sharedworks the same aspg_try_advisory_lock_shared, except the lock, ifacquired, is automatically released at the end of the currenttransaction and cannot be released explicitly.


PrevHomeNext
System InformationFunctionsUpTrigger Functions

[8]ページ先頭

©2009-2025 Movatter.jp