package com.qiaoba.common.base.utils;

import cn.hutool.core.convert.Convert;
import com.qiaoba.common.base.context.BaseContext;
import com.qiaoba.common.base.enums.DataBaseEnum;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据库工具类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/22 16:41
 */
@Slf4j
public class DatabaseUtil {

    /**
     * 根据数据库类型，处理find_in_set函数
     *
     * @param var1 参数1
     * @param var2 参数2
     * @return 处理后的sql
     */
    public static String handleFindInSet(Object var1, String var2) {
        DataBaseEnum dataBaseType = DataBaseEnum.find(BaseContext.getDatabaseType());
        String var = Convert.toStr(var1);
        if (dataBaseType == DataBaseEnum.SQL_SERVER) {
            // charindex(',100,' , ',0,100,101,') <> 0
            return "charindex('," + var + ",' , ','+" + var2 + "+',') <> 0";
        } else if (dataBaseType == DataBaseEnum.POSTGRE_SQL) {
            // (select position(',100,' in ',0,100,101,')) <> 0
            return "(select position('," + var + ",' in ','||" + var2 + "||',')) <> 0";
        } else if (dataBaseType == DataBaseEnum.ORACLE) {
            // instr(',0,100,101,' , ',100,') <> 0
            return "instr(','||" + var2 + "||',' , '," + var + ",') <> 0";
        }
        // find_in_set(100 , '0,100,101')
        return "find_in_set(" + var + " , " + var2 + ") <> 0";
    }
}
