Debian Codegraph @

src/main/org/h2/expression/function/MathFunction2.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.message.DbException;
12 import org.h2.value.TypeInfo;
13 import org.h2.value.Value;
14 import org.h2.value.ValueDouble;
15
16 /**
17 * A math function with two arguments and DOUBLE PRECISION result.
18 */
19 public final class MathFunction2 extends Function2 {
20
21 /**
22 * ATAN2() (non-standard).
23 */
24 public static final int ATAN2 = 0;
25
26 /**
27 * LOG().
28 */
29 public static final int LOG = ATAN2 + 1;
30
31 /**
32 * POWER().
33 */
34 public static final int POWER = LOG + 1;
35
36 private static final String[] NAMES = { //
37 "ATAN2", "LOG", "POWER" //
38 };
39
40 private final int function;
41
42 public MathFunction2(Expression arg1, Expression arg2, int function) {
43 super(arg1, arg2);
44 this.function = function;
45 }
46
47 @Override
48 public Value getValue(SessionLocal session, Value v1, Value v2) {
49 double d1 = v1.getDouble(), d2 = v2.getDouble();
50 switch (function) {
51 case ATAN2:
52 d1 = Math.atan2(d1, d2);
53 break;
54 case LOG: {
55 if (session.getMode().swapLogFunctionParameters) {
56 double t = d2;
57 d2 = d1;
58 d1 = t;
59 }
60 if (d2 <= 0) {
61 throw DbException.getInvalidValueException("LOG() argument", d2);
62 }
63 if (d1 <= 0 || d1 == 1) {
64 throw DbException.getInvalidValueException("LOG() base", d1);
65 }
66 if (d1 == Math.E) {
67 d1 = Math.log(d2);
68 } else if (d1 == 10d) {
69 d1 = Math.log10(d2);
70 } else {
71 d1 = Math.log(d2) / Math.log(d1);
72 }
73 break;
74 }
75 case POWER:
76 d1 = Math.pow(d1, d2);
77 break;
78 default:
79 throw DbException.getInternalError("function=" + function);
80 }
81 return ValueDouble.get(d1);
82 }
83
84 @Override
85 public Expression optimize(SessionLocal session) {
86 left = left.optimize(session);
87 right = right.optimize(session);
88 type = TypeInfo.TYPE_DOUBLE;
89 if (left.isConstant() && right.isConstant()) {
90 return TypedValueExpression.getTypedIfNull(getValue(session), type);
91 }
92 return this;
93 }
94
95 @Override
96 public String getName() {
97 return NAMES[function];
98 }
99
100 }