BUG: @OrderBy on chained properties do not work with distinct (fix)

This commit is contained in:
Roland Praml committed 2023-01-13 13:29:16 +01:00
1 parent b2e8e628fa
commit 6561f6f5e7
6 files changed
+63 -35

No files matched your search

@@ -585,16 +585,11 @@ final class CQueryBuilder {
}
if (distinct && dbOrderBy != null) {
// add the orderBy columns to the select clause (due to distinct)
final OrderBy<?> orderBy = query.getOrderBy();
if (orderBy != null && orderBy.supportsSelect()) {
String trimmed = DbOrderByTrim.trim(dbOrderBy);
if (query.isSingleAttribute() && select.selectSql().startsWith(trimmed)) {
// NOP, already in SQL
// TODO: what to do if we select("id").orderBy("prop,id")?
// Can we live with a query like "select t0.id, t0.prop, t0.id from"
// or should we elliminate the second "t0.id" from select
} else {
sb.append(", ").append(trimmed);
String[] tokens = DbOrderByTrim.trim(dbOrderBy).split(",");
for (String token : tokens) {
token = token.trim();
if (!DbOrderByTrim.contains(select.selectSql(), token)) {
sb.append(", ").append(token);
}
}
}
@@ -643,7 +638,7 @@ final class CQueryBuilder {
private void appendHistoryAsOfPredicate() {
if (query.isAsOfBaseTable()) {
query.incrementAsOfTableCount();
if (!historySupport.isStandardsBased()){
if (!historySupport.isStandardsBased()) {
appendAndOrWhere();
sb.append(historySupport.asOfPredicate(request.baseTableAlias()));
}
@@ -4,7 +4,7 @@ import java.util.regex.Pattern;
final class DbOrderByTrim {
private static final Pattern orderByTrim = Pattern.compile("(?i) asc\\b| desc\\b|\\b nulls first\\b|\\b nulls last\\b");
private static final Pattern orderByTrim = Pattern.compile("(?i) asc\\b| desc\\b| nulls first\\b| nulls last\\b");
/**
* Convert the dbOrderBy clause to be safe for adding to select or distinct on.
@@ -14,4 +14,21 @@ final class DbOrderByTrim {
return orderByTrim.matcher(dbOrderBy).replaceAll("");
}
/**
* Checks, if <code>sql</code> contains the <code>column</code>.
* <p>
* SQL is normally comma separated: "t0.id, t1.id, t2.name"
*/
static boolean contains(String sql, String column) {
if (sql.endsWith(column)) { // simplest way. sql ends with the column
return true;
} else if (sql.contains(column)) {
// We need to check, if it is really the correct column,
// sql="t0.name_short, t0.name_long" will match on column="t0.name"
return sql.contains(column + ",");
} else {
return false;
}
}
}
@@ -172,7 +172,7 @@ public final class SqlTreeBuilder {
String[] split = idCols.split(",");
for (String col : split) {
col = col.trim();
if (!dbOrderBy.contains(col)) {
if (!DbOrderByTrim.contains(dbOrderBy, col)) {
sb.append(", ").append(col);
}
}