Debian Codegraph @

src/main/org/h2/expression/function/CoalesceFunction.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.ValueNull;
15
16 /**
17 * A COALESCE, GREATEST, or LEAST function.
18 */
19 public final class CoalesceFunction extends FunctionN {
20
21 /**
22 * COALESCE().
23 */
24 public static final int COALESCE = 0;
25
26 /**
27 * GREATEST() (non-standard).
28 */
29 public static final int GREATEST = COALESCE + 1;
30
31 /**
32 * LEAST() (non-standard).
33 */
34 public static final int LEAST = GREATEST + 1;
35
36 private static final String[] NAMES = { //
37 "COALESCE", "GREATEST", "LEAST" //
38 };
39
40 private final int function;
41
42 public CoalesceFunction(int function) {
43 this(function, new Expression[4]);
44 }
45
46 public CoalesceFunction(int function, Expression... args) {
47 super(args);
48 this.function = function;
49 }
50
51 @Override
52 public Value getValue(SessionLocal session) {
53 Value v = ValueNull.INSTANCE;
54 switch (function) {
55 case COALESCE: {
56 for (int i = 0, l = args.length; i < l; i++) {
57 Value v2 = args[i].getValue(session);
58 if (v2 != ValueNull.INSTANCE) {
59 v = v2.convertTo(type, session);
60 break;
61 }
62 }
63 break;
64 }
65 case GREATEST:
66 case LEAST: {
67 for (int i = 0, l = args.length; i < l; i++) {
68 Value v2 = args[i].getValue(session);
69 if (v2 != ValueNull.INSTANCE) {
70 v2 = v2.convertTo(type, session);
71 if (v == ValueNull.INSTANCE) {
72 v = v2;
73 } else {
74 int comp = session.compareTypeSafe(v, v2);
75 if (function == GREATEST) {
76 if (comp < 0) {
77 v = v2;
78 }
79 } else if (comp > 0) {
80 v = v2;
81 }
82 }
83 }
84 }
85 break;
86 }
87 default:
88 throw DbException.getInternalError("function=" + function);
89 }
90 return v;
91 }
92
93 @Override
94 public Expression optimize(SessionLocal session) {
95 boolean allConst = optimizeArguments(session, true);
96 type = TypeInfo.getHigherType(args);
97 if (type.getValueType() <= Value.NULL) {
98 type = TypeInfo.TYPE_VARCHAR;
99 }
100 if (allConst) {
101 return TypedValueExpression.getTypedIfNull(getValue(session), type);
102 }
103 return this;
104 }
105
106 @Override
107 public String getName() {
108 return NAMES[function];
109 }
110
111 }