| 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.ValueBigint; |
| 15 |
import org.h2.value.ValueNull; |
| 16 |
|
| 17 |
/** |
| 18 |
* CHAR_LENGTH(), or OCTET_LENGTH() function. |
| 19 |
*/ |
| 20 |
public final class LengthFunction extends Function1 { |
| 21 |
|
| 22 |
/** |
| 23 |
* CHAR_LENGTH(). |
| 24 |
*/ |
| 25 |
public static final int CHAR_LENGTH = 0; |
| 26 |
|
| 27 |
/** |
| 28 |
* OCTET_LENGTH(). |
| 29 |
*/ |
| 30 |
public static final int OCTET_LENGTH = CHAR_LENGTH + 1; |
| 31 |
|
| 32 |
/** |
| 33 |
* BIT_LENGTH() (non-standard). |
| 34 |
*/ |
| 35 |
public static final int BIT_LENGTH = OCTET_LENGTH + 1; |
| 36 |
|
| 37 |
private static final String[] NAMES = { // |
| 38 |
"CHAR_LENGTH", "OCTET_LENGTH", "BIT_LENGTH" // |
| 39 |
}; |
| 40 |
|
| 41 |
private final int function; |
| 42 |
|
| 43 |
public LengthFunction(Expression arg, int function) { |
| 44 |
super(arg); |
| 45 |
this.function = function; |
| 46 |
} |
| 47 |
|
| 48 |
@Override |
| 49 |
public Value getValue(SessionLocal session) { |
| 50 |
Value v = arg.getValue(session); |
| 51 |
if (v == ValueNull.INSTANCE) { |
| 52 |
return ValueNull.INSTANCE; |
| 53 |
} |
| 54 |
long l; |
| 55 |
switch (function) { |
| 56 |
case CHAR_LENGTH: |
| 57 |
l = v.charLength(); |
| 58 |
break; |
| 59 |
case OCTET_LENGTH: |
| 60 |
l = v.octetLength(); |
| 61 |
break; |
| 62 |
case BIT_LENGTH: |
| 63 |
l = v.octetLength() * 8; |
| 64 |
break; |
| 65 |
default: |
| 66 |
throw DbException.getInternalError("function=" + function); |
| 67 |
} |
| 68 |
return ValueBigint.get(l); |
| 69 |
} |
| 70 |
|
| 71 |
@Override |
| 72 |
public Expression optimize(SessionLocal session) { |
| 73 |
arg = arg.optimize(session); |
| 74 |
type = TypeInfo.TYPE_BIGINT; |
| 75 |
if (arg.isConstant()) { |
| 76 |
return TypedValueExpression.getTypedIfNull(getValue(session), type); |
| 77 |
} |
| 78 |
return this; |
| 79 |
} |
| 80 |
|
| 81 |
@Override |
| 82 |
public String getName() { |
| 83 |
return NAMES[function]; |
| 84 |
} |
| 85 |
|
| 86 |
} |