/*
 * vl_errgroup_dbio.pgc - vl 모듈 DB 접근 함수 (vl_errgroup_dbio), archived into libvldbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 임계 이상 반복된 검증 에러코드 그룹 수 (GROUP BY HAVING 커서).
 */
#include <string.h>
#include <userlog.h>
#include "vl_errgroup_dbio.h"

/* 반복 임계(minc) 이상 발생한 에러코드(result_code) 그룹 수를 커서로 집계. */
long vldb_err_group_over(const char *bizdate, long minc)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_min, h_rc, h_cnt, groups = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    h_min = minc;
    EXEC SQL DECLARE veg CURSOR FOR
        SELECT result_code, count(*) FROM vl_check_log
        WHERE biz_date = :h_bizdate AND result_code > 0
        GROUP BY result_code HAVING count(*) >= :h_min;
    EXEC SQL OPEN veg;
    if (sqlca.sqlcode < 0) { userlog("vldb_err_group_over OPEN [%d]", sqlca.sqlcode); return -1; }
    for (;;) {
        EXEC SQL FETCH veg INTO :h_rc, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE veg; return -1; }
        groups++;
    }
    EXEC SQL CLOSE veg;
    return groups;
}
