org.apache.calcite.schema.Table Java Examples

The following examples show how to use org.apache.calcite.schema.Table. 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: DruidTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Creates a {@link DruidTable} by copying the given parameters.
 *
 * @param druidSchema Druid schema
 * @param dataSourceName Data source name in Druid, also table name
 * @param intervals Intervals, or null to use default
 * @param fieldMap Fully populated map of fields (dimensions plus metrics)
 * @param metricNameSet Fully populated set of metric names
 * @param timestampColumnName Name of timestamp column, or null
 * @param complexMetrics List of complex metrics in Druid (thetaSketch, hyperUnique)
 *
 * @return A table
 */
static Table create(DruidSchema druidSchema, String dataSourceName,
                    List<Interval> intervals, Map<String, SqlTypeName> fieldMap,
                    Set<String> metricNameSet, String timestampColumnName,
                    Map<String, List<ComplexMetric>> complexMetrics) {
  final ImmutableMap<String, SqlTypeName> fields =
          ImmutableMap.copyOf(fieldMap);
  return new DruidTable(druidSchema,
      dataSourceName,
      new MapRelProtoDataType(fields, timestampColumnName),
      ImmutableSet.copyOf(metricNameSet),
      timestampColumnName,
      intervals,
      complexMetrics,
      fieldMap);
}
 
Example #2
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public void validateSequenceValue(SqlValidatorScope scope, SqlIdentifier id) {
	// Resolve identifier as a table.
	final SqlValidatorScope.ResolvedImpl resolved =
		new SqlValidatorScope.ResolvedImpl();
	scope.resolveTable(id.names, catalogReader.nameMatcher(),
		SqlValidatorScope.Path.EMPTY, resolved);
	if (resolved.count() != 1) {
		throw newValidationError(id, RESOURCE.tableNameNotFound(id.toString()));
	}
	// We've found a table. But is it a sequence?
	final SqlValidatorNamespace ns = resolved.only().namespace;
	if (ns instanceof TableNamespace) {
		final Table table = ns.getTable().unwrap(Table.class);
		switch (table.getJdbcTableType()) {
			case SEQUENCE:
			case TEMPORARY_SEQUENCE:
				return;
		}
	}
	throw newValidationError(id, RESOURCE.notASequence(id.toString()));
}
 
Example #3
Source File: StreamRules.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Delta delta = call.rel(0);
  final TableScan scan = call.rel(1);
  final RelOptCluster cluster = delta.getCluster();
  final RelOptTable relOptTable = scan.getTable();
  final StreamableTable streamableTable =
      relOptTable.unwrap(StreamableTable.class);
  if (streamableTable != null) {
    final Table table1 = streamableTable.stream();
    final RelOptTable relOptTable2 =
        RelOptTableImpl.create(relOptTable.getRelOptSchema(),
            relOptTable.getRowType(), table1,
            ImmutableList.<String>builder()
                .addAll(relOptTable.getQualifiedName())
                .add("(STREAM)").build());
    final LogicalTableScan newScan =
        LogicalTableScan.create(cluster, relOptTable2);
    call.transformTo(newScan);
  }
}
 
Example #4
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
private boolean isRolledUpColumnAllowedInAgg(SqlIdentifier identifier, SqlValidatorScope scope,
	SqlCall aggCall, SqlNode parent) {
	Pair<String, String> pair = findTableColumnPair(identifier, scope);

	if (pair == null) {
		return true;
	}

	String columnName = pair.right;

	SqlValidatorTable sqlValidatorTable =
			scope.fullyQualify(identifier).namespace.getTable();
	if (sqlValidatorTable != null) {
		Table table = sqlValidatorTable.unwrap(Table.class);
		return table.rolledUpColumnValidInsideAgg(columnName, aggCall, parent,
				catalogReader.getConfig());
	}
	return true;
}
 
Example #5
Source File: TableFunctionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-2382">[CALCITE-2382]
 * Sub-query lateral joined to table function</a>. */
