Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/main/java/org/javawebstack/orm/query/Query.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import org.javawebstack.orm.SQLMapper;
import org.javawebstack.orm.connection.pool.PooledSQL;
import org.javawebstack.orm.exception.ORMQueryException;
import org.javawebstack.orm.connection.SQL;
import org.javawebstack.orm.renderer.SQLQueryString;

import java.sql.ResultSet;
Expand All @@ -31,6 +30,8 @@ public class Query<T extends Model> {
private QueryGroup<T> having;
private boolean applyAccessible = false;
private Object accessor;
private boolean distinct = false;
private String distinctColumn = null;

public Query(Class<T> model) {
this(Repo.get(model), model);
Expand All @@ -45,6 +46,14 @@ public boolean isWithDeleted() {
return withDeleted;
}

public boolean isDistinct() {
return distinct;
}

public String getDistinctColumn() {
return distinctColumn;
}

public boolean shouldApplyAccessible() {
return applyAccessible;
}
Expand Down Expand Up @@ -94,6 +103,25 @@ public Query<T> select(String... columns) {
return this;
}

public Query<T> distinct() {
this.distinct = true;
this.distinctColumn = null;
return this;
}
Comment thread
Copilot marked this conversation as resolved.

public Query<T> distinct(String column) {
this.distinct = true;
this.distinctColumn = column;
return this;
}

public Query<T> distinct(boolean distinct) {
this.distinct = distinct;
if (!distinct)
this.distinctColumn = null;
return this;
}

public Query<T> and(Function<QueryGroup<T>, QueryGroup<T>> group) {
where.and(group);
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,16 @@ public SQLQueryString buildQuery(Query<?> query) {
Repo<?> repo = query.getRepo();
List<Object> parameters = new ArrayList<>();
StringBuilder sb = new StringBuilder("SELECT ");
if(query.getSelect().size() == 0)
if (query.isDistinct()) {
sb.append("DISTINCT ");
// Prepend distinctColumn only when no explicit select list is set (i.e. SELECT *).
// With an explicit select list (e.g. count(*)) the column position must not shift.
if (query.getDistinctColumn() != null && query.getSelect().isEmpty()) {
String col = new QueryColumn(query.getDistinctColumn()).toString(repo.getInfo());
sb.append(col).append(", ");
}
}
if(query.getSelect().isEmpty())
sb.append("*");
else
sb.append(String.join(",", query.getSelect()));
Expand Down