Java Code Examples for org.apache.calcite.sql.type.BasicSqlType

The following examples show how to use org.apache.calcite.sql.type.BasicSqlType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   Source File: SqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNode getCastSpec(RelDataType type) {
  if (type instanceof BasicSqlType) {
    int precision = type.getPrecision();
    switch (type.getSqlTypeName()) {
    case VARCHAR:
      // if needed, adjust varchar length to max length supported by the system
      int maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName());
      if (type.getPrecision() > maxPrecision) {
        precision = maxPrecision;
      }
    }
    return new SqlDataTypeSpec(
        new SqlIdentifier(type.getSqlTypeName().name(), SqlParserPos.ZERO),
            precision,
            type.getScale(),
            type.getCharset() != null
                && supportsCharSet()
                ? type.getCharset().name()
                : null,
            null,
            SqlParserPos.ZERO);
  }
  return SqlTypeUtil.convertTypeToSpec(type);
}
 
Example 2
@Override
public RelDataType deriveSumType(RelDataTypeFactory typeFactory, RelDataType argumentType) {
    if (argumentType instanceof BasicSqlType) {
        switch (argumentType.getSqlTypeName()) {
        case INTEGER:
        case SMALLINT:
        case TINYINT:
            return typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT),
                    argumentType.isNullable());
        case DECIMAL:
            return typeFactory.createTypeWithNullability(
                    typeFactory.createSqlType(SqlTypeName.DECIMAL, 19, argumentType.getScale()),
                    argumentType.isNullable());
        default:
            break;
        }
    }
    return argumentType;
}
 
Example 3
Source Project: dremio-oss   Source File: TestValuesRel.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNumericValuesRelRowTypeAdjustment() {
  final int INListLength = 20;

  // Build RowType & Tuples
  RelDataTypeField relDataType = new RelDataTypeFieldImpl("ROW_VALUE", 0, new BasicSqlType(RelDataTypeSystemImpl.REL_DATA_TYPE_SYSTEM, SqlTypeName.ANY));
  RelDataType rowType = new RelRecordType(StructKind.FULLY_QUALIFIED, Arrays.asList(relDataType));
  ImmutableList.Builder<ImmutableList<RexLiteral>> tuples = new ImmutableList.Builder<>();
  for (int i = 0; i < INListLength; i++) {
    tuples.add(new ImmutableList.Builder<RexLiteral>().add(new RexBuilder(typeFactory).makeExactLiteral(new BigDecimal(i))).build());
  }

  // Check original types.
  assertEquals(1, rowType.getFieldCount());
  assertEquals(SqlTypeName.ANY, rowType.getFieldList().get(0).getType().getSqlTypeName());

  // Construct ValuesRel
  final ValuesRel valuesRel = new ValuesRel(cluster, rowType, tuples.build(), traits);

  // Check the adjusted types.
  RelDataType adjustedRowType = valuesRel.getRowType();
  assertEquals(1, adjustedRowType.getFieldCount());
  assertEquals(SqlTypeName.INTEGER, adjustedRowType.getFieldList().get(0).getType().getSqlTypeName());
}
 
Example 4
Source Project: dremio-oss   Source File: TestValuesRel.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCharValuesRelRowTypeAdjustment() {
  final int INListLength = 20;

  // Build RowType & Tuples
  RelDataTypeField relDataType = new RelDataTypeFieldImpl("ROW_VALUE", 0, new BasicSqlType(RelDataTypeSystemImpl.REL_DATA_TYPE_SYSTEM, SqlTypeName.ANY));
  RelDataType rowType = new RelRecordType(StructKind.FULLY_QUALIFIED, Arrays.asList(relDataType));
  ImmutableList.Builder<ImmutableList<RexLiteral>> tuples = new ImmutableList.Builder<>();
  for (int i = 0; i < INListLength; ++i) {
    tuples.add(new ImmutableList.Builder<RexLiteral>().add(new RexBuilder(typeFactory).makeLiteral(charLiteralBuilder(i))).build());
  }

  // Check original types.
  assertEquals(1, rowType.getFieldCount());
  assertEquals(SqlTypeName.ANY, rowType.getFieldList().get(0).getType().getSqlTypeName());

  // Construct ValuesRel
  final ValuesRel valuesRel = new ValuesRel(cluster, rowType, tuples.build(), traits);

  // Check the adjusted types.
  RelDataType adjustedRowType = valuesRel.getRowType();
  assertEquals(1, adjustedRowType.getFieldCount());
  assertEquals(SqlTypeName.CHAR, adjustedRowType.getFieldList().get(0).getType().getSqlTypeName());
  assertEquals(INListLength - 1, adjustedRowType.getFieldList().get(0).getType().getPrecision());
}
 
