Search in sources :

Example 36 with SqlTypeName

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);
    }
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) RelDataType(org.apache.calcite.rel.type.RelDataType)

Example 37 with 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)))));
    }
}
Also used : Primitive(org.apache.calcite.linq4j.tree.Primitive) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) Expression(org.apache.calcite.linq4j.tree.Expression) ConstantExpression(org.apache.calcite.linq4j.tree.ConstantExpression) UnaryExpression(org.apache.calcite.linq4j.tree.UnaryExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType)

Example 38 with SqlTypeName

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);
    }
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) Sarg(org.apache.calcite.util.Sarg) SqlTypeFamily(org.apache.calcite.sql.type.SqlTypeFamily) ArrayList(java.util.ArrayList) AbstractList(java.util.AbstractList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) SqlNodeList(org.apache.calcite.sql.SqlNodeList) BigDecimal(java.math.BigDecimal)

Example 39 with SqlTypeName

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;
}
Also used : ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) ArrayList(java.util.ArrayList) RexTableInputRef(org.apache.calcite.rex.RexTableInputRef) TimeUnitRange(org.apache.calcite.avatica.util.TimeUnitRange) RexNode(org.apache.calcite.rex.RexNode) SqlFunction(org.apache.calcite.sql.SqlFunction) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 40 with SqlTypeName

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);
}
Also used : LoadingCache(com.google.common.cache.LoadingCache) Time(java.sql.Time) AbstractList(java.util.AbstractList) ArrayList(java.util.ArrayList) Primitive(org.apache.calcite.linq4j.tree.Primitive) ImmutableList(com.google.common.collect.ImmutableList) Charset(java.nio.charset.Charset) Map(java.util.Map) MapSqlType(org.apache.calcite.sql.type.MapSqlType) Nullable(org.checkerframework.checker.nullness.qual.Nullable) SqlTypeFamily(org.apache.calcite.sql.type.SqlTypeFamily) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) ImmutableMap(com.google.common.collect.ImmutableMap) ArraySqlType(org.apache.calcite.sql.type.ArraySqlType) Timestamp(java.sql.Timestamp) Interners(com.google.common.collect.Interners) SqlTypeUtil(org.apache.calcite.sql.type.SqlTypeUtil) Interner(com.google.common.collect.Interner) SqlCollation(org.apache.calcite.sql.SqlCollation) Field(java.lang.reflect.Field) JavaToSqlTypeConversionRules(org.apache.calcite.sql.type.JavaToSqlTypeConversionRules) CacheLoader(com.google.common.cache.CacheLoader) Objects(java.util.Objects) MultisetSqlType(org.apache.calcite.sql.type.MultisetSqlType) List(java.util.List) Modifier(java.lang.reflect.Modifier) CacheBuilder(com.google.common.cache.CacheBuilder) Util(org.apache.calcite.util.Util) MultisetSqlType(org.apache.calcite.sql.type.MultisetSqlType) ArraySqlType(org.apache.calcite.sql.type.ArraySqlType) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Aggregations

SqlTypeName (org.apache.calcite.sql.type.SqlTypeName)184 RelDataType (org.apache.calcite.rel.type.RelDataType)62 Test (org.junit.jupiter.api.Test)39 List (java.util.List)31 BigDecimal (java.math.BigDecimal)30 ArrayList (java.util.ArrayList)30 ImmutableList (com.google.common.collect.ImmutableList)26 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)26 Map (java.util.Map)25 RexNode (org.apache.calcite.rex.RexNode)25 NlsString (org.apache.calcite.util.NlsString)21 DateString (org.apache.calcite.util.DateString)18 TimeString (org.apache.calcite.util.TimeString)18 TimestampString (org.apache.calcite.util.TimestampString)18 ByteString (org.apache.calcite.avatica.util.ByteString)17 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)16 SqlKind (org.apache.calcite.sql.SqlKind)15 Calendar (java.util.Calendar)14 Objects (java.util.Objects)13 Util (org.apache.calcite.util.Util)13