org.apache.calcite.adapter.java.JavaTypeFactory Java Examples

The following examples show how to use org.apache.calcite.adapter.java.JavaTypeFactory. 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 File: QuarkConnectionImpl.java    From quark with Apache License 2.0 6 votes vote down vote up
protected QuarkConnectionImpl(QuarkDriver driver, AvaticaFactory factory, String url,
                              Properties info, CalciteRootSchema rootSchema,
                              JavaTypeFactory typeFactory) throws SQLException {
  super(driver, factory, url, info);

  CalciteConnectionConfig cfg = new CalciteConnectionConfigImpl(info);

  if (typeFactory != null) {
    this.typeFactory = typeFactory;
  } else {
    final RelDataTypeSystem typeSystem =
        cfg.typeSystem(RelDataTypeSystem.class, RelDataTypeSystem.DEFAULT);
    this.typeFactory = new JavaTypeFactoryImpl(typeSystem);
  }

  this.properties.put(InternalProperty.CASE_SENSITIVE, cfg.caseSensitive());
  this.properties.put(InternalProperty.UNQUOTED_CASING, cfg.unquotedCasing());
  this.properties.put(InternalProperty.QUOTED_CASING, cfg.quotedCasing());
  this.properties.put(InternalProperty.QUOTING, cfg.quoting());
}
 
Example #2
Source File: TableDataContexImpl.java    From marble with Apache License 2.0 6 votes vote down vote up
public TableDataContexImpl(QueryProvider queryProvider,
    SchemaPlus rootSchema,
    JavaTypeFactory typeFactory, TableConfig tableConfig) {
  this.queryProvider = queryProvider;
  this.typeFactory = typeFactory;
  this.rootSchema = rootSchema;

  final long time = System.currentTimeMillis();
  final TimeZone timeZone = tableConfig.getTimeZone();
  final long localOffset = timeZone.getOffset(time);
  final long currentOffset = localOffset;
  ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
  builder.put(Variable.UTC_TIMESTAMP.camelName, time)
      .put(Variable.CURRENT_TIMESTAMP.camelName, time + currentOffset)
      .put(Variable.LOCAL_TIMESTAMP.camelName, time + localOffset)
      .put(Variable.TIME_ZONE.camelName, timeZone);

  map = builder.build();
}
 
Example #3
Source File: HiveRexExecutorImpl.java    From marble with Apache License 2.0 6 votes vote down vote up
public Expression field(BlockBuilder list, int index, Type storageType) {
  MethodCallExpression recFromCtx = Expressions.call(
      DataContext.ROOT,
      BuiltInMethod.DATA_CONTEXT_GET.method,
      Expressions.constant("inputRecord"));
  Expression recFromCtxCasted =
      RexToLixTranslator.convert(recFromCtx, Object[].class);
  IndexExpression recordAccess = Expressions.arrayIndex(recFromCtxCasted,
      Expressions.constant(index));
  if (storageType == null) {
    final RelDataType fieldType =
        rowType.getFieldList().get(index).getType();
    storageType = ((JavaTypeFactory) typeFactory).getJavaClass(fieldType);
  }
  return RexToLixTranslator.convert(recordAccess, storageType);
}
 
Example #4
Source File: ReflectivePredicateEvaluator.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private synchronized void initialize(JavaTypeFactory typeFactory) {
	if (this.initialized) {
		return;
	}

	this.methodsForFields = new ArrayList<>();
	List<RelDataTypeField> fields = new ArrayList<>();

	for (Method method : this.referenceInterface.getMethods()) {
		if (method.getParameterCount() == 0) {
			String fieldName = computeFieldName(method.getName());
			if (fieldName != null) {
				this.methodsForFields.add(extractorForMethod(method));
				Class<?> retType = method.getReturnType();
				if (retType.isEnum()) {
					retType = String.class;
				}
				fields.add(new RelDataTypeFieldImpl(fieldName.toUpperCase(), fields.size(), typeFactory.createType(retType)));
			}
		}
	}

	this.rowType = new MyDataType(fields, referenceInterface);
	this.initialized = true;
}
 
