Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
9.26. System Administration Functions
Prev UpChapter 9. Functions and OperatorsHome Next

9.26. System Administration Functions

The functions described in this section are used to control and monitor aPostgreSQL installation.

9.26.1. Configuration Settings Functions

Table 9.82 shows the functions available to query and alter run-time configuration parameters.

Table 9.82. Configuration Settings Functions

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

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

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

If there is no setting namedsetting_name,current_setting throws an error unlessmissing_ok is supplied and istrue.

set_config sets the parametersetting_name tonew_value. Ifis_local istrue, the new value will only apply to the current transaction. If you want the new value to apply for the current session, usefalse instead. The function corresponds to the SQL commandSET. An example:

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

The functions shown inTable 9.83 send control signals to other server processes. Use of these functions is restricted to superusers by default but access may be granted to others usingGRANT, with noted exceptions.

Table 9.83. Server Signaling Functions

NameReturn TypeDescription
pg_cancel_backend(pidint)booleanCancel a backend's current query. This is also allowed if the calling role is a member of the role whose backend is being canceled or the calling role has been grantedpg_signal_backend, however only superusers can cancel superuser backends.
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. This is also allowed if the calling role is a member of the role whose backend is being terminated or the calling role has been grantedpg_signal_backend, however only superusers can terminate superuser backends.

Each of these functions returnstrue if successful andfalse otherwise.

pg_cancel_backend andpg_terminate_backend send signals (SIGINT orSIGTERM respectively) to backend processes identified by process ID. The process ID of an active backend can be found from thepid column of thepg_stat_activity view, or by listing thepostgres processes on the server (usingps on Unix or theTask Manager onWindows). The role of an active backend can be found 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 server processes.

pg_rotate_logfile signals the log-file manager to switch to a new output file immediately. This works only when the built-in log collector is running, since otherwise there is no log-file manager subprocess.

9.26.3. Backup Control Functions

The functions shown inTable 9.84 assist in making on-line backups. These functions cannot be executed during recovery (except non-exclusivepg_start_backup, non-exclusivepg_stop_backup,pg_is_in_backup,pg_backup_start_time andpg_wal_lsn_diff).

Table 9.84. Backup Control Functions

NameReturn TypeDescription
pg_create_restore_point(nametext)pg_lsnCreate a named point for performing restore (restricted to superusers by default, but other users can be granted EXECUTE to run the function)
pg_current_wal_flush_lsn()pg_lsnGet current write-ahead log flush location
pg_current_wal_insert_lsn()pg_lsnGet current write-ahead log insert location
pg_current_wal_lsn()pg_lsnGet current write-ahead log write location
pg_start_backup(labeltext [,fastboolean [,exclusiveboolean]])pg_lsnPrepare for performing on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)
pg_stop_backup()pg_lsnFinish performing exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)
pg_stop_backup(exclusiveboolean [,wait_for_archiveboolean])setof recordFinish performing exclusive or non-exclusive on-line backup (restricted to superusers by default, but other users can be granted EXECUTE to run the function)
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_wal()pg_lsnForce switch to a new write-ahead log file (restricted to superusers by default, but other users can be granted EXECUTE to run the function)
pg_walfile_name(lsnpg_lsn)textConvert write-ahead log location to file name
pg_walfile_name_offset(lsnpg_lsn)text,integerConvert write-ahead log location to file name and decimal byte offset within file
pg_wal_lsn_diff(lsnpg_lsn,lsnpg_lsn)numericCalculate the difference between two write-ahead log locations

pg_start_backup accepts an arbitrary user-defined label for the backup. (Typically this would be the name under which the backup dump file will be stored.) When used in exclusive mode, the function writes a backup label file (backup_label) and, if there are any links in thepg_tblspc/ directory, a tablespace map file (tablespace_map) into the database cluster's data directory, performs a checkpoint, and then returns the backup's starting write-ahead log location as text. The user can ignore this result value, but it is provided in case it is useful. When used in non-exclusive mode, the contents of these files are instead returned by thepg_stop_backup function, and should be written to the backup by the caller.

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 specifies executingpg_start_backup as quickly as possible. This forces an immediate checkpoint which will cause a spike in I/O operations, slowing any concurrently executing queries.