@Test void testInlineViewLateralTableFunction() throws SQLException {
  try (Connection connection = DriverManager.getConnection("jdbc:calcite:")) {
    CalciteConnection calciteConnection =
        connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = calciteConnection.getRootSchema();
    SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
    final TableFunction table =
        TableFunctionImpl.create(Smalls.GENERATE_STRINGS_METHOD);
    schema.add("GenerateStrings", table);
    Table tbl = new ScannableTableTest.SimpleTable();
    schema.add("t", tbl);

    final String sql = "select *\n"
        + "from (select 5 as f0 from \"s\".\"t\") \"a\",\n"
        + "  lateral table(\"s\".\"GenerateStrings\"(f0)) as t(n, c)\n"
        + "where char_length(c) > 3";
    ResultSet resultSet = connection.createStatement().executeQuery(sql);
    final String expected = "F0=5; N=4; C=abcd\n"
        + "F0=5; N=4; C=abcd\n"
        + "F0=5; N=4; C=abcd\n"
        + "F0=5; N=4; C=abcd\n";
    assertThat(CalciteAssert.toString(resultSet), equalTo(expected));
  }
}
 
Example #6
Source File: BatsOptimizerTest.java    From Bats with Apache License 2.0 6 votes vote down vote up
static Table createTable() {
    return new AbstractTable() {
        @Override
        public RelDataType getRowType(final RelDataTypeFactory typeFactory) {
            RelDataTypeFactory.Builder builder = typeFactory.builder();

            RelDataType t1 = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.INTEGER),
                    true);
            RelDataType t2 = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.INTEGER),
                    true);
            RelDataType t3 = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.INTEGER),
                    true);

            builder.add("f1", t1);
            builder.add("f2", t2);
            builder.add("f3", t3);
            return builder.build();
        }
    };
}
 
Example #7
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private boolean isRolledUpColumnAllowedInAgg(SqlIdentifier identifier, SqlValidatorScope scope,
	SqlCall aggCall, SqlNode parent) {
	Pair<String, String> pair = findTableColumnPair(identifier, scope);

	if (pair == null) {
		return true;
	}

	String tableAlias = pair.left;
	String columnName = pair.right;

	Table table = findTable(tableAlias);
	if (table != null) {
		return table.rolledUpColumnValidInsideAgg(columnName, aggCall, parent,
			catalogReader.getConfig());
	}
	return true;
}
 
Example #8
Source File: ScannableTableTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testPFPushDownProjectFilterAggregateNested() {
  final StringBuilder buf = new StringBuilder();
  final String sql = "select \"k\", count(*) as c\n"
      + "from (\n"
      + "  select \"k\", \"i\" from \"s\".\"beatles\" group by \"k\", \"i\") t\n"
      + "where \"k\" = 1940\n"
      + "group by \"k\"";
  final Table table = new BeatlesProjectableFilterableTable(buf, false);
  final String explain = "PLAN="
      + "EnumerableAggregate(group=[{0}], C=[COUNT()])\n"
      + "  EnumerableAggregate(group=[{0, 1}])\n"
      + "    EnumerableInterpreter\n"
      + "      BindableTableScan(table=[[s, beatles]], filters=[[=($2, 1940)]], projects=[[2, 0]])";
  CalciteAssert.that()
      .with(newSchema("s", Pair.of("beatles", table)))
      .query(sql)
      .explainContains(explain)
      .returnsUnordered("k=1940; C=2");
}
 
