001/*
002 *  Copyright (c) 2022-2023, 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 * SQL 原生片段
026 */
027public class RawFragment extends QueryCondition {
028
029
030    protected String content;
031
032
033    public RawFragment(String content) {
034        this.content = content;
035    }
036
037    public RawFragment(String content, Object... paras) {
038        this.content = content;
039        this.setValue(paras);
040    }
041
042    @Override
043    boolean containsTable(String... tables) {
044        for (String table : tables) {
045            String[] tableNameWithAlisa = StringUtil.getTableNameWithAlisa(table);
046            if (content.contains(tableNameWithAlisa[0])
047                || (tableNameWithAlisa[1] != null && content.contains(tableNameWithAlisa[1]))) {
048                return true;
049            }
050        }
051        return false;
052    }
053
054    @Override
055    public String toSql(List<QueryTable> queryTables, IDialect dialect) {
056        StringBuilder sql = new StringBuilder();
057
058        //检测是否生效
059        if (checkEffective()) {
060            QueryCondition prevEffectiveCondition = getPrevEffectiveCondition();
061            if (prevEffectiveCondition != null) {
062                sql.append(prevEffectiveCondition.connector);
063            }
064            sql.append(SqlConsts.BLANK).append(content).append(SqlConsts.BLANK);
065        }
066
067        if (this.next != null) {
068            return sql + next.toSql(queryTables, dialect);
069        }
070
071        return sql.toString();
072    }
073
074    @Override
075    public RawFragment clone() {
076        return (RawFragment) super.clone();
077    }
078
079
080    public String getContent() {
081        return content;
082    }
083
084}