In an exclusive backup,pg_stop_backup removes the label file and, if it exists, thetablespace_map file created bypg_start_backup. In a non-exclusive backup, the contents of thebackup_label andtablespace_map are returned in the result of the function, and should be written to files in the backup (and not in the data directory). There is an optional second parameter of typeboolean. If false, thepg_stop_backup will return immediately after the backup is completed without waiting for WAL to be archived. This behavior is only useful for backup software which independently monitors WAL archiving. Otherwise, WAL required to make the backup consistent might be missing and make the backup useless. When this parameter is set to true,pg_stop_backup will wait for WAL to be archived when archiving is enabled; on the standby, this means that it will wait only whenarchive_mode = always. If write activity on the primary is low, it may be useful to runpg_switch_wal on the primary in order to trigger an immediate segment switch.

When executed on a primary, the function also creates a backup history file in the write-ahead log archive area. The history file includes the label given topg_start_backup, the starting and ending write-ahead log locations for the backup, and the starting and ending times of the backup. The return value is the backup's ending write-ahead log location (which again can be ignored). After recording the ending location, the current write-ahead log insertion point is automatically advanced to the next write-ahead log file, so that the ending write-ahead log file can be archived immediately to complete the backup.

pg_switch_wal moves to the next write-ahead log file, allowing the current file to be archived (assuming you are using continuous archiving). The return value is the ending write-ahead log location + 1 within the just-completed write-ahead log file. If there has been no write-ahead log activity since the last write-ahead log switch,pg_switch_wal does nothing and returns the start location of the write-ahead log file currently in use.

pg_create_restore_point creates a named write-ahead log record that can be used as recovery target, and returns the corresponding write-ahead log location. The given name can then be used withrecovery_target_name to specify the point up to which recovery will proceed. Avoid creating multiple restore points with the same name, since recovery will stop at the first one whose name matches the recovery target.

pg_current_wal_lsn displays the current write-ahead log write location in the same format used by the above functions. Similarly,pg_current_wal_insert_lsn displays the current write-ahead log insertion location andpg_current_wal_flush_lsn displays the current write-ahead log flush location. The insertion location is thelogical end of the write-ahead log at any instant, while the write location is the end of what has actually been written out from the server's internal buffers and flush location is the location guaranteed to be written to durable storage. The write location is the end of what can be examined from outside the server, and is usually what you want if you are interested in archiving partially-complete write-ahead log files. The insertion and flush locations are made available primarily for server debugging purposes. These are both read-only operations and do not require superuser permissions.

You can usepg_walfile_name_offset to extract the corresponding write-ahead log file name and byte offset from the results of any of the above functions. For example:

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

Similarly,pg_walfile_name extracts just the write-ahead log file name. When the given write-ahead log location is exactly at a write-ahead log file boundary, both these functions return the name of the preceding write-ahead log file. This is usually the desired behavior for managing write-ahead log archiving behavior, since the preceding file is the last one that currently needs to be archived.

pg_wal_lsn_diff calculates the difference in bytes between two write-ahead log locations. It can be used withpg_stat_replication or some functions shown inTable 9.84 to get the replication lag.

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

9.26.4. Recovery Control Functions

The functions shown inTable 9.85 provide information about the current status of the standby. These functions may be executed both during recovery and in normal running.

Table 9.85. Recovery Information Functions

