dropdb --if-exists stats_src
createdb stats_src

psql -X -v ON_ERROR_STOP=1 stats_src <<'SQL'
CREATE SCHEMA s1;

CREATE TABLE s1.t AS
  SELECT g AS a, g % 10 AS b
  FROM generate_series(1, 1000) AS g;

-- Expression index, so pg_statistic has index attribute stats to dump.
CREATE INDEX idx_expr ON s1.t ((a + 1));

ANALYZE s1.t;
SQL

pg_dump --statistics -Fc -f /tmp/stats.dump stats_src

pg_restore --statistics -n s1 --index idx_expr \
  -f /tmp/archive-index-with-stats.sql /tmp/stats.dump

pg_restore --statistics-only -n s1 --index idx_expr \
  -f /tmp/archive-index-stats-only.sql /tmp/stats.dump

echo 'archive TOC:'
pg_restore --list /tmp/stats.dump | grep -E 'INDEX|STATISTICS DATA'

echo 'pg_restore --statistics --index idx_expr:'
grep -E 'CREATE INDEX|pg_restore_(relation|attribute)_stats' \
  /tmp/archive-index-with-stats.sql

echo 'pg_restore --statistics-only --index idx_expr:'
grep -E 'CREATE INDEX|pg_restore_(relation|attribute)_stats' \
  /tmp/archive-index-stats-only.sql