Example 5
Source Project: kylin   Source File: KylinRelDataTypeSystem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType deriveSumType(RelDataTypeFactory typeFactory, RelDataType argumentType) {
    if (argumentType instanceof BasicSqlType) {
        switch (argumentType.getSqlTypeName()) {
        case INTEGER:
        case SMALLINT:
        case TINYINT:
            return typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT),
                    argumentType.isNullable());
        case DECIMAL:
            return typeFactory.createTypeWithNullability(
                    typeFactory.createSqlType(SqlTypeName.DECIMAL, 19, argumentType.getScale()),
                    argumentType.isNullable());
        default:
            break;
        }
    }
    return argumentType;
}
 
Example 6
Source Project: calcite   Source File: RelDataTypeSystemImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override public RelDataType deriveSumType(RelDataTypeFactory typeFactory,
    RelDataType argumentType) {
  if (argumentType instanceof BasicSqlType) {
    SqlTypeName typeName = argumentType.getSqlTypeName();
    if (typeName.allowsPrec()
        && argumentType.getPrecision() != RelDataType.PRECISION_NOT_SPECIFIED) {
      int precision = typeFactory.getTypeSystem().getMaxPrecision(typeName);
      if (typeName.allowsScale()) {
        argumentType = typeFactory.createTypeWithNullability(
            typeFactory.createSqlType(typeName, precision, argumentType.getScale()),
            argumentType.isNullable());
      } else {
        argumentType = typeFactory.createTypeWithNullability(
            typeFactory.createSqlType(typeName, precision), argumentType.isNullable());
      }
    }
  }
  return argumentType;
}
 
Example 7
Source Project: calcite   Source File: SqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns SqlNode for type in "cast(column as type)", which might be
* different between databases by type name, precision etc. */
public SqlNode getCastSpec(RelDataType type) {
  if (type instanceof BasicSqlType) {
    int maxPrecision = -1;
    switch (type.getSqlTypeName()) {
    case VARCHAR:
      // if needed, adjust varchar length to max length supported by the system
      maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName());
    }
    String charSet = type.getCharset() != null && supportsCharSet()
        ? type.getCharset().name()
        : null;
    return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision);
  }
  return SqlTypeUtil.convertTypeToSpec(type);
}
 
Example 8
Source Project: kylin-on-parquet-v2   Source File: OLAPProjectRel.java    License: Apache License 2.0 5 votes vote down vote up
private void rewriteProjectForIntersect(RexNode rex, SqlTypeName sqlTypeName, BasicSqlType eleSqlType,
        ArraySqlType arraySqlType, int idx) {
    if (rex.isA(SqlKind.ARRAY_VALUE_CONSTRUCTOR)) { // somethings like ['2012-01-01', '2012-01-02', '2012-01-03']
        List<RexNode> nodeList = ((RexCall) rex).getOperands();
        RexLiteral newNode = null;
        boolean needChange = true;
        List<RexNode> newerList = new ArrayList<>();
        if (!nodeList.isEmpty()) {
            for (RexNode node : nodeList) {
                if (node instanceof RexLiteral) {
                    RexLiteral literal = (RexLiteral) node;
                    if (literal.getTypeName() == sqlTypeName) {
                        needChange = false;
                        break;
                    } else {
                        newNode = RexLiteral.fromJdbcString(eleSqlType, sqlTypeName,
                                literal.getValue2().toString());
                    }
                }
                if (newNode != null) {
                    newerList.add(newNode);
                }
                newNode = null;
            }
            if (needChange) {
                rewriteProjects.set(idx, ((RexCall) rex).clone(arraySqlType, newerList));
                logger.debug("Rewrite project REL {} for intersect count.", rewriteProjects.get(idx));
            }
        }
    }
}
 
