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.dialect.IDialect;
019import com.mybatisflex.core.util.SqlUtil;
020import com.mybatisflex.core.util.StringUtil;
021
022import java.util.Arrays;
023import java.util.List;
024
025/**
026 * 数据库 聚合函数,例如 CONVERT(NVARCHAR(30), GETDATE(), 126) 等等
027 */
028public class StringFunctionQueryColumn extends QueryColumn {
029
030    protected String fnName;
031    protected List<String> params;
032
033    public StringFunctionQueryColumn(String fnName, String... params) {
034        SqlUtil.keepColumnSafely(fnName);
035        this.fnName = fnName;
036        this.params = Arrays.asList(params);
037    }
038
039
040    public String getFnName() {
041        return fnName;
042    }
043
044    public void setFnName(String fnName) {
045        this.fnName = fnName;
046    }
047
048
049    public List<String> getParams() {
050        return params;
051    }
052
053    public void setParams(List<String> params) {
054        this.params = params;
055    }
056
057    @Override
058    public String toSelectSql(List<QueryTable> queryTables, IDialect dialect) {
059        String sql = StringUtil.join(", ", params);
060        return StringUtil.isBlank(sql) ? "" : fnName + "(" + sql + ")" + WrapperUtil.buildAsAlias(alias, dialect);
061    }
062
063    @Override
064    String toConditionSql(List<QueryTable> queryTables, IDialect dialect) {
065        String sql = StringUtil.join(", ", params);
066        return StringUtil.isBlank(sql) ? "" : fnName + "(" + sql + ")";
067    }
068
069    @Override
070    public QueryColumn as(String alias) {
071        SqlUtil.keepColumnSafely(alias);
072        this.alias = alias;
073        return this;
074    }
075
076    @Override
077    public String toString() {
078        return "StringFunctionQueryColumn{" +
079                "fnName='" + fnName + '\'' +
080                ", params=" + params +
081                '}';
082    }
083}