Debian Codegraph @

src/main/org/h2/expression/FieldReference.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;
7
8 import java.util.Map.Entry;
9
10 import org.h2.api.ErrorCode;
11 import org.h2.engine.SessionLocal;
12 import org.h2.message.DbException;
13 import org.h2.mvstore.db.Store;
14 import org.h2.util.ParserUtil;
15 import org.h2.util.json.JSONObject;
16 import org.h2.util.json.JSONValue;
17 import org.h2.value.ExtTypeInfoRow;
18 import org.h2.value.TypeInfo;
19 import org.h2.value.Value;
20 import org.h2.value.ValueJson;
21 import org.h2.value.ValueNull;
22 import org.h2.value.ValueRow;
23
24 /**
25 * Field reference.
26 */
27 public final class FieldReference extends Operation1 {
28
29 private final String fieldName;
30
31 private int ordinal;
32
33 public FieldReference(Expression arg, String fieldName) {
34 super(arg);
35 this.fieldName = fieldName;
36 }
37
38 @Override
39 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
40 return ParserUtil.quoteIdentifier(arg.getEnclosedSQL(builder, sqlFlags).append('.'), fieldName, sqlFlags);
41 }
42
43 @Override
44 public Value getValue(SessionLocal session) {
45 Value l = arg.getValue(session);
46 if (l != ValueNull.INSTANCE) {
47 if (ordinal >= 0) {
48 return ((ValueRow) l).getList()[ordinal];
49 } else {
50 JSONValue value = l.convertToAnyJson().getDecomposition();
51 if (value instanceof JSONObject) {
52 JSONValue jsonValue = ((JSONObject) value).getFirst(fieldName);
53 if (jsonValue != null) {
54 return ValueJson.fromJson(jsonValue);
55 }
56 }
57 }
58 }
59 return ValueNull.INSTANCE;
60 }
61
62 @Override
63 public Expression optimize(SessionLocal session) {
64 arg = arg.optimize(session);
65 TypeInfo type = arg.getType();
66 int valueType = type.getValueType();
67 c: switch (valueType) {
68 case Value.JSON: {
69 this.type = TypeInfo.TYPE_JSON;
70 this.ordinal = -1;
71 break;
72 }
73 case Value.ROW: {
74 int ordinal = 0;
75 for (Entry<String, TypeInfo> entry : ((ExtTypeInfoRow) type.getExtTypeInfo()).getFields()) {
76 if (fieldName.equals(entry.getKey())) {
77 type = entry.getValue();
78 this.type = type;
79 this.ordinal = ordinal;
80 break c;
81 }
82 ordinal++;
83 }
84 throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, fieldName);
85 }
86 default:
87 throw Store.getInvalidExpressionTypeException("JSON | ROW", arg);
88 }
89 if (arg.isConstant()) {
90 return TypedValueExpression.get(getValue(session), type);
91 }
92 return this;
93 }
94
95 }