-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTransformedQuery.java
83 lines (73 loc) · 2.83 KB
/
TransformedQuery.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.db.jdbc;
import sirius.db.mixing.BaseMapper;
import sirius.db.mixing.EntityDescriptor;
import sirius.db.mixing.query.BaseQuery;
import sirius.kernel.health.Exceptions;
import java.sql.SQLException;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* A transformed query converts a plain {@link SQLQuery} into one that returns entities rather than rows.
* <p>
* This can be used to generate complex SQL queries which still use to O/R mixing to return entity objects
* read from a query result.
*
* @param <E> the generic type of entities being queried
*/
public class TransformedQuery<E extends SQLEntity> extends BaseQuery<TransformedQuery<E>, E> {
protected final String alias;
protected final SQLQuery qry;
protected TransformedQuery(EntityDescriptor descriptor, String alias, SQLQuery qry) {
super(descriptor);
this.alias = alias;
this.qry = qry;
}
@Override
protected void doIterate(Predicate<E> handler) {
try {
qry.iterate(row -> handler.test(mapToEntity(row)), getLimit());
} catch (SQLException e) {
throw Exceptions.handle()
.to(OMA.LOG)
.error(e)
.withSystemErrorMessage("Cannot transform a row into an entity of type '%s' for query '%s'",
descriptor.getType().getName(),
qry.toString())
.handle();
}
}
@Override
public Stream<E> streamBlockwise() {
throw new UnsupportedOperationException("`.streamBlockwise()` does not support arbitrary queries.");
}
@SuppressWarnings("unchecked")
private E mapToEntity(Row row) {
try {
E entity = (E) descriptor.make(OMA.class, alias, key -> row.hasValue(key) ? row.getValue(key) : null);
if (descriptor.isVersioned()) {
entity.setVersion(row.getValue(BaseMapper.VERSION).asInt(0));
}
entity.fetchRow = row;
return entity;
} catch (Exception e) {
throw Exceptions.handle()
.to(OMA.LOG)
.error(e)
.withSystemErrorMessage("Cannot transform a row into an entity of type '%s' for query '%s'",
descriptor.getType().getName(),
qry.toString())
.handle();
}
}
@Override
public String toString() {
return descriptor.getType() + " [" + qry + "]";
}
}