Search in sources :

Example 16 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class GenericDAO method makeConditionHavingString.

protected StringBuilder makeConditionHavingString(StringBuilder havingString, String prefix, ModelEntity modelEntity, EntityCondition havingEntityCondition, List<EntityCondition> viewHavingConditions, List<EntityConditionParam> havingEntityConditionParams) throws GenericEntityException {
    ModelViewEntity modelViewEntity = null;
    if (modelEntity instanceof ModelViewEntity) {
        modelViewEntity = (ModelViewEntity) modelEntity;
    }
    String entityCondHavingString = "";
    if (havingEntityCondition != null) {
        entityCondHavingString = havingEntityCondition.makeWhereString(modelEntity, havingEntityConditionParams, this.datasource);
    }
    String viewEntityCondHavingString = null;
    if (modelViewEntity != null) {
        EntityCondition viewHavingEntityCondition = EntityCondition.makeCondition(viewHavingConditions);
        viewEntityCondHavingString = viewHavingEntityCondition.makeWhereString(modelEntity, havingEntityConditionParams, this.datasource);
    }
    if (UtilValidate.isNotEmpty(entityCondHavingString) || UtilValidate.isNotEmpty(viewEntityCondHavingString)) {
        havingString.append(prefix);
    }
    if (UtilValidate.isNotEmpty(entityCondHavingString)) {
        boolean addParens = entityCondHavingString.charAt(0) != '(';
        if (addParens)
            havingString.append("(");
        havingString.append(entityCondHavingString);
        if (addParens)
            havingString.append(")");
    }
    if (UtilValidate.isNotEmpty(viewEntityCondHavingString)) {
        if (UtilValidate.isNotEmpty(entityCondHavingString))
            havingString.append(" AND ");
        boolean addParens = viewEntityCondHavingString.charAt(0) != '(';
        if (addParens)
            havingString.append("(");
        havingString.append(viewEntityCondHavingString);
        if (addParens)
            havingString.append(")");
    }
    return havingString;
}
Also used : ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Example 17 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class GenericDAO method selectCountByCondition.