Example #5
Source File: EnumerableInterpreter.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final JavaTypeFactory typeFactory = implementor.getTypeFactory();
  final BlockBuilder builder = new BlockBuilder();
  final PhysType physType =
      PhysTypeImpl.of(typeFactory, getRowType(), JavaRowFormat.ARRAY);
  final Expression interpreter_ = builder.append("interpreter",
      Expressions.new_(Interpreter.class,
          implementor.getRootExpression(),
          implementor.stash(getInput(), RelNode.class)));
  final Expression sliced_ =
      getRowType().getFieldCount() == 1
          ? Expressions.call(BuiltInMethod.SLICE0.method, interpreter_)
          : interpreter_;
  builder.add(sliced_);
  return implementor.result(physType, builder.toBlock());
}
 
Example #6
Source File: EnumerableTableFunctionScan.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Result defaultTableFunctionImplement(
    EnumerableRelImplementor implementor, Prefer pref) {
  BlockBuilder bb = new BlockBuilder();
  // Non-array user-specified types are not supported yet
  final JavaRowFormat format;
  if (getElementType() == null) {
    format = JavaRowFormat.ARRAY;
  } else if (rowType.getFieldCount() == 1 && isQueryable()) {
    format = JavaRowFormat.SCALAR;
  } else if (getElementType() instanceof Class
      && Object[].class.isAssignableFrom((Class) getElementType())) {
    format = JavaRowFormat.ARRAY;
  } else {
    format = JavaRowFormat.CUSTOM;
  }
  final PhysType physType =
      PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
          false);
  RexToLixTranslator t = RexToLixTranslator.forAggregation(
      (JavaTypeFactory) getCluster().getTypeFactory(), bb, null,
      implementor.getConformance());
  t = t.setCorrelates(implementor.allCorrelateVariables);
  bb.add(Expressions.return_(null, t.translate(getCall())));
  return implementor.result(physType, bb.toBlock());
}
 
