com.hazelcast.sql.impl.calcite.HazelcastRexBuilder Maven / Gradle / Ivy
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in com.hazelcast.com.liance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.com.hazelcast.org.licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.com.hazelcast.sql.impl.calcite;
import com.hazelcast.com.hazelcast.sql.impl.calcite.validate.types.HazelcastIntegerType;
import com.hazelcast.com.hazelcast.sql.impl.calcite.validate.types.HazelcastTypeFactory;
import com.hazelcast.org.apache.calcite.rel.type.RelDataType;
import com.hazelcast.org.apache.calcite.rel.type.RelDataTypeFactory;
import com.hazelcast.org.apache.calcite.rex.RexBuilder;
import com.hazelcast.org.apache.calcite.rex.RexNode;
import java.math.BigDecimal;
import static com.hazelcast.org.apache.calcite.sql.type.SqlTypeName.ANY;
import static com.hazelcast.org.apache.calcite.sql.type.SqlTypeName.DECIMAL;
import static com.hazelcast.org.apache.calcite.sql.type.SqlTypeName.DOUBLE;
import static com.hazelcast.org.apache.calcite.sql.type.SqlTypeName.REAL;
/**
* Custom Hazelcast expression builder.
*
* Currently, this custom expression builder is used just to workaround quirks
* of the default Calcite expression builder.
*/
public final class HazelcastRexBuilder extends RexBuilder {
public HazelcastRexBuilder(RelDataTypeFactory typeFactory) {
super(typeFactory);
assert typeFactory instanceof HazelcastTypeFactory;
}
@Override
public RexNode makeLiteral(Object value, RelDataType type, boolean allowCast) {
// XXX: Calcite evaluates casts like CAST(0 AS ANY) statically and
// assigns imprecise types: BIGINT for any integer value and DOUBLE for
// any floating-point value. The code below fixes that.
if (type.getSqlTypeName() == ANY && value instanceof Number) {
if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
Number number = (Number) value;
int bitWidth = HazelcastIntegerType.bitWidthOf(number.longValue());
type = HazelcastIntegerType.of(bitWidth, false);
} else if (value instanceof Float) {
type = HazelcastTypeFactory.INSTANCE.createSqlType(REAL);
} else if (value instanceof Double) {
type = HazelcastTypeFactory.INSTANCE.createSqlType(DOUBLE);
} else if (value instanceof BigDecimal) {
type = HazelcastTypeFactory.INSTANCE.createSqlType(DECIMAL);
}
}
return super.makeLiteral(value, type, allowCast);
}
}