Search in sources :

Example 1 with ReportQueryResult

use of org.eclipse.persistence.queries.ReportQueryResult in project eclipselink by eclipse-ee4j.

the class MapEntryDirectEntity1MReportQueryTest method removeFromResult.

@Override
protected void removeFromResult(ReportQueryResult result, Vector expected) {
    for (Enumeration e = expected.elements(); e.hasMoreElements(); ) {
        ReportQueryResult expectedResult = (ReportQueryResult) e.nextElement();
        Association expectedAssocication = (Association) expectedResult.getByIndex(0);
        Association resultAssocication = (Association) result.getByIndex(0);
        if (expectedAssocication.getKey().equals(resultAssocication.getKey()) && expectedAssocication.getValue().equals(resultAssocication.getValue())) {
            expected.removeElement(expectedResult);
            return;
        }
    }
    getSession().logMessage("missing element: " + result);
}
Also used : Enumeration(java.util.Enumeration) Association(org.eclipse.persistence.mappings.Association) ReportQueryResult(org.eclipse.persistence.queries.ReportQueryResult)

Example 2 with ReportQueryResult

use of org.eclipse.persistence.queries.ReportQueryResult in project eclipselink by eclipse-ee4j.

the class ReportQueryFunctionTypeTestCase method test.

@Override
public void test() {
    // on all platforms.
    if (getSession().getLogin().getDriverClassName().equals("com.oracle.ias.jdbc.db2.DB2Driver")) {
        throw new TestWarningException("This test is not supported on DB2 DataDirect");
    } else {
        ReportQuery reportQuery = new ReportQuery();
        reportQuery.setReferenceClass(Employee.class);
        ExpressionBuilder builder = reportQuery.getExpressionBuilder();
        reportQuery.addAverage("salary-ave", builder.get("salary"));
        // Oracle specific function.
        if (getSession().getDatasourcePlatform().isOracle()) {
            reportQuery.addVariance("salary-var", builder.get("salary"));
        }
        // Sybase, Symfoware (bug 304909) and TimesTen don't support
        if (!(getSession().getDatasourcePlatform().isSybase() || getSession().getDatasourcePlatform().isTimesTen() || getSession().getDatasourcePlatform().isDerby() || getSession().getDatasourcePlatform().isSymfoware())) {
            reportQuery.addStandardDeviation("salary-std", builder.get("salary"));
        }
        reportQuery.addSum("id-sum", builder.get("id"));
        reportQuery.addMinimum("id-min", builder.get("id"));
        reportQuery.addMaximum("id-max", builder.get("id"));
        if (this.shouldHaveReadAllQueryInDescriptor) {
            ClassDescriptor desc = getSession().getDescriptor(Employee.class);
            if (!desc.getQueryManager().hasReadAllQuery()) {
                desc.getQueryManager().setReadAllQuery(new ReadAllQuery());
                hasSetReadAllQueryIntoDescriptor = true;
            }
        }
        results = (Vector<ReportQueryResult>) getSession().executeQuery(reportQuery);
    }
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) ReportQuery(org.eclipse.persistence.queries.ReportQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) TestWarningException(org.eclipse.persistence.testing.framework.TestWarningException) ReportQueryResult(org.eclipse.persistence.queries.ReportQueryResult)

Example 3 with ReportQueryResult

use of org.eclipse.persistence.queries.ReportQueryResult in project eclipselink by eclipse-ee4j.

the class ReportQueryRetrievePrimaryKeysCursorTest method buildCursoredResultsReportQuery.

protected void buildCursoredResultsReportQuery() {
    cursoredResults = new HashMap<Object, ReportQueryResult>();
    reportQuery = new ReportQuery(Employee.class, new ExpressionBuilder());
    ExpressionBuilder builder = reportQuery.getExpressionBuilder();
    // required
    reportQuery.retrievePrimaryKeys();
    // number
    reportQuery.addAttribute("idResult", builder.get("id"));
    // string
    reportQuery.addAttribute("firstNameResult", builder.get("firstName"));
    // string
    reportQuery.addAttribute("lastNameResult", builder.get("lastName"));
    // number
    reportQuery.addAttribute("addressResult", builder.get("address").get("id"));
    // required
    reportQuery.useCursoredStream(5, 5);
}
Also used : Employee(org.eclipse.persistence.testing.models.employee.domain.Employee) ReportQuery(org.eclipse.persistence.queries.ReportQuery) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) ReportQueryResult(org.eclipse.persistence.queries.ReportQueryResult)

Example 4 with ReportQueryResult

use of org.eclipse.persistence.queries.ReportQueryResult in project eclipselink by eclipse-ee4j.

the class UpdateAllQueryTestHelper method execute.

