use of io.requery.query.Expression in project requery by requery.
the class SelectResult method iterator.
@Override
public CloseableIterator<E> iterator(int skip, int take) {
Statement statement = null;
try {
// connection held by the iterator if statement not reused
BoundParameters parameters = createQuery(skip, take);
statement = createStatement(!parameters.isEmpty());
statement.setFetchSize(limit == null ? 0 : limit);
StatementListener listener = configuration.getStatementListener();
listener.beforeExecuteQuery(statement, sql, parameters);
ResultSet results;
if (parameters.isEmpty()) {
results = statement.executeQuery(sql);
} else {
PreparedStatement preparedStatement = (PreparedStatement) statement;
Mapping mapping = configuration.getMapping();
for (int i = 0; i < parameters.count(); i++) {
Expression expression = parameters.expressionAt(i);
Object value = parameters.valueAt(i);
if (expression instanceof Attribute) {
// extract foreign key reference
Attribute attribute = (Attribute) expression;
if (attribute.isAssociation() && (attribute.isForeignKey() || attribute.isKey())) {
// get the referenced value
if (value != null && ((Expression<?>) expression).getClassType().isAssignableFrom(value.getClass())) {
value = Attributes.replaceKeyReference(value, attribute);
}
}
}
mapping.write(expression, preparedStatement, i + 1, value);
}
results = preparedStatement.executeQuery();
}
listener.afterExecuteQuery(statement);
return new ResultSetIterator<>(reader, results, selection, true, closeConnection);
} catch (Exception e) {
throw StatementExecutionException.closing(statement, e, sql);
}
}
use of io.requery.query.Expression in project requery by requery.
the class PreparedQueryOperation method mapParameters.
void mapParameters(PreparedStatement statement, BoundParameters parameters) throws SQLException {
for (int i = 0; i < parameters.count(); i++) {
Expression expression = parameters.expressionAt(i);
Object value = parameters.valueAt(i);
if (expression instanceof Attribute) {
Attribute attribute = (Attribute) expression;
if (attribute.isAssociation()) {
// get the referenced value
value = Attributes.replaceKeyReference(value, attribute);
}
}
Class<?> type = value == null ? null : value.getClass();
if (type != null) {
// allows entity arguments with single keys to be remapped to their keys
if (model.containsTypeOf(type)) {
Type<Object> entityType = model.typeOf(type);
Attribute<Object, ?> keyAttribute = entityType.getSingleKeyAttribute();
if (keyAttribute != null) {
value = keyAttribute.getProperty().get(value);
expression = (Expression) keyAttribute;
}
}
}
configuration.getMapping().write(expression, statement, i + 1, value);
}
}
use of io.requery.query.Expression in project requery by requery.
the class OrderByGenerator method write.
@Override
public void write(Output output, OrderByElement query) {
Set<Expression<?>> orderBy = query.getOrderByExpressions();
if (orderBy != null && orderBy.size() > 0) {
QueryBuilder qb = output.builder();
qb.keyword(ORDER, BY);
int i = 0;
int size = orderBy.size();
for (Expression<?> order : orderBy) {
if (order.getExpressionType() == ExpressionType.ORDERING) {
OrderingExpression ordering = (OrderingExpression) order;
output.appendColumn(ordering.getInnerExpression());
qb.keyword(ordering.getOrder() == Order.ASC ? ASC : DESC);
if (ordering.getNullOrder() != null) {
qb.keyword(NULLS);
switch(ordering.getNullOrder()) {
case FIRST:
qb.keyword(FIRST);
break;
case LAST:
qb.keyword(LAST);
break;
}
}
} else {
output.appendColumn(order);
}
if (i < size - 1) {
qb.append(",");
}
i++;
}
}
}
use of io.requery.query.Expression in project requery by requery.
the class EntityReader method batchRefresh.
@SafeVarargs
final Iterable<E> batchRefresh(Iterable<E> entities, Attribute<E, ?>... attributes) {
// if the type is immutable return a new collection with the rebuilt objects
final Collection<E> collection = type.isImmutable() ? new ArrayList<E>() : null;
if (keyAttribute == null) {
// non optimal case objects with multiple keys or no keys
for (E entity : entities) {
entity = refresh(entity, type.getProxyProvider().apply(entity), attributes);
if (collection != null) {
collection.add(entity);
}
}
} else {
Set<Expression<?>> selection = new LinkedHashSet<>();
Attribute[] selectAttributes;
if (attributes == null || attributes.length == 0) {
selection = defaultSelection;
selectAttributes = defaultSelectionAttributes;
} else {
LinkedHashSet<Attribute> selectedAttributes = new LinkedHashSet<>();
selection.add(keyAttribute);
selectedAttributes.add(keyAttribute);
for (Attribute<E, ?> attribute : attributes) {
if (attribute.isVersion()) {
selection.add(aliasVersion(attribute));
} else if (!attribute.isAssociation()) {
QueryAttribute<E, ?> queryAttribute = Attributes.query(attribute);
selection.add(queryAttribute);
}
selectedAttributes.add(attribute);
}
selectAttributes = selectedAttributes.toArray(new Attribute[selection.size()]);
}
Map<Object, EntityProxy<E>> map = new HashMap<>();
for (E entity : entities) {
EntityProxy<E> proxy = type.getProxyProvider().apply(entity);
Object key = proxy.key();
if (key == null) {
throw new MissingKeyException();
}
map.put(key, proxy);
}
Condition<?, ?> condition = Attributes.query(keyAttribute).in(map.keySet());
if (type.isCacheable()) {
final Consumer<E> collector = new Consumer<E>() {
@Override
public void accept(E e) {
if (collection != null) {
collection.add(e);
}
}
};
// readResult will merge the results into the target object in cache mode
ResultReader<E> resultReader = newResultReader(selectAttributes);
SelectOperation<E> select = new SelectOperation<>(context, resultReader);
QueryElement<? extends Result<E>> query = new QueryElement<>(QueryType.SELECT, context.getModel(), select);
try (Result<E> result = query.select(selection).where(condition).get()) {
result.each(collector);
}
} else {
try (Result<Tuple> result = queryable.select(selection).where(condition).get()) {
for (Tuple tuple : result) {
Object key = tuple.get((Expression) keyAttribute);
EntityProxy<E> proxy = map.get(key);
synchronized (proxy.syncObject()) {
for (Expression expression : selection) {
Object value = tuple.get(expression);
if (expression instanceof AliasedExpression) {
AliasedExpression aliased = (AliasedExpression) expression;
expression = aliased.getInnerExpression();
}
Attribute<E, Object> attribute = Attributes.query((Attribute) expression);
proxy.set(attribute, value, PropertyState.LOADED);
}
}
}
}
}
// associations TODO can be optimized
if (attributes != null) {
for (Attribute<E, ?> attribute : attributes) {
if (attribute.isAssociation()) {
for (EntityProxy<E> proxy : map.values()) {
refreshAssociation(proxy, attribute);
}
}
}
}
}
return collection == null ? entities : collection;
}
use of io.requery.query.Expression in project requery by requery.
the class SelectGenerator method write.
@Override
public void write(final Output output, SelectionElement query) {
QueryBuilder qb = output.builder();
qb.keyword(SELECT);
if (query.isDistinct()) {
qb.keyword(DISTINCT);
}
Set<? extends Expression<?>> selection = query.getSelection();
if (selection == null || selection.isEmpty()) {
qb.append("*");
} else {
qb.commaSeparated(selection, new QueryBuilder.Appender<Expression<?>>() {
@Override
public void append(QueryBuilder qb, Expression<?> value) {
output.appendColumnForSelect(value);
}
});
}
qb.keyword(FROM);
output.appendTables();
}
Aggregations