public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, List<ModelField> selectFields, EntityFindOptions findOptions) throws GenericEntityException {
    if (modelEntity == null) {
        return 0;
    }
    // if no find options passed, use default
    if (findOptions == null) {
        findOptions = new EntityFindOptions();
    }
    boolean verboseOn = Debug.verboseOn();
    if (verboseOn) {
        // put this inside an if statement so that we don't have to generate the string when not used...
        if (Debug.verboseOn())
            Debug.logVerbose("Doing selectListIteratorByCondition with whereEntityCondition: " + whereEntityCondition, module);
    }
    boolean isGroupBy = false;
    ModelViewEntity modelViewEntity = null;
    if (modelEntity instanceof ModelViewEntity) {
        modelViewEntity = (ModelViewEntity) modelEntity;
        isGroupBy = modelViewEntity.getGroupBysSize() > 0;
    }
    // To get a count of the rows that will be returned when there is a GROUP BY, must do something like:
    // SELECT COUNT(1) FROM (SELECT COUNT(1) FROM OFBIZ.POSTAL_ADDRESS PA GROUP BY PA.CITY) TEMP_NAME
    // instead of a simple:
    // SELECT COUNT(1) FROM OFBIZ.POSTAL_ADDRESS PA GROUP BY PA.CITY
    StringBuilder sqlBuffer = new StringBuilder("SELECT ");
    if (isGroupBy) {
        sqlBuffer.append("COUNT(1) FROM (SELECT ");
    }
    if (findOptions.getDistinct()) {
        /* DEJ20100304: the code below was causing problems so the line above may be used instead, but hopefully this is fixed now 
             * may need varying SQL for different databases, and also in view-entities in some cases it seems to 
             * cause the "COUNT(DISTINCT " to appear twice, causing an attempt to try to count a count (function="count-distinct", distinct=true in find options)
             */
        if (selectFields != null && selectFields.size() > 0) {
            ModelField firstSelectField = selectFields.get(0);
            ModelViewEntity.ModelAlias firstModelAlias = modelViewEntity != null ? modelViewEntity.getAlias(firstSelectField.getName()) : null;
            if (firstModelAlias != null && UtilValidate.isNotEmpty(firstModelAlias.getFunction())) {
                // if the field has a function already we don't want to count just it, would be meaningless
                sqlBuffer.append("COUNT(DISTINCT *) ");
            } else {
                sqlBuffer.append("COUNT(DISTINCT ");
                // this only seems to support a single column, which is not desirable but seems a lot better than no columns or in certain cases all columns
                sqlBuffer.append(firstSelectField.getColValue());
                // sqlBuffer.append(modelEntity.colNameString(selectFields, ", ", "", datasource.aliasViews));
                sqlBuffer.append(")");
            }
        } else {
            sqlBuffer.append("COUNT(DISTINCT *) ");
        }
    } else {
        // NOTE DEJ20080701 Changed from COUNT(*) to COUNT(1) to improve performance, and should get the same results at least when there is no DISTINCT
        sqlBuffer.append("COUNT(1) ");
    }
    // populate the info from entity-condition in the view-entity, if it is one and there is one
    List<EntityCondition> viewWhereConditions = null;
    List<EntityCondition> viewHavingConditions = null;
    List<String> viewOrderByList = null;
    if (modelViewEntity != null) {
        viewWhereConditions = new LinkedList<EntityCondition>();
        viewHavingConditions = new LinkedList<EntityCondition>();
        viewOrderByList = new LinkedList<String>();
        modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList, null);
    }
    // FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
    sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
    // WHERE clause
    List<EntityConditionParam> whereEntityConditionParams = new LinkedList<EntityConditionParam>();
    makeConditionWhereString(sqlBuffer, " WHERE ", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams);
    // GROUP BY clause for view-entity
    if (isGroupBy) {
        modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(), sqlBuffer, " GROUP BY ", ", ", "", false);
    }
    // HAVING clause
    List<EntityConditionParam> havingEntityConditionParams = new LinkedList<EntityConditionParam>();
    makeConditionHavingString(sqlBuffer, " HAVING ", modelEntity, havingEntityCondition, viewHavingConditions, havingEntityConditionParams);
    if (isGroupBy) {
        sqlBuffer.append(") TEMP_NAME");
    }
    String sql = sqlBuffer.toString();
    if (Debug.verboseOn())
        Debug.logVerbose("Count select sql: " + sql, module);
    try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) {
        sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows());
        if (verboseOn) {
            // put this inside an if statement so that we don't have to generate the string when not used...
            if (Debug.verboseOn())
                Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, module);
        }
        // set all of the values from the Where EntityCondition
        for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) {
            SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
        }
        if (verboseOn) {
            // put this inside an if statement so that we don't have to generate the string when not used...
            if (Debug.verboseOn())
                Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, module);
        }
        // set all of the values from the Having EntityCondition
        for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) {
            SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
        }
        try {
            sqlP.executeQuery();
            long count = 0;
            ResultSet resultSet = sqlP.getResultSet();
            if (resultSet.next()) {
                count = resultSet.getLong(1);
            }
            return count;
        } catch (SQLException e) {
            throw new GenericDataSourceException("Error getting count value", e);
        }
    }
}
Also used : SQLException(java.sql.SQLException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) SQLProcessor(org.apache.ofbiz.entity.jdbc.SQLProcessor) ModelField(org.apache.ofbiz.entity.model.ModelField) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ResultSet(java.sql.ResultSet) GenericDataSourceException(org.apache.ofbiz.entity.GenericDataSourceException) EntityConditionParam(org.apache.ofbiz.entity.condition.EntityConditionParam)

Example 18 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class GenericDAO method makeConditionWhereString.

