use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class DruidExpressions method toDruidExpression.
/**
* Translates a Calcite {@link RexNode} to a Druid expression, if possible;
* returns null if not possible.
*
* @param rexNode RexNode to convert to a Druid Expression
* @param inputRowType Input row type of the rexNode to translate
* @param druidRel Druid query
*
* @return Druid Expression, or null when can not convert the RexNode
*/
@Nullable
public static String toDruidExpression(final RexNode rexNode, final RelDataType inputRowType, final DruidQuery druidRel) {
SqlKind kind = rexNode.getKind();
SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName();
if (kind == SqlKind.INPUT_REF) {
final RexInputRef ref = (RexInputRef) rexNode;
final String columnName = inputRowType.getFieldNames().get(ref.getIndex());
if (columnName == null) {
return null;
}
if (druidRel.getDruidTable().timestampFieldName.equals(columnName)) {
return DruidExpressions.fromColumn(DruidTable.DEFAULT_TIMESTAMP_COLUMN);
}
return DruidExpressions.fromColumn(columnName);
}
if (rexNode instanceof RexCall) {
final SqlOperator operator = ((RexCall) rexNode).getOperator();
final DruidSqlOperatorConverter conversion = druidRel.getOperatorConversionMap().get(operator);
if (conversion == null) {
// unknown operator can not translate
return null;
} else {
return conversion.toDruidExpression(rexNode, inputRowType, druidRel);
}
}
if (kind == SqlKind.LITERAL) {
// Translate literal.
if (RexLiteral.isNullLiteral(rexNode)) {
// case the filter/project might yield to unknown let Calcite deal with this for now
return null;
} else if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) {
return DruidExpressions.numberLiteral((Number) RexLiteral.value(rexNode));
} else if (SqlTypeFamily.INTERVAL_DAY_TIME == sqlTypeName.getFamily()) {
// Calcite represents DAY-TIME intervals in milliseconds.
final long milliseconds = ((Number) RexLiteral.value(rexNode)).longValue();
return DruidExpressions.numberLiteral(milliseconds);
} else if (SqlTypeFamily.INTERVAL_YEAR_MONTH == sqlTypeName.getFamily()) {
// Calcite represents YEAR-MONTH intervals in months.
final long months = ((Number) RexLiteral.value(rexNode)).longValue();
return DruidExpressions.numberLiteral(months);
} else if (SqlTypeName.STRING_TYPES.contains(sqlTypeName)) {
return DruidExpressions.stringLiteral(RexLiteral.stringValue(rexNode));
} else if (SqlTypeName.DATE == sqlTypeName || SqlTypeName.TIMESTAMP == sqlTypeName || SqlTypeName.TIME_WITH_LOCAL_TIME_ZONE == sqlTypeName) {
return DruidExpressions.numberLiteral(DruidDateTimeUtils.literalValue(rexNode));
} else if (SqlTypeName.BOOLEAN == sqlTypeName) {
return DruidExpressions.numberLiteral(RexLiteral.booleanValue(rexNode) ? 1 : 0);
}
}
// Not Literal/InputRef/RexCall or unknown type?
return null;
}
use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class GeodeTable method query.
/**
* Executes an OQL query on the underlying table.
*
* <p>Called by the {@link GeodeQueryable} which in turn is
* called via the generated code.
*
* @param clientCache Geode client cache
* @param fields List of fields to project
* @param predicates A list of predicates which should be used in the query
* @return Enumerator of results
*/
public Enumerable<Object> query(final GemFireCache clientCache, final List<Map.Entry<String, Class>> fields, final List<Map.Entry<String, String>> selectFields, final List<Map.Entry<String, String>> aggregateFunctions, final List<String> groupByFields, List<String> predicates, List<String> orderByFields, Long limit) {
final RelDataTypeFactory typeFactory = new JavaTypeFactoryExtImpl();
final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder();
for (Map.Entry<String, Class> field : fields) {
SqlTypeName typeName = typeFactory.createJavaType(field.getValue()).getSqlTypeName();
RelDataType type;
if (typeName == SqlTypeName.ARRAY) {
type = typeFactory.createArrayType(typeFactory.createSqlType(SqlTypeName.ANY), -1);
} else if (typeName == SqlTypeName.MULTISET) {
type = typeFactory.createMultisetType(typeFactory.createSqlType(SqlTypeName.ANY), -1);
} else if (typeName == SqlTypeName.MAP) {
RelDataType anyType = typeFactory.createSqlType(SqlTypeName.ANY);
type = typeFactory.createMapType(anyType, anyType);
} else {
type = typeFactory.createSqlType(typeName);
}
fieldInfo.add(field.getKey(), type).nullable(true);
}
final RelProtoDataType resultRowType = RelDataTypeImpl.proto(fieldInfo.build());
ImmutableMap<String, String> aggFuncMap = ImmutableMap.of();
if (!aggregateFunctions.isEmpty()) {
ImmutableMap.Builder<String, String> aggFuncMapBuilder = ImmutableMap.builder();
for (Map.Entry<String, String> e : aggregateFunctions) {
aggFuncMapBuilder.put(e.getKey(), e.getValue());
}
aggFuncMap = aggFuncMapBuilder.build();
}
// Construct the list of fields to project
ImmutableList.Builder<String> selectBuilder = ImmutableList.builder();
if (!groupByFields.isEmpty()) {
// manually add GROUP BY to select clause (GeodeProjection was not visited)
for (String groupByField : groupByFields) {
selectBuilder.add(groupByField + " AS " + groupByField);
}
if (!aggFuncMap.isEmpty()) {
for (Map.Entry<String, String> e : aggFuncMap.entrySet()) {
selectBuilder.add(e.getValue() + " AS " + e.getKey());
}
}
} else {
if (selectFields.isEmpty()) {
if (!aggFuncMap.isEmpty()) {
for (Map.Entry<String, String> e : aggFuncMap.entrySet()) {
selectBuilder.add(e.getValue() + " AS " + e.getKey());
}
} else {
selectBuilder.add("*");
}
} else {
if (!aggFuncMap.isEmpty()) {
for (Map.Entry<String, String> e : aggFuncMap.entrySet()) {
selectBuilder.add(e.getValue() + " AS " + e.getKey());
}
} else {
for (Map.Entry<String, String> field : selectFields) {
selectBuilder.add(field.getKey() + " AS " + field.getValue());
}
}
}
}
final String oqlSelectStatement = Util.toString(selectBuilder.build(), "", ", ", "");
// Combine all predicates conjunctively
String whereClause = "";
if (!predicates.isEmpty()) {
whereClause = " WHERE ";
whereClause += Util.toString(predicates, "", " AND ", "");
}
// Build and issue the query and return an Enumerator over the results
StringBuilder queryBuilder = new StringBuilder("SELECT ");
queryBuilder.append(oqlSelectStatement);
queryBuilder.append(" FROM /" + regionName);
queryBuilder.append(whereClause);
if (!groupByFields.isEmpty()) {
queryBuilder.append(Util.toString(groupByFields, " GROUP BY ", ", ", ""));
}
if (!orderByFields.isEmpty()) {
queryBuilder.append(Util.toString(orderByFields, " ORDER BY ", ", ", ""));
}
if (limit != null) {
queryBuilder.append(" LIMIT " + limit);
}
final String oqlQuery = queryBuilder.toString();
Hook.QUERY_PLAN.run(oqlQuery);
LOGGER.info("OQL: " + oqlQuery);
return new AbstractEnumerable<Object>() {
@Override
public Enumerator<Object> enumerator() {
final QueryService queryService = clientCache.getQueryService();
try {
SelectResults results = (SelectResults) queryService.newQuery(oqlQuery).execute();
return new GeodeEnumerator(results, resultRowType);
} catch (Exception e) {
String message = String.format(Locale.ROOT, "Failed to execute query [%s] on %s", oqlQuery, clientCache.getName());
throw new RuntimeException(message, e);
}
}
};
}
use of org.apache.calcite.sql.type.SqlTypeName in project flink-mirror by flink-ci.
the class RexLiteral method appendAsJava.
/**
* Appends the specified value in the provided destination as a Java string. The value must be
* consistent with the type, as per {@link #valueMatchesType}.
*
* <p>Typical return values:
*
* <ul>
* <li>true
* <li>null
* <li>"Hello, world!"
* <li>1.25
* <li>1234ABCD
* </ul>
*
* @param value Value to be appended to the provided destination as a Java string
* @param sb Destination to which to append the specified value
* @param typeName Type name to be used for the transformation of the value to a Java string
* @param type Type to be used for the transformation of the value to a Java string
* @param includeType Whether to include the data type in the Java representation
*/
private static void appendAsJava(Comparable value, StringBuilder sb, SqlTypeName typeName, RelDataType type, boolean java, RexDigestIncludeType includeType) {
switch(typeName) {
case CHAR:
NlsString nlsString = (NlsString) value;
if (java) {
Util.printJavaString(sb, nlsString.getValue(), true);
} else {
boolean includeCharset = (nlsString.getCharsetName() != null) && !nlsString.getCharsetName().equals(CalciteSystemProperty.DEFAULT_CHARSET.value());
sb.append(nlsString.asSql(includeCharset, false));
}
break;
case BOOLEAN:
assert value instanceof Boolean;
sb.append(value.toString());
break;
case DECIMAL:
assert value instanceof BigDecimal;
sb.append(value.toString());
break;
case DOUBLE:
assert value instanceof BigDecimal;
sb.append(Util.toScientificNotation((BigDecimal) value));
break;
case BIGINT:
assert value instanceof BigDecimal;
long narrowLong = ((BigDecimal) value).longValue();
sb.append(String.valueOf(narrowLong));
sb.append('L');
break;
case BINARY:
assert value instanceof ByteString;
sb.append("X'");
sb.append(((ByteString) value).toString(16));
sb.append("'");
break;
case NULL:
assert value == null;
sb.append("null");
break;
case SARG:
assert value instanceof Sarg;
// noinspection unchecked,rawtypes
Util.asStringBuilder(sb, sb2 -> printSarg(sb2, (Sarg) value, type));
break;
case SYMBOL:
assert value instanceof Enum;
sb.append("FLAG(");
sb.append(value.toString());
sb.append(")");
break;
case DATE:
assert value instanceof DateString;
sb.append(value.toString());
break;
case TIME:
case TIME_WITH_LOCAL_TIME_ZONE:
assert value instanceof TimeString;
sb.append(value.toString());
break;
case TIMESTAMP:
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
assert value instanceof TimestampString;
sb.append(value.toString());
break;
case INTERVAL_YEAR:
case INTERVAL_YEAR_MONTH:
case INTERVAL_MONTH:
case INTERVAL_DAY:
case INTERVAL_DAY_HOUR:
case INTERVAL_DAY_MINUTE:
case INTERVAL_DAY_SECOND:
case INTERVAL_HOUR:
case INTERVAL_HOUR_MINUTE:
case INTERVAL_HOUR_SECOND:
case INTERVAL_MINUTE:
case INTERVAL_MINUTE_SECOND:
case INTERVAL_SECOND:
assert value instanceof BigDecimal;
sb.append(value.toString());
break;
case MULTISET:
case ROW:
final List<RexLiteral> list = (List) value;
Util.asStringBuilder(sb, sb2 -> Util.printList(sb, list.size(), (sb3, i) -> sb3.append(list.get(i).computeDigest(includeType))));
break;
case GEOMETRY:
final String wkt = GeoFunctions.ST_AsWKT((Geometries.Geom) value);
sb.append(wkt);
break;
default:
assert valueMatchesType(value, typeName, true);
throw Util.needToImplement(typeName);
}
}
use of org.apache.calcite.sql.type.SqlTypeName in project Mycat2 by MyCATApache.
the class CalciteCompiler method getPhysicalSortProperties.
public static List<PhysicalSortProperty> getPhysicalSortProperties(Sort sort) {
RelCollation collation = sort.collation;
List<PhysicalSortProperty> physicalSortProperties = new ArrayList<>();
List<RelDataTypeField> fieldList = sort.getRowType().getFieldList();
for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
int fieldIndex = fieldCollation.getFieldIndex();
RelFieldCollation.Direction direction = fieldCollation.direction;
SortOptions sortOptions = new SortOptions();
switch(direction) {
case ASCENDING:
sortOptions.descending = false;
break;
case DESCENDING:
sortOptions.descending = true;
break;
case STRICTLY_ASCENDING:
case STRICTLY_DESCENDING:
case CLUSTERED:
throw new UnsupportedOperationException();
}
switch(fieldCollation.nullDirection) {
case FIRST:
sortOptions.nullsFirst = true;
break;
case LAST:
case UNSPECIFIED:
sortOptions.nullsFirst = false;
break;
}
SqlTypeName sqlTypeName = fieldList.get(fieldIndex).getType().getSqlTypeName();
InnerType innerType = RexConverter.convertColumnType(sqlTypeName);
physicalSortProperties.add(PhysicalSortProperty.of(fieldIndex, sortOptions, innerType));
}
return physicalSortProperties;
}
use of org.apache.calcite.sql.type.SqlTypeName in project Mycat2 by MyCATApache.
the class DrdsExecutorCompiler method normalize.
private static List<Object> normalize(List<SqlTypeName> targetTypes, List<Object> params) {
int size = targetTypes.size();
if (targetTypes.isEmpty()) {
return Collections.emptyList();
}
if (params.get(0) instanceof List) {
// insert or update sql
return params;
}
List<Object> resParams = new ArrayList<>();
for (int i = 0; i < size; i++) {
Object param = params.get(i);
SqlTypeName targetTypeName = targetTypes.get(i);
SqlTypeName curTypeName = getObjectType(param);
Object curParam = params.get(i);
if (targetTypeName == curTypeName || curParam == null) {
resParams.add(curParam);
} else {
switch(targetTypeName) {
case BOOLEAN:
if (curParam instanceof Boolean) {
curParam = curParam;
} else if (curParam instanceof String) {
curParam = Boolean.parseBoolean((String) curParam);
} else if (curParam instanceof Number) {
long l = ((Number) curParam).longValue();
curParam = (l == -1 || l > 0);
}
throw new UnsupportedOperationException();
case TINYINT:
if (curParam instanceof Number) {
curParam = ((Number) curParam).byteValue();
} else if (curParam instanceof String) {
curParam = Byte.parseByte((String) curParam);
} else {
throw new UnsupportedOperationException();
}
break;
case SMALLINT:
if (curParam instanceof Number) {
curParam = ((Number) curParam).shortValue();
} else if (curParam instanceof String) {
curParam = Short.parseShort((String) curParam);
} else {
throw new UnsupportedOperationException();
}
break;
case INTEGER:
if (curParam instanceof Number) {
curParam = ((Number) curParam).intValue();
} else if (curParam instanceof String) {
curParam = Integer.parseInt((String) curParam);
} else {
throw new UnsupportedOperationException();
}
break;
case BIGINT:
if (curParam instanceof Number) {
curParam = ((Number) curParam).longValue();
} else if (curParam instanceof String) {
curParam = Long.parseLong((String) curParam);
} else {
throw new UnsupportedOperationException();
}
break;
case DECIMAL:
if (curParam instanceof Number) {
curParam = new BigDecimal(curParam.toString());
} else if (curParam instanceof String) {
curParam = new BigDecimal(curParam.toString());
} else {
throw new UnsupportedOperationException();
}
break;
case FLOAT:
if (curParam instanceof Float) {
curParam = ((Number) curParam).floatValue();
} else if (curParam instanceof String) {
curParam = Float.parseFloat(curParam.toString());
} else {
throw new UnsupportedOperationException();
}
break;
case REAL:
case DOUBLE:
if (curParam instanceof Number) {
curParam = ((Number) curParam).doubleValue();
} else if (curParam instanceof String) {
curParam = Double.parseDouble(curParam.toString());
} else {
throw new UnsupportedOperationException();
}
break;
case DATE:
if (curParam instanceof Date) {
curParam = new java.sql.Date(((Date) curParam).getTime()).toLocalDate();
} else if (curParam instanceof String) {
curParam = java.sql.Date.valueOf((String) curParam);
} else if (curParam instanceof LocalDate) {
curParam = curParam;
} else {
throw new UnsupportedOperationException();
}
break;
case TIME_WITH_LOCAL_TIME_ZONE:
case TIME:
if (curParam instanceof Duration) {
curParam = curParam;
} else {
curParam = curParam.toString();
}
curParam = MycatTimeUtil.timeStringToTimeDuration(curParam.toString());
break;
case TIMESTAMP:
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
if (curParam instanceof Timestamp) {
curParam = ((Timestamp) curParam).toLocalDateTime();
} else if (curParam instanceof String) {
curParam = Timestamp.valueOf((String) curParam).toLocalDateTime();
}
{
curParam = curParam;
}
break;
case CHAR:
curParam = curParam.toString();
break;
case VARCHAR:
curParam = curParam.toString();
break;
case BINARY:
case VARBINARY:
if (curParam instanceof byte[]) {
curParam = new ByteString((byte[]) curParam);
} else {
curParam = curParam;
}
break;
case NULL:
curParam = null;
break;
case ANY:
case SYMBOL:
case MULTISET:
case ARRAY:
case MAP:
case DISTINCT:
case STRUCTURED:
case ROW:
case OTHER:
case CURSOR:
case COLUMN_LIST:
case DYNAMIC_STAR:
case GEOMETRY:
case SARG:
curParam = curParam.toString();
break;
case INTERVAL_YEAR:
case INTERVAL_YEAR_MONTH:
case INTERVAL_MONTH:
case INTERVAL_DAY:
case INTERVAL_DAY_HOUR:
case INTERVAL_DAY_MINUTE:
case INTERVAL_DAY_SECOND:
case INTERVAL_HOUR:
case INTERVAL_HOUR_MINUTE:
case INTERVAL_HOUR_SECOND:
case INTERVAL_MINUTE:
case INTERVAL_MINUTE_SECOND:
case INTERVAL_SECOND:
case INTERVAL_MICROSECOND:
case INTERVAL_WEEK:
case INTERVAL_QUARTER:
case INTERVAL_SECOND_MICROSECOND:
case INTERVAL_MINUTE_MICROSECOND:
case INTERVAL_HOUR_MICROSECOND:
case INTERVAL_DAY_MICROSECOND:
throw new UnsupportedOperationException();
}
resParams.add(curParam);
}
}
return resParams;
}
Aggregations