+ if (entityClass.equals(StorableObjectEntity.class)) {
+ uniqueId += ("@" + mainTable);
+ }
+
+ StoreIdentifier search_sid = new StoreIdentifier(entityClass, uniqueId);
+ logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
+
+ Entity hit = (Entity) o_store.use(search_sid);
+
+ if (hit != null) {
+ return hit;
+ }
+ }
+
+ Connection con = obtainConnection();
+ Entity returnEntity = null;
+ PreparedStatement statement = null;
+
+ try {
+ ResultSet rs;
+ String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?";
+
+ statement = con.prepareStatement(query);
+ statement.setString(1, anId);
+
+ logQueryBefore(query);
+
+ long startTime = System.currentTimeMillis();
+ try {
+ rs = statement.executeQuery();
+
+ logQueryAfter(query, (System.currentTimeMillis() - startTime));
+ }
+ catch (SQLException e) {
+ logQueryError(query, (System.currentTimeMillis() - startTime), e);
+ throw e;
+ }
+
+ if (rs != null) {
+ if (rs.next()) {
+ returnEntity = makeEntityFromResultSet(rs);
+ }
+ else {
+ logger.warn("No data for id: " + anId + " in table " + mainTable);
+ }
+
+ rs.close();
+ }
+ else {
+ logger.warn("No Data for Id " + anId + " in Table " + mainTable);
+ }
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ finally {
+ freeConnection(con, statement);
+ }
+
+ return returnEntity;
+ }
+
+ public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, List extraTables, String aWhereClause) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, DEFAULT_LIMIT);
+ }
+
+ public EntityList selectByFieldValue(String aField, String aValue) throws DatabaseExc, DatabaseFailure {
+ return selectByFieldValue(aField, aValue, 0);
+ }
+
+ public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset);
+ }
+
+ public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(where, 0);
+ }
+
+ public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(whereClause, null, offset);
+ }
+
+ public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, DEFAULT_LIMIT);
+ }
+
+ public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT);
+ }
+
+ public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
+ int offset, int limit) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
+ }
+
+ public EntityList selectByWhereClause(
+ String aMainTablePrefix, List anExtraTables,
+ String aWhereClause, String anOrderByClause,
+ int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure {
+
+ if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){
+ anExtraTables=null;
+ }
+
+ // check o_store for entitylist
+ // only if no relational select
+ if (anExtraTables==null) {
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ StoreIdentifier searchSid = new StoreIdentifier(entityClass,
+ StoreContainerType.STOC_TYPE_ENTITYLIST,
+ StoreUtil.getEntityListUniqueIdentifierFor(mainTable,
+ aWhereClause, anOrderByClause, anOffset, aLimit));
+ EntityList hit = (EntityList) o_store.use(searchSid);
+
+ if (hit != null) {
+ return hit;
+ }
+ }
+ }
+
+ RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
+
+ EntityList result = null;
+ Connection connection = null;
+
+ if (anExtraTables!=null) {
+ Iterator i = anExtraTables.iterator();
+ while (i.hasNext()) {
+ String table = (String) i.next();
+ if (!"".equals(table)) {
+ retriever.addExtraTable(table);
+ }
+ }
+ }
+
+ if (aWhereClause != null) {
+ retriever.appendWhereClause(aWhereClause);
+ }
+
+ if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
+ retriever.appendOrderByClause(anOrderByClause);
+ }
+
+ if (anOffset>-1 && aLimit>-1) {
+ retriever.setLimit(aLimit+1);
+ retriever.setOffset(anOffset);
+ }
+
+ Iterator i = getFieldNames().iterator();
+ while (i.hasNext()) {
+ retriever.addField((String) i.next());
+ }
+
+ // execute sql
+ try {
+ connection = obtainConnection();
+ ResultSet resultSet = retriever.execute(connection);
+
+ boolean hasMore = false;
+
+ if (resultSet != null) {
+ result = new EntityList();
+ Entity entity;
+ int position = 0;
+
+ while (((aLimit == -1) || (position<aLimit)) && resultSet.next()) {
+ entity = makeEntityFromResultSet(resultSet);
+ result.add(entity);
+ position++;
+ }
+
+ hasMore = resultSet.next();
+ resultSet.close();
+ }
+
+ if (result != null) {
+ result.setOffset(anOffset);
+ result.setWhere(aWhereClause);
+ result.setOrder(anOrderByClause);
+ result.setStorage(this);
+ result.setLimit(aLimit);
+
+ if (hasMore) {
+ result.setNextBatch(anOffset + aLimit);
+ }
+
+ if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
+ StoreIdentifier sid = result.getStoreIdentifier();
+ logger.debug("CACHE (add): " + sid.toString());
+ o_store.add(sid);
+ }
+ }
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ finally {
+ try {
+ if (connection != null) {
+ freeConnection(connection);
+ }
+ } catch (Throwable t) {
+ }
+ }
+
+ return result;
+ }
+
+ private Entity makeEntityFromResultSet(ResultSet rs) {
+ Map fields = new HashMap();
+ String theResult = null;
+ int type;
+ Entity returnEntity = null;
+
+ try {
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ StoreIdentifier searchSid = StorableObjectEntity.getStoreIdentifier(this,
+ entityClass, rs);
+ Entity hit = (Entity) o_store.use(searchSid);
+ if (hit != null) return hit;
+ }
+
+ for (int i = 0; i < getFieldNames().size(); i++) {
+ type = fieldTypes[i];
+
+ if (type == java.sql.Types.LONGVARBINARY) {
+ InputStreamReader is =
+ (InputStreamReader) rs.getCharacterStream(i + 1);
+
+ if (is != null) {
+ char[] data = new char[32768];
+ StringBuffer theResultString = new StringBuffer();
+ int len;
+
+ while ((len = is.read(data)) > 0) {
+ theResultString.append(data, 0, len);
+ }
+
+ is.close();
+ theResult = theResultString.toString();
+ }
+ else {
+ theResult = null;
+ }
+ }
+ else {
+ theResult = getValueAsString(rs, (i + 1), type);
+ }
+
+ if (theResult != null) {
+ fields.put(getFieldNames().get(i), theResult);
+ }
+ }
+
+ if (entityClass != null) {
+ returnEntity = createNewEntity();
+ returnEntity.setFieldValues(fields);
+
+ if (returnEntity instanceof StorableObject) {
+ logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + mainTable);
+ o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
+ }
+ }
+ else {
+ throw new DatabaseExc("Internal Error: entityClass not set!");
+ }
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+
+ return returnEntity;
+ }
+
+ /**
+ * Inserts an entity into the database.
+ *
+ * @param anEntity
+ * @return the value of the primary key of the inserted record
+ */
+ public String insert(Entity anEntity) throws DatabaseFailure {
+ invalidateStore();
+
+ RecordInserter inserter =
+ new RecordInserter(mainTable, getPrimaryKeySequence());
+
+ String returnId = null;
+ Connection con = null;
+
+ try {
+ String fieldName;
+
+ // make sql-string
+ for (int i = 0; i < getFieldNames().size(); i++) {
+ fieldName = (String) getFieldNames().get(i);
+
+ if (!fieldName.equals(primaryKeyField)) {
+ // exceptions
+ if (!anEntity.hasFieldValue(fieldName) && (
+ fieldName.equals("webdb_create") ||
+ fieldName.equals("webdb_lastchange"))) {
+ inserter.assignVerbatim(fieldName, "now()");
+ }
+ else {
+ if (anEntity.hasFieldValue(fieldName)) {
+ inserter.assignString(fieldName, anEntity.getFieldValue(fieldName));
+ }
+ }
+ }
+ }
+
+ con = obtainConnection();
+ returnId = inserter.execute(con);
+
+ anEntity.setId(returnId);
+ }
+ finally {
+ freeConnection(con);
+ }
+
+ return returnId;
+ }
+
+ /**
+ * Updates an entity in the database
+ *
+ * @param theEntity
+ */
+ public void update(Entity theEntity) throws DatabaseFailure {
+ invalidateStore();
+
+ RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
+
+ // build sql statement
+ for (int i = 0; i < getFieldNames().size(); i++) {
+ String field = (String) getFieldNames().get(i);
+
+ if (!(field.equals(primaryKeyField) ||
+ "webdb_create".equals(field) ||
+ "webdb_lastchange".equals(field) ||
+ binaryFields.contains(field))) {
+
+ if (theEntity.hasFieldValue(field)) {
+ generator.assignString(field, theEntity.getFieldValue(field));
+ }
+ }
+ }
+
+ // exceptions
+ if (hasField("webdb_lastchange")) {
+ generator.assignVerbatim("webdb_lastchange", "now()");
+ }
+
+ // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
+ // format so anything extra will be ignored. -mh
+ if (hasField("webdb_create") &&
+ theEntity.hasFieldValue("webdb_create")) {
+ // minimum of 10 (yyyy-mm-dd)...
+ if (theEntity.getFieldValue("webdb_create").length() >= 10) {
+ String dateString = theEntity.getFieldValue("webdb_create");
+
+ // if only 10, then add 00:00 so it doesn't throw a ParseException
+ if (dateString.length() == 10) {
+ dateString = dateString + " 00:00";
+ }
+
+ // TimeStamp stuff
+ try {
+ java.util.Date d = userInputDateFormat.parse(dateString);
+ generator.assignDateTime("webdb_create", d);
+ }
+ catch (ParseException e) {
+ throw new DatabaseFailure(e);
+ }
+ }
+ }
+ Connection connection = null;
+
+ try {
+ connection = obtainConnection();
+ generator.execute(connection);
+ }
+ finally {
+ freeConnection(connection);
+ }
+ }
+
+ private void invalidateObject(String anId) {
+ // ostore send notification
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ String uniqueId = anId;
+
+ if (entityClass.equals(StorableObjectEntity.class)) {
+ uniqueId += ("@" + mainTable);
+ }
+
+ logger.debug("CACHE: (del) " + anId);
+
+ StoreIdentifier search_sid =
+ new StoreIdentifier(entityClass,
+ StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
+ o_store.invalidate(search_sid);
+ }
+ }
+
+ /*
+ * delete-Operator
+ * @param id des zu loeschenden Datensatzes
+ * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
+ */
+ public boolean delete(String id) throws DatabaseFailure {
+ invalidateObject(id);
+
+ int resultCode = 0;
+ Connection connection = obtainConnection();
+ PreparedStatement statement = null;
+
+ try {
+ statement = connection.prepareStatement("delete from " + mainTable + " where " + primaryKeyField + "=?");
+ statement.setInt(1, Integer.parseInt(id));
+ logQueryBefore("delete from " + mainTable + " where " + primaryKeyField + "=" + id + "");
+ resultCode = statement.executeUpdate();
+ }
+ catch (SQLException e) {
+ logger.warn("Can't delete record", e);
+ }
+ finally {
+ freeConnection(connection, statement);
+ }
+
+ invalidateStore();
+
+ return (resultCode > 0) ? true : false;
+ }
+
+ /**
+ * Deletes entities based on a where clause
+ */
+ public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure {
+ invalidateStore();
+
+ Statement stmt = null;
+ Connection con = null;
+ int res = 0;
+ String sql =
+ "delete from " + mainTable + " where " + aWhereClause;
+
+ //theLog.printInfo("DELETE " + sql);
+ try {
+ con = obtainConnection();
+ stmt = con.createStatement();
+ res = stmt.executeUpdate(sql);
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ finally {
+ freeConnection(con, stmt);
+ }
+
+ return res;
+ }
+
+ /* noch nicht implementiert.
+ * @return immer false
+ */
+ public boolean delete(EntityList theEntityList) {
+ return false;
+ }
+
+ public ResultSet executeSql(Statement stmt, String sql)
+ throws DatabaseFailure, SQLException {
+ ResultSet rs;
+ logQueryBefore(sql);
+ long startTime = System.currentTimeMillis();
+ try {
+ rs = stmt.executeQuery(sql);
+
+ logQueryAfter(sql, (System.currentTimeMillis() - startTime));
+ }
+ catch (SQLException e) {
+ logQueryError(sql, (System.currentTimeMillis() - startTime), e);
+ throw e;
+ }
+
+ return rs;
+ }
+
+ private Map processRow(ResultSet aResultSet) throws DatabaseFailure {
+ try {
+ Map result = new HashMap();
+ ResultSetMetaData metaData = aResultSet.getMetaData();
+ int nrColumns = metaData.getColumnCount();
+ for (int i=0; i<nrColumns; i++) {
+ result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
+ }
+
+ return result;
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ }
+
+ /**
+ * Executes 1 sql statement and returns the results as a <code>List</code> of
+ * <code>Map</code>s
+ */
+ public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc {
+ Connection connection = null;
+ Statement statement = null;
+ try {
+ List result = new ArrayList();
+ connection = obtainConnection();
+ statement = connection.createStatement();
+ ResultSet resultset = executeSql(statement, sql);
+ try {
+ while (resultset.next() && result.size() < aLimit) {
+ result.add(processRow(resultset));
+ }
+ }
+ finally {
+ resultset.close();
+ }
+
+ return result;
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ finally {
+ if (connection!=null) {
+ freeConnection(connection, statement);
+ }
+ }
+ }
+
+ /**
+ * Executes 1 sql statement and returns the first result row as a <code>Map</code>s
+ * (<code>null</code> if there wasn't any row)
+ */
+ public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc {
+ try {
+ List resultList = executeFreeSql(anSqlStatement, 1);
+ try {
+ if (resultList.size()>0)
+ return (Map) resultList.get(0);
+ return null;
+ }
+ finally {
+ }
+ }
+ catch (Throwable t) {
+ throw new DatabaseFailure(t);
+ }
+ }
+
+ /**
+ * Executes 1 sql statement and returns the first column of the first result row as a <code>String</code>s
+ * (<code>null</code> if there wasn't any row)
+ */
+ public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc {
+ Map row = executeFreeSingleRowSql(sql);
+
+ if (row==null)
+ return null;
+
+ Iterator i = row.values().iterator();
+ if (i.hasNext())
+ return (String) i.next();
+ return null;
+ }
+
+ public int getSize(String where) throws SQLException, DatabaseFailure {
+ return getSize("", null, where);
+ }
+ /**
+ * returns the number of rows in the table
+ */
+ public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure {
+
+ String useTable = mainTable;
+ if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
+ useTable+=" "+mainTablePrefix;
+ }
+ StringBuffer countSql =
+ new StringBuffer("select count(*) from ").append(useTable);
+ // append extratables, if necessary
+ if (extraTables!=null) {
+ for (int i=0;i < extraTables.size();i++) {
+ if (!extraTables.get(i).equals("")) {
+ countSql.append( ", " + extraTables.get(i));
+ }
+ }
+ }
+
+ if ((where != null) && (where.length() != 0)) {
+ countSql.append( " where " + where);
+ }
+
+ Connection con = null;
+ Statement stmt = null;
+ int result = 0;
+ logQueryBefore(countSql.toString());
+ long startTime = System.currentTimeMillis();
+
+ try {
+ con = obtainConnection();
+ stmt = con.createStatement();
+
+ ResultSet rs = executeSql(stmt, countSql.toString());
+
+ while (rs.next()) {
+ result = rs.getInt(1);
+ }
+ }
+ catch (SQLException e) {
+ logger.error("Database.getSize: " + e.getMessage());
+ }
+ finally {
+ freeConnection(con, stmt);
+ }
+ logQueryAfter(countSql.toString(), (System.currentTimeMillis() - startTime));
+
+ return result;
+ }
+
+ public int executeUpdate(Statement stmt, String sql)
+ throws DatabaseFailure, SQLException {
+ int rs;
+
+ logQueryBefore(sql);
+ long startTime = System.currentTimeMillis();
+
+ try {
+ rs = stmt.executeUpdate(sql);
+
+ logQueryAfter(sql, (System.currentTimeMillis() - startTime));
+ }
+ catch (SQLException e) {
+ logQueryError(sql, (System.currentTimeMillis() - startTime), e);
+ throw e;
+ }
+
+ return rs;
+ }
+
+ public int executeUpdate(String sql)
+ throws DatabaseFailure, SQLException {
+ int result = -1;
+ Connection con = null;
+ PreparedStatement pstmt = null;
+
+ logQueryBefore(sql);
+ long startTime = System.currentTimeMillis();
+ try {
+ con = obtainConnection();
+ pstmt = con.prepareStatement(sql);
+ result = pstmt.executeUpdate();
+ logQueryAfter(sql, System.currentTimeMillis() - startTime);
+ }
+ catch (Throwable e) {
+ logQueryError(sql, System.currentTimeMillis() - startTime, e);
+ throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
+ }
+ finally {
+ freeConnection(con, pstmt);
+ }
+ return result;
+ }
+
+ /**
+ * Processes the metadata for the table this Database object is responsible for.
+ */
+ private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure {
+ fieldNames = new ArrayList();
+ fieldNameToType = new HashMap();
+
+ try {
+ int numFields = aMetaData.getColumnCount();
+ fieldTypes = new int[numFields];
+
+ for (int i = 1; i <= numFields; i++) {
+ fieldNames.add(aMetaData.getColumnName(i));
+ fieldTypes[i - 1] = aMetaData.getColumnType(i);
+ fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i)));
+ }
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ }
+
+ /**
+ * Retrieves metadata from the table this Database object represents
+ */
+ private void acquireMetaData() throws DatabaseFailure {
+ Connection connection = null;
+ PreparedStatement statement = null;
+ String sql = "select * from " + mainTable + " where 0=1";
+
+ try {
+ connection = obtainConnection();
+ statement = connection.prepareStatement(sql);
+
+ logger.debug("METADATA: " + sql);
+ ResultSet resultSet = statement.executeQuery();
+ try {
+ processMetaData(resultSet.getMetaData());
+ }
+ finally {
+ resultSet.close();
+ }
+ }
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
+ }
+ finally {
+ freeConnection(connection, statement);
+ }
+ }
+
+ public Connection obtainConnection() throws DatabaseFailure {
+ try {
+ return MirGlobal.getDatabaseEngine().obtainConnection();
+ }
+ catch (Exception e) {
+ throw new DatabaseFailure(e);
+ }
+ }
+
+ public void freeConnection(Connection aConnection) throws DatabaseFailure {
+ try {
+ MirGlobal.getDatabaseEngine().releaseConnection(aConnection);
+ }
+ catch (Throwable t) {
+ logger.warn("Can't release connection: " + t.toString());
+ }
+ }
+
+ public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure {
+ try {
+ aStatement.close();
+ }
+ catch (Throwable t) {
+ logger.warn("Can't close statement", t);
+ }
+
+ freeConnection(aConnection);
+ }
+
+ protected void _throwStorageObjectException(Exception e, String aFunction)
+ throws DatabaseFailure {
+
+ if (e != null) {
+ logger.error(e.getMessage() + aFunction);
+ throw new DatabaseFailure(aFunction, e);
+ }
+ }
+
+
+ /**
+ * Invalidates any cached entity list
+ */
+ private void invalidateStore() {
+ // invalidating all EntityLists corresponding with entityClass
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ StoreContainerType stoc_type =
+ StoreContainerType.valueOf(entityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
+ o_store.invalidate(stoc_type);
+ }
+ }
+
+ /**
+ * Retrieves a binary value
+ */
+ public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException {
+ Connection connection=null;
+ Statement statement=null;
+ InputStream inputStream;
+
+ try {
+ connection = obtainConnection();
+ try {
+ connection.setAutoCommit(false);
+ statement = connection.createStatement();
+ ResultSet resultSet = executeSql(statement, aQuery);
+
+ if(resultSet!=null) {
+ if (resultSet.next()) {
+ if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
+ return resultSet.getBytes(1);
+ }
+ else {
+ inputStream = resultSet.getBlob(1).getBinaryStream();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ StreamCopier.copy(inputStream, outputStream);
+ return outputStream.toByteArray();
+ }
+ }
+ resultSet.close();
+ }
+ }
+ finally {
+ try {
+ connection.setAutoCommit(true);
+ }
+ catch (Throwable e) {
+ logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
+ e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ }
+
+ try {
+ freeConnection(connection, statement);
+ }
+ catch (Throwable e) {
+ logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
+ }
+
+ }
+ }
+ catch (Throwable t) {
+ logger.error("EntityImages.getImage failed: " + t.toString());
+ t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+
+ throw new DatabaseFailure(t);
+ }
+
+ return new byte[0];
+ }
+
+ /**
+ * Sets a binary value for a particular field in a record specified by its identifier
+ */
+ public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException {
+ PreparedStatement statement = null;
+ Connection connection = obtainConnection();
+
+ try {
+ connection.setAutoCommit(false);
+ try {
+ // are we using bytea ?
+ if (getFieldType(aFieldName) == java.sql.Types.BINARY) {
+ statement = connection.prepareStatement(
+ "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
+ statement.setBytes(1, aData);
+ statement.execute();
+ connection.commit();
+ }
+ // or the old oid's
+ else {
+ PGConnection postgresqlConnection = (org.postgresql.PGConnection) ((DelegatingConnection) connection).getDelegate();
+ LargeObjectManager lobManager = postgresqlConnection.getLargeObjectAPI();
+ int oid = lobManager.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
+ LargeObject obj = lobManager.open(oid, LargeObjectManager.WRITE); // Now open the file File file =
+ obj.write(aData);
+ obj.close();
+ statement = connection.prepareStatement(
+ "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
+ statement.setInt(1, oid);
+ statement.execute();
+ connection.commit();
+ }
+ }
+ finally {
+ connection.setAutoCommit(true);
+ }
+ }
+ finally {
+ freeConnection(connection, statement);
+ }
+ }
+
+ /**
+ * Can be overridden to specify a primary key sequence name not named according to
+ * the convention (tablename _id_seq)
+ */
+ protected String getPrimaryKeySequence() {
+ return mainTable+"_id_seq";
+ }
+
+ /**
+ * Can be called by subclasses to specify fields that are binary, and that shouldn't
+ * be updated outside of {@link #setBinaryField}
+ *
+ * @param aBinaryField The field name of the binary field
+ */
+ protected void markBinaryField(String aBinaryField) {
+ binaryFields.add(aBinaryField);
+ }
+
+ private void logQueryBefore(String aQuery) {
+ logger.debug("about to perform QUERY " + aQuery);
+// (new Throwable()).printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ }
+
+ private void logQueryAfter(String aQuery, long aTime) {
+ logger.info("QUERY " + aQuery + " took " + aTime + "ms.");
+ }
+
+ private void logQueryError(String aQuery, long aTime, Throwable anException) {
+ logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());
+ }
+
+ private int getFieldType(String aFieldName) {
+ if (fieldNameToType == null) {
+ acquireMetaData();
+ }
+
+ return ((Integer) fieldNameToType.get(aFieldName)).intValue();
+ }
+}