#!/bin/sh
psql -X "$@" <<'EOF'
-- WAL files to generate before and after the DELETE.
\set wal_files 10

CREATE EXTENSION pg_walinspect;

-- Keep the WAL files in pg_wal for this session.
SELECT pg_create_physical_replication_slot('keep_wal', true, true);

-- No checkpoint by WAL size or by time while this is run.
ALTER SYSTEM SET max_wal_size = '100GB';
ALTER SYSTEM SET checkpoint_timeout = '1h';
SELECT pg_reload_conf();

-- A checkpoint, WAL files, the DELETE, more WAL files.
CREATE TABLE t (id int);
CHECKPOINT;
INSERT INTO t SELECT i FROM generate_series(1, :wal_files) i
WHERE pg_switch_wal() IS NOT NULL;
DELETE FROM t WHERE id = 1;
INSERT INTO t SELECT i FROM generate_series(1, :wal_files) i
WHERE pg_switch_wal() IS NOT NULL;

-- Start from the last checkpoint.
SELECT redo_lsn AS from_lsn FROM pg_control_checkpoint() \gset

-- Or start from the oldest WAL kept in pg_wal, here by the slot.
SELECT restart_lsn AS from_lsn FROM pg_replication_slots
WHERE slot_name = 'keep_wal' \gset

-- Size of a WAL file.
SELECT pg_size_bytes(current_setting('wal_segment_size')) AS seg \gset

-- First DELETE on table t from there.
SELECT start_lsn AS lsn, pg_walfile_name(start_lsn) AS wal_file, xid
FROM pg_get_wal_records_info(:'from_lsn', pg_current_wal_flush_lsn())
WHERE record_type = 'DELETE'
  AND block_ref LIKE '%/' || pg_relation_filenode('t') || ' %'
ORDER BY start_lsn LIMIT 1 \gset

-- Commit time of its transaction.
SELECT split_part(description, ';', 1) AS ts
FROM pg_get_wal_records_info(:'lsn', pg_current_wal_flush_lsn())
WHERE record_type = 'COMMIT' AND xid = :'xid' \gset
\echo lsn :lsn wal_file :wal_file xid :xid ts :ts

-- Start of its WAL file.
SELECT :'lsn'::pg_lsn - file_offset AS file_lsn
FROM pg_walfile_name_offset(:'lsn') \gset

-- Move backward, from the start of the WAL file before it.
SELECT start_lsn, xid, record_type, block_ref, description
FROM pg_get_wal_records_info(:'file_lsn'::pg_lsn - :seg, :'lsn');

-- Move forward, one WAL file from it.
SELECT start_lsn, xid, record_type, block_ref, description
FROM pg_get_wal_records_info(:'lsn', :'lsn'::pg_lsn + :seg);

-- Move in time, the commits within this much of its commit time.
\set move_time '60 minute'
SELECT start_lsn, pg_walfile_name(start_lsn) AS wal_file, xid,
       description
FROM pg_get_wal_records_info(:'from_lsn', pg_current_wal_flush_lsn())
WHERE record_type = 'COMMIT'
  AND split_part(description, ';', 1)::timestamptz
      BETWEEN :'ts'::timestamptz - :'move_time'::interval
          AND :'ts'::timestamptz + :'move_time'::interval;
EOF
