Java Code Examples for org.apache.calcite.schema.Table#getRowType()

The following examples show how to use org.apache.calcite.schema.Table#getRowType() . 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: InfoSchemaRecordGenerator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Visit the tables in the given schema. The
 * @param  schemaPath  the path to the given schema
 * @param  schema  the given schema
 */
public void visitTables(String schemaPath, SchemaPlus schema) {
  final AbstractSchema drillSchema = schema.unwrap(AbstractSchema.class);
  for (Pair<String, ? extends Table> tableNameToTable : drillSchema.getTablesByNames(schema.getTableNames())) {
    final String tableName = tableNameToTable.getKey();
    final Table table = tableNameToTable.getValue();
    final TableType tableType = table.getJdbcTableType();
    // Visit the table, and if requested ...
    if(shouldVisitTable(schemaPath, tableName, tableType) && visitTable(schemaPath, tableName, table)) {
      // ... do for each of the table's fields.
      final RelDataType tableRow = table.getRowType(new JavaTypeFactoryImpl(DRILL_REL_DATATYPE_SYSTEM));
      for (RelDataTypeField field: tableRow.getFieldList()) {
        if (shouldVisitColumn(schemaPath, tableName, field.getName())) {
          visitField(schemaPath, tableName, field);
        }
      }
    }
  }
}
 
Example 2
Source File: StarTable.java    From Bats 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 3
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Validates updates against the constraint of a modifiable view.
 *
 * @param validatorTable A {@link SqlValidatorTable} that may wrap a
 *                       ModifiableViewTable
 * @param update         The UPDATE parse tree node
 * @param targetRowType  The target type
 */
private void checkConstraint(
	SqlValidatorTable validatorTable,
	SqlUpdate update,
	RelDataType targetRowType) {
	final ModifiableViewTable modifiableViewTable =
		validatorTable.unwrap(ModifiableViewTable.class);
	if (modifiableViewTable != null) {
		final Table table = modifiableViewTable.unwrap(Table.class);
		final RelDataType tableRowType = table.getRowType(typeFactory);

		final Map<Integer, RexNode> projectMap =
			RelOptUtil.getColumnConstraints(modifiableViewTable, targetRowType,
				typeFactory);
		final Map<String, Integer> nameToIndex =
			SqlValidatorUtil.mapNameToIndex(tableRowType.getFieldList());

		// Validate update values against the view constraint.
		final List<SqlNode> targets = update.getTargetColumnList().getList();
		final List<SqlNode> sources = update.getSourceExpressionList().getList();
		for (final Pair<SqlNode, SqlNode> column : Pair.zip(targets, sources)) {
			final String columnName = ((SqlIdentifier) column.left).getSimple();
			final Integer columnIndex = nameToIndex.get(columnName);
			if (projectMap.containsKey(columnIndex)) {
				final RexNode columnConstraint = projectMap.get(columnIndex);
				final ValidationError validationError =
					new ValidationError(column.right,
						RESOURCE.viewConstraintNotSatisfied(columnName,
							Util.last(validatorTable.getQualifiedName())));
				RelOptUtil.validateValueAgainstConstraint(column.right,
					columnConstraint, validationError);
			}
		}
	}
}
 
Example 4
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Validates updates against the constraint of a modifiable view.
 *
 * @param validatorTable A {@link SqlValidatorTable} that may wrap a
 *                       ModifiableViewTable
 * @param update         The UPDATE parse tree node
 * @param targetRowType  The target type
 */
private void checkConstraint(
	SqlValidatorTable validatorTable,
	SqlUpdate update,
	RelDataType targetRowType) {
	final ModifiableViewTable modifiableViewTable =
		validatorTable.unwrap(ModifiableViewTable.class);
	if (modifiableViewTable != null) {
		final Table table = modifiableViewTable.unwrap(Table.class);
		final RelDataType tableRowType = table.getRowType(typeFactory);

		final Map<Integer, RexNode> projectMap =
			RelOptUtil.getColumnConstraints(modifiableViewTable, targetRowType,
				typeFactory);
		final Map<String, Integer> nameToIndex =
			SqlValidatorUtil.mapNameToIndex(tableRowType.getFieldList());

		// Validate update values against the view constraint.
		final List<SqlNode> targets = update.getTargetColumnList().getList();
		final List<SqlNode> sources = update.getSourceExpressionList().getList();
		for (final Pair<SqlNode, SqlNode> column : Pair.zip(targets, sources)) {
			final String columnName = ((SqlIdentifier) column.left).getSimple();
			final Integer columnIndex = nameToIndex.get(columnName);
			if (projectMap.containsKey(columnIndex)) {
				final RexNode columnConstraint = projectMap.get(columnIndex);
				final ValidationError validationError =
					new ValidationError(column.right,
						RESOURCE.viewConstraintNotSatisfied(columnName,
							Util.last(validatorTable.getQualifiedName())));
				RelOptUtil.validateValueAgainstConstraint(column.right,
					columnConstraint, validationError);
			}
		}
	}
}
 
