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 org.apache.ibatis.jdbc.ScriptRunner;
import org.postgresql.jdbc.PgConnection;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/28 8:52
 */
public class DbUtil {

    /**
     * PgSQL 查询 schema 是否存在
     */
    private static final String PGSQL_CHECK_SCHEMA_EXIST_SQL = "SELECT count(1) FROM information_schema.schemata WHERE schema_name = '{}'";


    public static void setSchema(String dbType, Connection conn, String schema) throws SQLException {

        if (DataBaseEnum.MY_SQL.getType().equals(dbType)) {
            conn.setSchema(schema);
        } else if (DataBaseEnum.POSTGRE_SQL.getType().equals(dbType)) {
            conn.unwrap(PgConnection.class).setSchema(schema);
        } else if (DataBaseEnum.SQL_SERVER.getType().equals(dbType)) {

        }
    }

    public static Boolean checkSchema(String dbType, Connection conn, String schema) throws Exception {
        if (DataBaseEnum.POSTGRE_SQL.getType().equals(dbType)) {
            Statement statement = null;
            try {
                statement = conn.createStatement();
                ResultSet resultSet = statement.executeQuery(StrUtil.format(PGSQL_CHECK_SCHEMA_EXIST_SQL, schema));
                resultSet.next();
                return resultSet.getInt(1) > 0;

            } finally {
                IoUtil.close(statement);
            }
        }

        return false;
    }

    public static void runScript(Connection conn, String filePath) throws IOException {
        ClassPathResource resource = new ClassPathResource(filePath);
        File file = resource.getFile();
        FileReader reader = new FileReader(file);
        ScriptRunner scriptRunner = new ScriptRunner(conn);
        scriptRunner.setSendFullScript(true);
        scriptRunner.runScript(reader);
        reader.close();
    }

    public static void runSql(Connection conn, String sql) throws SQLException {
        Statement statement = null;
        try {
            statement = conn.createStatement();
            statement.execute(sql);
        } finally {
            IoUtil.close(statement);
        }
    }

}
