use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-rdbms by datanucleus.
the class MultiPersistableMapping method setObject.
/**
* Sets the specified positions in the PreparedStatement associated with this field, and value.
* If the number of positions in "pos" is not the same as the number of datastore mappings then it is assumed
* that we should only set the positions for the real implementation FK; this happens where we have a statement
* like "... WHERE IMPL1_ID_OID = ? AND IMPL2_ID_OID IS NULL" so we need to filter on the other implementations
* being null and only want to input parameter(s) for the real implementation of "value".
* @param ec execution context
* @param ps a datastore object that executes statements in the database
* @param pos The position(s) of the PreparedStatement to populate
* @param value the value stored in this field
* @param ownerOP the owner ObjectProvider
* @param ownerFieldNumber the owner absolute field number
*/
public void setObject(ExecutionContext ec, PreparedStatement ps, int[] pos, Object value, ObjectProvider ownerOP, int ownerFieldNumber) {
boolean setValueFKOnly = false;
if (pos != null && pos.length < getNumberOfDatastoreMappings()) {
setValueFKOnly = true;
}
// Make sure that this field has a sub-mapping appropriate for the specified value
int javaTypeMappingNumber = getMappingNumberForValue(ec, value);
if (value != null && javaTypeMappingNumber == -1) {
// TODO Change this to a multiple field mapping localised message
throw new ClassCastException(Localiser.msg("041044", mmd != null ? mmd.getFullFieldName() : "", getType(), value.getClass().getName()));
}
if (value != null) {
ApiAdapter api = ec.getApiAdapter();
ClassLoaderResolver clr = ec.getClassLoaderResolver();
// Make sure the value is persisted if it is persistable in its own right
if (!ec.isInserting(value)) {
// Object either already exists, or is not yet being inserted.
Object id = api.getIdForObject(value);
// Check if the persistable exists in this datastore
boolean requiresPersisting = false;
if (ec.getApiAdapter().isDetached(value) && ownerOP != null) {
// Detached object that needs attaching (or persisting if detached from a different datastore)
requiresPersisting = true;
} else if (id == null) {
// Transient object, so we need to persist it
requiresPersisting = true;
} else {
ExecutionContext valueEC = api.getExecutionContext(value);
if (valueEC != null && ec != valueEC) {
throw new NucleusUserException(Localiser.msg("041015"), id);
}
}
if (requiresPersisting) {
// The object is either not yet persistent or is detached and so needs attaching
Object pcNew = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
ec.flushInternal(false);
id = api.getIdForObject(pcNew);
if (ec.getApiAdapter().isDetached(value) && ownerOP != null) {
// Update any detached reference to refer to the attached variant
ownerOP.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
if (mmd != null) {
RelationType relationType = mmd.getRelationType(clr);
if (relationType == RelationType.ONE_TO_ONE_BI) {
ObjectProvider relatedSM = ec.findObjectProvider(pcNew);
AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
// TODO Allow for multiple related fields
relatedSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerOP.getObject());
} else if (relationType == RelationType.MANY_TO_ONE_BI) {
// TODO Update the container element with the attached variant
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug("PCMapping.setObject : object " + ownerOP.getInternalObjectId() + " has field " + ownerFieldNumber + " that is 1-N bidirectional - should really update the reference in the relation. Not yet supported");
}
}
}
}
}
if (getNumberOfDatastoreMappings() <= 0) {
// If the field doesn't map to any datastore fields, omit the set process
return;
}
}
}
if (pos == null) {
return;
}
ObjectProvider op = (value != null ? ec.findObjectProvider(value) : null);
try {
if (op != null) {
op.setStoringPC();
}
int n = 0;
NotYetFlushedException notYetFlushed = null;
for (int i = 0; i < javaTypeMappings.length; i++) {
// Set the PreparedStatement positions for this implementation mapping
int[] posMapping;
if (setValueFKOnly) {
// Only using first "pos" value(s)
n = 0;
} else if (n >= pos.length) {
// store all implementations to the same columns, so we reset the index
n = 0;
}
if (javaTypeMappings[i].getReferenceMapping() != null) {
posMapping = new int[javaTypeMappings[i].getReferenceMapping().getNumberOfDatastoreMappings()];
} else {
posMapping = new int[javaTypeMappings[i].getNumberOfDatastoreMappings()];
}
for (int j = 0; j < posMapping.length; j++) {
posMapping[j] = pos[n++];
}
try {
if (javaTypeMappingNumber == -2 || (value != null && javaTypeMappingNumber == i)) {
// This mapping is where the value is to be stored, or using persistent interfaces
javaTypeMappings[i].setObject(ec, ps, posMapping, value);
} else if (!setValueFKOnly) {
// Set null for this mapping, since the value is null or is for something else
javaTypeMappings[i].setObject(ec, ps, posMapping, null);
}
} catch (NotYetFlushedException e) {
notYetFlushed = e;
}
}
if (notYetFlushed != null) {
throw notYetFlushed;
}
} finally {
if (op != null) {
op.unsetStoringPC();
}
}
}
use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-rdbms by datanucleus.
the class TypeConverterMultiMapping method initialize.
public void initialize(AbstractMemberMetaData mmd, Table table, ClassLoaderResolver clr, TypeConverter conv) {
super.initialize(mmd, table, clr);
if (mmd.getTypeConverterName() != null) {
// Use specified converter (if found)
converter = table.getStoreManager().getNucleusContext().getTypeManager().getTypeConverterForName(mmd.getTypeConverterName());
if (converter == null) {
throw new NucleusUserException(Localiser.msg("044062", mmd.getFullFieldName(), mmd.getTypeConverterName()));
}
} else if (conv != null) {
converter = conv;
} else {
throw new NucleusUserException("Unable to initialise mapping of type " + getClass().getName() + " for field " + mmd.getFullFieldName() + " since no TypeConverter was provided");
}
if (!(converter instanceof MultiColumnConverter)) {
throw new NucleusUserException("Not able to use " + getClass().getName() + " for field " + mmd.getFullFieldName() + " since provided TypeConverter " + converter + " does not implement MultiColumnConverter");
}
// Add columns for this converter
MultiColumnConverter multiConv = (MultiColumnConverter) converter;
Class[] colTypes = multiConv.getDatastoreColumnTypes();
for (int i = 0; i < colTypes.length; i++) {
addColumns(colTypes[i].getName());
}
}
use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-rdbms by datanucleus.
the class FKListStore method validateElementForWriting.
/**
* Method to validate that an element is valid for writing to the datastore.
* TODO Minimise differences to super.validateElementForWriting()
* @param op ObjectProvider for the List
* @param element The element to validate
* @param index The position that the element is being stored at in the list
* @return Whether the element was inserted
*/
protected boolean validateElementForWriting(final ObjectProvider op, final Object element, final int index) {
final Object newOwner = op.getObject();
ComponentInfo info = getComponentInfoForElement(element);
final DatastoreClass elementTable;
if (storeMgr.getNucleusContext().getMetaDataManager().isPersistentInterface(elementType)) {
elementTable = storeMgr.getDatastoreClass(storeMgr.getNucleusContext().getMetaDataManager().getImplementationNameForPersistentInterface(elementType), clr);
} else {
elementTable = storeMgr.getDatastoreClass(element.getClass().getName(), clr);
}
final JavaTypeMapping orderMapping;
if (info != null) {
orderMapping = info.getDatastoreClass().getExternalMapping(ownerMemberMetaData, MappingType.EXTERNAL_INDEX);
} else {
orderMapping = this.orderMapping;
}
// Check if element is ok for use in the datastore, specifying any external mappings that may be required
boolean inserted = super.validateElementForWriting(op.getExecutionContext(), element, new FieldValues() {
public void fetchFields(ObjectProvider elemOP) {
// Find the (element) table storing the FK back to the owner
if (elementTable != null) {
JavaTypeMapping externalFKMapping = elementTable.getExternalMapping(ownerMemberMetaData, MappingType.EXTERNAL_FK);
if (externalFKMapping != null) {
// The element has an external FK mapping so set the value it needs to use in the INSERT
elemOP.setAssociatedValue(externalFKMapping, op.getObject());
}
if (relationDiscriminatorMapping != null) {
elemOP.setAssociatedValue(relationDiscriminatorMapping, relationDiscriminatorValue);
}
if (orderMapping != null && index >= 0) {
if (ownerMemberMetaData.getOrderMetaData() != null && ownerMemberMetaData.getOrderMetaData().getMappedBy() != null) {
// Order is stored in a field in the element so update it
// We support mapped-by fields of types int/long/Integer/Long currently
Object indexValue = null;
if (orderMapping.getMemberMetaData().getTypeName().equals(ClassNameConstants.JAVA_LANG_LONG) || orderMapping.getMemberMetaData().getTypeName().equals(ClassNameConstants.LONG)) {
indexValue = Long.valueOf(index);
} else {
indexValue = Integer.valueOf(index);
}
elemOP.replaceFieldMakeDirty(orderMapping.getMemberMetaData().getAbsoluteFieldNumber(), indexValue);
} else {
// Order is stored in a surrogate column so save its vaue for the element to use later
elemOP.setAssociatedValue(orderMapping, Integer.valueOf(index));
}
}
}
if (ownerMemberMetaData.getMappedBy() != null) {
// TODO This is ManagedRelations - move into RelationshipManager
// Managed Relations : 1-N bidir, so make sure owner is correct at persist
// TODO Support DOT notation in mappedBy
ObjectProvider ownerHolderOP = elemOP;
int ownerFieldNumberInHolder = -1;
if (ownerMemberMetaData.getMappedBy().indexOf('.') > 0) {
AbstractMemberMetaData otherMmd = null;
AbstractClassMetaData otherCmd = info.getAbstractClassMetaData();
String remainingMappedBy = ownerMemberMetaData.getMappedBy();
while (remainingMappedBy.indexOf('.') > 0) {
int dotPosition = remainingMappedBy.indexOf('.');
String thisMappedBy = remainingMappedBy.substring(0, dotPosition);
otherMmd = otherCmd.getMetaDataForMember(thisMappedBy);
Object holderValueAtField = ownerHolderOP.provideField(otherMmd.getAbsoluteFieldNumber());
ownerHolderOP = op.getExecutionContext().findObjectProviderForEmbedded(holderValueAtField, ownerHolderOP, otherMmd);
remainingMappedBy = remainingMappedBy.substring(dotPosition + 1);
otherCmd = storeMgr.getMetaDataManager().getMetaDataForClass(otherMmd.getTypeName(), clr);
if (remainingMappedBy.indexOf('.') < 0) {
otherMmd = otherCmd.getMetaDataForMember(remainingMappedBy);
ownerFieldNumberInHolder = otherMmd.getAbsoluteFieldNumber();
}
}
} else {
ownerFieldNumberInHolder = info.getAbstractClassMetaData().getAbsolutePositionOfMember(ownerMemberMetaData.getMappedBy());
}
Object currentOwner = ownerHolderOP.provideField(ownerFieldNumberInHolder);
if (currentOwner == null) {
// No owner, so correct it
NucleusLogger.PERSISTENCE.info(Localiser.msg("056037", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(ownerHolderOP.getObject())));
ownerHolderOP.replaceFieldMakeDirty(ownerFieldNumberInHolder, newOwner);
} else if (currentOwner != newOwner && op.getReferencedPC() == null) {
// Inconsistent owner, so throw exception
throw new NucleusUserException(Localiser.msg("056038", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(ownerHolderOP.getObject()), StringUtils.toJVMIDString(currentOwner)));
}
}
}
public void fetchNonLoadedFields(ObjectProvider op) {
}
public FetchPlan getFetchPlanForLoading() {
return null;
}
});
return inserted;
}
use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-rdbms by datanucleus.
the class JoinListStore method internalAdd.
/**
* Internal method to add element(s) to the List.
* Performs the add in 2 steps.
* <ol>
* <li>Shift all existing elements into their new positions so we can insert.</li>
* <li>Insert all new elements directly at their desired positions</li>
* </ol>
* Both steps can be batched (separately).
* @param op The ObjectProvider
* @param start The start location (if required)
* @param atEnd Whether to add the element at the end
* @param c The collection of objects to add.
* @param size Current size of list if known. -1 if not known
* @return Whether it was successful
*/
protected boolean internalAdd(ObjectProvider op, int start, boolean atEnd, Collection<E> c, int size) {
if (c == null || c.size() == 0) {
return true;
}
if (relationType == RelationType.MANY_TO_MANY_BI && ownerMemberMetaData.getMappedBy() != null) {
// M-N non-owner : don't add from this side to avoid duplicates
return true;
}
// Calculate the amount we need to shift any existing elements by
// This is used where inserting between existing elements and have to shift down all elements after the start point
int shift = c.size();
// check all elements are valid for persisting and exist (persistence-by-reachability)
ExecutionContext ec = op.getExecutionContext();
Iterator iter = c.iterator();
while (iter.hasNext()) {
Object element = iter.next();
validateElementForWriting(ec, element, null);
if (relationType == RelationType.ONE_TO_MANY_BI) {
// TODO This is ManagedRelations - move into RelationshipManager
ObjectProvider elementOP = ec.findObjectProvider(element);
if (elementOP != null) {
AbstractMemberMetaData[] relatedMmds = ownerMemberMetaData.getRelatedMemberMetaData(clr);
// TODO Cater for more than 1 related field
Object elementOwner = elementOP.provideField(relatedMmds[0].getAbsoluteFieldNumber());
if (elementOwner == null) {
// No owner, so correct it
NucleusLogger.PERSISTENCE.info(Localiser.msg("056037", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementOP.getObject())));
elementOP.replaceField(relatedMmds[0].getAbsoluteFieldNumber(), op.getObject());
} else if (elementOwner != op.getObject() && op.getReferencedPC() == null) {
// Inconsistent owner, so throw exception
throw new NucleusUserException(Localiser.msg("056038", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementOP.getObject()), StringUtils.toJVMIDString(elementOwner)));
}
}
}
}
// Check what we have persistent already
int currentListSize = 0;
if (size < 0) {
// Get the current size from the datastore
currentListSize = size(op);
} else {
currentListSize = size;
}
// Check for dynamic schema updates prior to addition
if (storeMgr.getBooleanObjectProperty(RDBMSPropertyNames.PROPERTY_RDBMS_DYNAMIC_SCHEMA_UPDATES).booleanValue()) {
DynamicSchemaFieldManager dynamicSchemaFM = new DynamicSchemaFieldManager(storeMgr, op);
dynamicSchemaFM.storeObjectField(getOwnerMemberMetaData().getAbsoluteFieldNumber(), c);
if (dynamicSchemaFM.hasPerformedSchemaUpdates()) {
invalidateAddStmt();
}
}
String addStmt = getAddStmtForJoinTable();
try {
ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
SQLController sqlControl = storeMgr.getSQLController();
try {
// Shift any existing elements so that we can insert the new element(s) at their position
if (!atEnd && start != currentListSize) {
boolean batched = currentListSize - start > 0;
for (int i = currentListSize - 1; i >= start; i--) {
// Shift the index for this row by "shift"
internalShift(op, mconn, batched, i, shift, (i == start));
}
} else {
start = currentListSize;
}
// Insert the elements at their required location
int jdbcPosition = 1;
boolean batched = (c.size() > 1);
Iterator elemIter = c.iterator();
while (elemIter.hasNext()) {
Object element = elemIter.next();
PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, addStmt, batched);
try {
jdbcPosition = 1;
jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
jdbcPosition = BackingStoreHelper.populateElementInStatement(ec, ps, element, jdbcPosition, elementMapping);
if (orderMapping != null) {
jdbcPosition = BackingStoreHelper.populateOrderInStatement(ec, ps, start, jdbcPosition, orderMapping);
}
if (relationDiscriminatorMapping != null) {
jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
}
start++;
// Execute the statement
sqlControl.executeStatementUpdate(ec, mconn, addStmt, ps, !iter.hasNext());
} finally {
sqlControl.closeStatement(mconn, ps);
}
}
} finally {
mconn.release();
}
} catch (SQLException | MappedDatastoreException e) {
throw new NucleusDataStoreException(Localiser.msg("056009", addStmt), e);
}
return true;
}
use of org.datanucleus.exceptions.NucleusUserException in project datanucleus-rdbms by datanucleus.
the class ElementContainerStore method validateElementForWriting.
/**
* Method to check if an element is already persistent, or is managed by a different ExecutionContext. If not persistent, this will persist it.
* @param ec execution context
* @param element The element
* @param fieldValues any initial field values to use if persisting the element
* @return Whether the element was persisted during this call
*/
protected boolean validateElementForWriting(ExecutionContext ec, Object element, FieldValues fieldValues) {
// Check the element type for this collection
if (!elementIsPersistentInterface && !validateElementType(ec.getClassLoaderResolver(), element)) {
throw new ClassCastException(Localiser.msg("056033", element.getClass().getName(), ownerMemberMetaData.getFullFieldName(), elementType));
}
boolean persisted = false;
if (elementsAreEmbedded || elementsAreSerialised) {
// Element is embedded/serialised so has no id
} else {
ObjectProvider elementSM = ec.findObjectProvider(element);
if (elementSM != null && elementSM.isEmbedded()) {
// Element is already with ObjectProvider and is embedded in another field!
throw new NucleusUserException(Localiser.msg("056028", ownerMemberMetaData.getFullFieldName(), element));
}
persisted = SCOUtils.validateObjectForWriting(ec, element, fieldValues);
}
return persisted;
}
Aggregations