/*
 * cl_corr_sub_dbio.pgc - cl 모듈 DB 접근 함수 (cl_corr_sub_dbio), archived into libcldbio.a.
 * 마감별 스냅샷 수 상관 서브쿼리 순회 최대치 (correlated subquery + cursor).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "cl_corr_sub_dbio.h"

/* 각 마감의 스냅샷 수를 상관 서브쿼리로 뽑아 커서로 훑어 최대값 반환. */
long clqdb_corr_max_snap(const char *ctype)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_type[16];
    long h_cid, h_snaps;
    EXEC SQL END DECLARE SECTION;
    long peak = 0;
    strncpy(h_type, ctype, sizeof(h_type)-1); h_type[sizeof(h_type)-1] = 0;
    EXEC SQL DECLARE ccs CURSOR FOR
        SELECT c.close_id,
               (SELECT count(*) FROM cl_snapshot s WHERE s.close_id = c.close_id)
        FROM cl_close_log c WHERE c.close_type = :h_type AND c.status <> 'X'
        ORDER BY c.close_id;
    EXEC SQL OPEN ccs;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH ccs INTO :h_cid, :h_snaps;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ccs; return -1; }
        if (h_snaps > peak) peak = h_snaps;
    }
    EXEC SQL CLOSE ccs;
    return peak;
}