NameReturn TypeDescription
pg_is_in_recovery()boolTrue if recovery is still in progress.
pg_last_wal_receive_lsn()pg_lsnGet last write-ahead log location received and synced to disk by streaming replication. While streaming replication is in progress this will increase monotonically. If recovery has completed this will remain static at the value of the last WAL record received and synced to disk during recovery. If streaming replication is disabled, or if it has not yet started, the function returns NULL.
pg_last_wal_replay_lsn()pg_lsnGet last write-ahead log location replayed during recovery. If recovery is still in progress this will increase monotonically. If recovery has completed then this value will remain static at the value of the last WAL record applied during that recovery. When the server has been started normally without recovery the function returns 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 that transaction was generated on the primary. If no transactions have been replayed during recovery, this function returns NULL. Otherwise, if recovery is still in progress this will increase monotonically. If recovery has completed then this value will remain static at the value of the last transaction applied during that recovery. When the server has been started normally without recovery the function returns NULL.

The functions shown inTable 9.86 control the progress of recovery. These functions may be executed only during recovery.

Table 9.86. Recovery Control Functions

NameReturn TypeDescription
pg_is_wal_replay_paused()boolTrue if recovery is paused.
pg_promote(waitboolean DEFAULT true,wait_secondsinteger DEFAULT 60)boolean Promotes a physical standby server. Withwait set totrue (the default), the function waits until promotion is completed orwait_seconds seconds have passed, and returnstrue if promotion is successful andfalse otherwise. Ifwait is set tofalse, the function returnstrue immediately after sendingSIGUSR1 to the postmaster to trigger the promotion. This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.
pg_wal_replay_pause()voidPauses recovery immediately (restricted to superusers by default, but other users can be granted EXECUTE to run the function).
pg_wal_replay_resume()voidRestarts recovery if it was paused (restricted to superusers by default, but other users can be granted EXECUTE to run the function).

While recovery is paused no further database changes are applied. If in hot standby, all new queries will see the same consistent snapshot of the database, and no further query conflicts will be generated until recovery is resumed.

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

9.26.5. Snapshot Synchronization Functions

PostgreSQL allows database sessions to synchronize their snapshots. Asnapshot determines which data is visible to the transaction that is using the snapshot. Synchronized snapshots are necessary when two or more sessions need to see identical content in the database. If two sessions just start their transactions independently, there is always a possibility that some third transaction commits between the executions of the twoSTART TRANSACTION commands, so that one session sees the 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 the exporting transaction remains open, other transactions canimport its snapshot, and thereby be guaranteed that they see exactly the same view of the database that the first transaction sees. But note that any database changes made by any one of these transactions remain invisible to the other transactions, as is usual for changes made by uncommitted transactions. So the transactions are synchronized with respect to pre-existing data, but act normally for changes they make themselves.

Snapshots are exported with thepg_export_snapshot function, shown inTable 9.87, and imported with theSET TRANSACTION command.

Table 9.87. Snapshot Synchronization Functions

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

The functionpg_export_snapshot saves the current snapshot and returns atext string 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 the transaction that exported it. A transaction can export more than one snapshot, if needed. Note that doing so is only useful inREAD COMMITTED transactions, since inREPEATABLE READ and higher isolation levels, transactions use the same snapshot throughout their lifetime. Once a transaction has exported any snapshots, it cannot be prepared withPREPARE TRANSACTION.

SeeSET TRANSACTION for details of how to use an exported snapshot.

9.26.6. Replication Functions

The functions shown inTable 9.88 are for controlling and interacting with replication features. SeeSection 26.2.5,Section 26.2.6, andChapter 49 for information about the underlying features. Use of functions for replication origin is restricted to superusers. Use of functions for replication slot is restricted to superusers and users havingREPLICATION privilege.

Many of these functions have equivalent commands in the replication protocol; seeSection 52.4.

The functions described inSection 9.26.3,Section 9.26.4, andSection 9.26.5 are also relevant for replication.

Table 9.88. ReplicationSQL Functions

