Skip to content

Commit 0d77acc

Browse files
committed
Add support for distinct queries in Query class
1 parent 881db6e commit 0d77acc

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

src/main/java/org/javawebstack/orm/query/Query.java

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import org.javawebstack.orm.SQLMapper;
66
import org.javawebstack.orm.connection.pool.PooledSQL;
77
import org.javawebstack.orm.exception.ORMQueryException;
8-
import org.javawebstack.orm.connection.SQL;
98
import org.javawebstack.orm.renderer.SQLQueryString;
109

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

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

49+
public boolean isDistinct() {
50+
return distinct;
51+
}
52+
53+
public String getDistinctColumn() {
54+
return distinctColumn;
55+
}
56+
4857
public boolean shouldApplyAccessible() {
4958
return applyAccessible;
5059
}
@@ -94,6 +103,24 @@ public Query<T> select(String... columns) {
94103
return this;
95104
}
96105

106+
public Query<T> distinct() {
107+
this.distinct = true;
108+
return this;
109+
}
110+
111+
public Query<T> distinct(String column) {
112+
this.distinct = true;
113+
this.distinctColumn = column;
114+
return this;
115+
}
116+
117+
public Query<T> distinct(boolean distinct) {
118+
this.distinct = distinct;
119+
if (!distinct)
120+
this.distinctColumn = null;
121+
return this;
122+
}
123+
97124
public Query<T> and(Function<QueryGroup<T>, QueryGroup<T>> group) {
98125
where.and(group);
99126
return this;

src/main/java/org/javawebstack/orm/renderer/MySQLQueryStringRenderer.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ public SQLQueryString buildQuery(Query<?> query) {
4949
Repo<?> repo = query.getRepo();
5050
List<Object> parameters = new ArrayList<>();
5151
StringBuilder sb = new StringBuilder("SELECT ");
52+
if (query.isDistinct()) {
53+
if (query.getDistinctColumn() != null) {
54+
String col = new QueryColumn(query.getDistinctColumn()).toString(repo.getInfo());
55+
sb.append("DISTINCT ").append(col).append(", ");
56+
} else {
57+
sb.append("DISTINCT ");
58+
}
59+
}
5260
if(query.getSelect().size() == 0)
5361
sb.append("*");
5462
else

0 commit comments

Comments
 (0)