Example 9
@Test
public void testLegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(30, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertEquals(relDataType.getPrecision(), 30);
    Assert.assertTrue(relDataType.getPrecision() <= typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example 10
@Test
public void testIllegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(40, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertTrue(typeSystem.getMaxNumericPrecision() < 40);
    Assert.assertEquals(relDataType.getPrecision(), typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example 11
Source Project: herddb   Source File: SQLExpressionCompiler.java    License: Apache License 2.0 5 votes vote down vote up
private static Object safeValue(Object value3, RelDataType relDataType, SqlTypeName sqlTypeName) {
    if (value3 instanceof BigDecimal) {
        if (relDataType instanceof BasicSqlType) {
            sqlTypeName = relDataType.getSqlTypeName();
        }
        if (sqlTypeName == SqlTypeName.DECIMAL) {
            return ((BigDecimal) value3).doubleValue();
        }
        return ((BigDecimal) value3).longValue();
    }
    return value3;
}
 
Example 12
Source Project: samza   Source File: CheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = SamzaSqlValidatorException.class)
public void testCheckOperandTypesShouldFailOnTypeMisMatch() throws NoSuchMethodException {
  Method udfMethod = TestUdfWithWrongTypes.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("TestUdfWithWrongTypes", "TestUDFClass",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.INT32), SamzaSqlFieldType.INT64, false);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  operandTypeChecker.checkOperandTypes(callBinding, true);
}
 
Example 13
Source Project: samza   Source File: CheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckOperandTypesShouldReturnTrueOnTypeMatch() throws NoSuchMethodException {
  Method udfMethod = MyTestPolyUdf.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("MyTestPoly", "Test Polymorphism UDF.",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.STRING), SamzaSqlFieldType.INT32, false);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  assertTrue(operandTypeChecker.checkOperandTypes(callBinding, true));
}
 
Example 14
Source Project: samza   Source File: CheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckOperandTypesShouldReturnTrueWhenArgumentCheckIsDisabled() throws NoSuchMethodException {
  Method udfMethod = TestUdfWithWrongTypes.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("TestUdfWithWrongTypes", "TestUDFClass",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.INT32), SamzaSqlFieldType.INT64, true);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  assertTrue(operandTypeChecker.checkOperandTypes(callBinding, true));
}
 
Example 15
Source Project: samza   Source File: CheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckOperandTypesShouldReturnFalseWhenThrowOnFailureIsFalse() throws NoSuchMethodException {
  Method udfMethod = MyTestPolyUdf.class.getMethod("execute", String.class);
  UdfMetadata udfMetadata = new UdfMetadata("MyTestPoly", "Test Polymorphism UDF.",
          udfMethod, new MapConfig(), ImmutableList.of(SamzaSqlFieldType.STRING), SamzaSqlFieldType.INT32, false);

  Checker operandTypeChecker = Checker.getChecker(1, 3, udfMetadata);

  SqlCallBinding callBinding = Mockito.mock(SqlCallBinding.class);
  Mockito.when(callBinding.getOperandCount()).thenReturn(1);
  Mockito.when(callBinding.getOperandType(0)).thenReturn(new BasicSqlType(RelDataTypeSystem.DEFAULT, SqlTypeName.VARCHAR, 12));

  assertTrue(operandTypeChecker.checkOperandTypes(callBinding, false));
}
 
