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.exception.FlexExceptions;
021import com.mybatisflex.core.util.ObjectUtil;
022
023public class UnionWrapper implements CloneSupport<UnionWrapper> {
024
025    private String key;
026    private QueryWrapper queryWrapper;
027
028    static UnionWrapper union(QueryWrapper queryWrapper) {
029        UnionWrapper unionWrapper = new UnionWrapper();
030        unionWrapper.key = SqlConsts.UNION;
031        unionWrapper.queryWrapper = queryWrapper;
032        return unionWrapper;
033    }
034
035    static UnionWrapper unionAll(QueryWrapper queryWrapper) {
036        UnionWrapper unionWrapper = new UnionWrapper();
037        unionWrapper.key = SqlConsts.UNION_ALL;
038        unionWrapper.queryWrapper = queryWrapper;
039        return unionWrapper;
040    }
041
042
043    private UnionWrapper() {
044    }
045
046    public String getKey() {
047        return key;
048    }
049
050    public void setKey(String key) {
051        this.key = key;
052    }
053
054    public QueryWrapper getQueryWrapper() {
055        return queryWrapper;
056    }
057
058    public void setQueryWrapper(QueryWrapper queryWrapper) {
059        this.queryWrapper = queryWrapper;
060    }
061
062    public void buildSql(StringBuilder sqlBuilder, IDialect dialect) {
063        sqlBuilder.append(key)
064            .append(SqlConsts.BRACKET_LEFT)
065            .append(dialect.buildSelectSql(queryWrapper))
066            .append(SqlConsts.BRACKET_RIGHT);
067    }
068
069    @Override
070    public UnionWrapper clone() {
071        try {
072            UnionWrapper clone = (UnionWrapper) super.clone();
073            // deep clone ...
074            clone.queryWrapper = ObjectUtil.clone(this.queryWrapper);
075            return clone;
076        } catch (CloneNotSupportedException e) {
077            throw FlexExceptions.wrap(e);
078        }
079    }
080
081}