PostgreSQL 的 pg_stat_file 函数
PostgreSQL 的 pg_stat_file 函数
pg_stat_file
是 PostgreSQL 提供的一个系统管理函数,用于获取文件系统上文件的元数据信息。这个函数对于数据库管理员进行文件级别的监控和诊断非常有用。
一 函数基本语法
pg_stat_file(filename text [, missing_ok boolean ])
RETURNS record
参数说明
filename
:要检查的文件路径(相对于 PostgreSQL 数据目录)missing_ok
:可选参数,设置为 true 时如果文件不存在不会报错(默认为 false)
返回字段
函数返回包含以下字段的记录:
size
:文件大小(字节)access
:最后访问时间(timestamp with time zone)modification
:最后修改时间(timestamp with time zone)change
:最后状态变更时间(timestamp with time zone)creation
:创建时间(timestamp with time zone,仅在Windows平台上可用)isdir
:是否为目录(boolean)
二 使用示例
2.1 基本用法
SELECT * FROM pg_stat_file('postgresql.conf');
输出示例:
white=# SELECT * FROM pg_stat_file('postgresql.conf');size | access | modification | change | creation | isdir
-------+------------------------+------------------------+------------------------+----------+-------30105 | 2025-05-03 18:23:16-07 | 2025-04-27 02:22:21-07 | 2025-04-27 02:22:21-07 | | f
(1 row)
2.2 查看特定字段
SELECT size, modification AS last_modified,pg_size_pretty(size) AS size_pretty
FROM pg_stat_file('postgresql.conf');
输出示例:
white=# SELECT
white-# size,
white-# modification AS last_modified,
white-# pg_size_pretty(size) AS size_pretty
white-# FROM pg_stat_file('postgresql.conf');size | last_modified | size_pretty
-------+------------------------+-------------30105 | 2025-04-27 02:22:21-07 | 29 kB
(1 row)
2.3 检查目录信息
SELECT * FROM pg_stat_file('base') WHERE isdir;
输出示例:
white=# SELECT * FROM pg_stat_file('base') WHERE isdir;size | access | modification | change | creation | isdir
------+------------------------+------------------------+------------------------+----------+-------102 | 2025-05-03 18:23:16-07 | 2024-08-19 20:27:11-07 | 2024-08-19 20:27:11-07 | | t
(1 row)
2. 4 安全使用(避免文件不存在的错误)
SELECT * FROM pg_stat_file('nonexistent_file', true);
输出示例:
white=# SELECT * FROM pg_stat_file('nonexistent_file', true);size | access | modification | change | creation | isdir
------+--------+--------------+--------+----------+-------| | | | |
(1 row)
三 权限要求
- 需要超级用户权限或具有
pg_read_server_files
角色的用户 - 只能访问数据库集群目录下的文件(不能访问任意系统文件)
四 注意事项
-
路径限制:
- 路径必须是相对于 PostgreSQL 数据目录的
- 不能包含
..
或绝对路径(安全限制)
-
平台差异:
creation
时间在 Linux 上通常不可用(返回 NULL)- 在 Windows 上可以获取创建时间
-
性能影响:
- 频繁调用可能影响性能
- 不适合在高频查询中使用
-
替代方案:
- 对于数据库对象,优先使用
pg_stat_*
系统视图 - 对于日志文件,考虑使用
pg_read_file
函数
- 对于数据库对象,优先使用
更详细的内容请查看官方文档:<9.27.9. Generic File Access Functions>
https://www.postgresql.org/docs/16/functions-admin.html
谨记:心存敬畏,行有所止。