org.apache.calcite.schema.TranslatableTable Java Examples

The following examples show how to use org.apache.calcite.schema.TranslatableTable. 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: ViewTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RelRoot expandView(RelOptTable.ToRelContext context,
    RelDataType rowType, String queryString) {
  try {
    final RelRoot root =
        context.expandView(rowType, queryString, schemaPath, viewPath);
    final RelNode rel = RelOptUtil.createCastRel(root.rel, rowType, true);
    // Expand any views
    final RelNode rel2 = rel.accept(
        new RelShuttleImpl() {
          @Override public RelNode visit(TableScan scan) {
            final RelOptTable table = scan.getTable();
            final TranslatableTable translatableTable =
                table.unwrap(TranslatableTable.class);
            if (translatableTable != null) {
              return translatableTable.toRel(context, table);
            }
            return super.visit(scan);
          }
        });
    return root.withRel(rel2);
  } catch (Exception e) {
    throw new RuntimeException("Error while parsing view definition: "
        + queryString, e);
  }
}
 
Example #2
Source File: ViewTableMacro.java    From Bats with Apache License 2.0 6 votes vote down vote up
public TranslatableTable apply(List<Object> arguments) {
//    final CalciteConnection connection =
//        MaterializedViewTable.MATERIALIZATION_CONNECTION;
//    CalcitePrepare.AnalyzeViewResult parsed =
//        Schemas.analyzeView(connection, schema, schemaPath, viewSql, viewPath,
//            modifiable != null && modifiable);
//    final List<String> schemaPath1 =
//        schemaPath != null ? schemaPath : schema.path(null);
//    if ((modifiable == null || modifiable)
//        && parsed.modifiable
//        && parsed.table != null) {
//      return modifiableViewTable(parsed, viewSql, schemaPath1, viewPath, schema);
//    } else {
//      return viewTable(parsed, viewSql, schemaPath1, viewPath);
//    }
//    
    throw new UnsupportedOperationException();
  }
 
Example #3
Source File: ViewTableMacro.java    From calcite with Apache License 2.0 6 votes vote down vote up
public TranslatableTable apply(List<Object> arguments) {
  final CalciteConnection connection =
      MaterializedViewTable.MATERIALIZATION_CONNECTION;
  CalcitePrepare.AnalyzeViewResult parsed =
      Schemas.analyzeView(connection, schema, schemaPath, viewSql, viewPath,
          modifiable != null && modifiable);
  final List<String> schemaPath1 =
      schemaPath != null ? schemaPath : schema.path(null);
  if ((modifiable == null || modifiable)
      && parsed.modifiable
      && parsed.table != null) {
    return modifiableViewTable(parsed, viewSql, schemaPath1, viewPath, schema);
  } else {
    return viewTable(parsed, viewSql, schemaPath1, viewPath);
  }
}
 
Example #4
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a {@code CREATE VIEW} command. */
public void execute(SqlCreateView create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair =
      schema(context, true, create.name);
  final SchemaPlus schemaPlus = pair.left.plus();
  for (Function function : schemaPlus.getFunctions(pair.right)) {
    if (function.getParameters().isEmpty()) {
      if (!create.getReplace()) {
        throw SqlUtil.newContextException(create.name.getParserPosition(),
            RESOURCE.viewExists(pair.right));
      }
      pair.left.removeFunction(pair.right);
    }
  }
  final SqlNode q = renameColumns(create.columnList, create.query);
  final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
  final ViewTableMacro viewTableMacro =
      ViewTable.viewMacro(schemaPlus, sql, pair.left.path(null),
          context.getObjectPath(), false);
  final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
  Util.discard(x);
  schemaPlus.add(pair.right, viewTableMacro);
}
 