Example #9
Source File: MockStorageEngine.java    From Bats with Apache License 2.0 6 votes vote down vote up
private Table getDirectTable(String name) {
  Pattern p = Pattern.compile("(\\w+)_(\\d+)(k|m)?", Pattern.CASE_INSENSITIVE);
  Matcher m = p.matcher(name);
  if (! m.matches()) {
    return null;
  }
  @SuppressWarnings("unused")
  String baseName = m.group(1);
  int n = Integer.parseInt(m.group(2));
  String unit = m.group(3);
  if (unit == null) { }
  else if (unit.equalsIgnoreCase("K")) { n *= 1000; }
  else if (unit.equalsIgnoreCase("M")) { n *= 1_000_000; }
  MockTableDef.MockScanEntry entry = new MockTableDef.MockScanEntry(n, true, 0, 1, null);
  List<MockTableDef.MockScanEntry> list = new ArrayList<>();
  list.add(entry);
  return new DynamicDrillTable(engine, this.name, list);
}
 
Example #10
Source File: ModifiableViewTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a mapping from the view index to the index in the underlying table.
 */
private static ImmutableIntList getNewColumnMapping(Table underlying,
    ImmutableIntList oldColumnMapping, List<RelDataTypeField> extendedColumns,
    RelDataTypeFactory typeFactory) {
  final List<RelDataTypeField> baseColumns =
      underlying.getRowType(typeFactory).getFieldList();
  final Map<String, Integer> nameToIndex = mapNameToIndex(baseColumns);

  final ImmutableList.Builder<Integer> newMapping = ImmutableList.builder();
  newMapping.addAll(oldColumnMapping);
  int newMappedIndex = baseColumns.size();
  for (RelDataTypeField extendedColumn : extendedColumns) {
    if (nameToIndex.containsKey(extendedColumn.getName())) {
      // The extended column duplicates a column in the underlying table.
      // Map to the index in the underlying table.
      newMapping.add(nameToIndex.get(extendedColumn.getName()));
    } else {
      // The extended column is not in the underlying table.
      newMapping.add(newMappedIndex++);
    }
  }
  return ImmutableIntList.copyOf(newMapping.build());
}
 
Example #11
Source File: Prepare.java    From calcite with Apache License 2.0 6 votes vote down vote up
public final RelOptTable extend(List<RelDataTypeField> extendedFields) {
  final Table table = unwrap(Table.class);

  // Get the set of extended columns that do not have the same name as a column
  // in the base table.
  final List<RelDataTypeField> baseColumns = getRowType().getFieldList();
  final List<RelDataTypeField> dedupedFields =
      RelOptUtil.deduplicateColumns(baseColumns, extendedFields);
  final List<RelDataTypeField> dedupedExtendedFields =
      dedupedFields.subList(baseColumns.size(), dedupedFields.size());

  if (table instanceof ExtensibleTable) {
    final Table extendedTable =
            ((ExtensibleTable) table).extend(dedupedExtendedFields);
    return extend(extendedTable);
  } else if (table instanceof ModifiableViewTable) {
    final ModifiableViewTable modifiableViewTable =
            (ModifiableViewTable) table;
    final ModifiableViewTable extendedView =
        modifiableViewTable.extend(dedupedExtendedFields,
            getRelOptSchema().getTypeFactory());
    return extend(extendedView);
  }
  throw new RuntimeException("Cannot extend " + table);
}
 
Example #12
Source File: CalciteCatalogReader.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Prepare.PreparingTable getTable(final List<String> names) {
  // First look in the default schema, if any.
  // If not found, look in the root schema.
  CalciteSchema.TableEntry entry = SqlValidatorUtil.getTableEntry(this, names);
  if (entry != null) {
    final Table table = entry.getTable();
    if (table instanceof Wrapper) {
      final Prepare.PreparingTable relOptTable =
          ((Wrapper) table).unwrap(Prepare.PreparingTable.class);
      if (relOptTable != null) {
        return relOptTable;
      }
    }
    return RelOptTableImpl.create(this,
        table.getRowType(typeFactory), entry, null);
  }
  return null;
}
 
Example #13
Source File: ReflectiveSchema.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Returns a table based on a particular field of this schema. If the
 * field is not of the right type to be a relation, returns null. */
