/*
 * Repeated small updates followed by analyze on large tables
 * causes pg_class.reltuples to grow.
 */

-- test is scaled to stats target * 1000000 rows 
\set scale 10
\set update_frac 0.10
\set iterations 10

\set ECHO all
\set QUIET on

set default_statistics_target = :scale ;
set work_mem = '512MB';
set maintenance_work_mem = '1GB';

begin;
-- table is padded to get reasonable number of rows per page
create table reltuples_test as
select id,
       id % 10 as ten, id % 100 as hun, id % 10000 as thou,
       id % 10000 as tenk, id %100000 as lahk, id % 1000000 as meg,
       'some extra padding to adjust rowsize' as padding
  from generate_series(1::bigint, (:scale * 1000000)::bigint) g(id);

-- avoid extranous vacuums and analyzes and add primary key
alter table reltuples_test
  set (autovacuum_enabled = false),
  add constraint reltuples_test_pkey primary key (id);
commit;

-- vacuum verbose reltuples_test;
analyze verbose reltuples_test;

\echo "-- Starting Status --"
select relpages, reltuples,
       (reltuples/relpages)::int as rows_per_page,
       relname
  from pg_class where relname ~ '^reltuples_test';
\echo
-- Update 1% of table at a time for :iterations.
-- Note: bug is that reltuples increases with each iteration.
select format('update reltuples_test set id = id + %s where id < %s',
              :scale * 1000000, n * :scale * 1000000 * :update_frac)
       as update_query,
       'analyze verbose reltuples_test' as estimate
  from generate_series(1, :iterations) g(n)
\gexec

-- final  reltuples and rows per page
\echo "-- Post Test Status --"
select relpages, reltuples,
       (reltuples/relpages)::int as rows_per_page,
       relname
  from pg_class where relname ~ '^reltuples_test';