Example #7
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Shared implementation for {@link #parse}, {@link #convert} and
 * {@link #analyzeView}. */
private ParseResult parse_(Context context, String sql, boolean convert,
    boolean analyze, boolean fail) {
  final JavaTypeFactory typeFactory = context.getTypeFactory();
  CalciteCatalogReader catalogReader =
      new CalciteCatalogReader(
          context.getRootSchema(),
          context.getDefaultSchemaPath(),
          typeFactory,
          context.config());
  SqlParser parser = createParser(sql);
  SqlNode sqlNode;
  try {
    sqlNode = parser.parseStmt();
  } catch (SqlParseException e) {
    throw new RuntimeException("parse failed", e);
  }
  final SqlValidator validator = createSqlValidator(context, catalogReader);
  SqlNode sqlNode1 = validator.validate(sqlNode);
  if (convert) {
    return convert_(
        context, sql, analyze, fail, catalogReader, validator, sqlNode1);
  }
  return new ParseResult(this, validator, sql, sqlNode1,
      validator.getValidatedNodeType(sqlNode1));
}
 
Example #8
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a prepare action. */
public <R> R perform(CalciteServerStatement statement,
    FrameworkConfig config, Frameworks.BasePrepareAction<R> action) {
  final CalcitePrepare.Context prepareContext =
      statement.createPrepareContext();
  final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
  final CalciteSchema schema =
      config.getDefaultSchema() != null
          ? CalciteSchema.from(config.getDefaultSchema())
          : prepareContext.getRootSchema();
  CalciteCatalogReader catalogReader =
      new CalciteCatalogReader(schema.root(),
          schema.path(null),
          typeFactory,
          prepareContext.config());
  final RexBuilder rexBuilder = new RexBuilder(typeFactory);
  final RelOptPlanner planner =
      createPlanner(prepareContext,
          config.getContext(),
          config.getCostFactory());
  final RelOptCluster cluster = createCluster(planner, rexBuilder);
  return action.apply(cluster, catalogReader,
      prepareContext.getRootSchema().plus(), statement);
}
 
Example #9
Source File: TestSQLAnalyzer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  // Create and Mock dependencies
  final SabotContext sabotContext = mock(SabotContext.class);
  final FunctionImplementationRegistry functionImplementationRegistry = mock(FunctionImplementationRegistry.class);
  final JavaTypeFactory typeFactory = JavaTypeFactoryImpl.INSTANCE;

  // Stub necessary methods
  when(sabotContext.getFunctionImplementationRegistry()).thenReturn(functionImplementationRegistry);

  // Utilize custom catalog reader implementation to return specific suggestions,
  // without requiring server startup
  MockCatalogReader mockCatalogReader = new MockCatalogReader(typeFactory, false);
  SqlValidatorWithHints validator =  new SqlAdvisorValidator(new OperatorTable(sabotContext.getFunctionImplementationRegistry()), mockCatalogReader, typeFactory, DremioSqlConformance.INSTANCE);
  sqlAnalyzer = new SQLAnalyzer(validator);
}
 
Example #10
Source File: SqlWorker.java    From quark with Apache License 2.0 6 votes vote down vote up
private void populateMaterializationsAndLattice(
    QuarkMaterializeCluster.RelOptPlannerHolder plannerHolder,
    CalciteSchema rootSchema) {
  if (materializations == null) {
    materializations =
        MaterializationService.instance().query(rootSchema);
  }
  Materializer materializer = new Materializer(materializations);

  materializer.populateMaterializations(context.getPrepareContext(), plannerHolder);

  List<CalciteSchema.LatticeEntry> lattices = Schemas.getLatticeEntries(rootSchema);

  for (CalciteSchema.LatticeEntry lattice : lattices) {
    final CalciteSchema.TableEntry starTable = lattice.getStarTable();
    final JavaTypeFactory typeFactory = context.getTypeFactory();
    final RelOptTableImpl starRelOptTable =
        RelOptTableImpl.create(catalogReader,
            starTable.getTable().getRowType(typeFactory), starTable, null);
    plannerHolder.getPlanner().addLattice(
        new RelOptLattice(lattice.getLattice(), starRelOptTable));
  }
}
 
Example #11
Source File: RexToLixTranslator.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Translates a {@link RexProgram} to a sequence of expressions and
 * declarations.
 *
 * @param program Program to be translated
 * @param typeFactory Type factory
 * @param conformance SQL conformance
 * @param list List of statements, populated with declarations
 * @param outputPhysType Output type, or null
 * @param root Root expression
 * @param inputGetter Generates expressions for inputs
 * @param correlates Provider of references to the values of correlated
 *                   variables
 * @return Sequence of expressions, optional condition
 */
public static List<Expression> translateProjects(RexProgram program,
    JavaTypeFactory typeFactory, SqlConformance conformance,
    BlockBuilder list, PhysType outputPhysType, Expression root,
    InputGetter inputGetter, Function1<String, InputGetter> correlates) {
  List<Type> storageTypes = null;
  if (outputPhysType != null) {
    final RelDataType rowType = outputPhysType.getRowType();
    storageTypes = new ArrayList<>(rowType.getFieldCount());
    for (int i = 0; i < rowType.getFieldCount(); i++) {
      storageTypes.add(outputPhysType.getJavaFieldType(i));
    }
  }
  return new RexToLixTranslator(program, typeFactory, root, inputGetter,
      list, new RexBuilder(typeFactory), conformance, null)
      .setCorrelates(correlates)
      .translateList(program.getProjectList(), storageTypes);
}
 
Example #12
Source File: KafkaEndpoint.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public RelInfo populateOutputDAG(DAG dag, JavaTypeFactory typeFactory)
{
  RelInfo spec = messageFormat.populateOutputDAG(dag, typeFactory);

  KafkaSinglePortOutputOperator kafkaOutput = dag.addOperator(OperatorUtils.getUniqueOperatorName("KafkaOutput"),
      KafkaSinglePortOutputOperator.class);
  kafkaOutput.setTopic((String)operands.get(KAFKA_TOPICS));

  Properties props = new Properties();
  props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, VALUE_SERIALIZER);
  props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KEY_SERIALIZER);
  props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, operands.get(KAFKA_SERVERS));
  kafkaOutput.setProperties(props);

  dag.addStream(OperatorUtils.getUniqueStreamName("Formatter", "Kafka"), spec.getOutPort(), kafkaOutput.inputPort);

  return new RelInfo("Output", spec.getInputPorts(), spec.getOperator(), null, messageFormat.getRowType(typeFactory));
}
 