protected static String execute(Session mainSession, UpdateAllQuery uq, boolean handleChildren, Class<?> rootClass) {
    String errorMsg = "";
    ClassDescriptor descriptor = mainSession.getDescriptor(uq.getReferenceClass());
    clearCache(mainSession);
    // original objects
    Vector objects = mainSession.readAllObjects(rootClass);
    // first update using the original TopLink approach - one by one.
    // That will be done using report query - it will use the same selection criteria
    // as UpdateAllQuery and each attribute will correspond to an update item.
    ReportQuery rq = new ReportQuery(uq.getReferenceClass(), uq.getExpressionBuilder());
    rq.setSelectionCriteria(uq.getSelectionCriteria());
    rq.setShouldRetrievePrimaryKeys(true);
    // some db platforms don't allow nulls in select clause - so add the fields with null values to the query result.
    Vector fieldsWithNullValues = new Vector();
    Iterator itEntrySets = uq.getUpdateClauses().entrySet().iterator();
    while (itEntrySets.hasNext()) {
        Map.Entry entry = (Map.Entry) itEntrySets.next();
        Expression valueExpression;
        String keyString = getQualifiedFieldNameFromKey(entry.getKey(), rq.getReferenceClass(), descriptor, mainSession);
        Object value = entry.getValue();
        DatabaseMapping mapping = descriptor.getObjectBuilder().getMappingForField(new DatabaseField(keyString));
        if (mapping != null && mapping.isOneToOneMapping() && value != null) {
            // Note that this only works in case the reference PK is not compound
            if (((OneToOneMapping) mapping).getSourceToTargetKeyFields().size() > 1) {
                errorMsg = "Attribute " + mapping.getAttributeName() + " mapped with 1to1 mapping that has more than one targetKeyField. UpdateAllQueryTestHelper currently doesn't support that.";
            }
            DatabaseField targetField = ((OneToOneMapping) mapping).getSourceToTargetKeyFields().get(new DatabaseField(keyString));
            if (value instanceof Expression) {
                valueExpression = ((Expression) (((Expression) value).clone())).getField(targetField);
            } else {
                ClassDescriptor targetDescriptor = mapping.getReferenceDescriptor();
                Object fieldValue = targetDescriptor.getObjectBuilder().extractValueFromObjectForField(value, targetField, (org.eclipse.persistence.internal.sessions.AbstractSession) mainSession);
                valueExpression = rq.getExpressionBuilder().value(fieldValue);
            }
        } else {
            if (value instanceof Expression) {
                valueExpression = (Expression) value;
            } else {
                valueExpression = rq.getExpressionBuilder().value(value);
            }
        }
        if (value == null) {
            fieldsWithNullValues.add(keyString);
        } else {
            rq.addAttribute(keyString, valueExpression);
        }
    }
    UnitOfWork uow = mainSession.acquireUnitOfWork();
    // mainSession could be a ServerSession
    AbstractSession session = uow.getParent();
    // report query results contain the values to be assigned for each object to be updated.
    Vector result = (Vector) session.executeQuery(rq);
    Vector objectsAfterOneByOneUpdate = new Vector(objects.size());
    session.beginTransaction();
    try {
        for (int i = 0; i < result.size(); i++) {
            // read through uow the object(clone) to be updated
            ReportQueryResult reportResult = (ReportQueryResult) result.elementAt(i);
            // hammer into the object the updated values
            Object obj = reportResult.readObject(rq.getReferenceClass(), uow);
            DatabaseRecord row = new DatabaseRecord();
            for (int j = 0; j < reportResult.getNames().size(); j++) {
                String name = reportResult.getNames().get(j);
                DatabaseField field = new DatabaseField(name);
                Object value = reportResult.getResults().get(j);
                row.add(field, value);
            }
            // some db platforms don't allow nulls in select clause - so add the fields with null values to the query result
            for (int j = 0; j < fieldsWithNullValues.size(); j++) {
                String name = (String) fieldsWithNullValues.elementAt(j);
                DatabaseField field = new DatabaseField(name);
                row.add(field, null);
            }
            rq.getDescriptor().getObjectBuilder().assignReturnRow(obj, (AbstractSession) uow, row, null);
        }
        // uow committed - objects updated.
        uow.commit();
        // objects are copied into another vector - later it will be compared with UpdateAllQuery result.
        for (int i = 0; i < objects.size(); i++) {
            Object original = objects.elementAt(i);
            Object copy = buildCopy(descriptor, original, uow);
            objectsAfterOneByOneUpdate.add(copy);
        }
    } finally {
        // transaction rolled back - objects back to the original state in the db.
        session.rollbackTransaction();
    }
    clearCache(mainSession);
    // now use UpdateAllQuery
    uow = mainSession.acquireUnitOfWork();
    // mainSession could be a ServerSession
    session = uow.getParent();
    Vector objectsAfterUpdateAll = new Vector(objects.size());
    session.beginTransaction();
    try {
        uow.executeQuery(uq);
        // uow committed - objects updated.
        uow.commit();
        // objects are copied into another vector - it will be compared with update one-by-one result.
        for (int i = 0; i < objects.size(); i++) {
            Object original = objects.elementAt(i);
            Object copy = buildCopy(descriptor, original, uow);
            objectsAfterUpdateAll.add(copy);
        }
    } finally {
        // transaction rolled back - objects back to the original state in the db.
        session.rollbackTransaction();
    }
    clearCache(mainSession);
    // verify
    String classErrorMsg = "";
    for (int i = 0; i < objects.size(); i++) {
        Object obj = objects.elementAt(i);
        Object obj1 = objectsAfterOneByOneUpdate.elementAt(i);
        Object obj2 = objectsAfterUpdateAll.elementAt(i);
        boolean equal = rq.getDescriptor().getObjectBuilder().compareObjects(obj, obj2, session);
        if (!equal) {
            classErrorMsg = classErrorMsg + "Difference: original = " + obj.toString() + "; afterOneByOneUpdate = " + obj1.toString() + "; afterUpdateAll = " + obj2.toString() + ";";
        }
    }
    if (classErrorMsg.length() > 0) {
        errorMsg = errorMsg + classErrorMsg;
    }
    if (handleChildren) {
        if (descriptor.hasInheritance() && descriptor.getInheritancePolicy().hasChildren()) {
            Iterator<ClassDescriptor> it = descriptor.getInheritancePolicy().getChildDescriptors().iterator();
            while (it.hasNext()) {
                ClassDescriptor childDescriptor = it.next();
                Class<?> childReferenceClass = childDescriptor.getJavaClass();
                UpdateAllQuery childUq = (UpdateAllQuery) uq.clone();
                childUq.setReferenceClass(childReferenceClass);
                childUq.setIsPrepared(false);
                errorMsg += execute(mainSession, childUq, handleChildren, rootClass);
            }
        }
    }
    return errorMsg;
}
Also used : UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) Iterator(java.util.Iterator) Vector(java.util.Vector) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) ReportQuery(org.eclipse.persistence.queries.ReportQuery) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) DataExpression(org.eclipse.persistence.internal.expressions.DataExpression) Expression(org.eclipse.persistence.expressions.Expression) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) HashMap(java.util.HashMap) Map(java.util.Map) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping) ReportQueryResult(org.eclipse.persistence.queries.ReportQueryResult) UpdateAllQuery(org.eclipse.persistence.queries.UpdateAllQuery)

