/*
 * cm_rankfx_dbio.pgc - cm 모듈 DB 접근 함수 (cm_rankfx_dbio), archived into libcmdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 기준일별 최고환율(랭크1) 통화 수 (ROW_NUMBER 윈도우 커서).
 */
#include <string.h>
#include <userlog.h>
#include "cm_rankfx_dbio.h"

long cmdb_rank_fx(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ccy[8];
    long h_rn, tops = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE crk CURSOR FOR
        SELECT ccy,
               ROW_NUMBER() OVER (PARTITION BY base_date ORDER BY rate_bps DESC)
        FROM cm_fx_rate WHERE base_date = :h_bizdate;
    EXEC SQL OPEN crk;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH crk INTO :h_ccy, :h_rn;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE crk; return -1; }
        if (h_rn == 1) tops++;
    }
    EXEC SQL CLOSE crk;
    return tops;
}