Example #13
Source File: RexExecutorImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Expression field(BlockBuilder list, int index, Type storageType) {
  MethodCallExpression recFromCtx = Expressions.call(
      DataContext.ROOT,
      BuiltInMethod.DATA_CONTEXT_GET.method,
      Expressions.constant("inputRecord"));
  Expression recFromCtxCasted =
      EnumUtils.convert(recFromCtx, Object[].class);
  IndexExpression recordAccess = Expressions.arrayIndex(recFromCtxCasted,
      Expressions.constant(index));
  if (storageType == null) {
    final RelDataType fieldType =
        rowType.getFieldList().get(index).getType();
    storageType = ((JavaTypeFactory) typeFactory).getJavaClass(fieldType);
  }
  return EnumUtils.convert(recordAccess, storageType);
}
 
Example #14
Source File: CalciteConvertors.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static List<Pair<ColumnMetaData.Rep, Integer>> fieldClasses(final RelProtoDataType protoRowType,
                                                                   final JavaTypeFactory typeFactory) {
    final RelDataType rowType = protoRowType.apply(typeFactory);
    return rowType.getFieldList().stream().map(f -> {
        final RelDataType type = f.getType();
        final Class clazz = (Class) typeFactory.getJavaClass(type);
        final ColumnMetaData.Rep rep =
                Util.first(ColumnMetaData.Rep.of(clazz),
                        ColumnMetaData.Rep.OBJECT);
        return Pair.of(rep, type.getSqlTypeName().getJdbcOrdinal());
    }).collect(Collectors.toList());
}
 
Example #15
Source File: TraitPropagationTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static RelNode run(PropAction action, RuleSet rules)
    throws Exception {

  FrameworkConfig config = Frameworks.newConfigBuilder()
      .ruleSets(rules).build();

  final Properties info = new Properties();
  final Connection connection = DriverManager
      .getConnection("jdbc:calcite:", info);
  final CalciteServerStatement statement = connection
      .createStatement().unwrap(CalciteServerStatement.class);
  final CalcitePrepare.Context prepareContext =
        statement.createPrepareContext();
  final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
  CalciteCatalogReader catalogReader =
        new CalciteCatalogReader(prepareContext.getRootSchema(),
            prepareContext.getDefaultSchemaPath(),
            typeFactory,
            prepareContext.config());
  final RexBuilder rexBuilder = new RexBuilder(typeFactory);
  final RelOptPlanner planner = new VolcanoPlanner(config.getCostFactory(),
      config.getContext());

  // set up rules before we generate cluster
  planner.clearRelTraitDefs();
  planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

  planner.clear();
  for (RelOptRule r : rules) {
    planner.addRule(r);
  }

  final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
  return action.apply(cluster, catalogReader,
      prepareContext.getRootSchema().plus());
}
 
Example #16
Source File: SamzaSqlQueryParser.java    From samza with Apache License 2.0 5 votes vote down vote up
private static Planner createPlanner() {
  Connection connection;
  SchemaPlus rootSchema;
  try {
    JavaTypeFactory typeFactory = new SamzaSqlJavaTypeFactoryImpl();
    SamzaSqlDriver driver = new SamzaSqlDriver(typeFactory);
    DriverManager.deregisterDriver(DriverManager.getDriver("jdbc:calcite:"));
    DriverManager.registerDriver(driver);
    connection = driver.connect("jdbc:calcite:", new Properties());
    CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
    rootSchema = calciteConnection.getRootSchema();
  } catch (SQLException e) {
    throw new SamzaException(e);
  }

  final List<RelTraitDef> traitDefs = new ArrayList<>();

  traitDefs.add(ConventionTraitDef.INSTANCE);
  traitDefs.add(RelCollationTraitDef.INSTANCE);

  FrameworkConfig frameworkConfig = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.configBuilder().setLex(Lex.JAVA).build())
      .defaultSchema(rootSchema)
      .operatorTable(SqlStdOperatorTable.instance())
      .traitDefs(traitDefs)
      .context(Contexts.EMPTY_CONTEXT)
      .costFactory(null)
      .build();
  return Frameworks.getPlanner(frameworkConfig);
}
 
