use of org.h2.schema.Constant in project h2database by h2database.
the class Function method optimize.
@Override
public Expression optimize(Session session) {
boolean allConst = info.deterministic;
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
if (e == null) {
continue;
}
e = e.optimize(session);
args[i] = e;
if (!e.isConstant()) {
allConst = false;
}
}
int t, s, d;
long p;
Expression p0 = args.length < 1 ? null : args[0];
switch(info.type) {
case IFNULL:
case NULLIF:
case COALESCE:
case LEAST:
case GREATEST:
{
t = Value.UNKNOWN;
s = 0;
p = 0;
d = 0;
for (Expression e : args) {
if (e != ValueExpression.getNull()) {
int type = e.getType();
if (type != Value.UNKNOWN && type != Value.NULL) {
t = Value.getHigherOrder(t, type);
s = Math.max(s, e.getScale());
p = Math.max(p, e.getPrecision());
d = Math.max(d, e.getDisplaySize());
}
}
}
if (t == Value.UNKNOWN) {
t = Value.STRING;
s = 0;
p = Integer.MAX_VALUE;
d = Integer.MAX_VALUE;
}
break;
}
case CASE:
case DECODE:
{
t = Value.UNKNOWN;
s = 0;
p = 0;
d = 0;
// (expr, when, then, when, then, else)
for (int i = 2, len = args.length; i < len; i += 2) {
Expression then = args[i];
if (then != ValueExpression.getNull()) {
int type = then.getType();
if (type != Value.UNKNOWN && type != Value.NULL) {
t = Value.getHigherOrder(t, type);
s = Math.max(s, then.getScale());
p = Math.max(p, then.getPrecision());
d = Math.max(d, then.getDisplaySize());
}
}
}
if (args.length % 2 == 0) {
Expression elsePart = args[args.length - 1];
if (elsePart != ValueExpression.getNull()) {
int type = elsePart.getType();
if (type != Value.UNKNOWN && type != Value.NULL) {
t = Value.getHigherOrder(t, type);
s = Math.max(s, elsePart.getScale());
p = Math.max(p, elsePart.getPrecision());
d = Math.max(d, elsePart.getDisplaySize());
}
}
}
if (t == Value.UNKNOWN) {
t = Value.STRING;
s = 0;
p = Integer.MAX_VALUE;
d = Integer.MAX_VALUE;
}
break;
}
case CASEWHEN:
t = Value.getHigherOrder(args[1].getType(), args[2].getType());
p = Math.max(args[1].getPrecision(), args[2].getPrecision());
d = Math.max(args[1].getDisplaySize(), args[2].getDisplaySize());
s = Math.max(args[1].getScale(), args[2].getScale());
break;
case NVL2:
switch(args[1].getType()) {
case Value.STRING:
case Value.CLOB:
case Value.STRING_FIXED:
case Value.STRING_IGNORECASE:
t = args[1].getType();
break;
default:
t = Value.getHigherOrder(args[1].getType(), args[2].getType());
break;
}
p = Math.max(args[1].getPrecision(), args[2].getPrecision());
d = Math.max(args[1].getDisplaySize(), args[2].getDisplaySize());
s = Math.max(args[1].getScale(), args[2].getScale());
break;
case CAST:
case CONVERT:
case TRUNCATE_VALUE:
// data type, precision and scale is already set
t = dataType;
p = precision;
s = scale;
d = displaySize;
break;
case TRUNCATE:
t = p0.getType();
s = p0.getScale();
p = p0.getPrecision();
d = p0.getDisplaySize();
if (t == Value.NULL) {
t = Value.INT;
p = ValueInt.PRECISION;
d = ValueInt.DISPLAY_SIZE;
s = 0;
} else if (t == Value.TIMESTAMP) {
t = Value.DATE;
p = ValueDate.PRECISION;
s = 0;
d = ValueDate.PRECISION;
}
break;
case ABS:
case FLOOR:
case ROUND:
t = p0.getType();
s = p0.getScale();
p = p0.getPrecision();
d = p0.getDisplaySize();
if (t == Value.NULL) {
t = Value.INT;
p = ValueInt.PRECISION;
d = ValueInt.DISPLAY_SIZE;
s = 0;
}
break;
case SET:
{
Expression p1 = args[1];
t = p1.getType();
p = p1.getPrecision();
s = p1.getScale();
d = p1.getDisplaySize();
if (!(p0 instanceof Variable)) {
throw DbException.get(ErrorCode.CAN_ONLY_ASSIGN_TO_VARIABLE_1, p0.getSQL());
}
break;
}
case FILE_READ:
{
if (args.length == 1) {
t = Value.BLOB;
} else {
t = Value.CLOB;
}
p = Integer.MAX_VALUE;
s = 0;
d = Integer.MAX_VALUE;
break;
}
case SUBSTRING:
case SUBSTR:
{
t = info.returnDataType;
p = args[0].getPrecision();
s = 0;
if (args[1].isConstant()) {
// if only two arguments are used,
// subtract offset from first argument length
p -= args[1].getValue(session).getLong() - 1;
}
if (args.length == 3 && args[2].isConstant()) {
// if the third argument is constant it is at most this value
p = Math.min(p, args[2].getValue(session).getLong());
}
p = Math.max(0, p);
d = MathUtils.convertLongToInt(p);
break;
}
default:
t = info.returnDataType;
DataType type = DataType.getDataType(t);
p = PRECISION_UNKNOWN;
d = 0;
s = type.defaultScale;
}
dataType = t;
precision = p;
scale = s;
displaySize = d;
if (allConst) {
Value v = getValue(session);
if (v == ValueNull.INSTANCE) {
if (info.type == CAST || info.type == CONVERT) {
return this;
}
}
return ValueExpression.get(v);
}
return this;
}
use of org.h2.schema.Constant in project h2database by h2database.
the class Value method convertTo.
/**
* Compare a value to the specified type.
*
* @param targetType the type of the returned value
* @param precision the precision of the column to convert this value to.
* The special constant <code>-1</code> is used to indicate that
* the precision plays no role when converting the value
* @param mode the conversion mode
* @param column the column (if any), used for to improve the error message if conversion fails
* @param enumerators the ENUM datatype enumerators (if any),
* for dealing with ENUM conversions
* @return the converted value
*/
public Value convertTo(int targetType, int precision, Mode mode, Object column, String[] enumerators) {
// converting BLOB to CLOB and vice versa is done in ValueLob
if (getType() == targetType) {
return this;
}
try {
// decimal conversion
switch(targetType) {
case BOOLEAN:
{
switch(getType()) {
case BYTE:
case SHORT:
case INT:
case LONG:
case DECIMAL:
case DOUBLE:
case FLOAT:
return ValueBoolean.get(getSignum() != 0);
case TIME:
case DATE:
case TIMESTAMP:
case TIMESTAMP_TZ:
case BYTES:
case JAVA_OBJECT:
case UUID:
case ENUM:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case BYTE:
{
switch(getType()) {
case BOOLEAN:
return ValueByte.get(getBoolean() ? (byte) 1 : (byte) 0);
case SHORT:
case ENUM:
case INT:
return ValueByte.get(convertToByte(getInt(), column));
case LONG:
return ValueByte.get(convertToByte(getLong(), column));
case DECIMAL:
return ValueByte.get(convertToByte(convertToLong(getBigDecimal(), column), column));
case DOUBLE:
return ValueByte.get(convertToByte(convertToLong(getDouble(), column), column));
case FLOAT:
return ValueByte.get(convertToByte(convertToLong(getFloat(), column), column));
case BYTES:
return ValueByte.get((byte) Integer.parseInt(getString(), 16));
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case SHORT:
{
switch(getType()) {
case BOOLEAN:
return ValueShort.get(getBoolean() ? (short) 1 : (short) 0);
case BYTE:
return ValueShort.get(getByte());
case ENUM:
case INT:
return ValueShort.get(convertToShort(getInt(), column));
case LONG:
return ValueShort.get(convertToShort(getLong(), column));
case DECIMAL:
return ValueShort.get(convertToShort(convertToLong(getBigDecimal(), column), column));
case DOUBLE:
return ValueShort.get(convertToShort(convertToLong(getDouble(), column), column));
case FLOAT:
return ValueShort.get(convertToShort(convertToLong(getFloat(), column), column));
case BYTES:
return ValueShort.get((short) Integer.parseInt(getString(), 16));
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case INT:
{
switch(getType()) {
case BOOLEAN:
return ValueInt.get(getBoolean() ? 1 : 0);
case BYTE:
case ENUM:
case SHORT:
return ValueInt.get(getInt());
case LONG:
return ValueInt.get(convertToInt(getLong(), column));
case DECIMAL:
return ValueInt.get(convertToInt(convertToLong(getBigDecimal(), column), column));
case DOUBLE:
return ValueInt.get(convertToInt(convertToLong(getDouble(), column), column));
case FLOAT:
return ValueInt.get(convertToInt(convertToLong(getFloat(), column), column));
case BYTES:
return ValueInt.get((int) Long.parseLong(getString(), 16));
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case LONG:
{
switch(getType()) {
case BOOLEAN:
return ValueLong.get(getBoolean() ? 1 : 0);
case BYTE:
case SHORT:
case ENUM:
case INT:
return ValueLong.get(getInt());
case DECIMAL:
return ValueLong.get(convertToLong(getBigDecimal(), column));
case DOUBLE:
return ValueLong.get(convertToLong(getDouble(), column));
case FLOAT:
return ValueLong.get(convertToLong(getFloat(), column));
case BYTES:
{
// parseLong doesn't work for ffffffffffffffff
byte[] d = getBytes();
if (d.length == 8) {
return ValueLong.get(Bits.readLong(d, 0));
}
return ValueLong.get(Long.parseLong(getString(), 16));
}
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case DECIMAL:
{
switch(getType()) {
case BOOLEAN:
return ValueDecimal.get(BigDecimal.valueOf(getBoolean() ? 1 : 0));
case BYTE:
case SHORT:
case ENUM:
case INT:
return ValueDecimal.get(BigDecimal.valueOf(getInt()));
case LONG:
return ValueDecimal.get(BigDecimal.valueOf(getLong()));
case DOUBLE:
{
double d = getDouble();
if (Double.isInfinite(d) || Double.isNaN(d)) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, "" + d);
}
return ValueDecimal.get(BigDecimal.valueOf(d));
}
case FLOAT:
{
float f = getFloat();
if (Float.isInfinite(f) || Float.isNaN(f)) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, "" + f);
}
// better rounding behavior than BigDecimal.valueOf(f)
return ValueDecimal.get(new BigDecimal(Float.toString(f)));
}
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case DOUBLE:
{
switch(getType()) {
case BOOLEAN:
return ValueDouble.get(getBoolean() ? 1 : 0);
case BYTE:
case SHORT:
case INT:
return ValueDouble.get(getInt());
case LONG:
return ValueDouble.get(getLong());
case DECIMAL:
return ValueDouble.get(getBigDecimal().doubleValue());
case FLOAT:
return ValueDouble.get(getFloat());
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case FLOAT:
{
switch(getType()) {
case BOOLEAN:
return ValueFloat.get(getBoolean() ? 1 : 0);
case BYTE:
case SHORT:
case INT:
return ValueFloat.get(getInt());
case LONG:
return ValueFloat.get(getLong());
case DECIMAL:
return ValueFloat.get(getBigDecimal().floatValue());
case DOUBLE:
return ValueFloat.get((float) getDouble());
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case DATE:
{
switch(getType()) {
case TIME:
// this will be the result
return ValueDate.fromDateValue(DateTimeUtils.EPOCH_DATE_VALUE);
case TIMESTAMP:
return ValueDate.fromDateValue(((ValueTimestamp) this).getDateValue());
case TIMESTAMP_TZ:
{
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
long dateValue = ts.getDateValue(), timeNanos = ts.getTimeNanos();
long millis = DateTimeUtils.getMillis(dateValue, timeNanos, ts.getTimeZoneOffsetMins());
return ValueDate.fromMillis(millis);
}
case ENUM:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case TIME:
{
switch(getType()) {
case DATE:
// has the time set to 0, the result will be 0
return ValueTime.fromNanos(0);
case TIMESTAMP:
return ValueTime.fromNanos(((ValueTimestamp) this).getTimeNanos());
case TIMESTAMP_TZ:
{
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
long dateValue = ts.getDateValue(), timeNanos = ts.getTimeNanos();
long millis = DateTimeUtils.getMillis(dateValue, timeNanos, ts.getTimeZoneOffsetMins());
return ValueTime.fromNanos(DateTimeUtils.nanosFromDate(millis) + timeNanos % 1_000_000);
}
case ENUM:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case TIMESTAMP:
{
switch(getType()) {
case TIME:
return DateTimeUtils.normalizeTimestamp(0, ((ValueTime) this).getNanos());
case DATE:
return ValueTimestamp.fromDateValueAndNanos(((ValueDate) this).getDateValue(), 0);
case TIMESTAMP_TZ:
{
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
long dateValue = ts.getDateValue(), timeNanos = ts.getTimeNanos();
long millis = DateTimeUtils.getMillis(dateValue, timeNanos, ts.getTimeZoneOffsetMins());
return ValueTimestamp.fromMillisNanos(millis, (int) (timeNanos % 1_000_000));
}
case ENUM:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case TIMESTAMP_TZ:
{
switch(getType()) {
case TIME:
{
ValueTimestamp ts = DateTimeUtils.normalizeTimestamp(0, ((ValueTime) this).getNanos());
return DateTimeUtils.timestampTimeZoneFromLocalDateValueAndNanos(ts.getDateValue(), ts.getTimeNanos());
}
case DATE:
return DateTimeUtils.timestampTimeZoneFromLocalDateValueAndNanos(((ValueDate) this).getDateValue(), 0);
case TIMESTAMP:
{
ValueTimestamp ts = (ValueTimestamp) this;
return DateTimeUtils.timestampTimeZoneFromLocalDateValueAndNanos(ts.getDateValue(), ts.getTimeNanos());
}
case ENUM:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case BYTES:
{
switch(getType()) {
case JAVA_OBJECT:
case BLOB:
return ValueBytes.getNoCopy(getBytesNoCopy());
case UUID:
case GEOMETRY:
return ValueBytes.getNoCopy(getBytes());
case BYTE:
return ValueBytes.getNoCopy(new byte[] { getByte() });
case SHORT:
{
int x = getShort();
return ValueBytes.getNoCopy(new byte[] { (byte) (x >> 8), (byte) x });
}
case INT:
{
byte[] b = new byte[4];
Bits.writeInt(b, 0, getInt());
return ValueBytes.getNoCopy(b);
}
case LONG:
{
byte[] b = new byte[8];
Bits.writeLong(b, 0, getLong());
return ValueBytes.getNoCopy(b);
}
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case JAVA_OBJECT:
{
switch(getType()) {
case BYTES:
case BLOB:
return ValueJavaObject.getNoCopy(null, getBytesNoCopy(), getDataHandler());
case ENUM:
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case ENUM:
{
switch(getType()) {
case BYTE:
case SHORT:
case INT:
case LONG:
case DECIMAL:
return ValueEnum.get(enumerators, getInt());
case STRING:
case STRING_IGNORECASE:
case STRING_FIXED:
return ValueEnum.get(enumerators, getString());
case JAVA_OBJECT:
Object object = JdbcUtils.deserialize(getBytesNoCopy(), getDataHandler());
if (object instanceof String) {
return ValueEnum.get(enumerators, (String) object);
} else if (object instanceof Integer) {
return ValueEnum.get(enumerators, (int) object);
}
// $FALL-THROUGH$
default:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
}
case BLOB:
{
switch(getType()) {
case BYTES:
return ValueLobDb.createSmallLob(Value.BLOB, getBytesNoCopy());
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case UUID:
{
switch(getType()) {
case BYTES:
return ValueUuid.get(getBytesNoCopy());
case JAVA_OBJECT:
Object object = JdbcUtils.deserialize(getBytesNoCopy(), getDataHandler());
if (object instanceof java.util.UUID) {
return ValueUuid.get((java.util.UUID) object);
}
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
case GEOMETRY:
{
switch(getType()) {
case BYTES:
return ValueGeometry.get(getBytesNoCopy());
case JAVA_OBJECT:
Object object = JdbcUtils.deserialize(getBytesNoCopy(), getDataHandler());
if (DataType.isGeometry(object)) {
return ValueGeometry.getFromGeometry(object);
}
// $FALL-THROUGH$
case TIMESTAMP_TZ:
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getString());
}
break;
}
}
// conversion by parsing the string value
String s = getString();
switch(targetType) {
case NULL:
return ValueNull.INSTANCE;
case BOOLEAN:
{
if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") || s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y")) {
return ValueBoolean.TRUE;
} else if (s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") || s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n")) {
return ValueBoolean.FALSE;
} else {
// convert to a number, and if it is not 0 then it is true
return ValueBoolean.get(new BigDecimal(s).signum() != 0);
}
}
case BYTE:
return ValueByte.get(Byte.parseByte(s.trim()));
case SHORT:
return ValueShort.get(Short.parseShort(s.trim()));
case INT:
return ValueInt.get(Integer.parseInt(s.trim()));
case LONG:
return ValueLong.get(Long.parseLong(s.trim()));
case DECIMAL:
return ValueDecimal.get(new BigDecimal(s.trim()));
case TIME:
return ValueTime.parse(s.trim());
case DATE:
return ValueDate.parse(s.trim());
case TIMESTAMP:
return ValueTimestamp.parse(s.trim(), mode);
case TIMESTAMP_TZ:
return ValueTimestampTimeZone.parse(s.trim());
case BYTES:
return ValueBytes.getNoCopy(StringUtils.convertHexToBytes(s.trim()));
case JAVA_OBJECT:
return ValueJavaObject.getNoCopy(null, StringUtils.convertHexToBytes(s.trim()), getDataHandler());
case STRING:
return ValueString.get(s);
case STRING_IGNORECASE:
return ValueStringIgnoreCase.get(s);
case STRING_FIXED:
return ValueStringFixed.get(s, precision, mode);
case DOUBLE:
return ValueDouble.get(Double.parseDouble(s.trim()));
case FLOAT:
return ValueFloat.get(Float.parseFloat(s.trim()));
case CLOB:
return ValueLobDb.createSmallLob(CLOB, s.getBytes(StandardCharsets.UTF_8));
case BLOB:
return ValueLobDb.createSmallLob(BLOB, StringUtils.convertHexToBytes(s.trim()));
case ARRAY:
return ValueArray.get(new Value[] { ValueString.get(s) });
case RESULT_SET:
{
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
rs.addColumn("X", Types.VARCHAR, s.length(), 0);
rs.addRow(s);
return ValueResultSet.get(rs);
}
case UUID:
return ValueUuid.get(s);
case GEOMETRY:
return ValueGeometry.get(s);
default:
if (JdbcUtils.customDataTypesHandler != null) {
return JdbcUtils.customDataTypesHandler.convert(this, targetType);
}
throw DbException.throwInternalError("type=" + targetType);
}
} catch (NumberFormatException e) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, e, getString());
}
}
use of org.h2.schema.Constant in project h2database by h2database.
the class Schema method removeChildrenAndResources.
@Override
public void removeChildrenAndResources(Session session) {
while (triggers != null && triggers.size() > 0) {
TriggerObject obj = (TriggerObject) triggers.values().toArray()[0];
database.removeSchemaObject(session, obj);
}
while (constraints != null && constraints.size() > 0) {
Constraint obj = (Constraint) constraints.values().toArray()[0];
database.removeSchemaObject(session, obj);
}
// There can be dependencies between tables e.g. using computed columns,
// so we might need to loop over them multiple times.
boolean runLoopAgain = false;
do {
runLoopAgain = false;
if (tablesAndViews != null) {
// Loop over a copy because the map is modified underneath us.
for (Table obj : new ArrayList<>(tablesAndViews.values())) {
// in one go underneath us.
if (obj.getName() != null) {
if (database.getDependentTable(obj, obj) == null) {
database.removeSchemaObject(session, obj);
} else {
runLoopAgain = true;
}
}
}
}
} while (runLoopAgain);
while (indexes != null && indexes.size() > 0) {
Index obj = (Index) indexes.values().toArray()[0];
database.removeSchemaObject(session, obj);
}
while (sequences != null && sequences.size() > 0) {
Sequence obj = (Sequence) sequences.values().toArray()[0];
database.removeSchemaObject(session, obj);
}
while (constants != null && constants.size() > 0) {
Constant obj = (Constant) constants.values().toArray()[0];
database.removeSchemaObject(session, obj);
}
while (functions != null && functions.size() > 0) {
FunctionAlias obj = (FunctionAlias) functions.values().toArray()[0];
database.removeSchemaObject(session, obj);
}
for (Right right : database.getAllRights()) {
if (right.getGrantedObject() == this) {
database.removeDatabaseObject(session, right);
}
}
database.removeMeta(session, getId());
owner = null;
invalidate();
}
use of org.h2.schema.Constant in project h2database by h2database.
the class TestOptimizations method testConstantTypeConversionToColumnType.
private void testConstantTypeConversionToColumnType() throws SQLException {
deleteDb("optimizations");
Connection conn = getConnection("optimizations;IGNORECASE=TRUE");
Statement stat = conn.createStatement();
stat.executeUpdate("CREATE TABLE test (x int)");
ResultSet resultSet;
resultSet = stat.executeQuery("EXPLAIN SELECT x FROM test WHERE x = '5'");
assertTrue(resultSet.next());
// String constant '5' has been converted to int constant 5 on
// optimization
assertTrue(resultSet.getString(1).endsWith("X = 5"));
stat.execute("drop table test");
conn.close();
}
Aggregations