Search in sources :

Example 31 with DatabaseRecord

use of org.eclipse.persistence.sessions.DatabaseRecord in project eclipselink by eclipse-ee4j.

the class AggregateCollectionMapping method initializeUpdateListOrderQuery.

protected void initializeUpdateListOrderQuery(AbstractSession session, String queryType) {
    DataModifyQuery query = new DataModifyQuery();
    if (queryType == pk) {
        this.pkUpdateListOrderFieldQuery = query;
    } else if (queryType == bulk) {
        this.bulkUpdateListOrderFieldQuery = query;
    } else {
        this.updateListOrderFieldQuery = query;
    }
    query.setSessionName(session.getName());
    // Build where clause expression.
    Expression whereClause = null;
    Expression builder = new ExpressionBuilder();
    AbstractRecord modifyRow = new DatabaseRecord();
    if (queryType == pk) {
        Iterator<DatabaseField> it = getReferenceDescriptor().getPrimaryKeyFields().iterator();
        while (it.hasNext()) {
            DatabaseField pkField = it.next();
            DatabaseField sourceField = targetForeignKeyToSourceKeys.get(pkField);
            DatabaseField parameterField = sourceField != null ? sourceField : pkField;
            Expression expression = builder.getField(pkField).equal(builder.getParameter(parameterField));
            whereClause = expression.and(whereClause);
        }
        modifyRow.add(this.listOrderField, null);
    } else {
        Iterator<Map.Entry<DatabaseField, DatabaseField>> it = targetForeignKeyToSourceKeys.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<DatabaseField, DatabaseField> entry = it.next();
            Expression expression = builder.getField(entry.getKey()).equal(builder.getParameter(entry.getValue()));
            whereClause = expression.and(whereClause);
        }
        Expression listOrderExpression;
        if (queryType == bulk) {
            listOrderExpression = builder.getField(this.listOrderField).between(builder.getParameter(min), builder.getParameter(max));
            modifyRow.add(this.listOrderField, ExpressionMath.add(builder.getField(this.listOrderField), builder.getParameter(shift)));
        } else {
            listOrderExpression = builder.getField(this.listOrderField).equal(builder.getParameter(min));
            modifyRow.add(this.listOrderField, null);
        }
        whereClause = listOrderExpression.and(whereClause);
    }
    SQLUpdateStatement statement = new SQLUpdateStatement();
    statement.setTable(getReferenceDescriptor().getDefaultTable());
    statement.setWhereClause(whereClause);
    statement.setModifyRow(modifyRow);
    query.setSQLStatement(statement);
}
Also used : DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) Expression(org.eclipse.persistence.expressions.Expression) SQLUpdateStatement(org.eclipse.persistence.internal.expressions.SQLUpdateStatement) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery)

Example 32 with DatabaseRecord

use of org.eclipse.persistence.sessions.DatabaseRecord in project eclipselink by eclipse-ee4j.

the class QueryTimeoutBatchTestCase method initializeDatabase.

protected void initializeDatabase(UnitOfWork uow) {
    try {
        // Add expected inserts to sequence
        DataModifyQuery modifyQuery = new DataModifyQuery();
        String sequenceTableName = "SEQUENCE";
        if (getSession().getPlatform().getDefaultSequence().isTable()) {
            sequenceTableName = getSession().getPlatform().getQualifiedSequenceTableName();
        }
        modifyQuery.setSQLString("UPDATE " + sequenceTableName + " SET SEQ_COUNT = SEQ_COUNT + 10 WHERE SEQ_NAME = 'EMP_SEQ'");
        modifyQuery.setForceBatchStatementExecution(true);
        uow.addQuery("modify1", modifyQuery);
        uow.executeQuery(modifyQuery);
        // uow.commit();
        // Get next sequence
        DataReadQuery readQuery = new DataReadQuery();
        readQuery.setSQLString("SELECT SEQ_COUNT FROM " + sequenceTableName + " WHERE SEQ_NAME = 'EMP_SEQ'");
        uow.addQuery("read1", readQuery);
        Object resultFromRead = uow.executeQuery(readQuery);
        DatabaseRecord dbRecord = (DatabaseRecord) ((Vector) resultFromRead).get(0);
        setCurrentIDSequence(((BigDecimal) dbRecord.get("SEQ_COUNT")).longValue());
        uow.commit();
    } catch (Exception e) {
        System.out.println("QueryTimeoutBatchTest could not get EMP_SEQ sequence");
        setCurrentIDSequence(40000 + Math.round(Math.random()));
    }
}
Also used : DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) DataReadQuery(org.eclipse.persistence.queries.DataReadQuery) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery) TestErrorException(org.eclipse.persistence.testing.framework.TestErrorException)

Example 33 with DatabaseRecord

use of org.eclipse.persistence.sessions.DatabaseRecord 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 34 with DatabaseRecord

use of org.eclipse.persistence.sessions.DatabaseRecord in project eclipselink by eclipse-ee4j.

the class EmulatedStatement method fetchRows.

/**
 * If the rows have not be fetched, fetch them from the database.
 */
