How to get the free disk space in PostgreSQL (PostgreSQL获取磁盘空间)

Posted eshizhan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了How to get the free disk space in PostgreSQL (PostgreSQL获取磁盘空间)相关的知识,希望对你有一定的参考价值。

Get the current free disk space in PostgreSQL

PostgreSQL获取磁盘空间

Here has a simple way to get free disk space without any extended language, just define a function using pgsql.

CREATE OR REPLACE FUNCTION sys_df() RETURNS SETOF text[]
LANGUAGE plpgsql $$
BEGIN
    CREATE TEMP TABLE IF NOT EXISTS tmp_sys_df (content text) ON COMMIT DROP;
    COPY tmp_sys_df FROM PROGRAM 'df | tail -n +2';
    RETURN QUERY SELECT regexp_split_to_array(content, '\s+') FROM tmp_sys_df;
END;
$$;

Usage:

select * from sys_df();
                      sys_df                               
-------------------------------------------------------------------
 overlay,15148428,6660248,7695656,46%,/
 overlay,15148428,6660248,7695656,46%,/
 tmpfs,65536,0,65536,0%,/dev
 tmpfs,768284,0,768284,0%,/sys/fs/cgroup
 /dev/sda2,15148428,6660248,7695656,46%,/etc/resolv.conf
 /dev/sda2,15148428,6660248,7695656,46%,/etc/hostname
 /dev/sda2,15148428,6660248,7695656,46%,/etc/hosts
 shm,65536,8,65528,0%,/dev/shm
 /dev/sda2,15148428,6660248,7695656,46%,/var/lib/postgresql/data
 tmpfs,65536,0,65536,0%,/proc/kcore
 tmpfs,65536,0,65536,0%,/proc/timer_list
 tmpfs,65536,0,65536,0%,/proc/sched_debug
 tmpfs,768284,0,768284,0%,/sys/firmware
(13 rows)

Using df $PGDATA | tail -n +2 instead of df | tail -n +2 while you saving all data in same path on disk. In this case, the function only return one row disk usage for $PGDATA path.

NOTE FOR SECURITY

PROGRAM can run any command by shell, it like two-edged sword. it is best to use a fixed command string, or at least avoid passing any user input in it. See detail on document.

PROGRAM可以运行任意的命令,所以最好是用固定字符串命令,尽量避免通过参数传入。

以上是关于How to get the free disk space in PostgreSQL (PostgreSQL获取磁盘空间)的主要内容,如果未能解决你的问题,请参考以下文章