我的目标是生成一个报告,显示在特定模式下 PostgreSQL 数据库中每天/每月保存的记录数。
到目前为止,我有一些类似字节的东西,大小(MB)不算数,总和
SELECT
table_schema || '.' || table_name AS table_full_name,
pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) AS size
FROM information_schema.tables
where table_schema = 'public'
ORDER BY
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC;
是否有生成此类报告的解决方案:
桌名 | 计数 | 数据 |
---|---|---|
福 | 312 | 30-03-2023 |
福 | 111 | 29-03-2023 |
酒吧 | 312 | 30-03-2023 |
酒吧 | 344 | 29-03-2023 |
如果你有能力获得近似计数(由 stuff like
vacuum analyze
statements 维护),那么你可以使用这样的查询:
create view table_stat as
select format('%I.%I', n.nspname, c.relname) "table name",
reltuples "count",
pg_size_pretty(pg_total_relation_size(c.oid)) "size",
now()::date "date"
from pg_class c
join pg_namespace n on c.relnamespace = n.oid
where n.nspname = 'public'
and c.relkind in ('r', 'm', 'p')
order by 3 desc;
然后创建一个表一次并插入第一批:
create table stat_history as select * from table_stat;
然后在 cron 或其他东西中,附加新数据:
insert into stat_history select * from table_stat;
然后,显示结果的最终查询:
select * from table_stat -- where "whatever you want";
注意使用
或format('%I')
以始终正确转义双引号。quote_ident()
否则,您将需要使用动态查询,使用 plpgsql 之类的东西: