Debian Codegraph @

src/main/org/h2/expression/function/ConcatFunction.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.expression.function;
7
8 import org.h2.engine.SessionLocal;
9 import org.h2.expression.Expression;
10 import org.h2.expression.TypedValueExpression;
11 import org.h2.value.DataType;
12 import org.h2.value.TypeInfo;
13 import org.h2.value.Value;
14 import org.h2.value.ValueNull;
15 import org.h2.value.ValueVarchar;
16
17 /**
18 * A CONCAT or CONCAT_WS function.
19 */
20 public final class ConcatFunction extends FunctionN {
21
22 /**
23 * CONCAT() (non-standard).
24 */
25 public static final int CONCAT = 0;
26
27 /**
28 * CONCAT_WS() (non-standard).
29 */
30 public static final int CONCAT_WS = CONCAT + 1;
31
32 private static final String[] NAMES = { //
33 "CONCAT", "CONCAT_WS" //
34 };
35
36 private final int function;
37
38 public ConcatFunction(int function) {
39 this(function, new Expression[4]);
40 }
41
42 public ConcatFunction(int function, Expression... args) {
43 super(args);
44 this.function = function;
45 }
46
47 @Override
48 public Value getValue(SessionLocal session) {
49 int i = 0;
50 String separator = null;
51 if (function == CONCAT_WS) {
52 i = 1;
53 separator = args[0].getValue(session).getString();
54 }
55 StringBuilder builder = new StringBuilder();
56 boolean f = false;
57 for (int l = args.length; i < l; i++) {
58 Value v = args[i].getValue(session);
59 if (v != ValueNull.INSTANCE) {
60 if (separator != null) {
61 if (f) {
62 builder.append(separator);
63 }
64 f = true;
65 }
66 builder.append(v.getString());
67 }
68 }
69 return ValueVarchar.get(builder.toString(), session);
70 }
71
72 @Override
73 public Expression optimize(SessionLocal session) {
74 boolean allConst = optimizeArguments(session, true);
75 int i = 0;
76 long extra = 0L;
77 if (function == CONCAT_WS) {
78 i = 1;
79 extra = getPrecision(0);
80 }
81 long precision = 0L;
82 int l = args.length;
83 boolean f = false;
84 for (; i < l; i++) {
85 if (args[i].isNullConstant()) {
86 continue;
87 }
88 precision = DataType.addPrecision(precision, getPrecision(i));
89 if (extra != 0L && f) {
90 precision = DataType.addPrecision(precision, extra);
91 }
92 f = true;
93 }
94 type = TypeInfo.getTypeInfo(Value.VARCHAR, precision, 0, null);
95 if (allConst) {
96 return TypedValueExpression.getTypedIfNull(getValue(session), type);
97 }
98 return this;
99 }
100
101 private long getPrecision(int i) {
102 TypeInfo t = args[i].getType();
103 int valueType = t.getValueType();
104 if (valueType == Value.NULL) {
105 return 0L;
106 } else if (DataType.isCharacterStringType(valueType)) {
107 return t.getPrecision();
108 } else {
109 return Long.MAX_VALUE;
110 }
111 }
112
113 @Override
114 public String getName() {
115 return NAMES[function];
116 }
117
118 }