Sunday 13 November 2011

checking all the tables record count cluster level in postgres

create table:
--------------------
create table table_count(databasename name,schemaname name,relname name,reccount integer);

create function :
------------------------
create or replace function table_record_count() returns text as $$
declare
dbname1 name;
schemaname1 name;
relationname1 name;
tablecount integer;
r record;
r1 record;
done text default 'successes';
reccount integer;
stmt1 text;
stmt2 text;
stmt3 text;
begin
for r in select datname from pg_stat_database
loop
dbname1 :=r.datname;
CONTINUE WHEN dbname1='template0';
stmt1 :='select * from dblink('
|| ''''
|| 'dbname='
|| dbname1
|| ''''
|| ','
|| ''''
|| 'select schemaname,relname from pg_statio_user_tables'
|| ''''
|| ') as t1(schemaname name,relname name)'
|| ';';
for r1 in execute stmt1
loop
schemaname1 :=r1.schemaname;
relationname1 :=r1.relname;
CONTINUE WHEN  relationname1 is null or schemaname1='_shadow';
stmt2 := 'select * from dblink('
||''''
|| 'dbname='
||dbname1
||''''
||','
||''''
||'select count(*) from  '
|| schemaname1
|| '.'
||relationname1
|| ''''
||') as t2(reccount integer)'
|| ';' ;
execute stmt2 into reccount;
stmt3 := 'insert into table_count(databasename,schemaname,relname,reccount) values ('
|| ''''
||dbname1
|| ''''
|| ','
|| ''''
|| schemaname1
|| ''''
|| ','
|| ''''
||relationname1
|| ''''
|| ','
|| reccount
|| ')'
|| ';' ;
execute stmt3;
end loop;
end loop;
return done;
end;
$$ language plpgsql;

No comments:

Post a Comment