@Override
public WriteResponse write(final Request request) throws SqlResourceException {
TriggerManager.executeTriggers(getName(), request, true);
// Init response
final WriteResponse response = new WriteResponse();
int rowsAffected = 0;
Set<ResponseValue> responseValues = null;
if (request.getType() == Type.INSERT) {
responseValues = new TreeSet<ResponseValue>();
}
boolean doParent = true;
Connection connection = null;
try {
connection = Factory.getConnection(SqlResourceDefinitionUtils.getDefaultDatabase(definition));
if (metaData.isHierarchical()) {
final Request childRequest = Factory.getChildRequest(request);
if (request.getChildrenParameters() != null) {
// Set up response
List<Set<ResponseValue>> childListResponseValues = null;
Set<ResponseValue> childResponseValues = null;
if (request.getType() == Type.INSERT) {
childListResponseValues = new ArrayList<Set<ResponseValue>>(request
.getChildrenParameters().size());
responseValues.add(new ResponseValue(getChildRowsName(), childListResponseValues,
Integer.MAX_VALUE));
// Add parent params, since we won't be executing the write on the parent
for (final TableMetaData table : metaData.getParentPlusExtTables()) {
addRequestParamsToResponseValues(request, responseValues, table);
}
}
// Delete, update or insert each specified child row
for (final List<RequestValue> childRowParams : request.getChildrenParameters()) {
if (request.getType() == Type.INSERT) {
// Set up response value set
childResponseValues = new TreeSet<ResponseValue>();
childListResponseValues.add(childResponseValues);
// Add the parent pks, since inserts ignore the resIds
childRowParams.addAll(request.getResourceIdentifiers());
} // else deletes and updates use resIds
childRequest.setParameters(childRowParams);
rowsAffected += execWrite(connection, childRequest, false, childResponseValues);
}
// Don't touch the parent(s)
doParent = false;
} else if (request.getType() == Request.Type.DELETE) {
// Delete all children and the parent(s)
if (request.getResourceIdentifiers() == null) {
childRequest.setParameters(request.getParameters());
}
rowsAffected += execWrite(connection, childRequest, false, responseValues);
// Now do the parent as well, doParent already equals true
}
// else just insert or update the parent (+ extensions)
} // else insert, update or delete the parent (+ extensions)
if (doParent) {
rowsAffected += execWrite(connection, request, true, responseValues);
}
TriggerManager.executeTriggers(getName(), request, false);
// Finalize response
if (request.getType() == Type.INSERT) {
response.addRow(responseValues);
}
response.addRowsAffected(rowsAffected);
} catch (final SQLException exception) {
throw new SqlResourceException(exception);
} finally {
if (connection != null) {