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

The following examples show how to use org.apache.calcite.adapter.java.JavaTypeFactory. 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: marble   Source File: HiveRexExecutorImpl.java    License: 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 2
Source Project: marble   Source File: TableDataContexImpl.java    License: 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 Project: calcite   Source File: EnumerableTableFunctionScan.java    License: 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 4
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 5
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 6
Source Project: dremio-oss   Source File: TestSQLAnalyzer.java    License: 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 7
Source Project: calcite   Source File: RexToLixTranslator.java    License: 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 8
Source Project: attic-apex-malhar   Source File: KafkaEndpoint.java    License: 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 9
Source Project: calcite   Source File: RexExecutorImpl.java    License: 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 10
Source Project: quark   Source File: QuarkConnectionImpl.java    License: 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 11
Source Project: quark   Source File: SqlWorker.java    License: 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 12
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 13
Source Project: calcite   Source File: EnumerableInterpreter.java    License: 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 14
Source Project: calcite   Source File: PhysTypeImpl.java    License: 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 15
Source Project: calcite   Source File: RexFuzzer.java    License: 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 16
Source Project: calcite   Source File: PhysTypeImpl.java    License: Apache License 2.0 5 votes vote down vote up
static PhysType of(
    final JavaTypeFactory typeFactory,
    Type javaRowClass) {
  final RelDataTypeFactory.Builder builder = typeFactory.builder();
  if (javaRowClass instanceof Types.RecordType) {
    final Types.RecordType recordType = (Types.RecordType) javaRowClass;
    for (Types.RecordField field : recordType.getRecordFields()) {
      builder.add(field.getName(), typeFactory.createType(field.getType()));
    }
  }
  RelDataType rowType = builder.build();
  // Do not optimize if there are 0 or 1 fields.
  return new PhysTypeImpl(typeFactory, rowType, javaRowClass,
      JavaRowFormat.CUSTOM);
}
 
Example 17
Source Project: dk-fitting   Source File: ElasticsearchProject.java    License: 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 18
Source Project: dk-fitting   Source File: ElasticsearchProject.java    License: 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 Project: Mycat2   Source File: CalciteConvertors.java    License: 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 20
Source Project: dremio-oss   Source File: SQLAnalyzerFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Factory method to create the SQLAnalyzer using the appropriate implementation of SqlValidatorWithHints.
 *
 * If createForSqlSuggestions is true, construct a SqlAdvisorValidator instance,
 * otherwise construct a SqlValidatorImpl instance. Inject this into the constructor
 * for a SQLAnalyzer object.
 *
 * @param username
 * @param sabotContext
 * @param context
 * @param createForSqlSuggestions
 * @return SQLAnalyzer instance
 */
public static SQLAnalyzer createSQLAnalyzer(final String username,
                                            final SabotContext sabotContext,
                                            final List<String> context,
                                            final boolean createForSqlSuggestions,
                                            ProjectOptionManager projectOptionManager) {
  final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(username);
  final OptionManager optionManager = OptionManagerWrapper.Builder.newBuilder()
    .withOptionManager(new DefaultOptionManager(sabotContext.getOptionValidatorListing()))
    .withOptionManager(new EagerCachingOptionManager(projectOptionManager))
    .withOptionManager(new QueryOptionManager(sabotContext.getOptionValidatorListing()))
    .build();
  final NamespaceKey defaultSchemaPath = context == null ? null : new NamespaceKey(context);

  final SchemaConfig newSchemaConfig = SchemaConfig.newBuilder(username)
    .defaultSchema(defaultSchemaPath)
    .optionManager(optionManager)
    .setViewExpansionContext(viewExpansionContext)
    .build();

  Catalog catalog = sabotContext.getCatalogService()
      .getCatalog(MetadataRequestOptions.of(newSchemaConfig));
  JavaTypeFactory typeFactory = JavaTypeFactoryImpl.INSTANCE;
  DremioCatalogReader catalogReader = new DremioCatalogReader(catalog, typeFactory);

  FunctionImplementationRegistry functionImplementationRegistry = optionManager.getOption
    (PlannerSettings.ENABLE_DECIMAL_V2_KEY).getBoolVal() ? sabotContext.getDecimalFunctionImplementationRegistry()
      : sabotContext.getFunctionImplementationRegistry();
  OperatorTable opTable = new OperatorTable(functionImplementationRegistry);
  SqlOperatorTable chainedOpTable =  new ChainedSqlOperatorTable(ImmutableList.<SqlOperatorTable>of(opTable, catalogReader));

  // Create the appropriate implementation depending on intended use of the validator.
  SqlValidatorWithHints validator =
    createForSqlSuggestions ?
      new SqlAdvisorValidator(chainedOpTable, catalogReader, typeFactory, DremioSqlConformance.INSTANCE) :
      SqlValidatorUtil.newValidator(chainedOpTable, catalogReader, typeFactory, DremioSqlConformance.INSTANCE);

  return new SQLAnalyzer(validator);
}
 
Example 21
Source Project: calcite   Source File: CloneSchema.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
    final RelProtoDataType protoRowType, final List<RelCollation> collations,
    final List<ColumnMetaData.Rep> repList, final Enumerable<T> source) {
  final Type elementType;
  if (source instanceof QueryableTable) {
    elementType = ((QueryableTable) source).getElementType();
  } else if (protoRowType.apply(typeFactory).getFieldCount() == 1) {
    if (repList != null) {
      elementType = repList.get(0).clazz;
    } else {
      elementType = Object.class;
    }
  } else {
    elementType = Object[].class;
  }
  return new ArrayTable(
      elementType,
      protoRowType,
      Suppliers.memoize(() -> {
        final ColumnLoader loader =
            new ColumnLoader<>(typeFactory, source, protoRowType,
                repList);
        final List<RelCollation> collation2 =
            collations.isEmpty()
                && loader.sortField >= 0
                ? RelCollations.createSingleton(loader.sortField)
                : collations;
        return new ArrayTable.Content(loader.representationValues,
            loader.size(), collation2);
      }));
}
 
Example 22
Source Project: calcite   Source File: TraitPropagationTest.java    License: 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 23
Source Project: samza   Source File: SamzaSqlQueryParser.java    License: 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 24
Source Project: calcite   Source File: CloneSchema.java    License: 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 25
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 26
Source Project: attic-apex-malhar   Source File: FileEndpoint.java    License: 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 27
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 28
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 Project: attic-apex-malhar   Source File: ExpressionCompiler.java    License: 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 Project: calcite   Source File: RexToLixTranslator.java    License: Apache License 2.0 5 votes vote down vote up
public static Expression translateCondition(RexProgram program,
    JavaTypeFactory typeFactory, BlockBuilder list, InputGetter inputGetter,
    Function1<String, InputGetter> correlates, SqlConformance conformance) {
  if (program.getCondition() == null) {
    return RexImpTable.TRUE_EXPR;
  }
  final ParameterExpression root = DataContext.ROOT;
  RexToLixTranslator translator =
      new RexToLixTranslator(program, typeFactory, root, inputGetter, list,
          new RexBuilder(typeFactory), conformance, null);
  translator = translator.setCorrelates(correlates);
  return translator.translate(
      program.getCondition(),
      RexImpTable.NullAs.FALSE);
}