package com.huatek.busi.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;

/**
 * 动态创建表结构工具类
 */
@Slf4j
public class DynamicCreateTable {

    /**
     * 动态创建表结构
     * @param jdbcTemplate
     * @param tableName
     * @param sqlSplice
     * @param dropSqlSplice
     * @return
     */
    public static int operateObject(JdbcTemplate jdbcTemplate, String tableName, String sqlSplice, String dropSqlSplice){
        int re = 0;
        try {
            if(getAllTableName(jdbcTemplate, tableName)){
                re = operateTable(jdbcTemplate, dropSqlSplice);
            }
            re = operateTable(jdbcTemplate, sqlSplice);
        } catch (Exception e) {
            log.error("<<<<<<<<<<<<动态创建表结构异常>>>>>>>>>>>>>>：{}", e.getMessage());
        }
        return re;
    }

    /**
     * 查询数据库是否有某表
     * @param jdbcTemplate
     * @param tableName
     * @return
     * @throws Exception
     */
    private static boolean getAllTableName(JdbcTemplate jdbcTemplate, String tableName) throws Exception {
        Connection conn = jdbcTemplate.getDataSource().getConnection();
        ResultSet tabs = null;
        try {
            DatabaseMetaData dbMetaData = conn.getMetaData();
            String[] types = { "TABLE" };
            tabs = dbMetaData.getTables(null, null, tableName, types);
            if (tabs.next()) {
                return true;
            }
        } catch (Exception e) {
            log.error("<<<<<<<<<<<<验证表结构异常>>>>>>>>>>>>>>：{}", e.getMessage());
        }finally{
            tabs.close();
            conn.close();
        }
        return false;
    }

    /**
     * 操作表结构
     * @param jdbcTemplate
     * @param sql
     * @return
     */
    private static int operateTable(JdbcTemplate jdbcTemplate, String sql){
        try {
            jdbcTemplate.update(sql);
            return 1;
        } catch (Exception e) {
            log.error("<<<<<<<<<<<<操作表结构异常>>>>>>>>>>>>>>：{}", e.getMessage());
        }
        return 0;
    }
}
