use of org.apache.ofbiz.entity.model.ModelFieldType in project ofbiz-framework by apache.
the class DatabaseUtil method updateCharacterSetAndCollation.
/* ====================================================================== */
/* ====================================================================== */
public void updateCharacterSetAndCollation(ModelEntity entity, List<String> messages) {
if (entity instanceof ModelViewEntity) {
return;
}
if (UtilValidate.isEmpty(this.datasourceInfo.getCharacterSet()) && UtilValidate.isEmpty(this.datasourceInfo.getCollate())) {
messages.add("Not setting character-set and collate for entity [" + entity.getEntityName() + "], options not specified in the datasource definition in the entityengine.xml file.");
return;
}
try (Connection connection = getConnectionLogged(messages)) {
if (connection == null) {
return;
}
StringBuilder sqlTableBuf = new StringBuilder("ALTER TABLE ");
sqlTableBuf.append(entity.getTableName(this.datasourceInfo));
// if there is a characterSet, add the CHARACTER SET arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
sqlTableBuf.append(" DEFAULT CHARACTER SET ");
sqlTableBuf.append(this.datasourceInfo.getCharacterSet());
}
// if there is a collate, add the COLLATE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
sqlTableBuf.append(" COLLATE ");
sqlTableBuf.append(this.datasourceInfo.getCollate());
}
if (Debug.verboseOn())
Debug.logVerbose("[updateCharacterSetAndCollation] character-set and collate sql=" + sqlTableBuf, module);
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sqlTableBuf.toString());
} catch (SQLException e) {
String errMsg = "SQL Exception while executing the following:\n" + sqlTableBuf + "\nError was: " + e.toString();
messages.add(errMsg);
Debug.logError(errMsg, module);
}
Iterator<ModelField> fieldIter = entity.getFieldsIterator();
while (fieldIter.hasNext()) {
ModelField field = fieldIter.next();
ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType());
if (type == null) {
messages.add("Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table.");
continue;
}
if (!"String".equals(type.getJavaType()) && !"java.lang.String".equals(type.getJavaType())) {
continue;
}
StringBuilder sqlBuf = new StringBuilder("ALTER TABLE ");
sqlBuf.append(entity.getTableName(this.datasourceInfo));
sqlBuf.append(" MODIFY COLUMN ");
sqlBuf.append(field.getColName());
sqlBuf.append(" ");
sqlBuf.append(type.getSqlType());
// 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.getIsPk() || field.getIsNotNull()) {
if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) {
sqlBuf.append(" CONSTRAINT NOT NULL");
} else {
sqlBuf.append(" NOT NULL");
}
}
if (Debug.verboseOn())
Debug.logVerbose("[updateCharacterSetAndCollation] character-set and collate sql=" + sqlBuf, module);
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sqlBuf.toString());
} catch (SQLException e) {
String errMsg = "SQL Exception while executing the following:\n" + sqlBuf + "\nError was: " + e.toString();
messages.add(errMsg);
Debug.logError(errMsg, module);
}
}
} catch (SQLException e) {
Debug.logError(e, module);
}
}
use of org.apache.ofbiz.entity.model.ModelFieldType in project ofbiz-framework by apache.
the class SqlJdbcUtil method getValue.
public static void getValue(ResultSet rs, int ind, ModelField curField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
ModelFieldType mft = modelFieldTypeReader.getModelFieldType(curField.getType());
if (mft == null) {
throw new GenericModelException("definition fieldType " + curField.getType() + " not found, cannot getValue for field " + entity.getEntityName() + "." + curField.getName() + ".");
}
ModelEntity model = entity.getModelEntity();
String encryptionKeyName = entity.getEntityName();
if (curField.getEncryptMethod().isEncrypted() && model instanceof ModelViewEntity) {
ModelViewEntity modelView = (ModelViewEntity) model;
encryptionKeyName = modelView.getAliasedEntity(modelView.getAlias(curField.getName()).getEntityAlias(), entity.getDelegator().getModelReader()).getEntityName();
}
// ----- Try out the new handler code -----
JdbcValueHandler<?> handler = mft.getJdbcValueHandler();
if (handler != null) {
try {
Object jdbcValue = handler.getValue(rs, ind);
if (jdbcValue instanceof String && curField.getEncryptMethod().isEncrypted()) {
jdbcValue = entity.getDelegator().decryptFieldValue(encryptionKeyName, curField.getEncryptMethod(), (String) jdbcValue);
}
entity.dangerousSetNoCheckButFast(curField, jdbcValue);
return;
} catch (Exception e) {
Debug.logError(e, module);
}
} else {
Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + ", falling back on switch statement. Entity = " + curField.getModelEntity().getEntityName() + ", field = " + curField.getName() + ".", module);
}
// ------------------------------------------
String fieldType = mft.getJavaType();
try {
// checking to see if the object is null is really only necessary for the numbers
int typeValue = getType(fieldType);
ResultSetMetaData rsmd = rs.getMetaData();
int colType = rsmd.getColumnType(ind);
if (typeValue <= 4 || typeValue >= 11) {
switch(typeValue) {
case 1:
if (java.sql.Types.CLOB == colType) {
// Debug.logInfo("For field " + curField.getName() + " of entity " + entity.getEntityName() + " getString is a CLOB, trying getCharacterStream", module);
// if the String is empty, try to get a text input stream, this is required for some databases for larger fields, like CLOBs
Clob valueClob = rs.getClob(ind);
Reader valueReader = null;
if (valueClob != null) {
valueReader = valueClob.getCharacterStream();
}
// Reader valueReader = rs.getCharacterStream(ind);
if (valueReader != null) {
char[] inCharBuffer = new char[CHAR_BUFFER_SIZE];
StringBuilder strBuf = new StringBuilder();
int charsRead = 0;
try {
while ((charsRead = valueReader.read(inCharBuffer, 0, CHAR_BUFFER_SIZE)) > 0) {
strBuf.append(inCharBuffer, 0, charsRead);
}
valueReader.close();
} catch (IOException e) {
throw new GenericEntityException("Error reading long character stream for field " + curField.getName() + " of entity " + entity.getEntityName(), e);
}
entity.dangerousSetNoCheckButFast(curField, strBuf.toString());
} else {
entity.dangerousSetNoCheckButFast(curField, null);
}
} else {
String value = rs.getString(ind);
if (curField.getEncryptMethod().isEncrypted()) {
value = (String) entity.getDelegator().decryptFieldValue(encryptionKeyName, curField.getEncryptMethod(), value);
}
entity.dangerousSetNoCheckButFast(curField, value);
}
break;
case 2:
entity.dangerousSetNoCheckButFast(curField, rs.getTimestamp(ind));
break;
case 3:
entity.dangerousSetNoCheckButFast(curField, rs.getTime(ind));
break;
case 4:
entity.dangerousSetNoCheckButFast(curField, rs.getDate(ind));
break;
case 11:
Object obj = null;
byte[] originalBytes = rs.getBytes(ind);
obj = deserializeField(originalBytes, ind, curField);
if (obj != null) {
entity.dangerousSetNoCheckButFast(curField, obj);
} else {
entity.dangerousSetNoCheckButFast(curField, originalBytes);
}
break;
case 12:
Object originalObject;
byte[] fieldBytes;
try {
Blob theBlob = rs.getBlob(ind);
fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null;
originalObject = theBlob;
} catch (SQLException e) {
// for backward compatibility if getBlob didn't work try getBytes
fieldBytes = rs.getBytes(ind);
originalObject = fieldBytes;
}
if (originalObject != null) {
// for backward compatibility, check to see if there is a serialized object and if so return that
Object blobObject = deserializeField(fieldBytes, ind, curField);
if (blobObject != null) {
entity.dangerousSetNoCheckButFast(curField, blobObject);
} else {
if (originalObject instanceof Blob) {
// NOTE using SerialBlob here instead of the Blob from the database to make sure we can pass it around, serialize it, etc
entity.dangerousSetNoCheckButFast(curField, new SerialBlob((Blob) originalObject));
} else {
entity.dangerousSetNoCheckButFast(curField, originalObject);
}
}
}
break;
case 13:
entity.dangerousSetNoCheckButFast(curField, new SerialClob(rs.getClob(ind)));
break;
case 14:
case 15:
entity.dangerousSetNoCheckButFast(curField, rs.getObject(ind));
break;
}
} else {
switch(typeValue) {
case 5:
int intValue = rs.getInt(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Integer.valueOf(intValue));
}
break;
case 6:
long longValue = rs.getLong(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Long.valueOf(longValue));
}
break;
case 7:
float floatValue = rs.getFloat(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Float.valueOf(floatValue));
}
break;
case 8:
double doubleValue = rs.getDouble(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Double.valueOf(doubleValue));
}
break;
case 9:
BigDecimal bigDecimalValue = rs.getBigDecimal(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, bigDecimalValue);
}
break;
case 10:
boolean booleanValue = rs.getBoolean(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Boolean.valueOf(booleanValue));
}
break;
}
}
} catch (SQLException sqle) {
throw new GenericDataSourceException("SQL Exception while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + ")", sqle);
}
}
use of org.apache.ofbiz.entity.model.ModelFieldType 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.ModelFieldType in project ofbiz-framework by apache.
the class DatabaseUtil method renameColumn.
public String renameColumn(ModelEntity entity, ModelField field, String newName) {
if (entity == null || field == null)
return "ModelEntity or ModelField where null, cannot rename column";
if (entity instanceof ModelViewEntity) {
return "ERROR: Cannot rename column for a view entity";
}
ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType());
if (type == null) {
return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not renaming column.";
}
StringBuilder sqlBuf = new StringBuilder("ALTER TABLE ");
sqlBuf.append(entity.getTableName(datasourceInfo));
sqlBuf.append(" RENAME ");
sqlBuf.append(field.getColName());
sqlBuf.append(" TO ");
sqlBuf.append(newName);
String sql = sqlBuf.toString();
if (Debug.infoOn())
Debug.logInfo("[renameColumn] sql=" + sql, module);
try (Connection connection = getConnection();
Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sql);
} catch (SQLException e) {
String errMsg = "SQL Exception while executing the following:\n" + sql + "\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.ModelFieldType 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;
}
Aggregations