use of org.apache.ofbiz.entity.GenericDataSourceException in project ofbiz-framework by apache.
the class GenericDAO method selectCountByCondition.
public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, List<ModelField> selectFields, EntityFindOptions findOptions) throws GenericEntityException {
if (modelEntity == null) {
return 0;
}
// if no find options passed, use default
if (findOptions == null) {
findOptions = new EntityFindOptions();
}
boolean verboseOn = Debug.verboseOn();
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Doing selectListIteratorByCondition with whereEntityCondition: " + whereEntityCondition, module);
}
boolean isGroupBy = false;
ModelViewEntity modelViewEntity = null;
if (modelEntity instanceof ModelViewEntity) {
modelViewEntity = (ModelViewEntity) modelEntity;
isGroupBy = modelViewEntity.getGroupBysSize() > 0;
}
// To get a count of the rows that will be returned when there is a GROUP BY, must do something like:
// SELECT COUNT(1) FROM (SELECT COUNT(1) FROM OFBIZ.POSTAL_ADDRESS PA GROUP BY PA.CITY) TEMP_NAME
// instead of a simple:
// SELECT COUNT(1) FROM OFBIZ.POSTAL_ADDRESS PA GROUP BY PA.CITY
StringBuilder sqlBuffer = new StringBuilder("SELECT ");
if (isGroupBy) {
sqlBuffer.append("COUNT(1) FROM (SELECT ");
}
if (findOptions.getDistinct()) {
/* DEJ20100304: the code below was causing problems so the line above may be used instead, but hopefully this is fixed now
* may need varying SQL for different databases, and also in view-entities in some cases it seems to
* cause the "COUNT(DISTINCT " to appear twice, causing an attempt to try to count a count (function="count-distinct", distinct=true in find options)
*/
if (selectFields != null && selectFields.size() > 0) {
ModelField firstSelectField = selectFields.get(0);
ModelViewEntity.ModelAlias firstModelAlias = modelViewEntity != null ? modelViewEntity.getAlias(firstSelectField.getName()) : null;
if (firstModelAlias != null && UtilValidate.isNotEmpty(firstModelAlias.getFunction())) {
// if the field has a function already we don't want to count just it, would be meaningless
sqlBuffer.append("COUNT(DISTINCT *) ");
} else {
sqlBuffer.append("COUNT(DISTINCT ");
// this only seems to support a single column, which is not desirable but seems a lot better than no columns or in certain cases all columns
sqlBuffer.append(firstSelectField.getColValue());
// sqlBuffer.append(modelEntity.colNameString(selectFields, ", ", "", datasource.aliasViews));
sqlBuffer.append(")");
}
} else {
sqlBuffer.append("COUNT(DISTINCT *) ");
}
} else {
// NOTE DEJ20080701 Changed from COUNT(*) to COUNT(1) to improve performance, and should get the same results at least when there is no DISTINCT
sqlBuffer.append("COUNT(1) ");
}
// populate the info from entity-condition in the view-entity, if it is one and there is one
List<EntityCondition> viewWhereConditions = null;
List<EntityCondition> viewHavingConditions = null;
List<String> viewOrderByList = null;
if (modelViewEntity != null) {
viewWhereConditions = new LinkedList<EntityCondition>();
viewHavingConditions = new LinkedList<EntityCondition>();
viewOrderByList = new LinkedList<String>();
modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList, null);
}
// FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
// WHERE clause
List<EntityConditionParam> whereEntityConditionParams = new LinkedList<EntityConditionParam>();
makeConditionWhereString(sqlBuffer, " WHERE ", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams);
// GROUP BY clause for view-entity
if (isGroupBy) {
modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(), sqlBuffer, " GROUP BY ", ", ", "", false);
}
// HAVING clause
List<EntityConditionParam> havingEntityConditionParams = new LinkedList<EntityConditionParam>();
makeConditionHavingString(sqlBuffer, " HAVING ", modelEntity, havingEntityCondition, viewHavingConditions, havingEntityConditionParams);
if (isGroupBy) {
sqlBuffer.append(") TEMP_NAME");
}
String sql = sqlBuffer.toString();
if (Debug.verboseOn())
Debug.logVerbose("Count select sql: " + sql, module);
try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) {
sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows());
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, module);
}
// set all of the values from the Where EntityCondition
for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, module);
}
// set all of the values from the Having EntityCondition
for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
try {
sqlP.executeQuery();
long count = 0;
ResultSet resultSet = sqlP.getResultSet();
if (resultSet.next()) {
count = resultSet.getLong(1);
}
return count;
} catch (SQLException e) {
throw new GenericDataSourceException("Error getting count value", e);
}
}
}
use of org.apache.ofbiz.entity.GenericDataSourceException 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.GenericDataSourceException in project ofbiz-framework by apache.
the class SQLProcessor method getConnection.
/**
* Get a connection from the TransactionFactoryLoader
*
* @return The connection created
*
* @throws GenericDataSourceException
* @throws GenericEntityException
*/
public Connection getConnection() throws GenericDataSourceException, GenericEntityException {
if (_connection != null)
return _connection;
_manualTX = true;
try {
_connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo);
if (Debug.verboseOn())
Debug.logVerbose("SQLProcessor:connection() : manualTx=" + _manualTX, module);
} catch (SQLException sqle) {
throw new GenericDataSourceException("Unable to establish a connection with the database.", sqle);
}
// make sure we actually did get a connection
if (_connection == null) {
throw new GenericDataSourceException("Unable to establish a connection with the database. Connection was null!");
}
// test the connection
testConnection(_connection);
// always try to set auto commit to false, but if we can't then later on we won't commit
try {
if (_connection.getAutoCommit()) {
try {
_connection.setAutoCommit(false);
if (Debug.verboseOn())
Debug.logVerbose("SQLProcessor:setAutoCommit(false) : manualTx=" + _manualTX, module);
} catch (SQLException sqle) {
_manualTX = false;
}
}
} catch (SQLException e) {
throw new GenericDataSourceException("Cannot get autoCommit status from connection", e);
}
try {
if (TransactionUtil.getStatus() == TransactionUtil.STATUS_ACTIVE) {
if (Debug.verboseOn())
Debug.logVerbose("[SQLProcessor.getConnection] : active transaction", module);
_manualTX = false;
}
} catch (GenericTransactionException e) {
// nevermind, don't worry about it, but print the exc anyway
Debug.logWarning("[SQLProcessor.getConnection]: Exception was thrown trying to check " + "transaction status: " + e.toString(), module);
}
if (Debug.verboseOn())
Debug.logVerbose("[SQLProcessor.getConnection] : con=" + _connection, module);
_bDeleteConnection = true;
return _connection;
}
use of org.apache.ofbiz.entity.GenericDataSourceException 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.GenericDataSourceException in project ofbiz-framework by apache.
the class SQLProcessor method prepareStatement.
/**
* Prepare a statement. In case no connection has been given, allocate a
* new one.
*
* @param sql The SQL statement to be executed
*
* @throws GenericDataSourceException
* @throws GenericEntityException
*/
public void prepareStatement(String sql, boolean specifyTypeAndConcur, int resultSetType, int resultSetConcurrency, int fetchSize, int maxRows) throws GenericDataSourceException, GenericEntityException {
if (Debug.verboseOn())
Debug.logVerbose("[SQLProcessor.prepareStatement] sql=" + sql, module);
if (_connection == null) {
getConnection();
}
try {
_sql = sql;
_ind = 1;
if (specifyTypeAndConcur) {
_ps = _connection.prepareStatement(sql, resultSetType, resultSetConcurrency);
if (Debug.verboseOn())
Debug.logVerbose("[SQLProcessor.prepareStatement] _ps=" + _ps, module);
} else {
_ps = _connection.prepareStatement(sql);
if (Debug.verboseOn())
Debug.logVerbose("[SQLProcessor.prepareStatement] (def) _ps=" + _ps, module);
}
if (maxRows > 0) {
_ps.setMaxRows(maxRows);
if (Debug.verboseOn())
Debug.logVerbose("[SQLProcessor.prepareStatement] max rows set : " + maxRows, module);
}
this.setFetchSize(_ps, fetchSize);
} catch (SQLException sqle) {
throw new GenericDataSourceException("SQL Exception while executing the following:" + sql, sqle);
}
}
Aggregations