use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class JdbcSchema method sqlType.
private static RelDataType sqlType(RelDataTypeFactory typeFactory, int dataType, int precision, int scale, @Nullable String typeString) {
// Fall back to ANY if type is unknown
final SqlTypeName sqlTypeName = Util.first(SqlTypeName.getNameForJdbcType(dataType), SqlTypeName.ANY);
switch(sqlTypeName) {
case ARRAY:
RelDataType component = null;
if (typeString != null && typeString.endsWith(" ARRAY")) {
// E.g. hsqldb gives "INTEGER ARRAY", so we deduce the component type
// "INTEGER".
final String remaining = typeString.substring(0, typeString.length() - " ARRAY".length());
component = parseTypeString(typeFactory, remaining);
}
if (component == null) {
component = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.ANY), true);
}
return typeFactory.createArrayType(component, -1);
default:
break;
}
if (precision >= 0 && scale >= 0 && sqlTypeName.allowsPrecScale(true, true)) {
return typeFactory.createSqlType(sqlTypeName, precision, scale);
} else if (precision >= 0 && sqlTypeName.allowsPrecNoScale()) {
return typeFactory.createSqlType(sqlTypeName, precision);
} else {
assert sqlTypeName.allowsNoPrecNoScale();
return typeFactory.createSqlType(sqlTypeName);
}
}
use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class JdbcToEnumerableConverter method generateGet.
private static void generateGet(EnumerableRelImplementor implementor, PhysType physType, BlockBuilder builder, ParameterExpression resultSet_, int i, Expression target, @Nullable Expression calendar_, SqlDialect.CalendarPolicy calendarPolicy) {
final Primitive primitive = Primitive.ofBoxOr(physType.fieldClass(i));
final RelDataType fieldType = physType.getRowType().getFieldList().get(i).getType();
final List<Expression> dateTimeArgs = new ArrayList<>();
dateTimeArgs.add(Expressions.constant(i + 1));
SqlTypeName sqlTypeName = fieldType.getSqlTypeName();
boolean offset = false;
switch(calendarPolicy) {
case LOCAL:
assert calendar_ != null : "calendar must not be null";
dateTimeArgs.add(calendar_);
break;
case NULL:
// instead use the version of the getXXX that doesn't take a Calendar
break;
case DIRECT:
sqlTypeName = SqlTypeName.ANY;
break;
case SHIFT:
switch(sqlTypeName) {
case TIMESTAMP:
case DATE:
offset = true;
break;
default:
break;
}
break;
default:
break;
}
final Expression source;
switch(sqlTypeName) {
case DATE:
case TIME:
case TIMESTAMP:
source = Expressions.call(getMethod(sqlTypeName, fieldType.isNullable(), offset), Expressions.<Expression>list().append(Expressions.call(resultSet_, getMethod2(sqlTypeName), dateTimeArgs)).appendIf(offset, getTimeZoneExpression(implementor)));
break;
case ARRAY:
final Expression x = Expressions.convert_(Expressions.call(resultSet_, jdbcGetMethod(primitive), Expressions.constant(i + 1)), java.sql.Array.class);
source = Expressions.call(BuiltInMethod.JDBC_ARRAY_TO_LIST.method, x);
break;
default:
source = Expressions.call(resultSet_, jdbcGetMethod(primitive), Expressions.constant(i + 1));
}
builder.add(Expressions.statement(Expressions.assign(target, source)));
// object
if (primitive != null) {
builder.add(Expressions.ifThen(Expressions.call(resultSet_, "wasNull"), Expressions.statement(Expressions.assign(target, Expressions.constant(null)))));
}
}
use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class SqlImplementor method toSql.
/**
* Converts a {@link RexLiteral} to a {@link SqlLiteral}.
*/
public static SqlNode toSql(RexLiteral literal) {
SqlTypeName typeName = literal.getTypeName();
switch(typeName) {
case SYMBOL:
final Enum symbol = (Enum) literal.getValue();
return SqlLiteral.createSymbol(symbol, POS);
case ROW:
// noinspection unchecked
final List<RexLiteral> list = castNonNull(literal.getValueAs(List.class));
return SqlStdOperatorTable.ROW.createCall(POS, list.stream().map(e -> toSql(e)).collect(Util.toImmutableList()));
case SARG:
final Sarg arg = literal.getValueAs(Sarg.class);
throw new AssertionError("sargs [" + arg + "] should be handled as part of predicates, not as literals");
default:
break;
}
SqlTypeFamily family = requireNonNull(typeName.getFamily(), () -> "literal " + literal + " has null SqlTypeFamily, and is SqlTypeName is " + typeName);
switch(family) {
case CHARACTER:
return SqlLiteral.createCharString((String) castNonNull(literal.getValue2()), POS);
case NUMERIC:
case EXACT_NUMERIC:
return SqlLiteral.createExactNumeric(castNonNull(literal.getValueAs(BigDecimal.class)).toPlainString(), POS);
case APPROXIMATE_NUMERIC:
return SqlLiteral.createApproxNumeric(castNonNull(literal.getValueAs(BigDecimal.class)).toPlainString(), POS);
case BOOLEAN:
return SqlLiteral.createBoolean(castNonNull(literal.getValueAs(Boolean.class)), POS);
case INTERVAL_YEAR_MONTH:
case INTERVAL_DAY_TIME:
final boolean negative = castNonNull(literal.getValueAs(Boolean.class));
return SqlLiteral.createInterval(negative ? -1 : 1, castNonNull(literal.getValueAs(String.class)), castNonNull(literal.getType().getIntervalQualifier()), POS);
case DATE:
return SqlLiteral.createDate(castNonNull(literal.getValueAs(DateString.class)), POS);
case TIME:
return SqlLiteral.createTime(castNonNull(literal.getValueAs(TimeString.class)), literal.getType().getPrecision(), POS);
case TIMESTAMP:
return SqlLiteral.createTimestamp(castNonNull(literal.getValueAs(TimestampString.class)), literal.getType().getPrecision(), POS);
case ANY:
case NULL:
switch(typeName) {
case NULL:
return SqlLiteral.createNull(POS);
default:
break;
}
// fall through
default:
throw new AssertionError(literal + ": " + typeName);
}
}
use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class MaterializedViewAggregateRule method generateMapping.
/**
* Mapping from node expressions to target expressions.
*
* <p>If any of the expressions cannot be mapped, we return null.
*/
@Nullable
protected Multimap<Integer, Integer> generateMapping(RexBuilder rexBuilder, RexSimplify simplify, RelMetadataQuery mq, RelNode node, RelNode target, ImmutableBitSet positions, BiMap<RelTableRef, RelTableRef> tableMapping, EquivalenceClasses sourceEC, List<RexNode> additionalExprs) {
Preconditions.checkArgument(additionalExprs.isEmpty());
Multimap<Integer, Integer> m = ArrayListMultimap.create();
Map<RexTableInputRef, Set<RexTableInputRef>> equivalenceClassesMap = sourceEC.getEquivalenceClassesMap();
Multimap<RexNode, Integer> exprsLineage = ArrayListMultimap.create();
final List<RexNode> timestampExprs = new ArrayList<>();
for (int i = 0; i < target.getRowType().getFieldCount(); i++) {
Set<RexNode> s = mq.getExpressionLineage(target, rexBuilder.makeInputRef(target, i));
if (s == null) {
// Bail out
continue;
}
// We only support project - filter - join, thus it should map to
// a single expression
final RexNode e = Iterables.getOnlyElement(s);
// Rewrite expr to be expressed on query tables
final RexNode simplified = simplify.simplifyUnknownAsFalse(e);
final RexNode expr = RexUtil.swapTableColumnReferences(rexBuilder, simplified, tableMapping.inverse(), equivalenceClassesMap);
exprsLineage.put(expr, i);
SqlTypeName sqlTypeName = expr.getType().getSqlTypeName();
if (sqlTypeName == SqlTypeName.TIMESTAMP || sqlTypeName == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) {
timestampExprs.add(expr);
}
}
// FLOOR(ts to DAY) via FLOOR(FLOOR(ts to HOUR) to DAY)
for (RexNode timestampExpr : timestampExprs) {
for (TimeUnitRange value : SUPPORTED_DATE_TIME_ROLLUP_UNITS) {
final SqlFunction[] functions = { getCeilSqlFunction(value), getFloorSqlFunction(value) };
for (SqlFunction function : functions) {
final RexNode call = rexBuilder.makeCall(function, timestampExpr, rexBuilder.makeFlag(value));
// References self-row
final RexNode rewrittenCall = shuttleReferences(rexBuilder, call, exprsLineage);
if (rewrittenCall == null) {
continue;
}
// We add the CEIL or FLOOR expression to the additional
// expressions, replacing the child expression by the position that
// it references
additionalExprs.add(rewrittenCall);
// Then we simplify the expression and we add it to the expressions
// lineage so we can try to find a match.
final RexNode simplified = simplify.simplifyUnknownAsFalse(call);
exprsLineage.put(simplified, target.getRowType().getFieldCount() + additionalExprs.size() - 1);
}
}
}
for (int i : positions) {
Set<RexNode> s = mq.getExpressionLineage(node, rexBuilder.makeInputRef(node, i));
if (s == null) {
// Bail out
return null;
}
// We only support project - filter - join, thus it should map to
// a single expression
final RexNode e = Iterables.getOnlyElement(s);
// Rewrite expr to be expressed on query tables
final RexNode simplified = simplify.simplifyUnknownAsFalse(e);
RexNode targetExpr = RexUtil.swapColumnReferences(rexBuilder, simplified, equivalenceClassesMap);
final Collection<Integer> c = exprsLineage.get(targetExpr);
if (!c.isEmpty()) {
for (Integer j : c) {
m.put(i, j);
}
} else {
// If we did not find the expression, try to navigate it
RexNode rewrittenTargetExpr = shuttleReferences(rexBuilder, targetExpr, exprsLineage);
if (rewrittenTargetExpr == null) {
// Some expressions were not present
return null;
}
m.put(i, target.getRowType().getFieldCount() + additionalExprs.size());
additionalExprs.add(rewrittenTargetExpr);
}
}
return m;
}
use of org.apache.calcite.sql.type.SqlTypeName in project calcite by apache.
the class RelDataTypeFactoryImpl method leastRestrictiveArrayMultisetType.
@Nullable
protected RelDataType leastRestrictiveArrayMultisetType(final List<RelDataType> types, SqlTypeName sqlTypeName) {
assert sqlTypeName == SqlTypeName.ARRAY || sqlTypeName == SqlTypeName.MULTISET;
boolean isNullable = false;
for (RelDataType type : types) {
if (type.getComponentType() == null) {
return null;
}
isNullable |= type.isNullable();
}
final RelDataType type = leastRestrictive(Util.transform(types, t -> t instanceof ArraySqlType ? ((ArraySqlType) t).getComponentType() : ((MultisetSqlType) t).getComponentType()));
if (type == null) {
return null;
}
return sqlTypeName == SqlTypeName.ARRAY ? new ArraySqlType(type, isNullable) : new MultisetSqlType(type, isNullable);
}
Aggregations