Example #5
Source File: QueryableRelBuilder.java    From calcite with Apache License 2.0 6 votes vote down vote up
RelNode toRel(Queryable<T> queryable) {
  if (queryable instanceof QueryableDefaults.Replayable) {
    //noinspection unchecked
    ((QueryableDefaults.Replayable) queryable).replay(this);
    return rel;
  }
  if (queryable instanceof AbstractTableQueryable) {
    final AbstractTableQueryable tableQueryable =
        (AbstractTableQueryable) queryable;
    final QueryableTable table = tableQueryable.table;
    final CalciteSchema.TableEntry tableEntry =
        CalciteSchema.from(tableQueryable.schema)
            .add(tableQueryable.tableName, tableQueryable.table);
    final RelOptTableImpl relOptTable =
        RelOptTableImpl.create(null, table.getRowType(translator.typeFactory),
            tableEntry, null);
    if (table instanceof TranslatableTable) {
      return ((TranslatableTable) table).toRel(translator.toRelContext(),
          relOptTable);
    } else {
      return LogicalTableScan.create(translator.cluster, relOptTable, ImmutableList.of());
    }
  }
  return translator.translate(queryable.getExpression());
}
 
Example #6
Source File: ReflectiveSchema.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Multimap<String, Function> createFunctionMap() {
  final ImmutableMultimap.Builder<String, Function> builder =
      ImmutableMultimap.builder();
  for (Method method : clazz.getMethods()) {
    final String methodName = method.getName();
    if (method.getDeclaringClass() == Object.class
        || methodName.equals("toString")) {
      continue;
    }
    if (TranslatableTable.class.isAssignableFrom(method.getReturnType())) {
      final TableMacro tableMacro =
          new MethodTableMacro(this, method);
      builder.put(methodName, tableMacro);
    }
  }
  return builder.build();
}
 
Example #7
Source File: ViewTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RelRoot expandView(RelOptTable.ToRelContext context,
    RelDataType rowType, String queryString) {
  try {
    final RelRoot root =
        context.expandView(rowType, queryString, schemaPath, viewPath);
    final RelNode rel = RelOptUtil.createCastRel(root.rel, rowType, true);
    // Expand any views
    final RelNode rel2 = rel.accept(
        new RelShuttleImpl() {
          @Override public RelNode visit(TableScan scan) {
            final RelOptTable table = scan.getTable();
            final TranslatableTable translatableTable =
                table.unwrap(TranslatableTable.class);
            if (translatableTable != null) {
              return translatableTable.toRel(context, table);
            }
            return super.visit(scan);
          }
        });
    return root.withRel(rel2);
  } catch (Exception e) {
    throw new RuntimeException("Error while parsing view definition: "
        + queryString, e);
  }
}
 
Example #8
Source File: SqlUserDefinedTableMacro.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Returns the table in this UDF, or null if there is no table. */
public TranslatableTable getTable(RelDataTypeFactory typeFactory,
    List<SqlNode> operandList) {
  List<Object> arguments = convertArguments(typeFactory, operandList,
      tableMacro, getNameAsId(), true);
  return tableMacro.apply(arguments);
}
 
Example #9
Source File: Smalls.java    From calcite with Apache License 2.0 5 votes vote down vote up
public TranslatableTable eval(
    @Parameter(name = "R", optional = true) String r,
    @Parameter(name = "S") String s,
    @Parameter(name = "T", optional = true) Integer t,
    @Parameter(name = "S2", optional = true) String s2) {
  final StringBuilder sb = new StringBuilder();
  abc(sb, r);
  abc(sb, s);
  abc(sb, t);
  return view(sb.toString());
}
 
Example #10
Source File: Smalls.java    From calcite with Apache License 2.0 5 votes vote down vote up
public TranslatableTable eval(
    @Parameter(name = "R", optional = true) String r,
    @Parameter(name = "S") String s,
    @Parameter(name = "T", optional = true) Integer t) {
  final StringBuilder sb = new StringBuilder();
  abc(sb, r);
  abc(sb, s);
  abc(sb, t);
  return view(sb.toString());
}
 