private <T> Table fieldRelation(final Field field) {
  final Type elementType = getElementType(field.getType());
  if (elementType == null) {
    return null;
  }
  Object o;
  try {
    o = field.get(target);
  } catch (IllegalAccessException e) {
    throw new RuntimeException(
        "Error while accessing field " + field, e);
  }
  @SuppressWarnings("unchecked")
  final Enumerable<T> enumerable = toEnumerable(o);
  return new FieldTable<>(field, elementType, enumerable);
}
 
Example #14
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a {@code DROP MATERIALIZED VIEW} command. */
public void execute(SqlDropMaterializedView drop,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair = schema(context, true, drop.name);
  final Table table = pair.left.plus().getTable(pair.right);
  if (table != null) {
    // Materialized view exists.
    execute((SqlDropObject) drop, context);
    if (table instanceof Wrapper) {
      final MaterializationKey materializationKey =
          ((Wrapper) table).unwrap(MaterializationKey.class);
      if (materializationKey != null) {
        MaterializationService.instance()
            .removeMaterialization(materializationKey);
      }
    }
  }
}
 
Example #15
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
public void validateSequenceValue(SqlValidatorScope scope, SqlIdentifier id) {
	// Resolve identifier as a table.
	final SqlValidatorScope.ResolvedImpl resolved =
		new SqlValidatorScope.ResolvedImpl();
	scope.resolveTable(id.names, catalogReader.nameMatcher(),
		SqlValidatorScope.Path.EMPTY, resolved);
	if (resolved.count() != 1) {
		throw newValidationError(id, RESOURCE.tableNameNotFound(id.toString()));
	}
	// We've found a table. But is it a sequence?
	final SqlValidatorNamespace ns = resolved.only().namespace;
	if (ns instanceof TableNamespace) {
		final Table table = ns.getTable().unwrap(Table.class);
		switch (table.getJdbcTableType()) {
			case SEQUENCE:
			case TEMPORARY_SEQUENCE:
				return;
		}
	}
	throw newValidationError(id, RESOURCE.notASequence(id.toString()));
}
 
Example #16
Source File: SqlExprToRexConverterImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a catalog reader that contains a single {@link Table} with temporary table name
 * and specified {@code rowType}.
 *
 * @param rowType     table row type
 * @return the {@link CalciteCatalogReader} instance
 */
private static CalciteCatalogReader createSingleTableCatalogReader(
		boolean lenientCaseSensitivity,
		FrameworkConfig config,
		FlinkTypeFactory typeFactory,
		RelDataType rowType) {

	// connection properties
	boolean caseSensitive = !lenientCaseSensitivity && config.getParserConfig().caseSensitive();
	Properties properties = new Properties();
	properties.put(
		CalciteConnectionProperty.CASE_SENSITIVE.camelName(),
		String.valueOf(caseSensitive));
	CalciteConnectionConfig connectionConfig = new CalciteConnectionConfigImpl(properties);

	// prepare root schema
	final RowTypeSpecifiedTable table = new RowTypeSpecifiedTable(rowType);
	final Map<String, Table> tableMap = Collections.singletonMap(TEMPORARY_TABLE_NAME, table);
	CalciteSchema schema = CalciteSchemaBuilder.asRootSchema(new TableSpecifiedSchema(tableMap));

	return new FlinkCalciteCatalogReader(
		schema,
		new ArrayList<>(new ArrayList<>()),
		typeFactory,
		connectionConfig);
}
 
Example #17
Source File: CachingCalciteSchema.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected void addImplicitTablesBasedOnNullaryFunctionsToBuilder(
    ImmutableSortedMap.Builder<String, Table> builder) {
  ImmutableSortedMap<String, Table> explicitTables = builder.build();

  final long now = System.currentTimeMillis();
  final NameSet set = implicitFunctionCache.get(now);
  for (String s : set.iterable()) {
    // explicit table wins.
    if (explicitTables.containsKey(s)) {
      continue;
    }
    for (Function function : schema.getFunctions(s)) {
      if (function instanceof TableMacro
          && function.getParameters().isEmpty()) {
        final Table table = ((TableMacro) function).apply(ImmutableList.of());
        builder.put(s, table);
      }
    }
  }
}
 
