package com.qiaoba.common.database.handlers.schema;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * MysqlSchemaHandler
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/20 9:25
 */
@Component
@Slf4j
public class MysqlSchemaHandler implements SchemaHandler {

    @Value("${spring.application.name}")
    private String baseDatabase;
    private static final String MYSQL_CHANGE_SCHEMA_SQL = "alter session set current_schema = {}";


    @Override
    public void setSchema(Connection conn) {
        // eg: use qiaoba-1;
        String sql = StrUtil.format("use `{}-{}`;", baseDatabase, BaseContext.getTenantId());
        log.debug("Run MysqlSchemaHandler, Sql: {}", sql);
        Statement statement = null;
        try {
            statement = conn.createStatement();
            statement.execute(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(statement);
        }
    }
}
