package com.sunxung.factoring.start.impl;

import java.sql.Connection;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.core.io.ClassPathResource;

import com.sunxung.factoring.component.util.SpringUtil;
import com.sunxung.factoring.component.util.SqlScriptUtil;

/** 数据库初始化 */
public class DataBaseInit {

    public void run() throws Exception {
        String[] sqlNames = {
                "data/init/00001.sql", "data/init/00002.sql"
        };
        Connection connection = getMasterDataSource().getConnection();
        try {
            for (String sqlName : sqlNames) {
                List<String> sqls = SqlScriptUtil.parseSqlFile(new ClassPathResource(sqlName).getInputStream());
                if (sqls == null || sqls.isEmpty()) {
                    continue;
                }
                SqlScriptUtil.executeBatchSql(sqls, connection);
            }
        } finally {
            connection.close();
        }
    }

    private static DataSource masterDataSource;

    private static DataSource getMasterDataSource() {
        if (masterDataSource == null) {
            masterDataSource = (DataSource) SpringUtil.getBeanByName("masterDataSource");
        }
        return masterDataSource;
    }
}
