Debian Codegraph @

src/main/org/h2/expression/Parameter.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 org.h2.api.ErrorCode;
9 import org.h2.engine.SessionLocal;
10 import org.h2.expression.condition.Comparison;
11 import org.h2.message.DbException;
12 import org.h2.table.Column;
13 import org.h2.value.TypeInfo;
14 import org.h2.value.Value;
15 import org.h2.value.ValueNull;
16 import org.h2.value.ValueVarchar;
17
18 /**
19 * A parameter of a prepared statement.
20 */
21 public final class Parameter extends Operation0 implements ParameterInterface {
22
23 private Value value;
24 private Column column;
25 private final int index;
26
27 public Parameter(int index) {
28 this.index = index;
29 }
30
31 @Override
32 public StringBuilder getUnenclosedSQL(StringBuilder builder, int sqlFlags) {
33 return builder.append('?').append(index + 1);
34 }
35
36 @Override
37 public void setValue(Value v, boolean closeOld) {
38 // don't need to close the old value as temporary files are anyway
39 // removed
40 this.value = v;
41 }
42
43 public void setValue(Value v) {
44 this.value = v;
45 }
46
47 @Override
48 public Value getParamValue() {
49 if (value == null) {
50 // to allow parameters in function tables
51 return ValueNull.INSTANCE;
52 }
53 return value;
54 }
55
56 @Override
57 public Value getValue(SessionLocal session) {
58 return getParamValue();
59 }
60
61 @Override
62 public TypeInfo getType() {
63 if (value != null) {
64 return value.getType();
65 }
66 if (column != null) {
67 return column.getType();
68 }
69 return TypeInfo.TYPE_UNKNOWN;
70 }
71
72 @Override
73 public void checkSet() {
74 if (value == null) {
75 throw DbException.get(ErrorCode.PARAMETER_NOT_SET_1, "#" + (index + 1));
76 }
77 }
78
79 @Override
80 public Expression optimize(SessionLocal session) {
81 if (session.getDatabase().getMode().treatEmptyStringsAsNull) {
82 if (value instanceof ValueVarchar && value.getString().isEmpty()) {
83 value = ValueNull.INSTANCE;
84 }
85 }
86 return this;
87 }
88
89 @Override
90 public boolean isValueSet() {
91 return value != null;
92 }
93
94 @Override
95 public boolean isEverything(ExpressionVisitor visitor) {
96 switch (visitor.getType()) {
97 case ExpressionVisitor.INDEPENDENT:
98 return value != null;
99 default:
100 return true;
101 }
102 }
103
104 @Override
105 public int getCost() {
106 return 0;
107 }
108
109 @Override
110 public Expression getNotIfPossible(SessionLocal session) {
111 return new Comparison(Comparison.EQUAL, this, ValueExpression.FALSE, false);
112 }
113
114 public void setColumn(Column column) {
115 this.column = column;
116 }
117
118 public int getIndex() {
119 return index;
120 }
121
122 }