Example 5
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 6
Source File: MockCatalogReader.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override protected RelOptTable extend(final Table extendedTable) {
  return new MockTable(catalogReader, names, stream, temporal, rowCount,
      resolver, initializerFactory) {
    @Override public RelDataType getRowType() {
      return extendedTable.getRowType(catalogReader.typeFactory);
    }
  };
}
 
Example 7
Source File: EmptyScope.java    From Bats with Apache License 2.0 4 votes vote down vote up
private void resolve_(final CalciteSchema rootSchema, List<String> names,
    List<String> schemaNames, SqlNameMatcher nameMatcher, Path path,
    Resolved resolved) {
  final List<String> concat = ImmutableList.<String>builder()
      .addAll(schemaNames).addAll(names).build();
  CalciteSchema schema = rootSchema;
  SqlValidatorNamespace namespace = null;
  List<String> remainingNames = concat;
  for (String schemaName : concat) {
    if (schema == rootSchema
        && nameMatcher.matches(schemaName, schema.name)) {
      remainingNames = Util.skip(remainingNames);
      continue;
    }
    final CalciteSchema subSchema =
        schema.getSubSchema(schemaName, nameMatcher.isCaseSensitive());
    if (subSchema != null) {
      path = path.plus(null, -1, subSchema.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      schema = subSchema;
      namespace = new SchemaNamespace(validator,
          ImmutableList.copyOf(path.stepNames()));
      continue;
    }
    CalciteSchema.TableEntry entry =
        schema.getTable(schemaName, nameMatcher.isCaseSensitive());
    if (entry == null) {
      entry = schema.getTableBasedOnNullaryFunction(schemaName,
          nameMatcher.isCaseSensitive());
    }
    if (entry != null) {
      path = path.plus(null, -1, entry.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      final Table table = entry.getTable();
      SqlValidatorTable table2 = null;
      if (table instanceof Wrapper) {
        table2 = ((Wrapper) table).unwrap(PreparingTable.class);
      }
      if (table2 == null) {
        final RelOptSchema relOptSchema =
            validator.catalogReader.unwrap(RelOptSchema.class);
        final RelDataType rowType = table.getRowType(validator.typeFactory);
        table2 = RelOptTableImpl.create(relOptSchema, rowType, entry, null);
      }
      namespace = new TableNamespace(validator, table2);
      resolved.found(namespace, false, null, path, remainingNames);
      return;
    }
    // neither sub-schema nor table
    if (namespace != null
        && !remainingNames.equals(names)) {
      resolved.found(namespace, false, null, path, remainingNames);
    }
    return;
  }
}
 
Example 8
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Validates insert values against the constraint of a modifiable view.
 *
 * @param validatorTable Table that may wrap a ModifiableViewTable
 * @param source        The values being inserted
 * @param targetRowType The target type for the view
 */
private void checkConstraint(
	SqlValidatorTable validatorTable,
	SqlNode source,
	RelDataType targetRowType) {
	final ModifiableViewTable modifiableViewTable =
		validatorTable.unwrap(ModifiableViewTable.class);
	if (modifiableViewTable != null && source instanceof SqlCall) {
		final Table table = modifiableViewTable.unwrap(Table.class);
		final RelDataType tableRowType = table.getRowType(typeFactory);
		final List<RelDataTypeField> tableFields = tableRowType.getFieldList();

		// Get the mapping from column indexes of the underlying table
		// to the target columns and view constraints.
		final Map<Integer, RelDataTypeField> tableIndexToTargetField =
			SqlValidatorUtil.getIndexToFieldMap(tableFields, targetRowType);
		final Map<Integer, RexNode> projectMap =
			RelOptUtil.getColumnConstraints(modifiableViewTable, targetRowType, typeFactory);

		// Determine columns (indexed to the underlying table) that need
		// to be validated against the view constraint.
		final ImmutableBitSet targetColumns =
			ImmutableBitSet.of(tableIndexToTargetField.keySet());
		final ImmutableBitSet constrainedColumns =
			ImmutableBitSet.of(projectMap.keySet());
		final ImmutableBitSet constrainedTargetColumns =
			targetColumns.intersect(constrainedColumns);

		// Validate insert values against the view constraint.
		final List<SqlNode> values = ((SqlCall) source).getOperandList();
		for (final int colIndex : constrainedTargetColumns.asList()) {
			final String colName = tableFields.get(colIndex).getName();
			final RelDataTypeField targetField = tableIndexToTargetField.get(colIndex);
			for (SqlNode row : values) {
				final SqlCall call = (SqlCall) row;
				final SqlNode sourceValue = call.operand(targetField.getIndex());
				final ValidationError validationError =
					new ValidationError(sourceValue,
						RESOURCE.viewConstraintNotSatisfied(colName,
							Util.last(validatorTable.getQualifiedName())));
				RelOptUtil.validateValueAgainstConstraint(sourceValue,
					projectMap.get(colIndex), validationError);
			}
		}
	}
}
 
Example 9
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Validates insert values against the constraint of a modifiable view.
 *
 * @param validatorTable Table that may wrap a ModifiableViewTable
 * @param source        The values being inserted
 * @param targetRowType The target type for the view
 */
private void checkConstraint(
	SqlValidatorTable validatorTable,
	SqlNode source,
	RelDataType targetRowType) {
	final ModifiableViewTable modifiableViewTable =
		validatorTable.unwrap(ModifiableViewTable.class);
	if (modifiableViewTable != null && source instanceof SqlCall) {
		final Table table = modifiableViewTable.unwrap(Table.class);
		final RelDataType tableRowType = table.getRowType(typeFactory);
		final List<RelDataTypeField> tableFields = tableRowType.getFieldList();

		// Get the mapping from column indexes of the underlying table
		// to the target columns and view constraints.
		final Map<Integer, RelDataTypeField> tableIndexToTargetField =
			SqlValidatorUtil.getIndexToFieldMap(tableFields, targetRowType);
		final Map<Integer, RexNode> projectMap =
			RelOptUtil.getColumnConstraints(modifiableViewTable, targetRowType, typeFactory);

		// Determine columns (indexed to the underlying table) that need
		// to be validated against the view constraint.
		final ImmutableBitSet targetColumns =
			ImmutableBitSet.of(tableIndexToTargetField.keySet());
		final ImmutableBitSet constrainedColumns =
			ImmutableBitSet.of(projectMap.keySet());
		final ImmutableBitSet constrainedTargetColumns =
			targetColumns.intersect(constrainedColumns);

		// Validate insert values against the view constraint.
		final List<SqlNode> values = ((SqlCall) source).getOperandList();
		for (final int colIndex : constrainedTargetColumns.asList()) {
			final String colName = tableFields.get(colIndex).getName();
			final RelDataTypeField targetField = tableIndexToTargetField.get(colIndex);
			for (SqlNode row : values) {
				final SqlCall call = (SqlCall) row;
				final SqlNode sourceValue = call.operand(targetField.getIndex());
				final ValidationError validationError =
					new ValidationError(sourceValue,
						RESOURCE.viewConstraintNotSatisfied(colName,
							Util.last(validatorTable.getQualifiedName())));
				RelOptUtil.validateValueAgainstConstraint(sourceValue,
					projectMap.get(colIndex), validationError);
			}
		}
	}
}
 
Example 10
Source File: MaterializationService.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Defines a new materialization. Returns its key. */
public MaterializationKey defineMaterialization(final CalciteSchema schema,
    TileKey tileKey, String viewSql, List<String> viewSchemaPath,
    String suggestedTableName, TableFactory tableFactory, boolean create,
    boolean existing) {
  final MaterializationActor.QueryKey queryKey =
      new MaterializationActor.QueryKey(viewSql, schema, viewSchemaPath);
  final MaterializationKey existingKey = actor.keyBySql.get(queryKey);
  if (existingKey != null) {
    return existingKey;
  }
  if (!create) {
    return null;
  }

  final CalciteConnection connection =
      CalciteMetaImpl.connect(schema.root(), null);
  CalciteSchema.TableEntry tableEntry;
  // If the user says the materialization exists, first try to find a table
  // with the name and if none can be found, lookup a view in the schema
  if (existing) {
    tableEntry = schema.getTable(suggestedTableName, true);
    if (tableEntry == null) {
      tableEntry = schema.getTableBasedOnNullaryFunction(suggestedTableName, true);
    }
  } else {
    tableEntry = null;
  }
  if (tableEntry == null) {
    tableEntry = schema.getTableBySql(viewSql);
  }

  RelDataType rowType = null;
  if (tableEntry == null) {
    Table table = tableFactory.createTable(schema, viewSql, viewSchemaPath);
    final String tableName = Schemas.uniqueTableName(schema,
        Util.first(suggestedTableName, "m"));
    tableEntry = schema.add(tableName, table, ImmutableList.of(viewSql));
    Hook.CREATE_MATERIALIZATION.run(tableName);
    rowType = table.getRowType(connection.getTypeFactory());
  }

  if (rowType == null) {
    // If we didn't validate the SQL by populating a table, validate it now.
    final CalcitePrepare.ParseResult parse =
        Schemas.parse(connection, schema, viewSchemaPath, viewSql);
    rowType = parse.rowType;
  }
  final MaterializationKey key = new MaterializationKey();
  final MaterializationActor.Materialization materialization =
      new MaterializationActor.Materialization(key, schema.root(),
          tableEntry, viewSql, rowType, viewSchemaPath);
  actor.keyMap.put(materialization.key, materialization);
  actor.keyBySql.put(queryKey, materialization.key);
  if (tileKey != null) {
    actor.keyByTile.put(tileKey, materialization.key);
  }
  return key;
}
 
Example 11
Source File: RelOptTableImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override protected RelOptTable extend(Table extendedTable) {
  final RelDataType extendedRowType =
      extendedTable.getRowType(getRelOptSchema().getTypeFactory());
  return new RelOptTableImpl(getRelOptSchema(), extendedRowType, getQualifiedName(),
      extendedTable, expressionFunction, getRowCount());
}
 
Example 12
Source File: EmptyScope.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void resolve_(final CalciteSchema rootSchema, List<String> names,
    List<String> schemaNames, SqlNameMatcher nameMatcher, Path path,
    Resolved resolved) {
  final List<String> concat = ImmutableList.<String>builder()
      .addAll(schemaNames).addAll(names).build();
  CalciteSchema schema = rootSchema;
  SqlValidatorNamespace namespace = null;
  List<String> remainingNames = concat;
  for (String schemaName : concat) {
    if (schema == rootSchema
        && nameMatcher.matches(schemaName, schema.name)) {
      remainingNames = Util.skip(remainingNames);
      continue;
    }
    final CalciteSchema subSchema =
        schema.getSubSchema(schemaName, nameMatcher.isCaseSensitive());
    if (subSchema != null) {
      path = path.plus(null, -1, subSchema.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      schema = subSchema;
      namespace = new SchemaNamespace(validator,
          ImmutableList.copyOf(path.stepNames()));
      continue;
    }
    CalciteSchema.TableEntry entry =
        schema.getTable(schemaName, nameMatcher.isCaseSensitive());
    if (entry == null) {
      entry = schema.getTableBasedOnNullaryFunction(schemaName,
          nameMatcher.isCaseSensitive());
    }
    if (entry != null) {
      path = path.plus(null, -1, entry.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      final Table table = entry.getTable();
      SqlValidatorTable table2 = null;
      if (table instanceof Wrapper) {
        table2 = ((Wrapper) table).unwrap(Prepare.PreparingTable.class);
      }
      if (table2 == null) {
        final RelOptSchema relOptSchema =
            validator.catalogReader.unwrap(RelOptSchema.class);
        final RelDataType rowType = table.getRowType(validator.typeFactory);
        table2 = RelOptTableImpl.create(relOptSchema, rowType, entry, null);
      }
      namespace = new TableNamespace(validator, table2);
      resolved.found(namespace, false, null, path, remainingNames);
      return;
    }
    // neither sub-schema nor table
    if (namespace != null
        && !remainingNames.equals(names)) {
      resolved.found(namespace, false, null, path, remainingNames);
    }
    return;
  }
}