Example 16
Source Project: quark   Source File: RelToSqlConverter.java    License: Apache License 2.0 5 votes vote down vote up
private SqlNode toSql(RelDataType type) {
  switch (dialect.getDatabaseProduct()) {
    case MYSQL:
      switch (type.getSqlTypeName()) {
        case VARCHAR:
          // MySQL doesn't have a VARCHAR type, only CHAR.
          return new SqlDataTypeSpec(new SqlIdentifier("CHAR", POS),
              type.getPrecision(), -1, null, null, POS);
        case INTEGER:
          return new SqlDataTypeSpec(new SqlIdentifier("_UNSIGNED", POS),
              type.getPrecision(), -1, null, null, POS);
      }
      break;
  }
  if (type instanceof BasicSqlType) {
    return new SqlDataTypeSpec(
        new SqlIdentifier(type.getSqlTypeName().name(), POS),
        type.getPrecision(),
        type.getScale(),
        type.getCharset() != null
            && dialect.supportsCharSet()
            ? type.getCharset().name()
            : null,
        null,
        POS);
  }

  return SqlTypeUtil.convertTypeToSpec(type);
  //throw new AssertionError(type); // TODO: implement
}
 
Example 17
Source Project: kylin   Source File: OLAPProjectRel.java    License: Apache License 2.0 5 votes vote down vote up
private void rewriteProjectForIntersect(RexNode rex, SqlTypeName sqlTypeName, BasicSqlType eleSqlType,
        ArraySqlType arraySqlType, int idx) {
    if (rex.isA(SqlKind.ARRAY_VALUE_CONSTRUCTOR)) { // somethings like ['2012-01-01', '2012-01-02', '2012-01-03']
        List<RexNode> nodeList = ((RexCall) rex).getOperands();
        RexLiteral newNode = null;
        boolean needChange = true;
        List<RexNode> newerList = new ArrayList<>();
        if (!nodeList.isEmpty()) {
            for (RexNode node : nodeList) {
                if (node instanceof RexLiteral) {
                    RexLiteral literal = (RexLiteral) node;
                    if (literal.getTypeName() == sqlTypeName) {
                        needChange = false;
                        break;
                    } else {
                        newNode = RexLiteral.fromJdbcString(eleSqlType, sqlTypeName,
                                literal.getValue2().toString());
                    }
                }
                if (newNode != null) {
                    newerList.add(newNode);
                }
                newNode = null;
            }
            if (needChange) {
                rewriteProjects.set(idx, ((RexCall) rex).clone(arraySqlType, newerList));
                logger.debug("Rewrite project REL {} for intersect count.", rewriteProjects.get(idx));
            }
        }
    }
}
 