Example #17
Source File: CsvTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns the field types of this CSV table. */
public List<CsvFieldType> getFieldTypes(RelDataTypeFactory typeFactory) {
  if (fieldTypes == null) {
    fieldTypes = new ArrayList<>();
    CsvEnumerator.deduceRowType((JavaTypeFactory) typeFactory, source,
        fieldTypes, isStream());
  }
  return fieldTypes;
}
 
Example #18
Source File: ElasticsearchProject.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
public void implement(Implementor implementor) {
     implementor.visitChild(0, getInput());

     ElasticsearchTable esTable = implementor.getElasticsearchTable();

     final ElasticsearchRules.RexToElasticsearchTranslator translator =
             new ElasticsearchRules.RexToElasticsearchTranslator(
                     (JavaTypeFactory) getCluster().getTypeFactory(),
                     ElasticsearchRules.elasticsearchFieldNames(getInput().getRowType()));
     for (Pair<RexNode, String> pair : getNamedProjects()) {
         final String selectField = pair.right;
         final String originalName = pair.left.accept(translator);
         implementor.add(selectField);
     }
}
 
Example #19
Source File: RexFuzzer.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Generates randomized {@link RexNode}.
 *
 * @param rexBuilder  builder to be used to create nodes
 * @param typeFactory type factory
 */
public RexFuzzer(RexBuilder rexBuilder, JavaTypeFactory typeFactory) {
  setUp();
  this.rexBuilder = rexBuilder;
  this.typeFactory = typeFactory;

  intType = typeFactory.createSqlType(SqlTypeName.INTEGER);
  nullableIntType = typeFactory.createTypeWithNullability(intType, true);
}
 
Example #20
Source File: CloneSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType,
    final List<ColumnMetaData.Rep> repList,
    final Enumerable<T> source) {
  return createCloneTable(typeFactory, protoRowType, ImmutableList.of(),
      repList, source);
}
 
Example #21
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private List<ColumnMetaData> getColumnMetaDataList(
    JavaTypeFactory typeFactory, RelDataType x, RelDataType jdbcType,
    List<List<String>> originList) {
  final List<ColumnMetaData> columns = new ArrayList<>();
  for (Ord<RelDataTypeField> pair : Ord.zip(jdbcType.getFieldList())) {
    final RelDataTypeField field = pair.e;
    final RelDataType type = field.getType();
    final RelDataType fieldType =
        x.isStruct() ? x.getFieldList().get(pair.i).getType() : type;
    columns.add(
        metaData(typeFactory, columns.size(), field.getName(), type,
            fieldType, originList.get(pair.i)));
  }
  return columns;
}
 
Example #22
Source File: PlanExecutor.java    From quark with Apache License 2.0 5 votes vote down vote up
private ColumnMetaData metaData(JavaTypeFactory typeFactory, int ordinal,
                                String fieldName, RelDataType type, RelDataType fieldType,
                                List<String> origins) {
  final ColumnMetaData.AvaticaType avaticaType =
      avaticaType(typeFactory, type, fieldType);
  return new ColumnMetaData(
      ordinal,
      false,
      true,
      false,
      false,
      type.isNullable()
          ? DatabaseMetaData.columnNullable
          : DatabaseMetaData.columnNoNulls,
      true,
      type.getPrecision(),
      fieldName,
      origin(origins, 0),
      origin(origins, 2),
      getPrecision(type),
      getScale(type),
      origin(origins, 1),
      null,
      avaticaType,
      true,
      false,
      false,
      avaticaType.columnClassName());
}
 