FunctionReturn TypeDescription
pg_create_physical_replication_slot(slot_namename [,immediately_reserveboolean,temporaryboolean]) (slot_namename,lsnpg_lsn) Creates a new physical replication slot namedslot_name. The optional second parameter, whentrue, specifies that theLSN for this replication slot be reserved immediately; otherwise theLSN is reserved on first connection from a streaming replication client. Streaming changes from a physical slot is only possible with the streaming-replication protocol — seeSection 52.4. The optional third parameter,temporary, when set to true, specifies that the slot should not be permanently stored to disk and is only meant for use by current session. Temporary slots are also released upon any error. This function corresponds to the replication protocol commandCREATE_REPLICATION_SLOT ... PHYSICAL.
pg_drop_replication_slot(slot_namename)void Drops the physical or logical replication slot namedslot_name. Same as replication protocol commandDROP_REPLICATION_SLOT. For logical slots, this must be called when connected to the same database the slot was created on.
pg_create_logical_replication_slot(slot_namename,pluginname [,temporaryboolean]) (slot_namename,lsnpg_lsn) Creates a new logical (decoding) replication slot namedslot_name using the output pluginplugin. The optional third parameter,temporary, when set to true, specifies that the slot should not be permanently stored to disk and is only meant for use by current session. Temporary slots are also released upon any error. A call to this function has the same effect as the replication protocol commandCREATE_REPLICATION_SLOT ... LOGICAL.
pg_copy_physical_replication_slot(src_slot_namename,dst_slot_namename [,temporaryboolean]) (slot_namename,lsnpg_lsn) Copies an existing physical replication slot namedsrc_slot_name to a physical replication slot nameddst_slot_name. The copied physical slot starts to reserve WAL from the sameLSN as the source slot.temporary is optional. Iftemporary is omitted, the same value as the source slot is used.
pg_copy_logical_replication_slot(src_slot_namename,dst_slot_namename [,temporaryboolean [,pluginname]]) (slot_namename,lsnpg_lsn) Copies an existing logical replication slot namedsrc_slot_name to a logical replication slot nameddst_slot_name while changing the output plugin and persistence. The copied logical slot starts from the sameLSN as the source logical slot. Bothtemporary andplugin are optional. Iftemporary orplugin are omitted, the same values as the source logical slot are used.
pg_logical_slot_get_changes(slot_namename,upto_lsnpg_lsn,upto_nchangesint, VARIADICoptionstext[]) (lsnpg_lsn,xidxid,datatext) Returns changes in the slotslot_name, starting from the point at which since changes have been consumed last. Ifupto_lsn andupto_nchanges are NULL, logical decoding will continue until end of WAL. Ifupto_lsn is non-NULL, decoding will include only those transactions which commit prior to the specified LSN. Ifupto_nchanges is non-NULL, decoding will stop when the number of rows produced by decoding exceeds the specified value. Note, however, that the actual number of rows returned may be larger, since this limit is only checked after adding the rows produced when decoding each new transaction commit.
pg_logical_slot_peek_changes(slot_namename,upto_lsnpg_lsn,upto_nchangesint, VARIADICoptionstext[]) (lsnpg_lsn,xidxid,datatext) Behaves just like thepg_logical_slot_get_changes() function, except that changes are not consumed; that is, they will be returned again on future calls.
pg_logical_slot_get_binary_changes(slot_namename,upto_lsnpg_lsn,upto_nchangesint, VARIADICoptionstext[]) (lsnpg_lsn,xidxid,databytea) Behaves just like thepg_logical_slot_get_changes() function, except that changes are returned asbytea.
pg_logical_slot_peek_binary_changes(slot_namename,upto_lsnpg_lsn,upto_nchangesint, VARIADICoptionstext[]) (lsnpg_lsn,xidxid,databytea) Behaves just like thepg_logical_slot_get_changes() function, except that changes are returned asbytea and that changes are not consumed; that is, they will be returned again on future calls.
pg_replication_slot_advance(slot_namename,upto_lsnpg_lsn) (slot_namename,end_lsnpg_lsn)bool Advances the current confirmed position of a replication slot namedslot_name. The slot will not be moved backwards, and it will not be moved beyond the current insert location. Returns the name of the slot and the real position to which it was advanced to. The information of the updated slot is written out at the follow-up checkpoint if any advancing is done. In the event of a crash, the slot may return to an earlier position.
pg_replication_origin_create(node_nametext)oid Create a replication origin with the given external name, and return the internal id assigned to it.
pg_replication_origin_drop(node_nametext)void Delete a previously created replication origin, including any associated replay progress.
pg_replication_origin_oid(node_nametext)oid Lookup a replication origin by name and return the internal ID. If no such replication origin is found,NULL is returned.
pg_replication_origin_session_setup(node_nametext)void Mark the current session as replaying from the given origin, allowing replay progress to be tracked. Usepg_replication_origin_session_reset to revert. Can only be used if no previous origin is configured.
pg_replication_origin_session_reset()void Cancel the effects ofpg_replication_origin_session_setup().
pg_replication_origin_session_is_setup()bool Has a replication origin been configured in the current session?
pg_replication_origin_session_progress(flushbool)pg_lsn Return the replay location for the replication origin configured in the current session. The parameterflush determines whether the corresponding local transaction will be guaranteed to have been flushed to disk or not.
pg_replication_origin_xact_setup(origin_lsnpg_lsn,origin_timestamptimestamptz)void Mark the current transaction as replaying a transaction that has committed at the givenLSN and timestamp. Can only be called when a replication origin has previously been configured usingpg_replication_origin_session_setup().
pg_replication_origin_xact_reset()void Cancel the effects ofpg_replication_origin_xact_setup().
pg_replication_origin_advance(node_nametext,lsnpg_lsn)void Set replication progress for the given node to the given location. This primarily is useful for setting up the initial location or a new location after configuration changes and similar. Be aware that careless use of this function can lead to inconsistently replicated data.
pg_replication_origin_progress(node_nametext,flushbool)pg_lsn Return the replay location for the given replication origin. The parameterflush determines whether the corresponding local transaction will be guaranteed to have been flushed to disk or not.
pg_logical_emit_message(transactionalbool,prefixtext,contenttext)pg_lsn Emit text logical decoding message. This can be used to pass generic messages to logical decoding plugins through WAL. The parametertransactional specifies if the message should be part of current transaction or if it should be written immediately and decoded as soon as the logical decoding reads the record. Theprefix is textual prefix used by the logical decoding plugins to easily recognize interesting messages for them. Thecontent is the text of the message.
pg_logical_emit_message(transactionalbool,prefixtext,contentbytea)pg_lsn Emit binary logical decoding message. This can be used to pass generic messages to logical decoding plugins through WAL. The parametertransactional specifies if the message should be part of current transaction or if it should be written immediately and decoded as soon as the logical decoding reads the record. Theprefix is textual prefix used by the logical decoding plugins to easily recognize interesting messages for them. Thecontent is the binary content of the message.

