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.CollectionUtil;
021import com.mybatisflex.core.util.StringUtil;
022
023import java.util.List;
024
025public class DistinctQueryColumn extends QueryColumn {
026
027    private List<QueryColumn> queryColumns;
028
029    public DistinctQueryColumn(QueryColumn... queryColumns) {
030        this.queryColumns = CollectionUtil.newArrayList(queryColumns);
031    }
032
033    @Override
034    public String toSelectSql(List<QueryTable> queryTables, IDialect dialect) {
035        if (CollectionUtil.isEmpty(queryTables)) {
036            return SqlConsts.EMPTY;
037        }
038
039        String sql = SqlConsts.DISTINCT + StringUtil.join(SqlConsts.DELIMITER, queryColumns, queryColumn ->
040            queryColumn.toSelectSql(queryTables, dialect));
041
042        return sql + WrapperUtil.buildColumnAlias(alias, dialect);
043    }
044
045
046    @Override
047    String toConditionSql(List<QueryTable> queryTables, IDialect dialect) {
048        if (CollectionUtil.isEmpty(queryTables)) {
049            return SqlConsts.EMPTY;
050        }
051
052        return SqlConsts.DISTINCT + StringUtil.join(SqlConsts.DELIMITER, queryColumns, queryColumn ->
053            queryColumn.toSelectSql(queryTables, dialect));
054
055    }
056
057    @Override
058    public DistinctQueryColumn clone() {
059        DistinctQueryColumn clone = (DistinctQueryColumn) super.clone();
060        // deep clone ...
061        clone.queryColumns = CollectionUtil.cloneArrayList(this.queryColumns);
062        return clone;
063    }
064
065}