Debian Codegraph @

src/main/org/h2/expression/function/CardinalityExpression.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.util.MathUtils;
13 import org.h2.util.json.JSONArray;
14 import org.h2.util.json.JSONValue;
15 import org.h2.value.TypeInfo;
16 import org.h2.value.Value;
17 import org.h2.value.ValueArray;
18 import org.h2.value.ValueInteger;
19 import org.h2.value.ValueNull;
20
21 /**
22 * Cardinality expression.
23 */
24 public final class CardinalityExpression extends Function1 {
25
26 private final boolean max;
27
28 /**
29 * Creates new instance of cardinality expression.
30 *
31 * @param arg
32 * argument
33 * @param max
34 * {@code false} for {@code CARDINALITY}, {@code true} for
35 * {@code ARRAY_MAX_CARDINALITY}
36 */
37 public CardinalityExpression(Expression arg, boolean max) {
38 super(arg);
39 this.max = max;
40 }
41
42 @Override
43 public Value getValue(SessionLocal session) {
44 int result;
45 if (max) {
46 TypeInfo t = arg.getType();
47 if (t.getValueType() == Value.ARRAY) {
48 result = MathUtils.convertLongToInt(t.getPrecision());
49 } else {
50 throw DbException.getInvalidValueException("array", arg.getValue(session).getTraceSQL());
51 }
52 } else {
53 Value v = arg.getValue(session);
54 if (v == ValueNull.INSTANCE) {
55 return ValueNull.INSTANCE;
56 }
57 switch (v.getValueType()) {
58 case Value.JSON: {
59 JSONValue value = v.convertToAnyJson().getDecomposition();
60 if (value instanceof JSONArray) {
61 result = ((JSONArray) value).length();
62 } else {
63 return ValueNull.INSTANCE;
64 }
65 break;
66 }
67 case Value.ARRAY:
68 result = ((ValueArray) v).getList().length;
69 break;
70 default:
71 throw DbException.getInvalidValueException("array", v.getTraceSQL());
72 }
73 }
74 return ValueInteger.get(result);
75 }
76
77 @Override
78 public Expression optimize(SessionLocal session) {
79 arg = arg.optimize(session);
80 type = TypeInfo.TYPE_INTEGER;
81 if (arg.isConstant()) {
82 return TypedValueExpression.getTypedIfNull(getValue(session), type);
83 }
84 return this;
85 }
86
87 @Override
88 public String getName() {
89 return max ? "ARRAY_MAX_CARDINALITY" : "CARDINALITY";
90 }
91
92 }