Example #18
Source File: TpchSchema.java    From calcite with Apache License 2.0 6 votes vote down vote up
public TpchSchema(double scaleFactor, int part, int partCount,
    boolean columnPrefix) {
  this.scaleFactor = scaleFactor;
  this.part = part;
  this.partCount = partCount;
  this.columnPrefix = columnPrefix;

  final ImmutableMap.Builder<String, Table> builder = ImmutableMap.builder();
  for (TpchTable<?> tpchTable : TpchTable.getTables()) {
    builder.put(tpchTable.getTableName().toUpperCase(Locale.ROOT),
        new TpchQueryableTable(tpchTable));
  }
  this.tableMap = builder.build();

  this.columnPrefixes = ImmutableMap.<String, String>builder()
      .put("LINEITEM", "L_")
      .put("CUSTOMER", "C_")
      .put("SUPPLIER", "S_")
      .put("PARTSUPP", "PS_")
      .put("PART", "P_")
      .put("ORDERS", "O_")
      .put("NATION", "N_")
      .put("REGION", "R_")
      .build();
}
 
Example #19
Source File: DatabaseCalciteSchemaTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testCatalogTable() throws TableAlreadyExistException, DatabaseNotExistException {
	GenericInMemoryCatalog catalog = new GenericInMemoryCatalog(catalogName, databaseName);
	DatabaseCalciteSchema calciteSchema = new DatabaseCalciteSchema(true,
		databaseName,
		catalogName,
		catalog);

	catalog.createTable(new ObjectPath(databaseName, tableName), new TestCatalogBaseTable(), false);
	Table table = calciteSchema.getTable(tableName);

	assertThat(table, instanceOf(TableSourceTable.class));
	TableSourceTable tableSourceTable = (TableSourceTable) table;
	assertThat(tableSourceTable.tableSource(), instanceOf(TestExternalTableSource.class));
	assertThat(tableSourceTable.isStreamingMode(), is(true));
}
 
Example #20
Source File: JdbcRelBuilder.java    From calcite-sql-rewriter with Apache License 2.0 6 votes vote down vote up
public JdbcRelBuilder insertCopying(
		LogicalTableModify original,
		Table table
) {
	List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);

	push(new LogicalTableModify(
			cluster,
			original.getTraitSet(),
			relOptSchema.getTableForMember(name),
			original.getCatalogReader(),
			peek(),
			TableModify.Operation.INSERT,
			null,
			null,
			original.isFlattened()
	));
	return this;
}
 
Example #21
Source File: RelOptTableImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Function<Class, Expression> getClassExpressionFunction(
    final SchemaPlus schema, final String tableName, final Table table) {
  if (table instanceof QueryableTable) {
    final QueryableTable queryableTable = (QueryableTable) table;
    return clazz -> queryableTable.getExpression(schema, tableName, clazz);
  } else if (table instanceof ScannableTable
      || table instanceof FilterableTable
      || table instanceof ProjectableFilterableTable) {
    return clazz -> Schemas.tableExpression(schema, Object[].class, tableName,
        table.getClass());
  } else if (table instanceof StreamableTable) {
    return getClassExpressionFunction(schema, tableName,
        ((StreamableTable) table).stream());
  } else {
    return input -> {
      throw new UnsupportedOperationException();
    };
  }
}
 
Example #22
Source File: MockCatalogReader.java    From calcite with Apache License 2.0 5 votes vote down vote up
MockModifiableViewTable(Type elementType, RelProtoDataType rowType,
    String viewSql, List<String> schemaPath, List<String> viewPath,
    Table table, Path tablePath, RexNode constraint,
    ImmutableIntList columnMapping) {
  super(elementType, rowType, viewSql, schemaPath, viewPath, table,
      tablePath, constraint, columnMapping);
  this.constraint = constraint;
}
 