protected List fetchRows() throws SQLException {
    List rows = this.connection.getRows(this.sql);
    if (rows == null) {
        Connection realConnection = this.connection.getRealConnection();
        PreparedStatement statement = realConnection.prepareStatement(this.sql);
        for (int index = 0; index < this.parameters.size(); index++) {
            statement.setObject(index + 1, this.parameters.get(index));
        }
        ResultSet result = statement.executeQuery();
        rows = new ArrayList();
        ResultSetMetaData metaData = result.getMetaData();
        while (result.next()) {
            DatabaseRecord row = new DatabaseRecord();
            for (int column = 0; column < metaData.getColumnCount(); column++) {
                row.add(new DatabaseField(metaData.getColumnName(column + 1)), result.getObject(column + 1));
            }
            rows.add(row);
        }
        result.close();
        statement.close();
    }
    this.connection.putRows(this.sql, rows);
    return rows;
}
Also used : DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField)

Example 35 with DatabaseRecord

use of org.eclipse.persistence.sessions.DatabaseRecord in project eclipselink by eclipse-ee4j.

the class DatabaseQueryMechanism method updateObjectAndRowWithReturnRow.

protected void updateObjectAndRowWithReturnRow(Collection returnFields, boolean isFirstCallForInsert) {
    WriteObjectQuery writeQuery = getWriteObjectQuery();
    AbstractRecord outputRow = (AbstractRecord) writeQuery.getProperties().get("output");
    if ((outputRow == null) || outputRow.isEmpty()) {
        return;
    }
    AbstractRecord row = new DatabaseRecord();
    for (Iterator iterator = returnFields.iterator(); iterator.hasNext(); ) {
        DatabaseField field = (DatabaseField) iterator.next();
        if (outputRow.containsKey(field)) {
            row.put(field, outputRow.get(field));
        }
    }
    if (row.isEmpty()) {
        return;
    }
    Object object = writeQuery.getObject();
    ObjectChangeSet objectChangeSet = null;
    if (getSession().isUnitOfWork()) {
        objectChangeSet = writeQuery.getObjectChangeSet();
        if ((objectChangeSet == null) && (((UnitOfWorkImpl) getSession()).getUnitOfWorkChangeSet() != null)) {
            objectChangeSet = (ObjectChangeSet) ((UnitOfWorkImpl) getSession()).getUnitOfWorkChangeSet().getObjectChangeSetForClone(object);
        }
    }
    getDescriptor().getObjectBuilder().assignReturnRow(object, writeQuery.getSession(), row, objectChangeSet);
    Object primaryKey = null;
    if (isFirstCallForInsert) {
        AbstractRecord pkToModify = new DatabaseRecord();
        List<DatabaseField> primaryKeyFields = getDescriptor().getPrimaryKeyFields();
        for (int i = 0; i < primaryKeyFields.size(); i++) {
            DatabaseField field = primaryKeyFields.get(i);
            if (row.containsKey(field)) {
                pkToModify.put(field, row.get(field));
            }
        }
        if (!pkToModify.isEmpty()) {
            primaryKey = getDescriptor().getObjectBuilder().extractPrimaryKeyFromObject(object, getSession());
            writeQuery.setPrimaryKey(primaryKey);
            // Now I need to update the row
            getModifyRow().putAll(pkToModify);
            getDescriptor().getObjectBuilder().addPrimaryKeyForNonDefaultTable(getModifyRow(), object, getSession());
        }
    }
    if (objectChangeSet != null) {
        if (primaryKey != null) {
            objectChangeSet.setId(primaryKey);
        }
    }
}
Also used : WriteObjectQuery(org.eclipse.persistence.queries.WriteObjectQuery) DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) Iterator(java.util.Iterator) ObjectChangeSet(org.eclipse.persistence.internal.sessions.ObjectChangeSet)

Aggregations

DatabaseRecord (org.eclipse.persistence.sessions.DatabaseRecord)110 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)44 AbstractRecord (org.eclipse.persistence.internal.sessions.AbstractRecord)43 Vector (java.util.Vector)31 ArrayList (java.util.ArrayList)17 NonSynchronizedVector (org.eclipse.persistence.internal.helper.NonSynchronizedVector)17 BigDecimal (java.math.BigDecimal)14 List (java.util.List)14 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)14 DatabaseSession (org.eclipse.persistence.sessions.DatabaseSession)14 Test (org.junit.Test)14 Expression (org.eclipse.persistence.expressions.Expression)12 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)12 HashMap (java.util.HashMap)11 Map (java.util.Map)10 EclipseLinkException (org.eclipse.persistence.exceptions.EclipseLinkException)7 ExpressionBuilder (org.eclipse.persistence.expressions.ExpressionBuilder)7 RelationalDescriptor (org.eclipse.persistence.descriptors.RelationalDescriptor)6 DescriptorException (org.eclipse.persistence.exceptions.DescriptorException)6 SQLUpdateStatement (org.eclipse.persistence.internal.expressions.SQLUpdateStatement)6