/*
 * cm_levelgroup_dbio.pgc - cm 모듈 DB 접근 함수 (cm_levelgroup_dbio), archived into libcmdbio.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 "cm_levelgroup_dbio.h"

long cmdb_level_groups(const char *bizdate, long minc)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_lvl[4];
    long h_min, 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 clg CURSOR FOR
        SELECT log_level, count(*) FROM cm_log
        WHERE biz_date = :h_bizdate
        GROUP BY log_level HAVING count(*) >= :h_min;
    EXEC SQL OPEN clg;
    if (sqlca.sqlcode < 0) { userlog("cmdb_level_groups OPEN [%d]", sqlca.sqlcode); return -1; }
    for (;;) {
        EXEC SQL FETCH clg INTO :h_lvl, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE clg; return -1; }
        groups++;
    }
    EXEC SQL CLOSE clg;
    return groups;
}
