package com.bytesw.bytebot.etl.batch.mapper;

import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class DynaBeanRowMapper<T> implements RowMapper<T> {

    @Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        DynaBean bean = new DynaBean();
        int columnCount = rsmd.getColumnCount();

        for (int i = 1; i <= columnCount; i++) {
            String column = JdbcUtils.lookupColumnName(rsmd, i);
            bean.putIfAbsent(column, JdbcUtils.getResultSetValue(rs, i));
        }

        return (T) bean;
    }
}