Example #23
Source File: DatabaseCalciteSchema.java    From flink with Apache License 2.0 5 votes vote down vote up
private Table convertCatalogTable(
		ObjectIdentifier identifier,
		CatalogTable table,
		TableSchema resolvedSchema,
		@Nullable TableFactory tableFactory) {
	final TableSource<?> tableSource;
	final TableSourceFactory.Context context = new TableSourceFactoryContextImpl(
			identifier, table, tableConfig.getConfiguration());
	if (tableFactory != null) {
		if (tableFactory instanceof TableSourceFactory) {
			tableSource = ((TableSourceFactory<?>) tableFactory).createTableSource(context);
		} else {
			throw new TableException(
				"Cannot query a sink-only table. TableFactory provided by catalog must implement TableSourceFactory");
		}
	} else {
		tableSource = TableFactoryUtil.findAndCreateTableSource(context);
	}

	if (!(tableSource instanceof StreamTableSource)) {
		throw new TableException("Catalog tables support only StreamTableSource and InputFormatTableSource");
	}

	return new TableSourceTable<>(
		resolvedSchema,
		tableSource,
		// this means the TableSource extends from StreamTableSource, this is needed for the
		// legacy Planner. Blink Planner should use the information that comes from the TableSource
		// itself to determine if it is a streaming or batch source.
		isStreamingMode,
		FlinkStatistic.UNKNOWN()
	);
}
 
Example #24
Source File: ViewHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Validates if view can be created in indicated schema:
 * checks if object (persistent / temporary table) with the same name exists
 * or if view with the same name exists but replace flag is not set
 * or if object with the same name exists but if not exists flag is set.
 *
 * @param drillSchema schema where views will be created
 * @param view create view call
 * @param context query context
 * @return if view can be created in indicated schema
 * @throws UserException if view cannot be created in indicated schema and no duplicate check requested
 */
private boolean checkViewCreationPossibility(AbstractSchema drillSchema, SqlCreateView view, QueryContext context) {
  final String schemaPath = drillSchema.getFullSchemaName();
  final String viewName = view.getName();
  final Table table = SqlHandlerUtil.getTableFromSchema(drillSchema, viewName);

  final boolean isTable = (table != null && table.getJdbcTableType() != Schema.TableType.VIEW)
    || context.getSession().isTemporaryTable(drillSchema, context.getConfig(), viewName);
  final boolean isView = (table != null && table.getJdbcTableType() == Schema.TableType.VIEW);

  switch (view.getSqlCreateType()) {
    case SIMPLE:
      if (isTable) {
        throw UserException
          .validationError()
          .message("A non-view table with given name [%s] already exists in schema [%s]", viewName, schemaPath)
          .build(logger);
      } else if (isView) {
        throw UserException
          .validationError()
          .message("A view with given name [%s] already exists in schema [%s]", viewName, schemaPath)
          .build(logger);
      }
      break;
    case OR_REPLACE:
      if (isTable) {
        throw UserException
          .validationError()
          .message("A non-view table with given name [%s] already exists in schema [%s]", viewName, schemaPath)
          .build(logger);
      }
      break;
    case IF_NOT_EXISTS:
      if (isTable || isView) {
        return false;
      }
      break;
  }
  return true;
}
 
Example #25
Source File: ModifiableViewTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a ModifiableViewTable. */
public ModifiableViewTable(Type elementType, RelProtoDataType rowType,
    String viewSql, List<String> schemaPath, List<String> viewPath,
    Table table, Path tablePath, RexNode constraint,
    ImmutableIntList columnMapping) {
  super(elementType, rowType, viewSql, schemaPath, viewPath);
  this.table = table;
  this.tablePath = tablePath;
  this.constraint = constraint;
  this.columnMapping = columnMapping;
  this.initializerExpressionFactory = new ModifiableViewTableInitializerExpressionFactory();
}
 
