/*
 * cm_codefxjoin_dbio.pgc - cm 모듈 DB 접근 함수 (cm_codefxjoin_dbio), archived into libcmdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 통화코드와 환율을 조인한 코드그룹별 합계 그룹 수 (JOIN + GROUP BY 커서).
 */
#include <string.h>
#include <userlog.h>
#include "cm_codefxjoin_dbio.h"

long cmdb_code_fx_groups(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_grp[16];
    long h_sum, groups = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE cfg CURSOR FOR
        SELECT c.code_grp, coalesce(sum(f.rate_bps),0)
        FROM cm_code c JOIN cm_fx_rate f ON f.ccy = c.code
        WHERE c.code_grp = 'CCY' AND f.base_date = :h_bizdate
        GROUP BY c.code_grp;
    EXEC SQL OPEN cfg;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH cfg INTO :h_grp, :h_sum;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cfg; return -1; }
        groups++;
    }
    EXEC SQL CLOSE cfg;
    return groups;
}
