/*
 * cl_snap_insert_sel_dbio.pgc - cl 모듈 DB 접근 함수 (cl_snap_insert_sel_dbio), archived into libcldbio.a.
 * merchant_summary 로부터 스냅샷 일괄 적재 (INSERT..SELECT).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "cl_snap_insert_sel_dbio.h"

/* 당일 merchant_summary 를 스냅샷으로 한 문장에 적재, 적재건수 반환. */
long cldb_snap_insert_sel(long cid, long sid_base, const char *period, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cid = cid, h_base = sid_base;
    char h_period[16], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_period, period, sizeof(h_period)-1); h_period[sizeof(h_period)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL INSERT INTO cl_snapshot
        (snapshot_id, close_id, period_key, biz_date, merchant_id,
         gross_amount, fee_amount, net_amount, txn_count)
        SELECT :h_base + row_number() OVER (ORDER BY merchant_id),
               :h_cid, :h_period, :h_bizdate, merchant_id,
               gross_amount, fee_amount, net_amount, txn_count
        FROM merchant_summary WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("cldb_snap_insert_sel FAIL [%d]", sqlca.sqlcode); return -1; }
    return (long) sqlca.sqlerrd[2];
}
