package com.qiaoba.common.database.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.enums.DataBaseEnum;
import com.qiaoba.common.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * JdbcUtil
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@Slf4j
public class JdbcUtil {

    /**
     * 检查数据源是否可以连接
     *
     * @param driver   数据库驱动
     * @param url      url
     * @param username 用户名
     * @param password 密码
     * @return true = 是
     */
    public static boolean checkConnect(String driver, String url, String username, String password) {
        Connection conn = null;
        try {
            Class.forName(driver);
            //建立连接
            conn = DriverManager.getConnection(url, username, password);
            return true;
        } catch (Exception e) {
            log.debug(e.getMessage());
            return false;
        } finally {
            IoUtil.close(conn);
        }
    }

    /**
     * 检查数据源连接可用性
     *
     * @param conn 数据源
     * @return 结果
     */
    public static boolean checkConnect(Connection conn) {
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            // 允许 2s 延时
            stmt.setQueryTimeout(2);
            rs = stmt.executeQuery(DataBaseEnum.getCheckSql(conn.getMetaData().getDatabaseProductName()));
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            IoUtil.close(rs);
            IoUtil.close(stmt);
        }
    }

    public static Connection getConnection(String driver, String url, String username, String password) {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            throw new ServiceException(StrUtil.format("数据源连接失败,错误: {}", e.getMessage()));
        }
    }

    public static Connection connection(String driver, String url, String username, String password) throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

}