Example #23
Source File: JdbcToEnumerableConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlString generateSql(SqlDialect dialect) {
  final JdbcImplementor jdbcImplementor =
      new JdbcImplementor(dialect,
          (JavaTypeFactory) getCluster().getTypeFactory());
  final JdbcImplementor.Result result =
      jdbcImplementor.visitChild(0, getInput());
  return result.asStatement().toSqlString(dialect);
}
 
Example #24
Source File: PhysTypeImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static PhysType of(
    JavaTypeFactory typeFactory,
    RelDataType rowType,
    JavaRowFormat format,
    boolean optimize) {
  if (optimize) {
    format = format.optimize(rowType);
  }
  final Type javaRowClass = format.javaRowClass(typeFactory, rowType);
  return new PhysTypeImpl(typeFactory, rowType, javaRowClass, format);
}
 
Example #25
Source File: FileEndpoint.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public RelInfo populateInputDAG(DAG dag, JavaTypeFactory typeFactory)
{
  LineReader fileInput = dag.addOperator(OperatorUtils.getUniqueOperatorName("FileInput"), LineReader.class);
  fileInput.setDirectory((String)operands.get(FILE_INPUT_DIRECTORY));

  RelInfo spec = messageFormat.populateInputDAG(dag, typeFactory);
  dag.addStream(OperatorUtils.getUniqueStreamName("File", "Parser"), fileInput.output, spec.getInputPorts().get(0));
  return new RelInfo("Input", Lists.<Operator.InputPort>newArrayList(), spec.getOperator(), spec.getOutPort(),
    messageFormat.getRowType(typeFactory));
}
 
Example #26
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private ColumnMetaData.AvaticaType avaticaType(JavaTypeFactory typeFactory,
    RelDataType type, RelDataType fieldType) {
  final String typeName = getTypeName(type);
  if (type.getComponentType() != null) {
    final ColumnMetaData.AvaticaType componentType =
        avaticaType(typeFactory, type.getComponentType(), null);
    final Type clazz = typeFactory.getJavaClass(type.getComponentType());
    final ColumnMetaData.Rep rep = ColumnMetaData.Rep.of(clazz);
    assert rep != null;
    return ColumnMetaData.array(componentType, typeName, rep);
  } else {
    int typeOrdinal = getTypeOrdinal(type);
    switch (typeOrdinal) {
    case Types.STRUCT:
      final List<ColumnMetaData> columns = new ArrayList<>(type.getFieldList().size());
      for (RelDataTypeField field : type.getFieldList()) {
        columns.add(
            metaData(typeFactory, field.getIndex(), field.getName(),
                field.getType(), null, null));
      }
      return ColumnMetaData.struct(columns);
    case ExtraSqlTypes.GEOMETRY:
      typeOrdinal = Types.VARCHAR;
      // fall through
    default:
      final Type clazz =
          typeFactory.getJavaClass(Util.first(fieldType, type));
      final ColumnMetaData.Rep rep = ColumnMetaData.Rep.of(clazz);
      assert rep != null;
      return ColumnMetaData.scalar(typeOrdinal, typeName, rep);
    }
  }
}
 
Example #27
Source File: FileRowConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
RelDataType getRowType(JavaTypeFactory typeFactory) {
  initialize();
  List<String> names = new ArrayList<>();
  List<RelDataType> types = new ArrayList<>();

  // iterate through FieldDefs, populating names and types
  for (FieldDef f : this.fields) {
    names.add(f.getName());

    FileFieldType fieldType = f.getType();
    RelDataType type;

    if (fieldType == null) {
      type = typeFactory.createJavaType(String.class);
    } else {
      type = fieldType.toType(typeFactory);
    }

    types.add(type);
  }

  if (names.isEmpty()) {
    names.add("line");
    types.add(typeFactory.createJavaType(String.class));
  }

  return typeFactory.createStructType(Pair.zip(names, types));
}
 