protected StringBuilder makeConditionWhereString(StringBuilder whereString, String prefix, ModelEntity modelEntity, EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException {
    ModelViewEntity modelViewEntity = null;
    if (modelEntity instanceof ModelViewEntity) {
        modelViewEntity = (ModelViewEntity) modelEntity;
    }
    List<EntityCondition> conditions = new LinkedList<EntityCondition>();
    if (UtilValidate.isNotEmpty(whereEntityCondition)) {
        conditions.add(whereEntityCondition);
    }
    if (modelViewEntity != null && !viewWhereConditions.isEmpty()) {
        EntityCondition viewWhereEntityCondition = EntityCondition.makeCondition(viewWhereConditions);
        if (!viewWhereEntityCondition.isEmpty()) {
            conditions.add(viewWhereEntityCondition);
        }
    }
    String viewClause = SqlJdbcUtil.makeViewWhereClause(modelEntity, datasource.getJoinStyle());
    if (viewClause.length() > 0) {
        conditions.add(EntityCondition.makeConditionWhere(viewClause));
    }
    if (!conditions.isEmpty()) {
        whereString.append(prefix);
        whereString.append(EntityCondition.makeCondition(conditions, EntityOperator.AND).makeWhereString(modelEntity, whereEntityConditionParams, this.datasource));
    }
    return whereString;
}
Also used : ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList)

Example 19 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class AbstractEntityConditionCache method getOrCreateConditionCache.

protected Map<K, V> getOrCreateConditionCache(String entityName, EntityCondition condition) {
    UtilCache<EntityCondition, ConcurrentMap<K, V>> utilCache = getOrCreateCache(entityName);
    EntityCondition conditionKey = getConditionKey(condition);
    ConcurrentMap<K, V> conditionCache = utilCache.get(conditionKey);
    if (conditionCache == null) {
        conditionCache = new ConcurrentHashMap<>();
        utilCache.put(conditionKey, conditionCache);
    }
    return conditionCache;
}
Also used : EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ConcurrentMap(java.util.concurrent.ConcurrentMap) GenericPK(org.apache.ofbiz.entity.GenericPK)

Example 20 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class EntitySyncContext method assembleKeysToRemove.

