View Javadoc
1   /*
2    * Copyright 2021 TiKV Project Authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  
18  package org.tikv.common.expression;
19  
20  import static java.util.Objects.requireNonNull;
21  
22  import com.google.common.base.Joiner;
23  import com.google.common.collect.ImmutableList;
24  import java.util.List;
25  import java.util.Objects;
26  import org.tikv.common.types.DataType;
27  
28  public class AggregateFunction extends Expression {
29    private final FunctionType type;
30    private final Expression argument;
31  
32    private AggregateFunction(FunctionType type, Expression argument, DataType dataType) {
33      super(dataType);
34      this.type = requireNonNull(type, "function type is null");
35      this.argument = requireNonNull(argument, "function argument is null");
36    }
37  
38    public static AggregateFunction newCall(FunctionType type, Expression argument) {
39      return newCall(type, argument, argument.dataType);
40    }
41  
42    public static AggregateFunction newCall(
43        FunctionType type, Expression argument, DataType dataType) {
44      return new AggregateFunction(type, argument, dataType);
45    }
46  
47    public FunctionType getType() {
48      return type;
49    }
50  
51    public Expression getArgument() {
52      return argument;
53    }
54  
55    @Override
56    public List<Expression> getChildren() {
57      return ImmutableList.of(argument);
58    }
59  
60    @Override
61    public <R, C> R accept(Visitor<R, C> visitor, C context) {
62      return visitor.visit(this, context);
63    }
64  
65    @Override
66    public boolean equals(Object other) {
67      if (this == other) {
68        return true;
69      }
70      if (!(other instanceof AggregateFunction)) {
71        return false;
72      }
73  
74      AggregateFunction that = (AggregateFunction) other;
75      return type == that.type && Objects.equals(argument, that.argument);
76    }
77  
78    @Override
79    public int hashCode() {
80      return Objects.hash(type, argument);
81    }
82  
83    @Override
84    public String toString() {
85      return String.format(
86          "%s(%s)", getType(), Joiner.on(",").useForNull("NULL").join(getChildren()));
87    }
88  
89    public enum FunctionType {
90      Sum,
91      Count,
92      Min,
93      Max,
94      First
95    }
96  }