package com.qiaoba.common.database.interceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.qiaoba.common.base.context.BaseContext;
import com.qiaoba.common.database.context.TenantDbTypeContext;
import com.qiaoba.common.database.properties.TenantSchema;
import com.qiaoba.common.database.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * SchemaInterceptor
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023-04-25 22:48:43
 */
@Slf4j
public class SchemaInterceptor implements InnerInterceptor {

    @Override
    public void beforePrepare(StatementHandler sh, Connection conn, Integer transactionTimeout) {

        // SCHEMA 模式
        if (Objects.nonNull(BaseContext.isSchemaMode()) && BaseContext.isSchemaMode()) {
            try {
                DbUtil.setSchema(TenantDbTypeContext.getDefault(), conn, TenantSchema.getSchema(BaseContext.getTenantId()));
            } catch (SQLException e) {
                log.error("切换SCHEMA失败, 原因: {}", e.getMessage());
            }
        }
    }


}
