use of org.apache.ofbiz.entity.model.ModelRelation in project ofbiz-framework by apache.
the class DatabaseUtil method createTable.
/* ====================================================================== */
/* ====================================================================== */
public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) {
if (entity == null) {
return "ModelEntity was null and is required to create a table";
}
if (entity instanceof ModelViewEntity) {
return "ERROR: Cannot create table for a view entity";
}
StringBuilder sqlBuf = new StringBuilder("CREATE TABLE ");
sqlBuf.append(entity.getTableName(this.datasourceInfo));
sqlBuf.append(" (");
Iterator<ModelField> fieldIter = entity.getFieldsIterator();
while (fieldIter.hasNext()) {
ModelField field = fieldIter.next();
ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType());
if (type == null) {
return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table.";
}
sqlBuf.append(field.getColName());
sqlBuf.append(" ");
sqlBuf.append(type.getSqlType());
if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) {
// if there is a characterSet, add the CHARACTER SET arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
sqlBuf.append(" CHARACTER SET ");
sqlBuf.append(this.datasourceInfo.getCharacterSet());
}
// if there is a collate, add the COLLATE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
sqlBuf.append(" COLLATE ");
sqlBuf.append(this.datasourceInfo.getCollate());
}
}
if (field.getIsNotNull() || field.getIsPk()) {
if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) {
sqlBuf.append(" CONSTRAINT NOT NULL, ");
} else {
sqlBuf.append(" NOT NULL, ");
}
} else {
sqlBuf.append(", ");
}
}
String pkName = makePkConstraintName(entity, this.datasourceInfo.getConstraintNameClipLength());
if (this.datasourceInfo.getUsePkConstraintNames()) {
sqlBuf.append("CONSTRAINT ");
sqlBuf.append(pkName);
}
sqlBuf.append(" PRIMARY KEY (");
entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, "");
sqlBuf.append(")");
if (addFks) {
// NOTE: This is kind of a bad idea anyway since ordering table creations is crazy, if not impossible
// go through the relationships to see if any foreign keys need to be added
Iterator<ModelRelation> relationsIter = entity.getRelationsIterator();
while (relationsIter.hasNext()) {
ModelRelation modelRelation = relationsIter.next();
if ("one".equals(modelRelation.getType())) {
ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
if (relModelEntity == null) {
Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), module);
continue;
}
if (relModelEntity instanceof ModelViewEntity) {
Debug.logError("Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(), module);
continue;
}
String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred());
if (UtilValidate.isNotEmpty(fkConstraintClause)) {
sqlBuf.append(", ");
sqlBuf.append(fkConstraintClause);
} else {
continue;
}
}
}
}
sqlBuf.append(")");
// if there is a tableType, add the TYPE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) {
// jaz:20101229 - This appears to be only used by mysql and now mysql has
// deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is
// changed to ENGINE which is supported starting at 4.1
sqlBuf.append(" ENGINE ");
// sqlBuf.append(" TYPE ");
sqlBuf.append(this.datasourceInfo.getTableType());
}
// if there is a characterSet, add the CHARACTER SET arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
sqlBuf.append(" CHARACTER SET ");
sqlBuf.append(this.datasourceInfo.getCharacterSet());
}
// if there is a collate, add the COLLATE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
sqlBuf.append(" COLLATE ");
sqlBuf.append(this.datasourceInfo.getCollate());
}
if (Debug.verboseOn())
Debug.logVerbose("[createTable] sql=" + sqlBuf.toString(), module);
try (Connection connection = getConnection();
Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sqlBuf.toString());
} catch (SQLException e) {
String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString();
Debug.logError(e, errMsg, module);
return errMsg;
} catch (GenericEntityException e) {
String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString();
Debug.logError(e, errMsg, module);
return errMsg;
}
return null;
}
use of org.apache.ofbiz.entity.model.ModelRelation in project ofbiz-framework by apache.
the class DatabaseUtil method createForeignKeys.
public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred, List<String> messages) {
if (entity == null) {
String errMsg = "ModelEntity was null and is required to create foreign keys for a table";
Debug.logError(errMsg, module);
if (messages != null)
messages.add(errMsg);
return 0;
}
if (entity instanceof ModelViewEntity) {
// if (messages != null) messages.add(errMsg);
return 0;
}
int fksCreated = 0;
// go through the relationships to see if any foreign keys need to be added
Iterator<ModelRelation> relationsIter = entity.getRelationsIterator();
while (relationsIter.hasNext()) {
ModelRelation modelRelation = relationsIter.next();
if ("one".equals(modelRelation.getType())) {
ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
if (relModelEntity == null) {
String errMsg = "Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName();
Debug.logError(errMsg, module);
if (messages != null)
messages.add(errMsg);
continue;
}
if (relModelEntity instanceof ModelViewEntity) {
String errMsg = "Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName();
Debug.logError(errMsg, module);
if (messages != null)
messages.add(errMsg);
continue;
}
String retMsg = createForeignKey(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred);
if (UtilValidate.isNotEmpty(retMsg)) {
Debug.logError(retMsg, module);
if (messages != null)
messages.add(retMsg);
continue;
}
fksCreated++;
}
}
if (fksCreated > 0) {
String message = "Created " + fksCreated + " foreign keys for entity [" + entity.getEntityName() + "]";
Debug.logImportant(message, module);
if (messages != null)
messages.add(message);
}
return fksCreated;
}
use of org.apache.ofbiz.entity.model.ModelRelation in project ofbiz-framework by apache.
the class GenericDelegator method getRelated.
/* (non-Javadoc)
* @see org.apache.ofbiz.entity.Delegator#getRelated(java.lang.String, java.util.Map, java.util.List, org.apache.ofbiz.entity.GenericValue, boolean)
*/
@Override
public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, GenericValue value, boolean useCache) throws GenericEntityException {
ModelEntity modelEntity = value.getModelEntity();
ModelRelation relation = modelEntity.getRelation(relationName);
if (relation == null) {
throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value);
}
// put the byAndFields (if not null) into the hash map first,
// they will be overridden by value's fields if over-specified this is important for security and cleanliness
Map<String, Object> fields = new HashMap<>();
if (byAndFields != null) {
fields.putAll(byAndFields);
}
for (ModelKeyMap keyMap : relation.getKeyMaps()) {
fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName()));
}
return this.findByAnd(relation.getRelEntityName(), fields, orderBy, useCache);
}
use of org.apache.ofbiz.entity.model.ModelRelation in project ofbiz-framework by apache.
the class GenericEntity method checkFks.
/**
* Checks to see if all foreign key records exist in the database. Will create a dummy value for
* those missing when specified.
*
* @param insertDummy Create a dummy record using the provided fields
* @return true if all FKs exist (or when all missing are created)
* @throws GenericEntityException
*/
public boolean checkFks(boolean insertDummy) throws GenericEntityException {
ModelEntity model = this.getModelEntity();
Iterator<ModelRelation> relItr = model.getRelationsIterator();
while (relItr.hasNext()) {
ModelRelation relation = relItr.next();
if ("one".equalsIgnoreCase(relation.getType())) {
// see if the related value exists
Map<String, Object> fields = new HashMap<>();
for (ModelKeyMap keyMap : relation.getKeyMaps()) {
fields.put(keyMap.getRelFieldName(), this.get(keyMap.getFieldName()));
}
EntityFieldMap ecl = EntityCondition.makeCondition(fields);
long count = this.getDelegator().findCountByCondition(relation.getRelEntityName(), ecl, null, null);
if (count == 0) {
if (insertDummy) {
// create the new related value (dummy)
GenericValue newValue = this.getDelegator().makeValue(relation.getRelEntityName());
boolean allFieldsSet = true;
for (ModelKeyMap mkm : relation.getKeyMaps()) {
if (this.get(mkm.getFieldName()) != null) {
newValue.set(mkm.getRelFieldName(), this.get(mkm.getFieldName()));
if (Debug.infoOn()) {
Debug.logInfo("Set [" + mkm.getRelFieldName() + "] to - " + this.get(mkm.getFieldName()), module);
}
} else {
allFieldsSet = false;
}
}
if (allFieldsSet) {
if (Debug.infoOn()) {
Debug.logInfo("Creating place holder value : " + newValue, module);
}
// inherit create and update times from this value in order to make this not seem like new/fresh data
newValue.put(ModelEntity.CREATE_STAMP_FIELD, this.get(ModelEntity.CREATE_STAMP_FIELD));
newValue.put(ModelEntity.CREATE_STAMP_TX_FIELD, this.get(ModelEntity.CREATE_STAMP_TX_FIELD));
newValue.put(ModelEntity.STAMP_FIELD, this.get(ModelEntity.STAMP_FIELD));
newValue.put(ModelEntity.STAMP_TX_FIELD, this.get(ModelEntity.STAMP_TX_FIELD));
// set isFromEntitySync so that create/update stamp fields set above will be preserved
newValue.setIsFromEntitySync(true);
// check the FKs for the newly created entity
newValue.checkFks(true);
newValue.create();
}
} else {
return false;
}
}
}
}
return true;
}
Aggregations