use of com.yahoo.elide.datastores.aggregation.queryengines.sql.calcite.CalciteInnerAggregationExtractor in project elide by yahoo.
the class SQLMetricProjection method nest.
@Override
public Pair<ColumnProjection, Set<ColumnProjection>> nest(Queryable source, MetaDataStore metaDataStore, boolean joinInOuter) {
SQLDialect dialect = source.getConnectionDetails().getDialect();
String sql = toSQL(source, metaDataStore);
SqlParser sqlParser = SqlParser.create(sql, CalciteUtils.constructParserConfig(dialect));
SqlNode node;
try {
node = sqlParser.parseExpression();
} catch (SqlParseException e) {
throw new IllegalStateException(e);
}
CalciteInnerAggregationExtractor innerExtractor = new CalciteInnerAggregationExtractor(dialect);
List<List<String>> innerAggExpressions = node.accept(innerExtractor);
List<List<String>> innerAggLabels = innerAggExpressions.stream().map(list -> list.stream().map((expression) -> getAggregationLabel(dialect.getCalciteDialect(), expression)).collect(Collectors.toList())).collect(Collectors.toList());
Set<ColumnProjection> innerAggProjections = new LinkedHashSet<>();
Iterator<String> labelIt = innerAggLabels.stream().flatMap(List::stream).iterator();
Iterator<String> expressionIt = innerAggExpressions.stream().flatMap(List::stream).iterator();
while (labelIt.hasNext() && expressionIt.hasNext()) {
String innerAggExpression = expressionIt.next();
String innerAggLabel = labelIt.next();
innerAggProjections.add(SQLMetricProjection.builder().projected(true).name(innerAggLabel).alias(innerAggLabel).expression(innerAggExpression).columnType(columnType).valueType(valueType).arguments(arguments).build());
}
CalciteOuterAggregationExtractor outerExtractor = new CalciteOuterAggregationExtractor(dialect, innerAggLabels);
SqlNode transformedParseTree = node.accept(outerExtractor);
String outerAggExpression = transformedParseTree.toSqlString(dialect.getCalciteDialect()).getSql();
// replace INNER_AGG_... with {{$INNER_AGG...}}
outerAggExpression = outerAggExpression.replaceAll(dialect.getBeginQuote() + "?(" + getAggregationLabelPrefix(dialect.getCalciteDialect()) + "\\w+)" + dialect.getEndQuote() + "?", "{{\\$" + "$1" + "}}");
String columnId = source.isRoot() ? getName() : getAlias();
boolean inProjection = source.getColumnProjection(columnId, arguments, true) != null;
ColumnProjection outerProjection = SQLMetricProjection.builder().projected(inProjection).expression(outerAggExpression).name(name).alias(alias).valueType(valueType).columnType(columnType).arguments(arguments).build();
return Pair.of(outerProjection, innerAggProjections);
}
Aggregations