/*
 * mm_grade_insert_sel_dbio.pgc - mm 모듈 DB 접근 함수 (mm_grade_insert_sel_dbio), archived into libmmdbio.a.
 * 등급별 가맹점 수 통계 일괄 적재 (INSERT..SELECT).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_grade_insert_sel_dbio.h"

/* 활성 가맹점을 등급별로 집계해 mm_grade_stat 에 한 문장으로 적재/갱신. */
long mmdb_grade_insert_sel(const char *statdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_date[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_date, statdate, sizeof(h_date)-1); h_date[sizeof(h_date)-1] = 0;
    EXEC SQL INSERT INTO mm_grade_stat (stat_date, grade, merch_cnt)
        SELECT :h_date, grade, count(*) FROM mm_merchant_ext
        WHERE status = 'ACTIVE' GROUP BY grade
        ON CONFLICT (stat_date, grade) DO UPDATE
        SET merch_cnt = EXCLUDED.merch_cnt, updated_at = now();
    if (sqlca.sqlcode < 0) { userlog("mmdb_grade_insert_sel FAIL [%d]", sqlca.sqlcode); return -1; }
    return (long) sqlca.sqlerrd[2];
}