The functions shown inTable 9.89 calculate the disk space usage of database objects.

Table 9.89. Database Object Size Functions

NameReturn TypeDescription
pg_column_size(any)intNumber of bytes used to store a particular value (possibly compressed)
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)bigint Total disk space used by indexes attached to the specified table
pg_relation_size(relationregclass,forktext)bigint Disk space used by the specified fork ('main','fsm','vm', or'init') of the specified table or index
pg_relation_size(relationregclass)bigint Shorthand forpg_relation_size(..., 'main')
pg_size_bytes(text)bigint Converts a size in human-readable format with size units into bytes
pg_size_pretty(bigint)text Converts a size in bytes expressed as a 64-bit integer into a human-readable format with size units
pg_size_pretty(numeric)text Converts a size in bytes expressed as a numeric value into a human-readable format with size units
pg_table_size(regclass)bigint Disk space used by the specified table, excluding indexes (but including 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)bigint Total disk space used by the specified table, including all indexes andTOAST data

pg_column_size shows the space used to store any individual data value.

pg_total_relation_size accepts the OID or name of a table or toast table, and returns the total on-disk space used for that table, including all associated indexes. This function is equivalent topg_table_size+pg_indexes_size.

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

pg_indexes_size accepts the OID or name of a table and returns the total disk space used by all the indexes attached to that table.

