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 */
016package com.mybatisflex.core.query;
017
018import com.mybatisflex.core.constant.SqlConsts;
019import com.mybatisflex.core.dialect.IDialect;
020import com.mybatisflex.core.util.StringUtil;
021
022import java.util.List;
023
024/**
025 * 原生条件。
026 *
027 * @author michael
028 * @author 王帅
029 */
030public class RawQueryCondition extends QueryCondition {
031
032    protected String content;
033
034    public RawQueryCondition(String content) {
035        this.content = content;
036    }
037
038    public RawQueryCondition(String content, Object... paras) {
039        this.content = content;
040        this.setValue(paras);
041    }
042
043    @Override
044    boolean containsTable(String... tables) {
045        for (String table : tables) {
046            String[] tableNameWithAlias = StringUtil.getTableNameWithAlias(table);
047            if (content.contains(tableNameWithAlias[0])
048                || (tableNameWithAlias[1] != null && content.contains(tableNameWithAlias[1]))) {
049                return true;
050            }
051        }
052        return false;
053    }
054
055    @Override
056    public String toSql(List<QueryTable> queryTables, IDialect dialect) {
057        StringBuilder sql = new StringBuilder();
058
059        //检测是否生效
060        if (checkEffective()) {
061            QueryCondition prevEffectiveCondition = getPrevEffectiveCondition();
062            if (prevEffectiveCondition != null && this.connector != null) {
063                sql.append(this.connector);
064            }
065            sql.append(SqlConsts.BLANK).append(content).append(SqlConsts.BLANK);
066        }
067
068        if (this.next != null) {
069            return sql + next.toSql(queryTables, dialect);
070        }
071
072        return sql.toString();
073    }
074
075    @Override
076    public String toString() {
077        return "RawQueryCondition{" +
078            "content='" + content + '\'' +
079            '}';
080    }
081
082    public String getContent() {
083        return content;
084    }
085
086    @Override
087    public RawQueryCondition clone() {
088        return (RawQueryCondition) super.clone();
089    }
090
091}