001/*
002 *  Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package com.mybatisflex.core.query;
018
019import com.mybatisflex.core.dialect.IDialect;
020import com.mybatisflex.core.util.ArrayUtil;
021
022import java.util.List;
023
024/**
025 * IF 函数查询列。
026 *
027 * @author 王帅
028 * @since 2023-07-07
029 */
030public class IfFunctionQueryColumn extends QueryColumn implements HasParamsColumn {
031
032    private QueryCondition condition;
033    private QueryColumn trueValue;
034    private QueryColumn falseValue;
035
036    public IfFunctionQueryColumn(QueryCondition condition, QueryColumn trueValue, QueryColumn falseValue) {
037        this.condition = condition;
038        this.trueValue = trueValue;
039        this.falseValue = falseValue;
040    }
041
042    @Override
043    String toConditionSql(List<QueryTable> queryTables, IDialect dialect) {
044        return "IF(" + condition.toSql(queryTables, dialect) + ", " +
045            trueValue.toConditionSql(queryTables, dialect) + ", " +
046            falseValue.toConditionSql(queryTables, dialect) + ")";
047    }
048
049    @Override
050    public Object[] getParamValues() {
051        Object[] params = WrapperUtil.getValues(condition);
052        // IF 函数嵌套
053        if (trueValue instanceof HasParamsColumn) {
054            Object[] paramValues = ((HasParamsColumn) trueValue).getParamValues();
055            params = ArrayUtil.concat(params, paramValues);
056        }
057        if (falseValue instanceof HasParamsColumn) {
058            Object[] paramValues = ((HasParamsColumn) falseValue).getParamValues();
059            params = ArrayUtil.concat(params, paramValues);
060        }
061        return params;
062    }
063
064    @Override
065    public IfFunctionQueryColumn clone() {
066        IfFunctionQueryColumn clone = (IfFunctionQueryColumn) super.clone();
067        // deep clone ...
068        clone.condition = this.condition.clone();
069        clone.trueValue = this.trueValue.clone();
070        clone.falseValue = this.falseValue.clone();
071        return clone;
072    }
073
074}