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.FlexConsts; 019import com.mybatisflex.core.dialect.IDialect; 020import com.mybatisflex.core.util.SqlUtil; 021import com.mybatisflex.core.util.StringUtil; 022 023import java.util.List; 024 025/** 026 * 数据库 聚合函数,例如 count(id) ,max(account.age) 等等 027 */ 028public class FunctionQueryColumn extends QueryColumn implements HasParamsColumn { 029 030 protected String fnName; 031 protected QueryColumn column; 032 033 public FunctionQueryColumn(String fnName, String column) { 034 SqlUtil.keepColumnSafely(fnName); 035 SqlUtil.keepColumnSafely(column); 036 this.fnName = fnName; 037 this.column = new QueryColumn(column); 038 } 039 040 public FunctionQueryColumn(String fnName, QueryColumn column) { 041 SqlUtil.keepColumnSafely(fnName); 042 this.fnName = fnName; 043 this.column = column; 044 } 045 046 public String getFnName() { 047 return fnName; 048 } 049 050 public void setFnName(String fnName) { 051 this.fnName = fnName; 052 } 053 054 public QueryColumn getColumn() { 055 return column; 056 } 057 058 public void setColumn(QueryColumn column) { 059 this.column = column; 060 } 061 062 @Override 063 public Object[] getParamValues() { 064 if (column instanceof HasParamsColumn) { 065 return ((HasParamsColumn) column).getParamValues(); 066 } 067 return FlexConsts.EMPTY_ARRAY; 068 } 069 070 @Override 071 public String toSelectSql(List<QueryTable> queryTables, IDialect dialect) { 072 String sql = column.toSelectSql(queryTables, dialect); 073 return StringUtil.isBlank(sql) ? "" : fnName + "(" + sql + ")" + WrapperUtil.buildAsAlias(alias, dialect); 074 } 075 076 @Override 077 public QueryColumn as(String alias) { 078 SqlUtil.keepColumnSafely(alias); 079 this.alias = alias; 080 return this; 081 } 082 083 @Override 084 public String toString() { 085 return "FunctionQueryColumn{" + 086 "fnName='" + fnName + '\'' + 087 ", column=" + column + 088 '}'; 089 } 090 091 092}