Example #11
Source File: Smalls.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static TranslatableTable str(Object o, Object p) {
  assertThat(RexLiteral.validConstant(o, Litmus.THROW), is(true));
  assertThat(RexLiteral.validConstant(p, Litmus.THROW), is(true));
  return new ViewTable(Object.class, typeFactory ->
      typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100).build(),
      "values " + CalciteSqlDialect.DEFAULT.quoteStringLiteral(o.toString())
          + ", " + CalciteSqlDialect.DEFAULT.quoteStringLiteral(p.toString()),
      ImmutableList.of(), Arrays.asList("view"));
}
 
Example #12
Source File: MaterializedViewTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public TranslatableTable apply(List<Object> arguments) {
  assert arguments.isEmpty();
  CalcitePrepare.ParseResult parsed =
      Schemas.parse(MATERIALIZATION_CONNECTION, schema, schemaPath,
          viewSql);
  final List<String> schemaPath1 =
      schemaPath != null ? schemaPath : schema.path(null);
  final JavaTypeFactory typeFactory =
      MATERIALIZATION_CONNECTION.getTypeFactory();
  return new MaterializedViewTable(typeFactory.getJavaClass(parsed.rowType),
      RelDataTypeImpl.proto(parsed.rowType), viewSql, schemaPath1, viewPath, key);
}
 
Example #13
Source File: MaterializedViewTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelNode toRel(RelOptTable.ToRelContext context,
    RelOptTable relOptTable) {
  final CalciteSchema.TableEntry tableEntry =
      MaterializationService.instance().checkValid(key);
  if (tableEntry != null) {
    Table materializeTable = tableEntry.getTable();
    if (materializeTable instanceof TranslatableTable) {
      TranslatableTable table = (TranslatableTable) materializeTable;
      return table.toRel(context, relOptTable);
    }
  }
  return super.toRel(context, relOptTable);
}
 
Example #14
Source File: TableMacroImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a {@code TableMacro} from a method. */
public static TableMacro create(final Method method) {
  Class clazz = method.getDeclaringClass();
  if (!Modifier.isStatic(method.getModifiers())) {
    if (!classHasPublicZeroArgsConstructor(clazz)) {
      throw RESOURCE.requireDefaultConstructor(clazz.getName()).ex();
    }
  }
  final Class<?> returnType = method.getReturnType();
  if (!TranslatableTable.class.isAssignableFrom(returnType)) {
    return null;
  }
  return new TableMacroImpl(method);
}
 
Example #15
Source File: SqlUserDefinedTableMacro.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns the table in this UDF, or null if there is no table. */
public TranslatableTable getTable(RelDataTypeFactory typeFactory,
    List<SqlNode> operandList) {
  List<Object> arguments = convertArguments(typeFactory, operandList,
      tableMacro, getNameAsId(), true);
  return tableMacro.apply(arguments);
}
 
Example #16
Source File: ReflectiveSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
public TranslatableTable apply(final List<Object> arguments) {
  try {
    final Object o = method.invoke(schema.getTarget(), arguments.toArray());
    return (TranslatableTable) o;
  } catch (IllegalAccessException | InvocationTargetException e) {
    throw new RuntimeException(e);
  }
}
 
Example #17
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Executes a {@code CREATE MATERIALIZED VIEW} command. */
public void execute(SqlCreateMaterializedView create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair = schema(context, true, create.name);
  if (pair.left.plus().getTable(pair.right) != null) {
    // Materialized view exists.
    if (!create.ifNotExists) {
      // They did not specify IF NOT EXISTS, so give error.
      throw SqlUtil.newContextException(create.name.getParserPosition(),
          RESOURCE.tableExists(pair.right));
    }
    return;
  }
  final SqlNode q = renameColumns(create.columnList, create.query);
  final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
  final List<String> schemaPath = pair.left.path(null);
  final ViewTableMacro viewTableMacro =
      ViewTable.viewMacro(pair.left.plus(), sql, schemaPath,
          context.getObjectPath(), false);
  final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
  final RelDataType rowType = x.getRowType(context.getTypeFactory());

  // Table does not exist. Create it.
  final MaterializedViewTable table =
      new MaterializedViewTable(pair.right, RelDataTypeImpl.proto(rowType));
  pair.left.add(pair.right, table);
  populate(create.name, create.query, context);
  table.key =
      MaterializationService.instance().defineMaterialization(pair.left, null,
          sql, schemaPath, pair.right, true, true);
}
 
