/*
 * vl_refinteg_batch.pgc - 참조무결성(가맹점 orphan) 검사 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; the 검증 SELECT/집계 runs on that branch, then tpcommit drives XA 2PC.
 * Usage: vl_refinteg_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"

int main(int argc, char **argv)
{
    long rows = 0; (void)rows; (void)argc; (void)argv;

    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt;
    EXEC SQL END DECLARE SECTION;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL SELECT count(*) INTO :h_cnt FROM purchase p
        WHERE NOT EXISTS (SELECT 1 FROM merchant m WHERE m.merchant_id = p.merchant_id);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_refinteg_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_refinteg_batch COMMIT: orphan=%ld\n", h_cnt);

    tpclose(); tpterm();
    return 0;
}
