package cn.web.init;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import cn.util.core.LogKit;

import javax.sql.DataSource;

/**
 * 启动执行sql脚本文件 见注解
 * */
@Configuration
public class DBInitializer 
{
	@Value("${sam.init.db.scheme}")
	private boolean db_scheme;
	@Value("${sam.init.db.data}")
	private boolean db_data;

    @Value("classpath:config/database/script/schema.sql")
    private Resource sqlScriptSchema;
    @Value("classpath:config/database/script/data.sql")
    private Resource sqlScriptData;
 
    /*@Value("classpath:sql/procedure.sql")
    private Resource sqlScriptProcedure;
    @Value("classpath:sql/function.sql")
    private Resource sqlScriptFunction;
	*/
    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource ds)
    {
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(ds);
       	dataSourceInitializer.setDatabasePopulator(databasePopulator());
       	return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator()
    {
    	LogKit.info("执行SQL脚本！");
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        if(db_scheme) {
        	populator.addScript(sqlScriptSchema);
        }
        if(db_data) {
        	populator.addScript(sqlScriptData);
        }
       // populator.addScript(sqlScriptProcedure);
      //  populator.addScript(sqlScriptFunction); 
       // populator.setSeparator("$$$"); // 分隔符，默认为;
        
        /**自动生成实体类文件*/
        // QuickVOStart.run();
        
        return populator;
    }
    
}
