BEGIN;
SET LOCAL search_path TO adempiere, public;
SET CONSTRAINTS ALL IMMEDIATE;
DO $$
DECLARE
  tgt record; r record; det text; blockers text;
BEGIN
  FOR tgt IN
    SELECT * FROM (VALUES
      ('m_inout',    'ad_client_id=1000000'),
      ('c_order',    'ad_client_id=1000000'),
      ('c_invoice',  'ad_client_id=1000000'),
      ('c_payment',  'ad_client_id=1000000'),
      ('c_bpartner', 'ad_client_id=1000000 AND ad_org_id<>0'),
      ('m_product',  'ad_client_id=1000000'),
      ('ad_user',    'ad_client_id=1000000 AND c_bpartner_id IS NOT NULL'),
      ('pp_product_bomline', 'ad_client_id=1000000'),
      ('cust_fulfillmentproductpricingrules', 'ad_client_id=1000000'),
      ('ad_role',    'ad_org_id<>0 AND ad_client_id=1000000'),
      ('m_rma',      'ad_client_id=1000000'),
      ('ad_session', 'true'),
      ('m_warehouse','ad_org_id NOT IN (0,1000000) AND ad_client_id=1000000')
    ) v(tbl, cond)
  LOOP
    blockers := '';
    FOR r IN EXECUTE format('SELECT ctid AS rid FROM adempiere.%I WHERE %s LIMIT 8', tgt.tbl, tgt.cond) LOOP
      BEGIN
        EXECUTE format('DELETE FROM adempiere.%I WHERE ctid = $1', tgt.tbl) USING r.rid;
      EXCEPTION WHEN foreign_key_violation THEN
        GET STACKED DIAGNOSTICS det = PG_EXCEPTION_DETAIL;
        IF position(det in blockers) = 0 THEN
          blockers := blockers || ' | ' || det;
        END IF;
      END;
    END LOOP;
    RAISE NOTICE '%: %', tgt.tbl, COALESCE(NULLIF(blockers,''),'(deletable now)');
  END LOOP;
END $$;
ROLLBACK;