pg_database_size andpg_tablespace_size accept the OID or name of a database or tablespace, and return the total disk space used therein. To usepg_database_size, you must haveCONNECT permission on the specified database (which is granted by default), or be a member of thepg_read_all_stats role. To usepg_tablespace_size, you must haveCREATE permission on the specified tablespace, or be a member of thepg_read_all_stats role unless it is the default tablespace for the current database.

pg_relation_size accepts the OID or name of a table, index or toast table, and returns the on-disk size in bytes of one fork of that relation. (Note that for most purposes it is more convenient to use the higher-level functionspg_total_relation_size orpg_table_size, which sum the sizes of all forks.) With one argument, it returns the size of the main data fork of the relation. The second argument can be provided to specify which fork to examine:

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

  • 'fsm' returns the size of the Free Space Map (seeSection 69.3) associated with the relation.

  • 'vm' returns the size of the Visibility Map (seeSection 69.4) associated with the relation.

  • 'init' returns the size of the initialization fork, if any, associated with the relation.

pg_size_pretty can be used to format the result of one of the other functions in a human-readable way, using bytes, kB, MB, GB or TB as appropriate.

pg_size_bytes can be used to get the size in bytes from a string in human-readable format. The input may have units of bytes, kB, MB, GB or TB, and is parsed case-insensitively. If no units are specified, bytes are assumed.

Note

The units kB, MB, GB and TB used by the functionspg_size_pretty andpg_size_bytes are defined using powers of 2 rather than powers of 10, so 1kB is 1024 bytes, 1MB is 10242 = 1048576 bytes, and so on.

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

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

The functions shown inTable 9.90 assist in identifying the specific disk files associated with database objects.

Table 9.90. Database Object Location Functions

NameReturn TypeDescription
pg_relation_filenode(relationregclass)oid Filenode number of the specified relation
pg_relation_filepath(relationregclass)text File path name of the specified relation
pg_filenode_relation(tablespaceoid,filenodeoid)regclass Find the relation associated with a given tablespace and filenode

pg_relation_filenode accepts the OID or name of a table, index, sequence, or toast table, and returns thefilenode number currently assigned to it. The filenode is the base component of the file name(s) used for the relation (seeSection 69.1 for more information). For most tables the result is the same aspg_class.relfilenode, but for certain system catalogsrelfilenode is zero and this function must be used to get the correct value. The function returns NULL if passed a relation that does not have storage, such as a view.

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

pg_filenode_relation is the reverse ofpg_relation_filenode. Given atablespace OID and afilenode, it returns the associated relation's OID. For a table in the database's default tablespace, the tablespace can be specified as 0.

Table 9.91 lists functions used to manage collations.

Table 9.91. Collation Management Functions

NameReturn TypeDescription
pg_collation_actual_version(oid)textReturn actual version of collation from operating system
pg_import_system_collations(schemaregnamespace)integerImport operating system collations

pg_collation_actual_version returns the actual version of the collation object as it is currently installed in the operating system. If this is different from the value inpg_collation.collversion, then objects depending on the collation might need to be rebuilt. See alsoALTER COLLATION.

pg_import_system_collations adds collations to the system catalogpg_collation based on all the locales it finds in the operating system. This is whatinitdb uses; seeSection 23.2.2 for more details. If additional locales are installed into the operating system later on, this function can be run again to add collations for the new locales. Locales that match existing entries inpg_collation will be skipped. (But collation objects based on locales that are no longer present in the operating system are not removed by this function.) Theschema parameter would typically bepg_catalog, but that is not a requirement; the collations could be installed into some other schema as well. The function returns the number of new collation objects it created. Use of this function is restricted to superusers.

Table 9.92. Partitioning Information Functions

NameReturn TypeDescription
pg_partition_tree(regclass)setof record List information about tables or indexes in a partition tree for a given partitioned table or partitioned index, with one row for each partition. Information provided includes the name of the partition, the name of its immediate parent, a boolean value telling if the partition is a leaf, and an integer telling its level in the hierarchy. The value of level begins at0 for the input table or index in its role as the root of the partition tree,1 for its partitions,2 for their partitions, and so on.
pg_partition_ancestors(regclass)setof regclass List the ancestor relations of the given partition, including the partition itself.
pg_partition_root(regclass)regclass Return the top-most parent of a partition tree to which the given relation belongs.