Example #26
Source File: EnumerableTableScan.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns whether EnumerableTableScan can generate code to handle a
 * particular variant of the Table SPI.
 **/
public static boolean canHandle(RelOptTable relOptTable) {
  Table table = relOptTable.unwrap(Table.class);
  if (table != null && !canHandle(table)) {
    return false;
  }
  boolean supportArray = CalciteSystemProperty.ENUMERABLE_ENABLE_TABLESCAN_ARRAY.value();
  boolean supportMap = CalciteSystemProperty.ENUMERABLE_ENABLE_TABLESCAN_MAP.value();
  boolean supportMultiset = CalciteSystemProperty.ENUMERABLE_ENABLE_TABLESCAN_MULTISET.value();
  if (supportArray && supportMap && supportMultiset) {
    return true;
  }
  // Struct fields are not supported in EnumerableTableScan
  for (RelDataTypeField field : relOptTable.getRowType().getFieldList()) {
    boolean unsupportedType = false;
    switch (field.getType().getSqlTypeName()) {
    case ARRAY:
      unsupportedType = supportArray;
      break;
    case MAP:
      unsupportedType = supportMap;
      break;
    case MULTISET:
      unsupportedType = supportMultiset;
      break;
    default:
      break;
    }
    if (unsupportedType) {
      return false;
    }
  }
  return true;
}
 
Example #27
Source File: JdbcSchema.java    From quark with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(QueryContext queryContext, SchemaPlus schemaPlus) {
  this.schemaPlus = schemaPlus;
  for (Map.Entry<String, Table> entry : tableMap.entrySet()) {
    this.schemaPlus.add(entry.getKey(), entry.getValue());
  }
}
 
Example #28
Source File: EnumerableTableScan.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates an EnumerableTableScan. */
public static EnumerableTableScan create(RelOptCluster cluster,
    RelOptTable relOptTable) {
  final Table table = relOptTable.unwrap(Table.class);
  Class elementType = EnumerableTableScan.deduceElementType(table);
  final RelTraitSet traitSet =
      cluster.traitSetOf(EnumerableConvention.INSTANCE)
          .replaceIfs(RelCollationTraitDef.INSTANCE, () -> {
            if (table != null) {
              return table.getStatistic().getCollations();
            }
            return ImmutableList.of();
          });
  return new EnumerableTableScan(cluster, traitSet, relOptTable, elementType);
}
 
Example #29
Source File: StarTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelDataType getRowType(RelDataTypeFactory typeFactory) {
  final List<RelDataType> typeList = new ArrayList<>();
  final List<Integer> fieldCounts = new ArrayList<>();
  for (Table table : tables) {
    final RelDataType rowType = table.getRowType(typeFactory);
    typeList.addAll(RelOptUtil.getFieldTypeList(rowType));
    fieldCounts.add(rowType.getFieldCount());
  }
  // Compute fieldCounts the first time this method is called. Safe to assume
  // that the field counts will be the same whichever type factory is used.
  if (this.fieldCounts == null) {
    this.fieldCounts = ImmutableIntList.copyOf(fieldCounts);
  }
  return typeFactory.createStructType(typeList, lattice.uniqueColumnNames());
}
 
Example #30
Source File: RedisTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
static Table create(
    RedisSchema schema,
    String tableName,
    RedisConfig redisConfig,
    RelProtoDataType protoRowType) {
  RedisTableFieldInfo tableFieldInfo = schema.getTableFieldInfo(tableName);
  Map<String, Object> allFields = RedisEnumerator.deduceRowType(tableFieldInfo);
  return new RedisTable(schema, tableName, protoRowType,
      allFields, tableFieldInfo.getDataFormat(), redisConfig);
}