Debian Codegraph @

src/main/org/h2/expression/function/MathFunction.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 java.math.BigDecimal;
9 import java.math.RoundingMode;
10
11 import org.h2.api.ErrorCode;
12 import org.h2.engine.SessionLocal;
13 import org.h2.expression.Expression;
14 import org.h2.expression.TypedValueExpression;
15 import org.h2.message.DbException;
16 import org.h2.mvstore.db.Store;
17 import org.h2.value.DataType;
18 import org.h2.value.TypeInfo;
19 import org.h2.value.Value;
20 import org.h2.value.ValueBigint;
21 import org.h2.value.ValueDecfloat;
22 import org.h2.value.ValueDouble;
23 import org.h2.value.ValueInteger;
24 import org.h2.value.ValueNull;
25 import org.h2.value.ValueNumeric;
26 import org.h2.value.ValueReal;
27
28 /**
29 * A math function.
30 */
31 public final class MathFunction extends Function1_2 {
32
33 /**
34 * ABS().
35 */
36 public static final int ABS = 0;
37
38 /**
39 * MOD().
40 */
41 public static final int MOD = ABS + 1;
42
43 /**
44 * FLOOR().
45 */
46 public static final int FLOOR = MOD + 1;
47
48 /**
49 * CEIL() or CEILING().
50 */
51 public static final int CEIL = FLOOR + 1;
52
53 /**
54 * ROUND() (non-standard)
55 */
56 public static final int ROUND = CEIL + 1;
57
58 /**
59 * ROUNDMAGIC() (non-standard)
60 */
61 public static final int ROUNDMAGIC = ROUND + 1;
62
63 /**
64 * SIGN() (non-standard)
65 */
66 public static final int SIGN = ROUNDMAGIC + 1;
67
68 /**
69 * TRUNC() (non-standard)
70 */
71 public static final int TRUNC = SIGN + 1;
72
73 private static final String[] NAMES = { //
74 "ABS", "MOD", "FLOOR", "CEIL", "ROUND", "ROUNDMAGIC", "SIGN", "TRUNC" //
75 };
76
77 private final int function;
78
79 private TypeInfo commonType;
80
81 public MathFunction(Expression arg1, Expression arg2, int function) {
82 super(arg1, arg2);
83 this.function = function;
84 }
85
86 @Override
87 public Value getValue(SessionLocal session, Value v1, Value v2) {
88 switch (function) {
89 case ABS:
90 if (v1.getSignum() < 0) {
91 v1 = v1.negate();
92 }
93 break;
94 case MOD:
95 v1 = v1.convertTo(commonType, session).modulus(v2.convertTo(commonType, session)).convertTo(type, session);
96 break;
97 case FLOOR:
98 v1 = round(v1, v2, RoundingMode.FLOOR);
99 break;
100 case CEIL:
101 v1 = round(v1, v2, RoundingMode.CEILING);
102 break;
103 case ROUND:
104 v1 = round(v1, v2, RoundingMode.HALF_UP);
105 break;
106 case ROUNDMAGIC:
107 v1 = ValueDouble.get(roundMagic(v1.getDouble()));
108 break;
109 case SIGN:
110 v1 = ValueInteger.get(v1.getSignum());
111 break;
112 case TRUNC:
113 v1 = round(v1, v2, RoundingMode.DOWN);
114 break;
115 default:
116 throw DbException.getInternalError("function=" + function);
117 }
118 return v1;
119 }
120
121 @SuppressWarnings("incomplete-switch")
122 private Value round(Value v1, Value v2, RoundingMode roundingMode) {
123 int scale = v2 != null ? v2.getInt() : 0;
124 int t = type.getValueType();
125 c: switch (t) {
126 case Value.TINYINT:
127 case Value.SMALLINT:
128 case Value.INTEGER:
129 case Value.BIGINT: {
130 if (scale < 0) {
131 long original = v1.getLong();
132 long scaled = BigDecimal.valueOf(original).setScale(scale, roundingMode).longValue();
133 if (original != scaled) {
134 v1 = ValueBigint.get(scaled).convertTo(type);
135 }
136 }
137 break;
138 }
139 case Value.NUMERIC: {
140 int targetScale = type.getScale();
141 BigDecimal bd = v1.getBigDecimal();
142 if (scale < targetScale) {
143 bd = bd.setScale(scale, roundingMode);
144 }
145 v1 = ValueNumeric.get(bd.setScale(targetScale, roundingMode));
146 break;
147 }
148 case Value.REAL:
149 case Value.DOUBLE: {
150 l: if (scale == 0) {
151 double d;
152 switch (roundingMode) {
153 case DOWN:
154 d = v1.getDouble();
155 d = d < 0 ? Math.ceil(d) : Math.floor(d);
156 break;
157 case CEILING:
158 d = Math.ceil(v1.getDouble());
159 break;
160 case FLOOR:
161 d = Math.floor(v1.getDouble());
162 break;
163 default:
164 break l;
165 }
166 v1 = t == Value.REAL ? ValueReal.get((float) d) : ValueDouble.get(d);
167 break c;
168 }
169 BigDecimal bd = v1.getBigDecimal().setScale(scale, roundingMode);
170 v1 = t == Value.REAL ? ValueReal.get(bd.floatValue()) : ValueDouble.get(bd.doubleValue());
171 break;
172 }
173 case Value.DECFLOAT:
174 v1 = ValueDecfloat.get(v1.getBigDecimal().setScale(scale, roundingMode));
175 }
176 return v1;
177 }
178
179 private static double roundMagic(double d) {
180 if ((d < 0.000_000_000_000_1) && (d > -0.000_000_000_000_1)) {
181 return 0.0;
182 }
183 if ((d > 1_000_000_000_000d) || (d < -1_000_000_000_000d)) {
184 return d;
185 }
186 StringBuilder s = new StringBuilder();
187 s.append(d);
188 if (s.toString().indexOf('E') >= 0) {
189 return d;
190 }
191 int len = s.length();
192 if (len < 16) {
193 return d;
194 }
195 if (s.toString().indexOf('.') > len - 3) {
196 return d;
197 }
198 s.delete(len - 2, len);
199 len -= 2;
200 char c1 = s.charAt(len - 2);
201 char c2 = s.charAt(len - 3);
202 char c3 = s.charAt(len - 4);
203 if ((c1 == '0') && (c2 == '0') && (c3 == '0')) {
204 s.setCharAt(len - 1, '0');
205 } else if ((c1 == '9') && (c2 == '9') && (c3 == '9')) {
206 s.setCharAt(len - 1, '9');
207 s.append('9');
208 s.append('9');
209 s.append('9');
210 }
211 return Double.parseDouble(s.toString());
212 }
213
214 @Override
215 public Expression optimize(SessionLocal session) {
216 left = left.optimize(session);
217 if (right != null) {
218 right = right.optimize(session);
219 }
220 switch (function) {
221 case ABS:
222 type = left.getType();
223 if (type.getValueType() == Value.NULL) {
224 type = TypeInfo.TYPE_NUMERIC_FLOATING_POINT;
225 }
226 break;
227 case FLOOR:
228 case CEIL: {
229 Expression e = optimizeRound(0, true, false, true);
230 if (e != null) {
231 return e;
232 }
233 break;
234 }
235 case MOD:
236 TypeInfo divisorType = right.getType();
237 commonType = TypeInfo.getHigherType(left.getType(), divisorType);
238 int valueType = commonType.getValueType();
239 if (valueType == Value.NULL) {
240 commonType = TypeInfo.TYPE_BIGINT;
241 } else if (!DataType.isNumericType(valueType)) {
242 throw Store.getInvalidExpressionTypeException("MOD argument",
243 DataType.isNumericType(left.getType().getValueType()) ? right : left);
244 }
245 type = DataType.isNumericType(divisorType.getValueType()) ? divisorType : commonType;
246 break;
247 case ROUND: {
248 Expression e = optimizeRoundWithScale(session, true);
249 if (e != null) {
250 return e;
251 }
252 break;
253 }
254 case ROUNDMAGIC:
255 type = TypeInfo.TYPE_DOUBLE;
256 break;
257 case SIGN:
258 type = TypeInfo.TYPE_INTEGER;
259 break;
260 case TRUNC:
261 switch (left.getType().getValueType()) {
262 case Value.VARCHAR:
263 left = new CastSpecification(left, TypeInfo.getTypeInfo(Value.TIMESTAMP, -1L, 0, null))
264 .optimize(session);
265 //$FALL-THROUGH$
266 case Value.TIMESTAMP:
267 case Value.TIMESTAMP_TZ:
268 if (right != null) {
269 throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, "TRUNC", "1");
270 }
271 return new DateTimeFunction(DateTimeFunction.DATE_TRUNC, DateTimeFunction.DAY, left, null)
272 .optimize(session);
273 case Value.DATE:
274 if (right != null) {
275 throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, "TRUNC", "1");
276 }
277 return new CastSpecification(left, TypeInfo.getTypeInfo(Value.TIMESTAMP, -1L, 0, null))
278 .optimize(session);
279 default: {
280 Expression e = optimizeRoundWithScale(session, false);
281 if (e != null) {
282 return e;
283 }
284 }
285 }
286 break;
287 default:
288 throw DbException.getInternalError("function=" + function);
289 }
290 if (left.isConstant() && (right == null || right.isConstant())) {
291 return TypedValueExpression.getTypedIfNull(getValue(session), type);
292 }
293 return this;
294 }
295
296 private Expression optimizeRoundWithScale(SessionLocal session, boolean possibleRoundUp) {
297 int scale;
298 boolean scaleIsKnown = false, scaleIsNull = false;
299 if (right != null) {
300 if (right.isConstant()) {
301 Value scaleValue = right.getValue(session);
302 scaleIsKnown = true;
303 if (scaleValue != ValueNull.INSTANCE) {
304 scale = scaleValue.getInt();
305 } else {
306 scale = -1;
307 scaleIsNull = true;
308 }
309 } else {
310 scale = -1;
311 }
312 } else {
313 scale = 0;
314 scaleIsKnown = true;
315 }
316 return optimizeRound(scale, scaleIsKnown, scaleIsNull, possibleRoundUp);
317 }
318
319 /**
320 * Optimizes rounding and truncation functions.
321 *
322 * @param scale
323 * the scale, if known
324 * @param scaleIsKnown
325 * whether scale is known
326 * @param scaleIsNull
327 * whether scale is {@code NULL}
328 * @param possibleRoundUp
329 * {@code true} if result of rounding can have larger precision
330 * than precision of argument, {@code false} otherwise
331 * @return the optimized expression or {@code null} if this function should
332 * be used
333 */
334 private Expression optimizeRound(int scale, boolean scaleIsKnown, boolean scaleIsNull, boolean possibleRoundUp) {
335 TypeInfo leftType = left.getType();
336 switch (leftType.getValueType()) {
337 case Value.NULL:
338 type = TypeInfo.TYPE_NUMERIC_SCALE_0;
339 break;
340 case Value.TINYINT:
341 case Value.SMALLINT:
342 case Value.INTEGER:
343 case Value.BIGINT:
344 if (scaleIsKnown && scale >= 0) {
345 return left;
346 }
347 type = leftType;
348 break;
349 case Value.REAL:
350 case Value.DOUBLE:
351 case Value.DECFLOAT:
352 type = leftType;
353 break;
354 case Value.NUMERIC: {
355 long precision;
356 int originalScale = leftType.getScale();
357 if (scaleIsKnown) {
358 if (originalScale <= scale) {
359 return left;
360 } else {
361 if (scale < 0) {
362 scale = 0;
363 } else if (scale > ValueNumeric.MAXIMUM_SCALE) {
364 scale = ValueNumeric.MAXIMUM_SCALE;
365 }
366 precision = leftType.getPrecision() - originalScale + scale;
367 if (possibleRoundUp) {
368 precision++;
369 }
370 }
371 } else {
372 precision = leftType.getPrecision();
373 if (possibleRoundUp) {
374 precision++;
375 }
376 scale = originalScale;
377 }
378 type = TypeInfo.getTypeInfo(Value.NUMERIC, precision, scale, null);
379 break;
380 }
381 default:
382 throw Store.getInvalidExpressionTypeException(getName() + " argument", left);
383 }
384 if (scaleIsNull) {
385 return TypedValueExpression.get(ValueNull.INSTANCE, type);
386 }
387 return null;
388 }
389
390 @Override
391 public String getName() {
392 return NAMES[function];
393 }
394
395 }