To check the total size of the data contained inmeasurement table described inSection 5.11.2.1, one could use the following query:

=# SELECT pg_size_pretty(sum(pg_relation_size(relid))) AS total_size     FROM pg_partition_tree('measurement'); total_size ------------ 24 kB(1 row)

9.26.8. Index Maintenance Functions

Table 9.93 shows the functions available for index maintenance tasks. These functions cannot be executed during recovery. Use of these functions is restricted to superusers and the owner of the given index.

Table 9.93. Index Maintenance Functions

NameReturn TypeDescription
brin_summarize_new_values(indexregclass)integersummarize page ranges not already summarized
brin_summarize_range(indexregclass,blockNumberbigint)integersummarize the page range covering the given block, if not already summarized
brin_desummarize_range(indexregclass,blockNumberbigint)integerde-summarize the page range covering the given block, if summarized
gin_clean_pending_list(indexregclass)bigintmove GIN pending list entries into main index structure

brin_summarize_new_values accepts the OID or name of a BRIN index and inspects the index to find page ranges in the base table that are not currently summarized by the index; for any such range it creates a new summary index tuple by scanning the table pages. It returns the number of new page range summaries that were inserted into the index.brin_summarize_range does the same, except it only summarizes the range that covers the given block number.

gin_clean_pending_list accepts the OID or name of a GIN index and cleans up the pending list of the specified index by moving entries in it to the main GIN data structure in bulk. It returns the number of pages removed from the pending list. Note that if the argument is a GIN index built with thefastupdate option disabled, no cleanup happens and the return value is 0, because the index doesn't have a pending list. Please seeSection 66.4.1 andSection 66.5 for details of the pending list andfastupdate option.

9.26.9. Generic File Access Functions

The functions shown inTable 9.94 provide native access to files on the machine hosting the server. Only files within the database cluster directory and thelog_directory can be accessed unless the user is granted the rolepg_read_server_files. Use a relative path for files in the cluster directory, and a path matching thelog_directory configuration setting for log files.

Note that granting users the EXECUTE privilege onpg_read_file(), or related functions, allows them the ability to read any file on the server which the database can read and that those reads bypass all in-database privilege checks. This means that, among other things, a user with this access is able to read the contents of thepg_authid table where authentication information is contained, as well as read any file in the database. Therefore, granting access to these functions should be carefully considered.

Table 9.94. Generic File Access Functions

NameReturn TypeDescription
pg_ls_dir(dirnametext [,missing_okboolean,include_dot_dirsboolean])setof text List the contents of a directory. Restricted to superusers by default, but other users can be granted EXECUTE to run the function.
pg_ls_logdir()setof record List the name, size, and last modification time of files in the log directory. Access is granted to members of thepg_monitor role and may be granted to other non-superuser roles.
pg_ls_waldir()setof record List the name, size, and last modification time of files in the WAL directory. Access is granted to members of thepg_monitor role and may be granted to other non-superuser roles.
pg_ls_archive_statusdir()setof record List the name, size, and last modification time of files in the WAL archive status directory. Access is granted to members of thepg_monitor role and may be granted to other non-superuser roles.
pg_ls_tmpdir([tablespaceoid])setof record List the name, size, and last modification time of files in the temporary directory fortablespace. Iftablespace is not provided, thepg_default tablespace is used. Access is granted to members of thepg_monitor role and may be granted to other non-superuser roles.
pg_read_file(filenametext [,offsetbigint,lengthbigint [,missing_okboolean] ])text Return the contents of a text file. Restricted to superusers by default, but other users can be granted EXECUTE to run the function.
pg_read_binary_file(filenametext [,offsetbigint,lengthbigint [,missing_okboolean] ])bytea Return the contents of a file. Restricted to superusers by default, but other users can be granted EXECUTE to run the function.
pg_stat_file(filenametext[,missing_okboolean])record Return information about a file. Restricted to superusers by default, but other users can be granted EXECUTE to run the function.