Example #18
Source File: WorkspaceSchemaFactory.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public TranslatableTable apply(List<Object> arguments) {
  DrillTable drillTable = schema.getDrillTable(new TableInstance(sig, arguments));
  if (drillTable == null) {
    throw UserException
        .validationError()
        .message("Unable to find table [%s] in schema [%s]", sig.name, schema.getFullSchemaName())
        .build(logger);
}
  return new DrillTranslatableTable(drillTable);
}
 
Example #19
Source File: TableMacroImpl.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Creates a {@code TableMacro} from a method. */
public static TableMacro create(final Method method) {
  Class<?> clazz = method.getDeclaringClass();
  if (!Modifier.isStatic(method.getModifiers())) {
    if (!classHasPublicZeroArgsConstructor(clazz)) {
      throw RESOURCE.requireDefaultConstructor(clazz.getName()).ex();
    }
  }
  final Class<?> returnType = method.getReturnType();
  if (!TranslatableTable.class.isAssignableFrom(returnType)) {
    return null;
  }
  return new TableMacroImpl(method);
}
 
Example #20
Source File: RelFactories.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link TableScanFactory} that uses a
 * {@link org.apache.calcite.plan.RelOptTable.ViewExpander} to handle
 * {@link TranslatableTable} instances, and falls back to a default
 * factory for other tables.
 *
 * @param viewExpander View expander
 * @param tableScanFactory Factory for non-translatable tables
 * @return Table scan factory
 */
public static TableScanFactory expandingScanFactory(
    RelOptTable.ViewExpander viewExpander,
    TableScanFactory tableScanFactory) {
  return (cluster, table) -> {
    final TranslatableTable translatableTable =
        table.unwrap(TranslatableTable.class);
    if (translatableTable != null) {
      final RelOptTable.ToRelContext toRelContext =
          ViewExpanders.toRelContext(viewExpander, cluster);
      return translatableTable.toRel(toRelContext, table);
    }
    return tableScanFactory.createScan(cluster, table);
  };
}
 
Example #21
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static TranslatableTable view(String s) {
  return new ViewTable(Object.class, typeFactory ->
      typeFactory.builder().add("c", SqlTypeName.INTEGER).build(),
      "values (1), (3), " + s, ImmutableList.of(), Arrays.asList("view"));
}
 
Example #22
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static TranslatableTable strView(String s) {
  return new ViewTable(Object.class, typeFactory ->
      typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100).build(),
      "values (" + CalciteSqlDialect.DEFAULT.quoteStringLiteral(s) + ")",
      ImmutableList.of(), Arrays.asList("view"));
}
 
Example #23
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public TranslatableTable eval(String s) {
  return view(s);
}
 
Example #24
Source File: Smalls.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static TranslatableTable eval(String s) {
  return view(s);
}
 
Example #25
Source File: MaterializationTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
public TranslatableTable view(String s) {
  return Smalls.view(s);
}
 
Example #26
Source File: MaterializationTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
public TranslatableTable matview() {
  return Smalls.strView("noname");
}
 
