[improvement][headless]Enhance translation of derived metrics and refactor translator code.

This commit is contained in:
jerryjzhang
2024-12-15 11:37:16 +08:00
parent 14087825df
commit ed5c129a4a
21 changed files with 218 additions and 445 deletions

View File

@@ -594,7 +594,14 @@ public class SqlReplaceHelper {
Select selectStatement = SqlSelectHelper.getSelect(sql);
List<PlainSelect> plainSelectList = new ArrayList<>();
if (selectStatement instanceof PlainSelect) {
plainSelectList.add((PlainSelect) selectStatement);
// if with statement exists, replace expression in the with statement.
if (!CollectionUtils.isEmpty(selectStatement.getWithItemsList())) {
selectStatement.getWithItemsList().forEach(withItem -> {
plainSelectList.add(withItem.getSelect().getPlainSelect());
});
} else {
plainSelectList.add((PlainSelect) selectStatement);
}
} else if (selectStatement instanceof SetOperationList) {
SetOperationList setOperationList = (SetOperationList) selectStatement;
if (!CollectionUtils.isEmpty(setOperationList.getSelects())) {
@@ -606,9 +613,13 @@ public class SqlReplaceHelper {
} else {
return sql;
}
List<PlainSelect> plainSelects = SqlSelectHelper.getPlainSelects(plainSelectList);
for (PlainSelect plainSelect : plainSelects) {
replacePlainSelectByExpr(plainSelect, replace);
if (SqlSelectHelper.hasAggregateFunction(plainSelect)) {
SqlSelectHelper.addMissingGroupby(plainSelect);
}
}
return selectStatement.toString();
}

View File

@@ -914,4 +914,31 @@ public class SqlSelectHelper {
}
});
}
public static void addMissingGroupby(PlainSelect plainSelect) {
if (Objects.nonNull(plainSelect.getGroupBy())
&& !plainSelect.getGroupBy().getGroupByExpressionList().isEmpty()) {
return;
}
GroupByElement groupBy = new GroupByElement();
for (SelectItem selectItem : plainSelect.getSelectItems()) {
Expression expression = selectItem.getExpression();
if (expression instanceof Column) {
groupBy.addGroupByExpression(expression);
}
}
if (!groupBy.getGroupByExpressionList().isEmpty()) {
plainSelect.setGroupByElement(groupBy);
}
}
public static boolean hasAggregateFunction(PlainSelect plainSelect) {
List<SelectItem<?>> selectItems = plainSelect.getSelectItems();
FunctionVisitor visitor = new FunctionVisitor();
for (SelectItem selectItem : selectItems) {
selectItem.accept(visitor);
}
return !visitor.getFunctionNames().isEmpty();
}
}