PostgreSQL每月/每日数据库增长

anhgbhbe  于 2023-03-17  发布在  PostgreSQL
关注(0)|答案(2)|浏览(345)

我的目标是生成一个报告,显示在特定模式下PostgreSQL数据库中每天/每月保存的记录数。
到目前为止,我有一些类似的字节与大小(MB)不计数和与overal总和

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;

是否有生成此类报告的解决方案:
| 表格名称|计数|资料|
| - ------|- ------|- ------|
| 富|三一二|二○二三年三月三十日|
| 富|一百一十一|二○二三年三月二十九日|
| 棒|三一二|二○二三年三月三十日|
| 棒|三四四|二○二三年三月二十九日|

x7rlezfr

x7rlezfr1#

如果您可以获得近似计数(由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;

然后创建一个表once并插入第一批:

create table stat_history as select * from table_stat;

然后在cron或别的什么东西中,添加新数据:

insert into stat_history select * from table_stat;

然后,最后查询显示结果:

select * from stat_history -- where "whatever you want";

请注意,使用format('%I')quote_ident()始终可以正确转义双引号。
否则,您将需要使用动态查询,使用plpgsql,例如:

  • 网址:https://www.postgresql.org/docs/15/plpgsql-control-structures.html#id-1.8.8.8.3.4
  • execute format('…'),如www.example.com中的示例https://www.postgresql.org/docs/15/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING
deyfvvtc

deyfvvtc2#

查看pg_stat_all_tables系统视图:

create table test as select 1 AS a;

select n_tup_ins,n_tup_upd,n_tup_del,n_tup_hot_upd,n_live_tup,n_dead_tup 
from pg_stat_all_tables where schemaname='public' and relname='test';
-- n_tup_ins | n_tup_upd | n_tup_del | n_tup_hot_upd | n_live_tup | n_dead_tup
-------------+-----------+-----------+---------------+------------+------------
--         1 |         0 |         0 |             0 |          1 |          0

insert into test select 2; 
insert into test select 3; 
delete from test where a=1; 
update test set a=5 where a=2;

select n_tup_ins,n_tup_upd,n_tup_del,n_tup_hot_upd,n_live_tup,n_dead_tup 
from pg_stat_all_tables where schemaname='public' and relname='test';
-- n_tup_ins | n_tup_upd | n_tup_del | n_tup_hot_upd | n_live_tup | n_dead_tup
-------------+-----------+-----------+---------------+------------+------------
--         3 |         1 |         1 |             1 |          2 |          2

您可以使用cronpg_cron每天对此视图进行快照,以便不仅监视估计的行数,还监视导致该行数的流量。
要实时查看所有流量,您可以使用pg_recvlogical接入logical streaming replication protocol

相关问题