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);
}
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()));
}
}
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;
}
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;
}
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);
}
}
}
Aggregations