package com.sunxung.factoring.component.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SqlScriptUtil {

    private static Logger log = LogManager.getLogger(SqlScriptUtil.class);

    /** 解析sql脚本文件 */
    public static List<String> parseSqlFile(InputStream inputStream) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        StringBuffer sqlSb = new StringBuffer();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            if (!str.startsWith("/*!") && !str.startsWith("--") && str.indexOf("/*") <= 0 && str.trim().length() > 0) {
                sqlSb.append("\n" + str);
            }
        }
        inputStream.close();
        bufferedReader.close();
        String[] sqls = sqlSb.toString().split(";");
        List<String> sqlList = new ArrayList<String>();
        for (int i = 0; i < sqls.length; i++) {
            sqlList.add(sqls[i]);
        }
        return sqlList;
    }

    /** 批量执行sql */
    public static void executeBatchSql(List<String> sqls, Connection conn) throws SQLException {
        conn.setAutoCommit(false);
        Statement statement = conn.createStatement();
        try {
            int i = 0, len = sqls.size();
            for (; i < len; i++) {
                if (!StringUtil.isEmpty(sqls.get(i))) {
                    statement.addBatch(sqls.get(i));
                    if (i % 50 == 0 && i > 0) {
                        statement.executeBatch();
                        statement.clearBatch();
                    }
                }
            }
            if (len % 50 != 0) {
                statement.executeBatch();
            }
            conn.commit();
        } catch (SQLException e) {
            log.error("异常信息", e);
            conn.rollback();
            throw e;
        } finally {
            statement.close();
        }
    }
}