Example 18
Source Project: kylin   Source File: KylinRelDataTypeSystemTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(30, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertEquals(relDataType.getPrecision(), 30);
    Assert.assertTrue(relDataType.getPrecision() <= typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example 19
Source Project: kylin   Source File: KylinRelDataTypeSystemTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIllegalDecimalType() {
    RelDataTypeSystem typeSystem = new KylinRelDataTypeSystem();
    RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(typeSystem);
    
    DataType dataType = DataType.getType("decimal(40, 10)");
    RelDataType relDataType = OLAPTable.createSqlType(typeFactory, dataType, true);
    
    Assert.assertTrue(relDataType instanceof BasicSqlType);
    Assert.assertEquals(relDataType.getSqlTypeName(), SqlTypeName.DECIMAL);
    Assert.assertTrue(typeSystem.getMaxNumericPrecision() < 40);
    Assert.assertEquals(relDataType.getPrecision(), typeSystem.getMaxNumericPrecision());
    Assert.assertEquals(relDataType.getScale(), 10);
    Assert.assertTrue(relDataType.getScale() <= typeSystem.getMaxNumericScale());
}
 
Example 20
Source Project: calcite   Source File: BigQuerySqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/** BigQuery data type reference:
 * <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types">
 * BigQuery Standard SQL Data Types</a>
 */
@Override public SqlNode getCastSpec(final RelDataType type) {
  if (type instanceof BasicSqlType) {
    final SqlTypeName typeName = type.getSqlTypeName();
    switch (typeName) {
    // BigQuery only supports INT64 for integer types.
    case TINYINT:
    case SMALLINT:
    case INTEGER:
    case BIGINT:
      return createSqlDataTypeSpecByName("INT64", typeName);
    // BigQuery only supports FLOAT64(aka. Double) for floating point types.
    case FLOAT:
    case DOUBLE:
      return createSqlDataTypeSpecByName("FLOAT64", typeName);
    case DECIMAL:
      return createSqlDataTypeSpecByName("NUMERIC", typeName);
    case BOOLEAN:
      return createSqlDataTypeSpecByName("BOOL", typeName);
    case CHAR:
    case VARCHAR:
      return createSqlDataTypeSpecByName("STRING", typeName);
    case BINARY:
    case VARBINARY:
      return createSqlDataTypeSpecByName("BYTES", typeName);
    case DATE:
      return createSqlDataTypeSpecByName("DATE", typeName);
    case TIME:
      return createSqlDataTypeSpecByName("TIME", typeName);
    case TIMESTAMP:
      return createSqlDataTypeSpecByName("TIMESTAMP", typeName);
    }
  }
  return super.getCastSpec(type);
}
 
Example 21
Source Project: calcite   Source File: HiveSqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode getCastSpec(final RelDataType type) {
  if (type instanceof BasicSqlType) {
    switch (type.getSqlTypeName()) {
    case INTEGER:
      SqlAlienSystemTypeNameSpec typeNameSpec = new SqlAlienSystemTypeNameSpec(
          "INT", type.getSqlTypeName(), SqlParserPos.ZERO);
      return new SqlDataTypeSpec(typeNameSpec, SqlParserPos.ZERO);
    }
  }
  return super.getCastSpec(type);
}
 
Example 22
Source Project: calcite   Source File: ClickHouseSqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode getCastSpec(RelDataType type) {
  if (type instanceof BasicSqlType) {
    SqlTypeName typeName = type.getSqlTypeName();
    switch (typeName) {
    case VARCHAR:
      return createSqlDataTypeSpecByName("String", typeName);
    case TINYINT:
      return createSqlDataTypeSpecByName("Int8", typeName);
    case SMALLINT:
      return createSqlDataTypeSpecByName("Int16", typeName);
    case INTEGER:
      return createSqlDataTypeSpecByName("Int32", typeName);
    case BIGINT:
      return createSqlDataTypeSpecByName("Int64", typeName);
    case FLOAT:
      return createSqlDataTypeSpecByName("Float32", typeName);
    case DOUBLE:
      return createSqlDataTypeSpecByName("Float64", typeName);
    case DATE:
      return createSqlDataTypeSpecByName("Date", typeName);
    case TIMESTAMP:
    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
      return createSqlDataTypeSpecByName("DateTime", typeName);
    }
  }

  return super.getCastSpec(type);
}
 
Example 23
Source Project: calcite   Source File: SqlLimitsTest.java    License: Apache License 2.0 5 votes vote down vote up
private void printLimit(
    PrintWriter pw,
    String desc,
    RelDataType type,
    boolean sign,
    SqlTypeName.Limit limit,
    boolean beyond) {
  Object o = ((BasicSqlType) type).getLimit(sign, limit, beyond);
  if (o == null) {
    return;
  }
  pw.print(desc);
  String s;
  if (o instanceof byte[]) {
    int k = 0;
    StringBuilder buf = new StringBuilder("{");
    for (byte b : (byte[]) o) {
      if (k++ > 0) {
        buf.append(", ");
      }
      buf.append(Integer.toHexString(b & 0xff));
    }
    buf.append("}");
    s = buf.toString();
  } else if (o instanceof Calendar) {
    Calendar calendar = (Calendar) o;
    DateFormat dateFormat = getDateFormat(type.getSqlTypeName());
    dateFormat.setTimeZone(DateTimeUtils.UTC_ZONE);
    s = dateFormat.format(calendar.getTime());
  } else {
    s = o.toString();
  }
  pw.print(s);
  SqlLiteral literal =
      type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
  pw.print("; as SQL: ");
  pw.print(literal.toSqlString(AnsiSqlDialect.DEFAULT));
  pw.println();
}
 
Example 24
Source Project: calcite   Source File: RexBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override public RelDataType createTypeWithNullability(
    final RelDataType type,
    final boolean nullable) {
  if (type.getSqlTypeName() == SqlTypeName.VARCHAR) {
    return new BasicSqlType(this.typeSystem, type.getSqlTypeName(),
        PRECISION);
  }
  return super.createTypeWithNullability(type, nullable);
}
 
Example 25
Source Project: kylin-on-parquet-v2   Source File: QueryService.java    License: Apache License 2.0 4 votes vote down vote up
private SQLResponse getPrepareOnlySqlResponse(String projectName, String correctedSql, Connection conn,
        Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws SQLException {

    CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(true);

    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = conn.prepareStatement(correctedSql);
        throw new IllegalStateException("Should have thrown OnlyPrepareEarlyAbortException");
    } catch (Exception e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null && rootCause instanceof OnlyPrepareEarlyAbortException) {
            OnlyPrepareEarlyAbortException abortException = (OnlyPrepareEarlyAbortException) rootCause;
            CalcitePrepare.Context context = abortException.getContext();
            CalcitePrepare.ParseResult preparedResult = abortException.getPreparedResult();
            List<RelDataTypeField> fieldList = preparedResult.rowType.getFieldList();

            CalciteConnectionConfig config = context.config();

            // Fill in selected column meta
            for (int i = 0; i < fieldList.size(); ++i) {

                RelDataTypeField field = fieldList.get(i);
                String columnName = field.getKey();

                if (columnName.startsWith("_KY_")) {
                    continue;
                }
                BasicSqlType basicSqlType = (BasicSqlType) field.getValue();

                columnMetas.add(new SelectedColumnMeta(false, config.caseSensitive(), false, false,
                        basicSqlType.isNullable() ? 1 : 0, true, basicSqlType.getPrecision(), columnName,
                        columnName, null, null, null, basicSqlType.getPrecision(),
                        basicSqlType.getScale() < 0 ? 0 : basicSqlType.getScale(),
                        basicSqlType.getSqlTypeName().getJdbcOrdinal(), basicSqlType.getSqlTypeName().getName(),
                        true, false, false));
            }

        } else {
            throw e;
        }
    } finally {
        CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(false);
        DBUtils.closeQuietly(preparedStatement);
    }

    return buildSqlResponse(projectName, isPushDown, results, columnMetas);
}
 
Example 26
Source Project: kylin   Source File: QueryService.java    License: Apache License 2.0 4 votes vote down vote up
private SQLResponse getPrepareOnlySqlResponse(String projectName, String correctedSql, Connection conn,
        Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws SQLException {

    CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(true);

    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = conn.prepareStatement(correctedSql);
        throw new IllegalStateException("Should have thrown OnlyPrepareEarlyAbortException");
    } catch (Exception e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null && rootCause instanceof OnlyPrepareEarlyAbortException) {
            OnlyPrepareEarlyAbortException abortException = (OnlyPrepareEarlyAbortException) rootCause;
            CalcitePrepare.Context context = abortException.getContext();
            CalcitePrepare.ParseResult preparedResult = abortException.getPreparedResult();
            List<RelDataTypeField> fieldList = preparedResult.rowType.getFieldList();

            CalciteConnectionConfig config = context.config();

            // Fill in selected column meta
            for (int i = 0; i < fieldList.size(); ++i) {

                RelDataTypeField field = fieldList.get(i);
                String columnName = field.getKey();

                if (columnName.startsWith("_KY_")) {
                    continue;
                }
                BasicSqlType basicSqlType = (BasicSqlType) field.getValue();

                columnMetas.add(new SelectedColumnMeta(false, config.caseSensitive(), false, false,
                        basicSqlType.isNullable() ? 1 : 0, true, basicSqlType.getPrecision(), columnName,
                        columnName, null, null, null, basicSqlType.getPrecision(),
                        basicSqlType.getScale() < 0 ? 0 : basicSqlType.getScale(),
                        basicSqlType.getSqlTypeName().getJdbcOrdinal(), basicSqlType.getSqlTypeName().getName(),
                        true, false, false));
            }

        } else {
            throw e;
        }
    } finally {
        CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(false);
        DBUtils.closeQuietly(preparedStatement);
    }

    return buildSqlResponse(projectName, isPushDown, results, columnMetas);
}