CREATE OR REPLACE PROCEDURE pg_recover_proc()
LANGUAGE plpgsql AS $$
DECLARE
	cnt BIGINT := 0;
BEGIN
	-- Get the maximum page_view_id from the page_views table
	cnt := (SELECT MAX(pgr_primary_key) FROM pgr_table);
	pgr_start_at

	-- Loop through the page_views table in reverse order by page_view_id
	LOOP
		pgr_skips

		BEGIN
			-- Insert the row with the current page_view_id into page_views2
			INSERT INTO pgr_table_recovery
			SELECT * FROM pgr_table WHERE pgr_primary_key = cnt and pgr_nonnull_col is not null;

			-- Decrement the counter
			cnt := cnt - 1;

			-- Exit the loop when cnt < 1
			EXIT WHEN cnt < 1;
		EXCEPTION
			WHEN OTHERS THEN
				-- Handle exceptions (e.g., data corruption)
				IF POSITION('block' in SQLERRM) > 0 OR POSITION('status of transaction' in SQLERRM) > 0 OR POSITION('memory alloc' in SQLERRM) > 0 OR POSITION('data is corrupt' in SQLERRM) > 0 OR POSITION('MultiXactId' in SQLERRM) > 0 THEN
					RAISE WARNING 'PGR_SKIP: %', cnt;
					cnt := cnt - 1;
					CONTINUE;
				ELSE
					RAISE;
				END IF;
			END;

		IF MOD(cnt, pgr_commit_size) = 0 THEN
			RAISE WARNING 'PGR_COMMIT: %', cnt;
			COMMIT;
		END IF;
	END LOOP;
END;
$$;
