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
謹記:心存敬畏,行有所止。