use of io.prestosql.spi.plan.Assignments in project hetu-core by openlookeng.
the class TestTypeValidator method testInvalidProject.
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "type of symbol 'expr(_[0-9]+)?' is expected to be bigint, but the actual type is integer")
public void testInvalidProject() {
Expression expression1 = new Cast(toSymbolReference(columnB), StandardTypes.INTEGER);
Expression expression2 = new Cast(toSymbolReference(columnA), StandardTypes.INTEGER);
Assignments assignments = Assignments.builder().put(planSymbolAllocator.newSymbol(expression1, BIGINT), // should be INTEGER
castToRowExpression(expression1)).put(planSymbolAllocator.newSymbol(expression1, INTEGER), castToRowExpression(expression2)).build();
PlanNode node = new ProjectNode(newId(), baseTableScan, assignments);
assertTypesValid(node);
}
use of io.prestosql.spi.plan.Assignments in project hetu-core by openlookeng.
the class TestStarTreeAggregationRule method testSupportedProjectNode.
@Test
public void testSupportedProjectNode() {
// node is projectNode and expression instance of cast
Assignments assignment1 = Assignments.builder().put(columnCustkey, new VariableReferenceExpression(columnCustkey.getName(), custkeyHandle.getType())).build();
Optional<PlanNode> planNode1 = Optional.of(new ProjectNode(newId(), baseTableScan, assignment1));
assertTrue(CubeOptimizerUtil.supportedProjectNode(planNode1));
// not projectNode
ListMultimap<Symbol, Symbol> mappings = ImmutableListMultimap.<Symbol, Symbol>builder().put(output, columnOrderkey).put(output, columnOrderkey).build();
Optional<PlanNode> planNode2 = Optional.of(new UnionNode(newId(), ImmutableList.of(baseTableScan, baseTableScan), mappings, ImmutableList.copyOf(mappings.keySet())));
assertFalse(CubeOptimizerUtil.supportedProjectNode(planNode2));
// expression not instance of Cast
Assignments assignment2 = Assignments.builder().put(columnCustkey, new InputReferenceExpression(1, INTEGER)).build();
Optional<PlanNode> planNode3 = Optional.of(new ProjectNode(newId(), baseTableScan, assignment2));
assertFalse(CubeOptimizerUtil.supportedProjectNode(planNode3));
// expression is instance of SymbolReference OR Literal
Assignments assignment3 = Assignments.builder().put(columnCustkey, // should be INTEGER
new VariableReferenceExpression(columnCustkey.getName(), custkeyHandle.getType())).build();
Optional<PlanNode> planNode4 = Optional.of(new ProjectNode(newId(), baseTableScan, assignment3));
assertTrue(CubeOptimizerUtil.supportedProjectNode(planNode4));
// empty node
Optional<PlanNode> emptyPlanNode = Optional.empty();
assertTrue(CubeOptimizerUtil.supportedProjectNode(emptyPlanNode));
}
use of io.prestosql.spi.plan.Assignments in project hetu-core by openlookeng.
the class QueryPlanner method planUpdateRowAsInsert.
public UpdateDeleteRelationPlan planUpdateRowAsInsert(Update node) {
Table table = node.getTable();
RelationType descriptor = analysis.getOutputDescriptor(table);
TableHandle handle = analysis.getTableHandle(table);
ColumnHandle rowIdHandle = analysis.getRowIdHandle(table);
ColumnMetadata rowIdColumnMetadata = metadata.getColumnMetadata(session, handle, rowIdHandle);
// add table columns
ImmutableList.Builder<Symbol> outputSymbols = ImmutableList.builder();
ImmutableMap.Builder<Symbol, ColumnHandle> columnsBuilder = ImmutableMap.builder();
ImmutableList.Builder<Field> fields = ImmutableList.builder();
for (Field field : descriptor.getAllFields()) {
Symbol symbol = planSymbolAllocator.newSymbol(field);
outputSymbols.add(symbol);
columnsBuilder.put(symbol, analysis.getColumn(field));
fields.add(field);
}
// create table scan
ImmutableMap<Symbol, ColumnHandle> columns = columnsBuilder.build();
PlanNode tableScan = TableScanNode.newInstance(idAllocator.getNextId(), handle, outputSymbols.build(), columns, ReuseExchangeOperator.STRATEGY.REUSE_STRATEGY_DEFAULT, new UUID(0, 0), 0, true);
Scope scope = Scope.builder().withRelationType(RelationId.anonymous(), new RelationType(fields.build())).build();
RelationPlan relationPlan = new RelationPlan(tableScan, scope, outputSymbols.build());
TranslationMap translations = new TranslationMap(relationPlan, analysis, lambdaDeclarationToSymbolMap);
translations.setFieldMappings(relationPlan.getFieldMappings());
PlanBuilder builder = new PlanBuilder(translations, relationPlan.getRoot());
Optional<RowExpression> predicate = Optional.empty();
if (node.getWhere().isPresent()) {
builder = filter(builder, node.getWhere().get(), node);
if (builder.getRoot() instanceof FilterNode) {
predicate = Optional.of(((FilterNode) builder.getRoot()).getPredicate());
}
}
List<AssignmentItem> assignmentItems = node.getAssignmentItems();
Analysis.Update update = analysis.getUpdate().get();
Assignments.Builder assignments = Assignments.builder();
TableMetadata tableMetadata = metadata.getTableMetadata(session, update.getTarget());
Symbol orderBySymbol = null;
for (Map.Entry<Symbol, ColumnHandle> entry : columns.entrySet()) {
ColumnMetadata column;
ColumnHandle columnHandle = entry.getValue();
Symbol input = entry.getKey();
if (columnHandle.getColumnName().equals(rowIdHandle.getColumnName())) {
column = rowIdColumnMetadata;
} else {
column = tableMetadata.getColumn(columnHandle.getColumnName());
}
if (column != rowIdColumnMetadata && column.isHidden()) {
continue;
}
Symbol output = planSymbolAllocator.newSymbol(column.getName(), column.getType());
Type tableType = column.getType();
Type queryType = planSymbolAllocator.getTypes().get(input);
List<AssignmentItem> assignment = assignmentItems.stream().filter(item -> item.getName().equals(QualifiedName.of(column.getName()))).collect(Collectors.toList());
if (!assignment.isEmpty()) {
Expression expression = assignment.get(0).getValue();
Expression cast;
if (expression instanceof Identifier) {
// assigning by column reference
Optional<Symbol> first = columns.entrySet().stream().filter(e -> e.getValue().getColumnName().equals(((Identifier) expression).getValue())).map(Entry::getKey).findFirst();
Symbol source = (first.orElseThrow(() -> new IllegalArgumentException("Unable to find column " + ((Identifier) expression).getValue())));
cast = new Cast(toSymbolReference(source), tableType.getTypeSignature().toString());
} else {
cast = new Cast(expression, tableType.getTypeSignature().toString());
}
assignments.put(output, castToRowExpression(cast));
} else if (queryType.equals(tableType) || typeCoercion.isTypeOnlyCoercion(queryType, tableType)) {
assignments.put(output, castToRowExpression(toSymbolReference(input)));
} else {
Expression cast = new Cast(toSymbolReference(input), tableType.getTypeSignature().toString());
assignments.put(output, castToRowExpression(cast));
}
if (column == rowIdColumnMetadata) {
orderBySymbol = output;
}
}
ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), builder.getRoot(), assignments.build());
PlanBuilder planBuilder = new PlanBuilder(translations, projectNode);
SortOrder sortOrder = SortOrder.ASC_NULLS_LAST;
Symbol sortSymbol = orderBySymbol;
Map<Symbol, SortOrder> sortOrderMap = ImmutableMap.<Symbol, SortOrder>builder().put(sortSymbol, sortOrder).build();
OrderingScheme orderingScheme = new OrderingScheme(ImmutableList.of(sortSymbol), sortOrderMap);
builder = sort(planBuilder, Optional.of(orderingScheme));
ImmutableList.Builder<Field> projectFields = ImmutableList.builder();
projectFields.addAll(fields.build().stream().filter(x -> !x.isHidden()).collect(toImmutableList()));
scope = Scope.builder().withRelationType(RelationId.anonymous(), new RelationType(projectFields.build())).build();
RelationPlan plan = new RelationPlan(builder.getRoot(), scope, projectNode.getOutputSymbols());
List<String> visibleTableColumnNames = tableMetadata.getColumns().stream().filter(c -> !c.isHidden()).map(ColumnMetadata::getName).collect(Collectors.toList());
visibleTableColumnNames.add(rowIdColumnMetadata.getName());
return new UpdateDeleteRelationPlan(plan, visibleTableColumnNames, columns, predicate);
}
use of io.prestosql.spi.plan.Assignments in project hetu-core by openlookeng.
the class QueryPlanner method explicitCoercionSymbols.
private PlanBuilder explicitCoercionSymbols(PlanBuilder subPlan, List<Symbol> alreadyCoerced, Iterable<? extends Expression> uncoerced) {
TranslationMap translations = subPlan.copyTranslations();
Assignments assignments = Assignments.builder().putAll(coerce(uncoerced, subPlan, translations)).putAll(AssignmentUtils.identityAsSymbolReferences(alreadyCoerced)).build();
return new PlanBuilder(translations, new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), assignments));
}
use of io.prestosql.spi.plan.Assignments in project hetu-core by openlookeng.
the class QueryPlanner method aggregate.
private PlanBuilder aggregate(PlanBuilder inputSubPlan, QuerySpecification node) {
PlanBuilder subPlan = inputSubPlan;
if (!analysis.isAggregation(node)) {
return subPlan;
}
// 1. Pre-project all scalar inputs (arguments and non-trivial group by expressions)
Set<Expression> groupByExpressions = ImmutableSet.copyOf(analysis.getGroupByExpressions(node));
ImmutableList.Builder<Expression> arguments = ImmutableList.builder();
analysis.getAggregates(node).stream().map(FunctionCall::getArguments).flatMap(List::stream).filter(// lambda expression is generated at execution time
exp -> !(exp instanceof LambdaExpression)).forEach(arguments::add);
analysis.getAggregates(node).stream().map(FunctionCall::getOrderBy).filter(Optional::isPresent).map(Optional::get).map(OrderBy::getSortItems).flatMap(List::stream).map(SortItem::getSortKey).forEach(arguments::add);
// filter expressions need to be projected first
analysis.getAggregates(node).stream().map(FunctionCall::getFilter).filter(Optional::isPresent).map(Optional::get).forEach(arguments::add);
Iterable<Expression> inputs = Iterables.concat(groupByExpressions, arguments.build());
subPlan = handleSubqueries(subPlan, node, inputs);
if (!Iterables.isEmpty(inputs)) {
// avoid an empty projection if the only aggregation is COUNT (which has no arguments)
subPlan = project(subPlan, inputs);
}
// 2. Aggregate
// 2.a. Rewrite aggregate arguments
TranslationMap argumentTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToSymbolMap);
ImmutableList.Builder<Symbol> aggregationArgumentsBuilder = ImmutableList.builder();
for (Expression argument : arguments.build()) {
Symbol symbol = subPlan.translate(argument);
argumentTranslations.put(argument, symbol);
aggregationArgumentsBuilder.add(symbol);
}
List<Symbol> aggregationArguments = aggregationArgumentsBuilder.build();
// 2.b. Rewrite grouping columns
TranslationMap groupingTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToSymbolMap);
Map<Symbol, Symbol> groupingSetMappings = new LinkedHashMap<>();
for (Expression expression : groupByExpressions) {
Symbol input = subPlan.translate(expression);
Symbol output = planSymbolAllocator.newSymbol(expression, analysis.getTypeWithCoercions(expression), "gid");
groupingTranslations.put(expression, output);
groupingSetMappings.put(output, input);
}
// This tracks the grouping sets before complex expressions are considered (see comments below)
// It's also used to compute the descriptors needed to implement grouping()
List<Set<FieldId>> columnOnlyGroupingSets = ImmutableList.of(ImmutableSet.of());
List<List<Symbol>> groupingSets = ImmutableList.of(ImmutableList.of());
if (node.getGroupBy().isPresent()) {
// For the purpose of "distinct", we need to canonicalize column references that may have varying
// syntactic forms (e.g., "t.a" vs "a"). Thus we need to enumerate grouping sets based on the underlying
// fieldId associated with each column reference expression.
// The catch is that simple group-by expressions can be arbitrary expressions (this is a departure from the SQL specification).
// But, they don't affect the number of grouping sets or the behavior of "distinct" . We can compute all the candidate
// grouping sets in terms of fieldId, dedup as appropriate and then cross-join them with the complex expressions.
Analysis.GroupingSetAnalysis groupingSetAnalysis = analysis.getGroupingSets(node);
columnOnlyGroupingSets = enumerateGroupingSets(groupingSetAnalysis);
if (node.getGroupBy().get().isDistinct()) {
columnOnlyGroupingSets = columnOnlyGroupingSets.stream().distinct().collect(toImmutableList());
}
// add in the complex expressions an turn materialize the grouping sets in terms of plan columns
ImmutableList.Builder<List<Symbol>> groupingSetBuilder = ImmutableList.builder();
for (Set<FieldId> groupingSet : columnOnlyGroupingSets) {
ImmutableList.Builder<Symbol> columns = ImmutableList.builder();
groupingSetAnalysis.getComplexExpressions().stream().map(groupingTranslations::get).forEach(columns::add);
groupingSet.stream().map(field -> groupingTranslations.get(new FieldReference(field.getFieldIndex()))).forEach(columns::add);
groupingSetBuilder.add(columns.build());
}
groupingSets = groupingSetBuilder.build();
}
// 2.c. Generate GroupIdNode (multiple grouping sets) or ProjectNode (single grouping set)
Optional<Symbol> groupIdSymbol = Optional.empty();
if (groupingSets.size() > 1) {
groupIdSymbol = Optional.of(planSymbolAllocator.newSymbol("groupId", BIGINT));
GroupIdNode groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), groupingSets, groupingSetMappings, aggregationArguments, groupIdSymbol.get());
subPlan = new PlanBuilder(groupingTranslations, groupId);
} else {
Assignments.Builder assignments = Assignments.builder();
aggregationArguments.forEach(symbol -> assignments.put(symbol, castToRowExpression(toSymbolReference(symbol))));
groupingSetMappings.forEach((key, value) -> assignments.put(key, castToRowExpression(toSymbolReference(value))));
ProjectNode project = new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), assignments.build());
subPlan = new PlanBuilder(groupingTranslations, project);
}
TranslationMap aggregationTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis, lambdaDeclarationToSymbolMap);
aggregationTranslations.copyMappingsFrom(groupingTranslations);
// 2.d. Rewrite aggregates
ImmutableMap.Builder<Symbol, Aggregation> aggregationsBuilder = ImmutableMap.builder();
boolean needPostProjectionCoercion = false;
for (FunctionCall aggregate : analysis.getAggregates(node)) {
Expression rewritten = argumentTranslations.rewrite(aggregate);
Symbol newSymbol = planSymbolAllocator.newSymbol(rewritten, analysis.getType(aggregate));
// Therefore we can end up with this implicit cast, and have to move it into a post-projection
if (rewritten instanceof Cast) {
rewritten = ((Cast) rewritten).getExpression();
needPostProjectionCoercion = true;
}
aggregationTranslations.put(aggregate, newSymbol);
FunctionCall functionCall = (FunctionCall) rewritten;
aggregationsBuilder.put(newSymbol, new Aggregation(call(aggregate.getName().getSuffix(), analysis.getFunctionHandle(aggregate), analysis.getType(aggregate), functionCall.getArguments().stream().map(OriginalExpressionUtils::castToRowExpression).collect(toImmutableList())), functionCall.getArguments().stream().map(OriginalExpressionUtils::castToRowExpression).collect(toImmutableList()), functionCall.isDistinct(), functionCall.getFilter().map(SymbolUtils::from), functionCall.getOrderBy().map(OrderingSchemeUtils::fromOrderBy), Optional.empty()));
}
Map<Symbol, Aggregation> aggregations = aggregationsBuilder.build();
ImmutableSet.Builder<Integer> globalGroupingSets = ImmutableSet.builder();
for (int i = 0; i < groupingSets.size(); i++) {
if (groupingSets.get(i).isEmpty()) {
globalGroupingSets.add(i);
}
}
ImmutableList.Builder<Symbol> groupingKeys = ImmutableList.builder();
groupingSets.stream().flatMap(List::stream).distinct().forEach(groupingKeys::add);
groupIdSymbol.ifPresent(groupingKeys::add);
AggregationNode aggregationNode = new AggregationNode(idAllocator.getNextId(), subPlan.getRoot(), aggregations, groupingSets(groupingKeys.build(), groupingSets.size(), globalGroupingSets.build()), ImmutableList.of(), AggregationNode.Step.SINGLE, Optional.empty(), groupIdSymbol, AggregationNode.AggregationType.HASH, Optional.empty());
subPlan = new PlanBuilder(aggregationTranslations, aggregationNode);
// TODO: this is a hack, we should change type coercions to coerce the inputs to functions/operators instead of coercing the output
if (needPostProjectionCoercion) {
ImmutableList.Builder<Expression> alreadyCoerced = ImmutableList.builder();
alreadyCoerced.addAll(groupByExpressions);
groupIdSymbol.map(SymbolUtils::toSymbolReference).ifPresent(alreadyCoerced::add);
subPlan = explicitCoercionFields(subPlan, alreadyCoerced.build(), analysis.getAggregates(node));
}
// 4. Project and re-write all grouping functions
return handleGroupingOperations(subPlan, node, groupIdSymbol, columnOnlyGroupingSets);
}
Aggregations