Search in sources :

Example 6 with Expression

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);
    }
}
Also used : Expression(io.requery.query.Expression) Attribute(io.requery.meta.Attribute) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException)

Example 7 with Expression

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);
    }
}
Also used : Expression(io.requery.query.Expression) Attribute(io.requery.meta.Attribute)

Example 8 with Expression

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++;
        }
    }
}
Also used : OrderingExpression(io.requery.query.OrderingExpression) Expression(io.requery.query.Expression) OrderingExpression(io.requery.query.OrderingExpression) QueryBuilder(io.requery.sql.QueryBuilder)

Example 9 with Expression

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;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) WHERE(io.requery.sql.Keyword.WHERE) QueryAttribute(io.requery.meta.QueryAttribute) Attribute(io.requery.meta.Attribute) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QueryElement(io.requery.query.element.QueryElement) AliasedExpression(io.requery.query.AliasedExpression) EntityProxy(io.requery.proxy.EntityProxy) Consumer(io.requery.util.function.Consumer) AliasedExpression(io.requery.query.AliasedExpression) Expression(io.requery.query.Expression) QueryAttribute(io.requery.meta.QueryAttribute) Tuple(io.requery.query.Tuple)

Example 10 with Expression

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();
}
Also used : Expression(io.requery.query.Expression) QueryBuilder(io.requery.sql.QueryBuilder)

Aggregations

Expression (io.requery.query.Expression)14 QueryBuilder (io.requery.sql.QueryBuilder)9 Attribute (io.requery.meta.Attribute)6 NamedExpression (io.requery.query.NamedExpression)4 RowExpression (io.requery.query.RowExpression)4 QueryAttribute (io.requery.meta.QueryAttribute)3 Function (io.requery.query.function.Function)2 Collection (java.util.Collection)2 LinkedHashSet (java.util.LinkedHashSet)2 Map (java.util.Map)2 EntityProxy (io.requery.proxy.EntityProxy)1 AliasedExpression (io.requery.query.AliasedExpression)1 Condition (io.requery.query.Condition)1 OrderingExpression (io.requery.query.OrderingExpression)1 Tuple (io.requery.query.Tuple)1 InsertType (io.requery.query.element.InsertType)1 QueryElement (io.requery.query.element.QueryElement)1 QueryWrapper (io.requery.query.element.QueryWrapper)1 Case (io.requery.query.function.Case)1 WHERE (io.requery.sql.Keyword.WHERE)1