Example 5 with ReportQueryResult

use of org.eclipse.persistence.queries.ReportQueryResult in project eclipselink by eclipse-ee4j.

the class ReportQueryAdvancedJUnitTest method testPhoneCountGroupByOwner.

public void testPhoneCountGroupByOwner() {
    ExpressionBuilder builder = new ExpressionBuilder();
    ReportQuery reportQuery = new ReportQuery(PhoneNumber.class, builder);
    Expression groupingExp = builder.get("owner");
    reportQuery.addItem("owner", groupingExp);
    reportQuery.addItem("phonesCount", builder.count());
    reportQuery.addGrouping(groupingExp);
    Vector results = (Vector) getDbSession().executeQuery(reportQuery);
    for (int i = 0; i < results.size(); i++) {
        ReportQueryResult reportResult = (ReportQueryResult) (results.elementAt(i));
        Employee employee = (Employee) reportResult.get("owner");
        int count = ((Number) reportResult.get("phonesCount")).intValue();
        if (employee.getPhoneNumbers().size() != count) {
            fail(employee.toString() + " has " + employee.getPhoneNumbers().size() + " phones, ReportQuery returned " + count);
        }
    }
}
Also used : Expression(org.eclipse.persistence.expressions.Expression) ReportQuery(org.eclipse.persistence.queries.ReportQuery) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) Vector(java.util.Vector) ReportQueryResult(org.eclipse.persistence.queries.ReportQueryResult)

Aggregations

ReportQueryResult (org.eclipse.persistence.queries.ReportQueryResult)27 ReportQuery (org.eclipse.persistence.queries.ReportQuery)24 ExpressionBuilder (org.eclipse.persistence.expressions.ExpressionBuilder)23 Vector (java.util.Vector)22 Iterator (java.util.Iterator)11 Expression (org.eclipse.persistence.expressions.Expression)11 EntityManager (jakarta.persistence.EntityManager)6 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)5 Employee (org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Employee)5 List (java.util.List)4 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)2 ConstructorReportItem (org.eclipse.persistence.queries.ConstructorReportItem)2 BigDecimal (java.math.BigDecimal)1 Enumeration (java.util.Enumeration)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 DataExpression (org.eclipse.persistence.internal.expressions.DataExpression)1 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)1 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)1 Association (org.eclipse.persistence.mappings.Association)1