-- POs purged from LGDAT.POH. An incremental merge only deletes keys that are
-- present in staging, so a purged PO would sit in cms.poh / cms.poi forever;
-- this list drives the hooks below that remove them.
--
-- DQ0ACTN = '3' is the delete action (verified 2026-08-18: PO 618973's last log
-- event was an action 3 and the row is gone from POH). The NOT EXISTS is what
-- makes this exact rather than a guess about action ordering -- a PO number that
-- was deleted and later re-used is back in POH, so it drops out of the list on
-- its own, and hook 1 clears any tombstone left from an earlier run.
--
-- DQ0TMSP is CHAR(26) 'YYYY-MM-DD-HH.MM.SS.ffffff', so the watermark compare is
-- lexical, and POHL has a timestamp-only logical (POHLX1) to range-scan it.
SELECT
  l."DQ0PO#" AS "dq0po#",
  MAX(l.DQ0TMSP) AS dq0tmsp
FROM LGDAT.POHL l
WHERE l.DQ0ACTN = '3'
  AND l.DQ0TMSP >= '{poh_deleted_wm}'
  AND NOT EXISTS (SELECT 1 FROM LGDAT.POH p WHERE p."KAPO#" = l."DQ0PO#")
GROUP BY l."DQ0PO#"