Example #27
Source File: MockCatalogReaderDynamic.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override public MockCatalogReader init() {
  // Register "DYNAMIC" schema.
  MockSchema schema = new MockSchema("SALES");
  registerSchema(schema);

  MockDynamicTable nationTable =
      new MockDynamicTable(schema.getCatalogName(),
          schema.getName(), "NATION");
  registerTable(nationTable);

  Supplier<MockDynamicTable> customerTableSupplier = () ->
      new MockDynamicTable(schema.getCatalogName(), schema.getName(), "CUSTOMER");

  MockDynamicTable customerTable = customerTableSupplier.get();
  registerTable(customerTable);

  // CREATE TABLE "REGION" - static table with known schema.
  final RelDataType intType =
      typeFactory.createSqlType(SqlTypeName.INTEGER);
  final RelDataType varcharType =
      typeFactory.createSqlType(SqlTypeName.VARCHAR);

  MockTable regionTable =
      MockTable.create(this, schema, "REGION", false, 100);
  regionTable.addColumn("R_REGIONKEY", intType);
  regionTable.addColumn("R_NAME", varcharType);
  regionTable.addColumn("R_COMMENT", varcharType);
  registerTable(regionTable);

  List<String> custModifiableViewNames = Arrays.asList(
      schema.getCatalogName(), schema.getName(), "CUSTOMER_MODIFIABLEVIEW");
  TableMacro custModifiableViewMacro = MockModifiableViewRelOptTable.viewMacro(rootSchema,
      "select n_name from SALES.CUSTOMER", custModifiableViewNames.subList(0, 2),
      Collections.singletonList(custModifiableViewNames.get(2)), true);
  TranslatableTable empModifiableView = custModifiableViewMacro.apply(Collections.emptyList());
  MockTable mockCustViewTable = MockRelViewTable.create(
      (ViewTable) empModifiableView, this,
      custModifiableViewNames.get(0), custModifiableViewNames.get(1),
      custModifiableViewNames.get(2), false, 20, null);
  registerTable(mockCustViewTable);

  // re-registers customer table to clear its row type after view registration
  reregisterTable(customerTableSupplier.get());

  return this;
}
 
Example #28
Source File: ExtensionDdlExecutor.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Executes a {@code CREATE TABLE} command. Called via reflection. */
public void execute(SqlCreateTable create, CalcitePrepare.Context context) {
  final CalciteSchema schema =
      Schemas.subSchema(context.getRootSchema(),
          context.getDefaultSchemaPath());
  final JavaTypeFactory typeFactory = context.getTypeFactory();
  final RelDataType queryRowType;
  if (create.query != null) {
    // A bit of a hack: pretend it's a view, to get its row type
    final String sql =
        create.query.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
    final ViewTableMacro viewTableMacro =
        ViewTable.viewMacro(schema.plus(), sql, schema.path(null),
            context.getObjectPath(), false);
    final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
    queryRowType = x.getRowType(typeFactory);

    if (create.columnList != null
        && queryRowType.getFieldCount() != create.columnList.size()) {
      throw SqlUtil.newContextException(create.columnList.getParserPosition(),
          RESOURCE.columnCountMismatch());
    }
  } else {
    queryRowType = null;
  }
  final RelDataTypeFactory.Builder builder = typeFactory.builder();
  if (create.columnList != null) {
    final SqlValidator validator = new ContextSqlValidator(context, false);
    create.forEachNameType((name, typeSpec) ->
        builder.add(name.getSimple(), typeSpec.deriveType(validator, true)));
  } else {
    if (queryRowType == null) {
      // "CREATE TABLE t" is invalid; because there is no "AS query" we need
      // a list of column names and types, "CREATE TABLE t (INT c)".
      throw SqlUtil.newContextException(create.name.getParserPosition(),
          RESOURCE.createTableRequiresColumnList());
    }
    builder.addAll(queryRowType.getFieldList());
  }
  final RelDataType rowType = builder.build();
  schema.add(create.name.getSimple(),
      new MutableArrayTable(create.name.getSimple(),
          RelDataTypeImpl.proto(rowType)));
  if (create.query != null) {
    populate(create.name, create.query, context);
  }
}