X-Git-Url: http://erislabs.net/gitweb/?a=blobdiff_plain;f=source%2Fmir%2Fstorage%2FDatabase.java;h=f86f043d1209013cf82369e87446bf90f3163ac1;hb=42680c1f9fe3250bcbd0f9ed5d9dee6188333b15;hp=0f886dbb41a72934d309157a6d19ce7995782702;hpb=e44404fac09c8da04b5ef7874160cb91f8fc98a9;p=mir.git diff --git a/source/mir/storage/Database.java b/source/mir/storage/Database.java index 0f886dbb..f86f043d 100755 --- a/source/mir/storage/Database.java +++ b/source/mir/storage/Database.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2001, 2002 The Mir-coders group + * Copyright (C) 2001-2006 The Mir-coders group * * This file is part of Mir. * @@ -19,8 +19,6 @@ * * In addition, as a special exception, The Mir-coders gives permission to link * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), * and distribute linked combinations including the two. You must obey the * GNU General Public License in all respects for all of the code used other than * the above mentioned libraries. If you modify this file, you may extend this @@ -29,113 +27,85 @@ */ package mir.storage; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - import mir.config.MirPropertiesConfiguration; import mir.entity.AbstractEntity; import mir.entity.Entity; import mir.entity.EntityList; import mir.entity.StorableObjectEntity; import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.store.ObjectStore; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; +import mir.storage.store.*; import mir.util.JDBCStringRoutines; +import mir.util.StreamCopier; import mircoders.global.MirGlobal; - import org.apache.commons.dbcp.DelegatingConnection; import org.postgresql.PGConnection; import org.postgresql.largeobject.LargeObject; import org.postgresql.largeobject.LargeObjectManager; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.sql.*; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + /** * Implements database access. * - * @version $Id: Database.java,v 1.44.2.27 2005/02/10 16:22:33 rhindes Exp $ + * @version $Id: Database.java,v 1.44.2.37 2006/12/25 20:10:22 zapata Exp $ * @author rk + * @author Zapata * */ public class Database { - private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + private static final int DEFAULT_LIMIT = 20; + private static final Class GENERIC_ENTITY_CLASS = StorableObjectEntity.class; protected static final ObjectStore o_store = ObjectStore.getInstance(); - private static final int _millisPerHour = 60 * 60 * 1000; protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; protected String mainTable; - protected String primaryKeySequence = null; protected String primaryKeyField = "id"; - protected List fieldNames; - protected int[] fieldTypes; - protected Map fieldNameToType; + private List fieldNames; + private int[] fieldTypes; + private Map fieldNameToType; protected Class entityClass; - private int defaultLimit; - TimeZone timezone; - SimpleDateFormat internalDateFormat; - SimpleDateFormat userInputDateFormat; + // + private Set binaryFields; - /** - * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. - * Aus diesem file werden Database.Logfile, - * Database.Username,Database.Password, - * Database.Host und Database.Adaptor - * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank - * erzeugt. - */ - public Database() throws StorageObjectFailure { - configuration = MirPropertiesConfiguration.instance(); + private TimeZone timezone; + private SimpleDateFormat userInputDateFormat; + + public Database() throws DatabaseFailure { + MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); logger = new LoggerWrapper("Database"); timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone")); - internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - internalDateFormat.setTimeZone(timezone); userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); userInputDateFormat.setTimeZone(timezone); - String theAdaptorName = configuration.getString("Database.Adaptor"); - defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); + binaryFields = new HashSet(); + + String adapterName = configuration.getString("Database.Adaptor"); try { entityClass = GENERIC_ENTITY_CLASS; } catch (Throwable e) { - logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); - throw new StorageObjectFailure("Error in Database() constructor.", e); + logger.error("Error in Database() constructor with " + adapterName + " -- " + e.getMessage()); + throw new DatabaseFailure("Error in Database() constructor.", e); } } - public java.lang.Class getEntityClass() { + public Class getEntityClass() { return entityClass; } - public Entity createNewEntity() throws StorageObjectFailure { + public Entity createNewEntity() throws DatabaseFailure { try { AbstractEntity result = (AbstractEntity) entityClass.newInstance(); result.setStorage(this); @@ -143,51 +113,22 @@ public class Database { return result; } catch (Throwable t) { - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } } - /** - * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also - * wieviel Datens?tze per Default selektiert werden. - * - * @return Standard-Anzahl der Datens?tze - */ - public int getLimit() { - return defaultLimit; - } - public String getIdFieldName() { return primaryKeyField; } - /** - * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. - * - * @return Name der Tabelle - */ public String getTableName() { return mainTable; } /** - * Returns the id that was most recently added to the database - */ - private String getLatestInsertedId(Connection aConnection) throws SQLException { - if (primaryKeySequence==null) - primaryKeySequence = mainTable+"_id_seq"; - - PreparedStatement statement = aConnection.prepareStatement("select currval('" + primaryKeySequence + "')"); - - ResultSet rs = statement.executeQuery(); - rs.next(); - return rs.getString(1); - } - - /** * Returns a list of field names for this Database */ - public List getFieldNames() throws StorageObjectFailure { + public List getFieldNames() throws DatabaseFailure { if (fieldNames == null) { acquireMetaData(); } @@ -195,23 +136,28 @@ public class Database { return fieldNames; } + public boolean hasField(String aFieldName) { + return getFieldNames().contains(aFieldName); + } + /** * Gets value out of ResultSet according to type and converts to String - * @param rs ResultSet. + * + * @param aResultSet ResultSet. * @param aType a type from java.sql.Types.* - * @param valueIndex index in ResultSet + * @param aFieldIndex index in ResultSet * @return returns the value as String. If no conversion is possible * /unsupported value/ is returned */ - private String getValueAsString(ResultSet rs, int valueIndex, int aType) - throws StorageObjectFailure { + private String getValueAsString(ResultSet aResultSet, int aFieldIndex, int aType) + throws DatabaseFailure { String outValue = null; - if (rs != null) { + if (aResultSet != null) { try { switch (aType) { case java.sql.Types.BIT: - outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; + outValue = (aResultSet.getBoolean(aFieldIndex) == true) ? "1" : "0"; break; @@ -220,21 +166,18 @@ public class Database { case java.sql.Types.TINYINT: case java.sql.Types.BIGINT: - int out = rs.getInt(valueIndex); + int out = aResultSet.getInt(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { outValue = new Integer(out).toString(); } break; case java.sql.Types.NUMERIC: + long outl = aResultSet.getLong(aFieldIndex); - /** todo Numeric can be float or double depending upon - * metadata.getScale() / especially with oracle */ - long outl = rs.getLong(valueIndex); - - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { outValue = new Long(outl).toString(); } @@ -242,9 +185,9 @@ public class Database { case java.sql.Types.REAL: - float tempf = rs.getFloat(valueIndex); + float tempf = aResultSet.getFloat(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { tempf *= 10; tempf += 0.5; @@ -259,9 +202,9 @@ public class Database { case java.sql.Types.DOUBLE: - double tempd = rs.getDouble(valueIndex); + double tempd = aResultSet.getDouble(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { tempd *= 10; tempd += 0.5; @@ -277,12 +220,12 @@ public class Database { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: - outValue = rs.getString(valueIndex); + outValue = aResultSet.getString(aFieldIndex); break; case java.sql.Types.LONGVARBINARY: - outValue = rs.getString(valueIndex); + outValue = aResultSet.getString(aFieldIndex); break; @@ -292,34 +235,22 @@ public class Database { // as a string is undefined and is only there for debugging // according to the API. we can make it a string through formatting. // -mh - Timestamp timestamp = (rs.getTimestamp(valueIndex)); + Timestamp timestamp = (aResultSet.getTimestamp(aFieldIndex)); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { java.util.Date date = new java.util.Date(timestamp.getTime()); - - Calendar calendar = new GregorianCalendar(); - calendar.setTime(date); - calendar.setTimeZone(timezone); - outValue = internalDateFormat.format(date); - - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2); - - if (offset<0) - outValue = outValue + "-"; - else - outValue = outValue + "+"; - outValue = outValue + tzOffset; + outValue = DatabaseHelper.convertDateToInternalRepresenation(date); } break; default: outValue = ""; - logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); + logger.warn("Unsupported Datatype: at " + aFieldIndex + " (" + aType + ")"); } - } catch (SQLException e) { - throw new StorageObjectFailure("Could not get Value out of Resultset -- ", + } + catch (SQLException e) { + throw new DatabaseFailure("Could not get Value out of Resultset -- ", e); } } @@ -328,18 +259,17 @@ public class Database { } /** - * select-Operator um einen Datensatz zu bekommen. - * @param id Primaerschluessel des Datensatzes. - * @return liefert EntityObject des gefundenen Datensatzes oder null. + * Return an entity specified by id, or null if no such + * entity exists. */ - public Entity selectById(String id) throws StorageObjectExc { - if ((id == null) || id.equals("")) { - throw new StorageObjectExc("Database.selectById: Missing id"); + public Entity selectById(String anId) throws DatabaseExc { + if ((anId == null) || anId.equals("")) { + throw new DatabaseExc("Database.selectById: Missing id"); } // ask object store for object if (StoreUtil.extendsStorableEntity(entityClass)) { - String uniqueId = id; + String uniqueId = anId; if (entityClass.equals(StorableObjectEntity.class)) { uniqueId += ("@" + mainTable); @@ -355,173 +285,96 @@ public class Database { } } - Statement stmt = null; Connection con = obtainConnection(); Entity returnEntity = null; + PreparedStatement statement = null; try { ResultSet rs; + String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?"; - /** todo better prepared statement */ - String selectSql = - "select * from " + mainTable + " where " + primaryKeyField + "=" + id; - stmt = con.createStatement(); - rs = executeSql(stmt, selectSql); + 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: " + id + " in table " + mainTable); + logger.warn("No data for id: " + anId + " in table " + mainTable); } rs.close(); } else { - logger.warn("No Data for Id " + id + " in Table " + mainTable); + logger.warn("No Data for Id " + anId + " in Table " + mainTable); } } - catch (SQLException sqe) { - throwSQLException(sqe, "selectById"); - return null; - } - catch (NumberFormatException e) { - logger.error("ID is no number: " + id); + catch (Throwable e) { + throw new DatabaseFailure(e); } finally { - freeConnection(con, stmt); + freeConnection(con, statement); } return returnEntity; } - /** - * This method makes it possible to make selects across multiple tables - * - * @param mainTablePrefix prefix for the mainTable - * @param extraTables a vector of tables for relational select - * @param aWhereClause whereClause - * @return EntityList of selected Objects - * @throws StorageObjectFailure - */ - - public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, - List extraTables, String aWhereClause ) - throws StorageObjectFailure { - return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, defaultLimit); + 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 StorageObjectFailure { + 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 StorageObjectFailure { + public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure { return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * - * @param where where-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String where) throws StorageObjectFailure { + public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure { return selectByWhereClause(where, 0); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param whereClause where-Clause - * @param offset ab welchem Datensatz. - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure { + public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure { return selectByWhereClause(whereClause, null, offset); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param where where-Clause - * @param order orderBy-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure { - return selectByWhereClause(where, order, 0); + 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 mainTablePrefix, List extraTables, String where, String order) throws StorageObjectFailure { - return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, defaultLimit); + public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure { + return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param whereClause where-Clause - * @param orderBy orderBy-Clause - * @param offset ab welchem Datensatz - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure { - return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); - } - - /** - * select-Operator returns EntityList with matching rows in Database. - * @param aWhereClause where-Clause - * @param anOrderByClause orderBy-Clause - * @param offset ab welchem Datensatz - * @param limit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause, - int offset, int limit) throws StorageObjectFailure { + int offset, int limit) throws DatabaseExc, DatabaseFailure { return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit); } - - /** - * select-Operator returns EntityList with matching rows in Database. - * @param aWhereClause where-Clause - * @param anOrderByClause orderBy-Clause - * @param anOffset ab welchem Datensatz - * @param aLimit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ public EntityList selectByWhereClause( String aMainTablePrefix, List anExtraTables, String aWhereClause, String anOrderByClause, - int anOffset, int aLimit) throws StorageObjectFailure { - - // TODO get rid of emtpy Strings in anExtraTables - // make anExtraTables null, if single empty String in it - // cause StringUtil.splitString puts in emptyString + int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure { if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){ anExtraTables=null; } - String useTable = mainTable; - String selection = "*"; - - if (aMainTablePrefix != null && aMainTablePrefix.trim().length() > 0) { - useTable += " " + aMainTablePrefix; - selection = aMainTablePrefix.trim() + ".*"; - } - // check o_store for entitylist // only if no relational select if (anExtraTables==null) { @@ -538,101 +391,96 @@ public class Database { } } - // local - EntityList theReturnList = null; - Connection connection = null; - Statement statement = null; - ResultSet resultSet; + RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix); - // build sql-statement - - if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) { - aWhereClause = null; - } - - StringBuffer selectSql = - new StringBuffer("select "+selection+" from ").append(useTable); + EntityList result = null; + Connection connection = null; - // append extratables, if necessary if (anExtraTables!=null) { - for (int i=0;i < anExtraTables.size();i++) { - if (!anExtraTables.get(i).equals("")) { - selectSql.append( ", " + anExtraTables.get(i)); + Iterator i = anExtraTables.iterator(); + while (i.hasNext()) { + String table = (String) i.next(); + if (!"".equals(table)) { + retriever.addExtraTable(table); } } } if (aWhereClause != null) { - selectSql.append(" where ").append(aWhereClause); + retriever.appendWhereClause(aWhereClause); } if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) { - selectSql.append(" order by ").append(anOrderByClause); + retriever.appendOrderByClause(anOrderByClause); + } + + if (anOffset>-1 && aLimit>-1) { + retriever.setLimit(aLimit+1); + retriever.setOffset(anOffset); } - if ((aLimit > -1) && (anOffset > -1)) { - selectSql.append(" LIMIT ").append(aLimit+1).append(" OFFSET ").append(anOffset); + Iterator i = getFieldNames().iterator(); + while (i.hasNext()) { + retriever.addField((String) i.next()); } // execute sql try { connection = obtainConnection(); - statement = connection.createStatement(); - boolean hasMore = false; + ResultSet resultSet = retriever.execute(connection); - // selecting... - resultSet = executeSql(statement, selectSql.toString()); + boolean hasMore = false; if (resultSet != null) { - theReturnList = new EntityList(); - Entity theResultEntity; + result = new EntityList(); + Entity entity; int position = 0; + while (((aLimit == -1) || (position= 10) { @@ -875,92 +640,76 @@ public class Database { // TimeStamp stuff try { java.util.Date d = userInputDateFormat.parse(dateString); -// Timestamp tStamp = new Timestamp(d.getTime()); - sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'"); + generator.assignDateTime("webdb_create", d); } catch (ParseException e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } } - - sql.append(" where id=").append(id); - logQueryBefore(sql.toString()); + Connection connection = null; try { - con = obtainConnection(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql.toString()); - - pstmt.executeUpdate(); - } - catch (SQLException sqe) { - throwSQLException(sqe, "update"); + connection = obtainConnection(); + generator.execute(connection); } finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - - - } - - freeConnection(con, pstmt); + freeConnection(connection); } } - - /* - * delete-Operator - * @param id des zu loeschenden Datensatzes - * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. - */ - public boolean delete(String id) throws StorageObjectFailure { + + private void invalidateObject(String anId) { // ostore send notification if (StoreUtil.extendsStorableEntity(entityClass)) { - String uniqueId = id; + String uniqueId = anId; if (entityClass.equals(StorableObjectEntity.class)) { uniqueId += ("@" + mainTable); } - logger.debug("CACHE: (del) " + id); + logger.debug("CACHE: (del) " + anId); StoreIdentifier search_sid = new StoreIdentifier(entityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId); o_store.invalidate(search_sid); } + } - /** todo could be prepared Statement */ - Statement stmt = null; - Connection con = null; - int res = 0; - String sql = - "delete from " + mainTable + " where " + primaryKeyField + "='" + id + "'"; + /* + * 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; - logQueryBefore(sql); try { - con = obtainConnection(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); + 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 sqe) { - throwSQLException(sqe, "delete"); + catch (SQLException e) { + logger.warn("Can't delete record", e); } finally { - freeConnection(con, stmt); + freeConnection(connection, statement); } invalidateStore(); - return (res > 0) ? true : false; + return (resultCode > 0) ? true : false; } /** * Deletes entities based on a where clause */ - public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure { + public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure { invalidateStore(); Statement stmt = null; @@ -975,8 +724,8 @@ public class Database { stmt = con.createStatement(); res = stmt.executeUpdate(sql); } - catch (SQLException sqe) { - throwSQLException(sqe, "delete"); + catch (Throwable e) { + throw new DatabaseFailure(e); } finally { freeConnection(con, stmt); @@ -992,13 +741,8 @@ public class Database { return false; } - /** - * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. - * @param stmt Statemnt - * @param sql Sql-String - */ public ResultSet executeSql(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { + throws DatabaseFailure, SQLException { ResultSet rs; logQueryBefore(sql); long startTime = System.currentTimeMillis(); @@ -1015,7 +759,7 @@ public class Database { return rs; } - private Map processRow(ResultSet aResultSet) throws StorageObjectFailure { + private Map processRow(ResultSet aResultSet) throws DatabaseFailure { try { Map result = new HashMap(); ResultSetMetaData metaData = aResultSet.getMetaData(); @@ -1027,7 +771,7 @@ public class Database { return result; } catch (Throwable e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } @@ -1035,7 +779,7 @@ public class Database { * Executes 1 sql statement and returns the results as a List of * Maps */ - public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc { + public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc { Connection connection = null; Statement statement = null; try { @@ -1055,7 +799,7 @@ public class Database { return result; } catch (Throwable e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } finally { if (connection!=null) { @@ -1068,7 +812,7 @@ public class Database { * Executes 1 sql statement and returns the first result row as a Maps * (null if there wasn't any row) */ - public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc { + public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc { try { List resultList = executeFreeSql(anSqlStatement, 1); try { @@ -1080,7 +824,7 @@ public class Database { } } catch (Throwable t) { - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } } @@ -1088,7 +832,7 @@ public class Database { * Executes 1 sql statement and returns the first column of the first result row as a Strings * (null if there wasn't any row) */ - public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc { + public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc { Map row = executeFreeSingleRowSql(sql); if (row==null) @@ -1100,13 +844,13 @@ public class Database { return null; } - public int getSize(String where) throws SQLException, StorageObjectFailure { + 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, StorageObjectFailure { + public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure { String useTable = mainTable; if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) { @@ -1155,7 +899,7 @@ public class Database { } public int executeUpdate(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { + throws DatabaseFailure, SQLException { int rs; logQueryBefore(sql); @@ -1175,7 +919,7 @@ public class Database { } public int executeUpdate(String sql) - throws StorageObjectFailure, SQLException { + throws DatabaseFailure, SQLException { int result = -1; Connection con = null; PreparedStatement pstmt = null; @@ -1190,7 +934,7 @@ public class Database { } catch (Throwable e) { logQueryError(sql, System.currentTimeMillis() - startTime, e); - throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); + throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); } finally { freeConnection(con, pstmt); @@ -1201,7 +945,7 @@ public class Database { /** * Processes the metadata for the table this Database object is responsible for. */ - private void processMetaData(ResultSetMetaData aMetaData) throws StorageObjectFailure { + private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure { fieldNames = new ArrayList(); fieldNameToType = new HashMap(); @@ -1215,15 +959,15 @@ public class Database { fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i))); } } - catch (SQLException e) { - throwSQLException(e, "processMetaData"); + catch (Throwable e) { + throw new DatabaseFailure(e); } } /** * Retrieves metadata from the table this Database object represents */ - private void acquireMetaData() throws StorageObjectFailure { + private void acquireMetaData() throws DatabaseFailure { Connection connection = null; PreparedStatement statement = null; String sql = "select * from " + mainTable + " where 0=1"; @@ -1241,31 +985,24 @@ public class Database { resultSet.close(); } } - catch (SQLException e) { - throwSQLException(e, "acquireMetaData"); + catch (Throwable e) { + throw new DatabaseFailure(e); } finally { freeConnection(connection, statement); } } - public Connection obtainConnection() throws StorageObjectFailure { + public Connection obtainConnection() throws DatabaseFailure { try { return MirGlobal.getDatabaseEngine().obtainConnection(); } catch (Exception e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } - public void freeConnection(Connection aConnection, Statement aStatement) throws StorageObjectFailure { - try { - aStatement.close(); - } - catch (Throwable t) { - logger.warn("Can't close statemnet: " + t.toString()); - } - + public void freeConnection(Connection aConnection) throws DatabaseFailure { try { MirGlobal.getDatabaseEngine().releaseConnection(aConnection); } @@ -1274,53 +1011,26 @@ public class Database { } } - /** - * Wertet SQLException aus und wirft dannach eine StorageObjectException - * @param sqe SQLException - * @param aFunction Funktonsname, in der die SQLException geworfen wurde - */ - protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure { - String state = ""; - String message = ""; - int vendor = 0; - - if (sqe != null) { - state = sqe.getSQLState(); - message = sqe.getMessage(); - vendor = sqe.getErrorCode(); + public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure { + try { + aStatement.close(); + } + catch (Throwable t) { + logger.warn("Can't close statement", t); } - String information = - "SQL Error: " + - "state= " + state + - ", vendor= " + vendor + - ", message=" + message + - ", function= " + aFunction; - - logger.error(information); - - throw new StorageObjectFailure(information, sqe); + freeConnection(aConnection); } protected void _throwStorageObjectException(Exception e, String aFunction) - throws StorageObjectFailure { + throws DatabaseFailure { if (e != null) { logger.error(e.getMessage() + aFunction); - throw new StorageObjectFailure(aFunction, e); + throw new DatabaseFailure(aFunction, e); } } - /** - * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach - * eine StorageObjectException - * @param aMessage Nachricht mit dem Fehler - * @exception StorageObjectFailure - */ - void throwStorageObjectException(String aMessage) throws StorageObjectFailure { - logger.error(aMessage); - throw new StorageObjectFailure(aMessage, null); - } /** * Invalidates any cached entity list @@ -1337,11 +1047,10 @@ public class Database { /** * Retrieves a binary value */ - public InputStream getBinaryField(String aQuery) throws StorageObjectFailure, SQLException { + public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException { Connection connection=null; Statement statement=null; InputStream inputStream; - InputStream imageInputStream = null; try { connection = obtainConnection(); @@ -1353,49 +1062,50 @@ public class Database { if(resultSet!=null) { if (resultSet.next()) { if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) { - byte[] data = resultSet.getBytes(1); - imageInputStream = new ByteArrayInputStream(data); + return resultSet.getBytes(1); } else { inputStream = resultSet.getBlob(1).getBinaryStream(); - imageInputStream = new BinaryFieldInputStream(inputStream, connection, statement); + 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)); - 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()); - } - - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } - return imageInputStream; + 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 StorageObjectFailure, SQLException { + public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException { PreparedStatement statement = null; Connection connection = obtainConnection(); @@ -1434,6 +1144,24 @@ public class Database { } } + /** + * 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)); @@ -1454,36 +1182,4 @@ public class Database { return ((Integer) fieldNameToType.get(aFieldName)).intValue(); } - - - /** - * a small wrapper class that allows us to store the DB connection resources - * that the BlobInputStream is using and free them upon closing of the stream - */ - private class BinaryFieldInputStream extends InputStream { - InputStream inputStream; - Connection connection; - Statement statement; - - public BinaryFieldInputStream(InputStream aBlobInputStream, Connection aConnection, Statement aStatement ) { - inputStream = aBlobInputStream; - connection = aConnection; - statement = aStatement; - } - - public void close () throws IOException { - inputStream.close(); - try { - connection.setAutoCommit(true); - freeConnection(connection, statement); - } - catch (Exception e) { - throw new IOException("close(): "+e.toString()); - } - } - - public int read() throws IOException { - return inputStream.read(); - } - } }