use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class SqlJdbcUtil method makeViewTable.
public static String makeViewTable(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) throws GenericEntityException {
if (modelEntity instanceof ModelViewEntity) {
StringBuilder sql = new StringBuilder("(SELECT ");
Iterator<ModelField> fieldsIter = modelEntity.getFieldsIterator();
if (fieldsIter.hasNext()) {
ModelField curField = fieldsIter.next();
sql.append(curField.getColValue());
sql.append(" AS ");
sql.append(curField.getColName());
while (fieldsIter.hasNext()) {
curField = fieldsIter.next();
sql.append(", ");
sql.append(curField.getColValue());
sql.append(" AS ");
sql.append(curField.getColName());
}
}
sql.append(makeFromClause(modelEntity, modelFieldTypeReader, datasourceInfo));
String viewWhereClause = makeViewWhereClause(modelEntity, datasourceInfo.getJoinStyle());
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
List<EntityCondition> whereConditions = new LinkedList<EntityCondition>();
List<EntityCondition> havingConditions = new LinkedList<EntityCondition>();
List<String> orderByList = new LinkedList<String>();
modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, whereConditions, havingConditions, orderByList, null);
String viewConditionClause;
if (!whereConditions.isEmpty()) {
viewConditionClause = EntityCondition.makeCondition(whereConditions, EntityOperator.AND).makeWhereString(modelViewEntity, null, datasourceInfo);
} else {
viewConditionClause = null;
}
if (UtilValidate.isNotEmpty(viewWhereClause) || UtilValidate.isNotEmpty(viewConditionClause)) {
sql.append(" WHERE ");
if (UtilValidate.isNotEmpty(viewWhereClause)) {
sql.append("(").append(viewWhereClause).append(")");
if (UtilValidate.isNotEmpty(viewConditionClause)) {
sql.append(" AND ");
}
}
if (UtilValidate.isNotEmpty(viewConditionClause)) {
sql.append("(").append(viewConditionClause).append(")");
}
}
// FIXME: handling HAVING, don't need ORDER BY for nested views
modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(), sql, " GROUP BY ", ", ", "", false);
sql.append(")");
return sql.toString();
} else {
return modelEntity.getTableName(datasourceInfo);
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class SqlJdbcUtil method setValue.
public static <T> void setValue(SQLProcessor sqlP, ModelField modelField, String entityName, Object fieldValue, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
ModelFieldType mft = modelFieldTypeReader.getModelFieldType(modelField.getType());
if (mft == null) {
throw new GenericModelException("GenericDAO.getValue: definition fieldType " + modelField.getType() + " not found, cannot setValue for field " + entityName + "." + modelField.getName() + ".");
}
// if the value is the GenericEntity.NullField, treat as null
if (fieldValue == GenericEntity.NULL_FIELD) {
fieldValue = null;
}
// ----- Try out the new handler code -----
ModelField.EncryptMethod encryptMethod = modelField.getEncryptMethod();
if (encryptMethod.isEncrypted()) {
fieldValue = sqlP.getDelegator().encryptFieldValue(entityName, encryptMethod, fieldValue);
}
JdbcValueHandler<T> handler = UtilGenerics.cast(mft.getJdbcValueHandler());
if (handler != null) {
try {
sqlP.setValue(handler, handler.getJavaClass().cast(fieldValue));
return;
} catch (SQLException e) {
throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", e);
}
} else {
Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + ", falling back on switch statement. Entity = " + modelField.getModelEntity().getEntityName() + ", field = " + modelField.getName() + ".", module);
}
// ------------------------------------------
String fieldType = mft.getJavaType();
if (fieldValue != null) {
if (!ObjectType.instanceOf(fieldValue, fieldType)) {
// this is only an info level message because under normal operation for most JDBC
// drivers this will be okay, but if not then the JDBC driver will throw an exception
// and when lower debug levels are on this should help give more info on what happened
String fieldClassName = fieldValue.getClass().getName();
if (fieldValue instanceof byte[]) {
fieldClassName = "byte[]";
}
if (Debug.verboseOn())
Debug.logVerbose("type of field " + entityName + "." + modelField.getName() + " is " + fieldClassName + ", was expecting " + mft.getJavaType() + "; this may " + "indicate an error in the configuration or in the class, and may result " + "in an SQL-Java data conversion error. Will use the real field type: " + fieldClassName + ", not the definition.", module);
fieldType = fieldClassName;
}
}
try {
int typeValue = getType(fieldType);
switch(typeValue) {
case 1:
sqlP.setValue((String) fieldValue);
break;
case 2:
sqlP.setValue((java.sql.Timestamp) fieldValue);
break;
case 3:
sqlP.setValue((java.sql.Time) fieldValue);
break;
case 4:
sqlP.setValue((java.sql.Date) fieldValue);
break;
case 5:
sqlP.setValue((java.lang.Integer) fieldValue);
break;
case 6:
sqlP.setValue((java.lang.Long) fieldValue);
break;
case 7:
sqlP.setValue((java.lang.Float) fieldValue);
break;
case 8:
sqlP.setValue((java.lang.Double) fieldValue);
break;
case 9:
sqlP.setValue((java.math.BigDecimal) fieldValue);
break;
case 10:
sqlP.setValue((java.lang.Boolean) fieldValue);
break;
case 11:
sqlP.setBinaryStream(fieldValue);
break;
case 12:
if (fieldValue instanceof byte[]) {
sqlP.setBytes((byte[]) fieldValue);
} else if (fieldValue instanceof ByteBuffer) {
sqlP.setBytes(((ByteBuffer) fieldValue).array());
} else {
sqlP.setValue((java.sql.Blob) fieldValue);
}
break;
case 13:
sqlP.setValue((java.sql.Clob) fieldValue);
break;
case 14:
if (fieldValue != null) {
sqlP.setValue(new java.sql.Date(((java.util.Date) fieldValue).getTime()));
} else {
sqlP.setValue((java.sql.Date) null);
}
break;
case 15:
sqlP.setValue(UtilGenerics.<Collection<?>>cast(fieldValue));
break;
}
} catch (GenericNotImplementedException e) {
throw new GenericNotImplementedException("Not Implemented Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": " + e.toString(), e);
} catch (SQLException sqle) {
throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", sqle);
}
}
use of org.apache.ofbiz.entity.model.ModelField 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.ModelField in project ofbiz-framework by apache.
the class DatabaseUtil method makeIndexClause.
public String makeIndexClause(ModelEntity entity, ModelIndex modelIndex) {
StringBuilder mainCols = new StringBuilder();
for (ModelIndex.Field field : modelIndex.getFields()) {
ModelIndex.Function function = field.getFunction();
if (mainCols.length() > 0) {
mainCols.append(", ");
}
if (function != null) {
mainCols.append(function.toString()).append('(');
}
ModelField mainField = entity.getField(field.getFieldName());
mainCols.append(mainField.getColName());
if (function != null) {
mainCols.append(')');
}
}
StringBuilder indexSqlBuf = new StringBuilder("CREATE ");
if (datasourceInfo.getUseIndicesUnique() && modelIndex.getUnique()) {
indexSqlBuf.append("UNIQUE ");
}
indexSqlBuf.append("INDEX ");
indexSqlBuf.append(makeIndexName(modelIndex, datasourceInfo.getConstraintNameClipLength()));
indexSqlBuf.append(" ON ");
indexSqlBuf.append(entity.getTableName(datasourceInfo));
indexSqlBuf.append(" (");
indexSqlBuf.append(mainCols.toString());
indexSqlBuf.append(")");
return indexSqlBuf.toString();
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class DatabaseUtil method makeFkConstraintClause.
public String makeFkConstraintClause(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) {
// make the two column lists
StringBuilder mainCols = new StringBuilder();
StringBuilder relCols = new StringBuilder();
for (ModelKeyMap keyMap : modelRelation.getKeyMaps()) {
ModelField mainField = entity.getField(keyMap.getFieldName());
if (mainField == null) {
Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", module);
return null;
}
if (mainCols.length() > 0) {
mainCols.append(", ");
}
mainCols.append(mainField.getColName());
ModelField relField = relModelEntity.getField(keyMap.getRelFieldName());
if (relField == null) {
Debug.logError("The field '" + keyMap.getRelFieldName() + "' was not found at related entity - check relations at entity '" + entity.getEntityName() + "'!", module);
}
if (relCols.length() > 0) {
relCols.append(", ");
}
relCols.append(relField.getColName());
}
StringBuilder sqlBuf = new StringBuilder("");
if ("name_constraint".equals(fkStyle)) {
sqlBuf.append("CONSTRAINT ");
String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength);
sqlBuf.append(relConstraintName);
sqlBuf.append(" FOREIGN KEY (");
sqlBuf.append(mainCols.toString());
sqlBuf.append(") REFERENCES ");
sqlBuf.append(relModelEntity.getTableName(datasourceInfo));
sqlBuf.append(" (");
sqlBuf.append(relCols.toString());
sqlBuf.append(")");
if (useFkInitiallyDeferred) {
sqlBuf.append(" INITIALLY DEFERRED");
}
} else if ("name_fk".equals(fkStyle)) {
sqlBuf.append(" FOREIGN KEY ");
String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength);
sqlBuf.append(relConstraintName);
sqlBuf.append(" (");
sqlBuf.append(mainCols.toString());
sqlBuf.append(") REFERENCES ");
sqlBuf.append(relModelEntity.getTableName(datasourceInfo));
sqlBuf.append(" (");
sqlBuf.append(relCols.toString());
sqlBuf.append(")");
if (useFkInitiallyDeferred) {
sqlBuf.append(" INITIALLY DEFERRED");
}
} else {
String emsg = "ERROR: fk-style specified for this data-source is not valid: " + fkStyle;
Debug.logError(emsg, module);
throw new IllegalArgumentException(emsg);
}
return sqlBuf.toString();
}
Aggregations