/*
 * py_ledger_mix_dbio.pgc - py 모듈 DB 접근 함수 세트 (py_ledger_mix_dbio), archived into libpydbio.a.
 * 지급원장 상세의 엔트리 종류 수와 OUT 금액을 count DISTINCT + FILTER 로 함께 구한다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "py_ledger_mix_dbio.h"

/* count DISTINCT + FILTER: 엔트리 종류 수와 OUT 합계 동시 산출. */
int pydb_ledger_type_mix(const char *bizdate, long *kinds_out, long *out_amt_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_kinds = 0, h_out = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT count(DISTINCT entry_type),
                    coalesce(sum(amount) FILTER (WHERE entry_type = 'OUT'), 0)
        INTO :h_kinds, :h_out FROM py_ledger WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("pydb_ledger_type_mix FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    *kinds_out = h_kinds; *out_amt_out = h_out;
    return 0;
}
