#!/bin/bash

killall -9 postgres

# Setup Postgres
rm -rf /tmp/data
initdb -D /tmp/data
cat <<EOL >> /tmp/data/postgresql.conf
logging_collector = on
log_min_messages = debug1
log_min_error_statement = debug1
#log_line_prefix = '%m [%p]: [%l-1] db=%d,user=%u,app=%a,client=%h '
recovery_prefetch = off
EOL
pg_ctl start -D /tmp/data
createdb $USER

psql  <<EOL
CREATE TABLE aa (a int);
CHECKPOINT;
INSERT INTO aa VALUES (1);
-- Generate enough records to trigger the OOM counter in xlogreader.c.
DO \$\$
BEGIN
  FOR i IN 1..1000 LOOP
    EXECUTE 'SELECT pg_logical_emit_message(true, ''foo'', ''bar'');';
  END LOOP;
END; \$\$;
INSERT INTO aa VALUES (2);
SELECT pg_current_wal_lsn();
EOL

# Force OOM at recovery.
killall -9 postgres
touch /tmp/xlogreader_oom
# Startup bumps on OOM, succeeds earlier, but it should not.
pg_ctl start -D /tmp/data
# This loses some data, only one record is returned..
psql -c 'table aa'
rm /tmp/xlogreader_oom