Example #28
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private ParseResult convert_(Context context, String sql, boolean analyze,
    boolean fail, CalciteCatalogReader catalogReader, SqlValidator validator,
    SqlNode sqlNode1) {
  final JavaTypeFactory typeFactory = context.getTypeFactory();
  final Convention resultConvention =
      enableBindable ? BindableConvention.INSTANCE
          : EnumerableConvention.INSTANCE;
  // Use the Volcano because it can handle the traits.
  final VolcanoPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

  final SqlToRelConverter.ConfigBuilder configBuilder =
      SqlToRelConverter.configBuilder().withTrimUnusedFields(true);

  final CalcitePreparingStmt preparingStmt =
      new CalcitePreparingStmt(this, context, catalogReader, typeFactory,
          context.getRootSchema(), null, createCluster(planner, new RexBuilder(typeFactory)),
          resultConvention, createConvertletTable());
  final SqlToRelConverter converter =
      preparingStmt.getSqlToRelConverter(validator, catalogReader,
          configBuilder.build());

  final RelRoot root = converter.convertQuery(sqlNode1, false, true);
  if (analyze) {
    return analyze_(validator, sql, sqlNode1, root, fail);
  }
  return new ConvertResult(this, validator, sql, sqlNode1,
      validator.getValidatedNodeType(sqlNode1), root);
}
 
Example #29
Source File: ExpressionCompiler.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * Create quasi-Java expression from given {@link RexNode}
 *
 * @param node Expression in the form of {@link RexNode}
 * @param inputRowType Input Data type to expression in the form of {@link RelDataType}
 * @param outputRowType Output data type of expression in the form of {@link RelDataType}
 *
 * @return Returns quasi-Java expression
 */
public String getExpression(RexNode node, RelDataType inputRowType, RelDataType outputRowType)
{
  final RexProgramBuilder programBuilder = new RexProgramBuilder(inputRowType, rexBuilder);
  programBuilder.addProject(node, null);
  final RexProgram program = programBuilder.getProgram();

  final BlockBuilder builder = new BlockBuilder();
  final JavaTypeFactory javaTypeFactory = (JavaTypeFactory)rexBuilder.getTypeFactory();

  final RexToLixTranslator.InputGetter inputGetter = new RexToLixTranslator.InputGetterImpl(ImmutableList
      .of(Pair.<Expression, PhysType>of(Expressions.variable(Object[].class, "inputValues"),
      PhysTypeImpl.of(javaTypeFactory, inputRowType, JavaRowFormat.ARRAY, false))));
  final Function1<String, RexToLixTranslator.InputGetter> correlates =
      new Function1<String, RexToLixTranslator.InputGetter>()
    {
      public RexToLixTranslator.InputGetter apply(String a0)
      {
        throw new UnsupportedOperationException();
      }
    };

  final List<Expression> list = RexToLixTranslator.translateProjects(program, javaTypeFactory, builder,
      PhysTypeImpl.of(javaTypeFactory, outputRowType, JavaRowFormat.ARRAY, false), null, inputGetter, correlates);

  for (int i = 0; i < list.size(); i++) {
    Statement statement = Expressions.statement(list.get(i));
    builder.add(statement);
  }

  return finalizeExpression(builder.toBlock(), inputRowType);
}
 
Example #30
Source File: PlanExecutor.java    From quark with Apache License 2.0 5 votes vote down vote up
private List<ColumnMetaData> getColumnMetaDataList(
    JavaTypeFactory typeFactory, RelDataType x, RelDataType jdbcType) {
  final List<ColumnMetaData> columns = new ArrayList<>();
  for (Ord<RelDataTypeField> pair : Ord.zip(jdbcType.getFieldList())) {
    final RelDataTypeField field = pair.e;
    final RelDataType type = field.getType();
    final RelDataType fieldType =
        x.isStruct() ? x.getFieldList().get(pair.i).getType() : type;
    columns.add(
        metaData(typeFactory, columns.size(), field.getName(), type,
            fieldType, null));
  }
  return columns;
}