[fix][headless] Fix order by and group by not enclosed in backticks. (#2041)
Some checks are pending
supersonic CentOS CI / build (21) (push) Waiting to run
supersonic mac CI / build (21) (push) Waiting to run
supersonic ubuntu CI / build (21) (push) Waiting to run
supersonic windows CI / build (21) (push) Waiting to run

This commit is contained in:
Hwwwww
2025-02-10 12:55:05 +08:00
committed by GitHub
parent a8157ee769
commit 3ca46bee36
3 changed files with 42 additions and 3 deletions

View File

@@ -5,8 +5,13 @@ import net.sf.jsqlparser.statement.select.SelectItem;
import net.sf.jsqlparser.statement.select.SelectItemVisitorAdapter;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class FieldAliasReplaceWithBackticksVisitor extends SelectItemVisitorAdapter {
private Map<String, String> fieldAliasReplacedMap = new HashMap<>();
@Override
public void visit(SelectItem selectExpressionItem) {
Alias alias = selectExpressionItem.getAlias();
@@ -19,6 +24,7 @@ public class FieldAliasReplaceWithBackticksVisitor extends SelectItemVisitorAdap
return;
}
alias.setName(replaceValue);
fieldAliasReplacedMap.put(aliasName, replaceValue);
}
private String addBackticks(String aliasName) {
@@ -30,4 +36,8 @@ public class FieldAliasReplaceWithBackticksVisitor extends SelectItemVisitorAdap
}
return "`" + aliasName + "`";
}
public Map<String, String> getFieldAliasReplacedMap() {
return fieldAliasReplacedMap;
}
}

View File

@@ -487,7 +487,7 @@ public class SqlReplaceHelper {
}
public static String replaceAliasWithBackticks(String sql) {
Select selectStatement = SqlSelectHelper.getSelect(sql);
Select selectStatement = SqlSelectHelper.getSelect(sql);
if (!(selectStatement instanceof PlainSelect)) {
return sql;
}
@@ -496,6 +496,26 @@ public class SqlReplaceHelper {
for (SelectItem selectItem : plainSelect.getSelectItems()) {
selectItem.accept(visitor);
}
// Replace `order by` and `group by`
// Get the map of field aliases that have been replaced
Map<String, String> aliasReplacedMap = visitor.getFieldAliasReplacedMap();
// If no aliases have been replaced, return the original SQL statement as a string
if (aliasReplacedMap.isEmpty()) {
return selectStatement.toString();
}
// Order by elements
List<OrderByElement> orderByElements = selectStatement.getOrderByElements();
if (!CollectionUtils.isEmpty(orderByElements)) {
for (OrderByElement orderByElement : orderByElements) {
orderByElement.accept(new OrderByReplaceVisitor(aliasReplacedMap, true));
}
}
// Group by elements
GroupByElement groupByElement = plainSelect.getGroupBy();
if (Objects.nonNull(groupByElement)) {
groupByElement.accept(new GroupByReplaceVisitor(aliasReplacedMap, true));
}
return selectStatement.toString();
}