public LinkedList<GenericEntity> assembleKeysToRemove() throws SyncDataErrorException {
    // get all removed items from the given time range, add to list for those
    LinkedList<GenericEntity> keysToRemove = new LinkedList<GenericEntity>();
    if (this.nextRemoveTxTime != null && (this.nextRemoveTxTime.equals(currentRunEndTime) || this.nextRemoveTxTime.after(currentRunEndTime))) {
        // this means that for all entities in this pack we found on the last pass that there would be nothing for this one, so just return nothing...
        return keysToRemove;
    }
    // Debug.logInfo("Getting keys to remove; currentRunStartTime=" + currentRunStartTime + ", currentRunEndTime=" + currentRunEndTime, module);
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin(7200);
    } catch (GenericTransactionException e) {
        throw new SyncDataErrorException("Unable to begin JTA transaction", e);
    }
    try {
        // find all instances of this entity with the STAMP_TX_FIELD != null, sort ascending to get lowest/oldest value first, then grab first and consider as candidate currentRunStartTime
        EntityCondition findValCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunStartTime), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime));
        EntityListIterator removeEli = EntityQuery.use(delegator).from("EntitySyncRemove").where(findValCondition).orderBy(ModelEntity.STAMP_TX_FIELD, ModelEntity.STAMP_FIELD).queryIterator();
        GenericValue entitySyncRemove = null;
        while ((entitySyncRemove = removeEli.next()) != null) {
            // pull the PK from the EntitySyncRemove in the primaryKeyRemoved field, de-XML-serialize it
            String primaryKeyRemoved = entitySyncRemove.getString("primaryKeyRemoved");
            GenericEntity pkToRemove = null;
            try {
                pkToRemove = (GenericEntity) XmlSerializer.deserialize(primaryKeyRemoved, delegator);
            } catch (IOException e) {
                String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
                Debug.logError(e, errorMsg, module);
                throw new SyncDataErrorException(errorMsg, e);
            } catch (SAXException e) {
                String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
                Debug.logError(e, errorMsg, module);
                throw new SyncDataErrorException(errorMsg, e);
            } catch (ParserConfigurationException e) {
                String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
                Debug.logError(e, errorMsg, module);
                throw new SyncDataErrorException(errorMsg, e);
            } catch (SerializeException e) {
                String errorMsg = "Error deserializing GenericPK to remove in Entity Sync Data for entitySyncId [" + entitySyncId + "] and entitySyncRemoveId [" + entitySyncRemove.getString("entitySyncRemoveId") + "]: " + e.toString();
                Debug.logError(e, errorMsg, module);
                throw new SyncDataErrorException(errorMsg, e);
            }
            // set the stamp fields for future reference
            pkToRemove.set(ModelEntity.STAMP_TX_FIELD, entitySyncRemove.get(ModelEntity.STAMP_TX_FIELD));
            pkToRemove.set(ModelEntity.STAMP_FIELD, entitySyncRemove.get(ModelEntity.STAMP_FIELD));
            pkToRemove.set(ModelEntity.CREATE_STAMP_TX_FIELD, entitySyncRemove.get(ModelEntity.CREATE_STAMP_TX_FIELD));
            pkToRemove.set(ModelEntity.CREATE_STAMP_FIELD, entitySyncRemove.get(ModelEntity.CREATE_STAMP_FIELD));
            if (this.entityNameToUseSet.contains(pkToRemove.getEntityName())) {
                keysToRemove.add(pkToRemove);
            }
        }
        removeEli.close();
        // if we didn't find anything for this entity, find the next value's Timestamp and keep track of it
        if (keysToRemove.size() == 0) {
            EntityCondition findNextCondition = EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunEndTime);
            EntityListIterator eliNext = EntityQuery.use(delegator).from("EntitySyncRemove").where(findNextCondition).orderBy(ModelEntity.STAMP_TX_FIELD).queryIterator();
            // get the first element and it's tx time value...
            GenericValue firstVal = eliNext.next();
            eliNext.close();
            if (firstVal != null) {
                Timestamp nextTxTime = firstVal.getTimestamp(ModelEntity.STAMP_TX_FIELD);
                if (this.nextRemoveTxTime == null || nextTxTime.before(this.nextRemoveTxTime)) {
                    this.nextRemoveTxTime = nextTxTime;
                }
            }
        }
    } catch (GenericEntityException e) {
        try {
            TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleKeysToRemove", e);
        } catch (GenericTransactionException e2) {
            Debug.logWarning(e2, "Unable to call rollback()", module);
        }
        throw new SyncDataErrorException("Error getting keys to remove from the datasource", e);
    } catch (Throwable t) {
        try {
            TransactionUtil.rollback(beganTransaction, "General error in assembleKeysToRemove", t);
        } catch (GenericTransactionException e2) {
            Debug.logWarning(e2, "Unable to call rollback()", module);
        }
        throw new SyncDataErrorException("Caught runtime error while getting keys to remove", t);
    }
    try {
        TransactionUtil.commit(beganTransaction);
    } catch (GenericTransactionException e) {
        throw new SyncDataErrorException("Commit transaction failed", e);
    }
    // TEST SECTION: leave false for normal use
    boolean logValues = false;
    if (logValues && keysToRemove.size() > 0) {
        StringBuilder toRemoveInfo = new StringBuilder();
        for (GenericEntity keyToRemove : keysToRemove) {
            toRemoveInfo.append("\n-->[");
            toRemoveInfo.append(keyToRemove.get(ModelEntity.STAMP_TX_FIELD));
            toRemoveInfo.append(":");
            toRemoveInfo.append(keyToRemove.get(ModelEntity.STAMP_FIELD));
            toRemoveInfo.append("] ");
            toRemoveInfo.append(keyToRemove);
        }
        Debug.logInfo(toRemoveInfo.toString(), module);
    }
    // this calculation is false, so it needs to be nullified
    if (keysToRemove.size() > 0) {
        this.nextRemoveTxTime = null;
    }
    return keysToRemove;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) SerializeException(org.apache.ofbiz.entity.serialize.SerializeException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) SAXException(org.xml.sax.SAXException) GenericEntity(org.apache.ofbiz.entity.GenericEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)118 GenericValue (org.apache.ofbiz.entity.GenericValue)96 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)78 Delegator (org.apache.ofbiz.entity.Delegator)60 LinkedList (java.util.LinkedList)58 Locale (java.util.Locale)43 Timestamp (java.sql.Timestamp)40 HashMap (java.util.HashMap)32 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)29 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)26 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)24 Map (java.util.Map)22 BigDecimal (java.math.BigDecimal)21 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)18 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)14 GeneralException (org.apache.ofbiz.base.util.GeneralException)12 ArrayList (java.util.ArrayList)11 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)9 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)8 HashSet (java.util.HashSet)7