Some of these functions take an optionalmissing_ok parameter, which specifies the behavior when the file or directory does not exist. Iftrue, the function returns NULL (exceptpg_ls_dir, which returns an empty result set). Iffalse, an error is raised. The default isfalse.

pg_ls_dir returns the names of all files (and directories and other special files) in the specified directory. The include_dot_dirs indicates whether. and.. are included in the result set. The default is to exclude them (false), but including them can be useful whenmissing_ok istrue, to distinguish an empty directory from an non-existent directory.

pg_ls_logdir returns the name, size, and last modified time (mtime) of each file in the log directory. By default, only superusers and members of thepg_monitor role can use this function. Access may be granted to others usingGRANT. Filenames beginning with a dot, directories, and other special files are not shown.

pg_ls_waldir returns the name, size, and last modified time (mtime) of each file in the write ahead log (WAL) directory. By default only superusers and members of thepg_monitor role can use this function. Access may be granted to others usingGRANT. Filenames beginning with a dot, directories, and other special files are not shown.

pg_ls_archive_statusdir returns the name, size, and last modified time (mtime) of each file in the WAL archive status directorypg_wal/archive_status. By default only superusers and members of thepg_monitor role can use this function. Access may be granted to others usingGRANT. Filenames beginning with a dot, directories, and other special files are not shown.

pg_ls_tmpdir returns the name, size, and last modified time (mtime) of each file in the temporary file directory for the specifiedtablespace. Iftablespace is not provided, thepg_default tablespace is used. By default only superusers and members of thepg_monitor role can use this function. Access may be granted to others usingGRANT. Filenames beginning with a dot, directories, and other special files are not shown.

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

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

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

pg_stat_file returns a record containing the file size, last accessed time stamp, last modified time stamp, last file status change time stamp (Unix platforms only), file creation time stamp (Windows only), and aboolean indicating if it is a directory. Typical usages include:

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

9.26.10. Advisory Lock Functions

The functions shown inTable 9.95 manage advisory locks. For details about proper use of these functions, seeSection 13.3.5.

Table 9.95. 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 current session
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 if available
pg_try_advisory_xact_lock(key1int,key2int)booleanObtain exclusive transaction level advisory lock if available
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 an application-defined resource, which can be identified either by a single 64-bit key value or two 32-bit key values (note that these two key spaces do not overlap). If another session already holds a lock on the same resource identifier, this function will wait until the resource becomes available. The lock is exclusive. Multiple lock requests stack, so that if the same resource is locked three times it must then be unlocked three times to be released for other sessions' use.

pg_advisory_lock_shared works the same aspg_advisory_lock, except the lock 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 function will not wait for the lock to become available. It will either obtain the lock immediately and returntrue, or returnfalse if the lock cannot be acquired immediately.

pg_try_advisory_lock_shared works the same aspg_try_advisory_lock, except it attempts to acquire a shared rather than an exclusive lock.

pg_advisory_unlock will release a previously-acquired exclusive session level advisory lock. It returnstrue if the lock is successfully released. If the lock was not held, it will returnfalse, and in addition, an SQL warning will be reported by the server.

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

pg_advisory_unlock_all will release all session level advisory locks held by the current session. (This function is implicitly invoked at session end, even if the client disconnects ungracefully.)

pg_advisory_xact_lock works the same aspg_advisory_lock, except the lock is automatically released at the end of the current transaction and cannot be released explicitly.

pg_advisory_xact_lock_shared works the same aspg_advisory_lock_shared, except the lock is automatically released at the end of the current transaction and cannot be released explicitly.

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

pg_try_advisory_xact_lock_shared works the same aspg_try_advisory_lock_shared, except the lock, if acquired, is automatically released at the end of the current transaction and cannot be released explicitly.


Prev Up Next
9.25. System Information Functions and Operators Home 9.27. Trigger Functions
epubpdf
Go to PostgreSQL 12
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp