some code cleanup. removed unnecessary semikolons, unused vars, etc.
[mir.git] / source / mir / storage / Database.java
index a236a48..0f886db 100755 (executable)
@@ -29,7 +29,9 @@
  */
 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;
@@ -48,10 +50,9 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.TimeZone;
-import java.util.Vector;
 
 import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
+import mir.entity.AbstractEntity;
 import mir.entity.Entity;
 import mir.entity.EntityList;
 import mir.entity.StorableObjectEntity;
@@ -63,40 +64,37 @@ import mir.storage.store.StoreContainerType;
 import mir.storage.store.StoreIdentifier;
 import mir.storage.store.StoreUtil;
 import mir.util.JDBCStringRoutines;
+import mircoders.global.MirGlobal;
 
-import com.codestudio.util.SQLManager;
-
+import org.apache.commons.dbcp.DelegatingConnection;
+import org.postgresql.PGConnection;
+import org.postgresql.largeobject.LargeObject;
+import org.postgresql.largeobject.LargeObjectManager;
 
 /**
- * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
- * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
- * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
- * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
- * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
- * Datenbank erfolgt.
+ * Implements database access.
  *
- * @version $Id: Database.java,v 1.44.2.22 2004/02/08 21:05:01 zapata Exp $
+ * @version $Id: Database.java,v 1.44.2.27 2005/02/10 16:22:33 rhindes Exp $
  * @author rk
  *
  */
-public class Database implements StorageObject {
+public class Database {
   private static Class GENERIC_ENTITY_CLASS = mir.entity.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 boolean evaluatedMetaData = false;
-  protected ArrayList metadataFields;
-  protected ArrayList metadataLabels;
-  protected ArrayList metadataNotNullFields;
-  protected int[] metadataTypes;
-  protected Class theEntityClass;
-  protected boolean hasTimestamp = true;
+  protected List fieldNames;
+  protected int[] fieldTypes;
+  protected Map fieldNameToType;
+
+  protected Class entityClass;
   private int defaultLimit;
 
   TimeZone timezone;
@@ -112,12 +110,7 @@ public class Database implements StorageObject {
    * erzeugt.
    */
   public Database() throws StorageObjectFailure {
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new StorageObjectFailure(e);
-    }
+    configuration = MirPropertiesConfiguration.instance();
     logger = new LoggerWrapper("Database");
     timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
     internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -130,7 +123,7 @@ public class Database implements StorageObject {
     defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
 
     try {
-      theEntityClass = GENERIC_ENTITY_CLASS;
+      entityClass = GENERIC_ENTITY_CLASS;
     }
     catch (Throwable e) {
       logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
@@ -138,15 +131,20 @@ public class Database implements StorageObject {
     }
   }
 
-  /**
-   * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
-   * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
-   * wird eine mir.entity.GenericEntity erzeugt.
-   *
-   * @return Class-Objekt der Entity
-   */
   public java.lang.Class getEntityClass() {
-    return theEntityClass;
+    return entityClass;
+  }
+
+  public Entity createNewEntity() throws StorageObjectFailure {
+    try {
+      AbstractEntity result = (AbstractEntity) entityClass.newInstance();
+      result.setStorage(this);
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new StorageObjectFailure(t);
+    }
   }
 
   /**
@@ -159,12 +157,7 @@ public class Database implements StorageObject {
     return defaultLimit;
   }
 
-  /**
-   * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
-   * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
-   * @return Name des Primary-Keys
-   */
-  public String getIdName() {
+  public String getIdFieldName() {
     return primaryKeyField;
   }
 
@@ -192,39 +185,14 @@ public class Database implements StorageObject {
   }
 
   /**
-   * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
-   * @return int-Array mit den Typen der Felder
-   * @exception StorageObjectFailure
-   */
-  public int[] getTypes() throws StorageObjectFailure {
-    if (metadataTypes == null) {
-      get_meta_data();
-    }
-
-    return metadataTypes;
-  }
-
-  /**
-   * Liefert eine Liste der Labels der Tabellenfelder
-   */
-  public List getLabels() throws StorageObjectFailure {
-    if (metadataLabels == null) {
-      get_meta_data();
-    }
-
-    return metadataLabels;
-  }
-
-  /**
-   * Liefert eine Liste der Felder der Tabelle
-   * @return ArrayList mit Feldern
+   * Returns a list of field names for this <code>Database</code>
    */
-  public List getFields() throws StorageObjectFailure {
-    if (metadataFields == null) {
-      get_meta_data();
+  public List getFieldNames() throws StorageObjectFailure {
+    if (fieldNames == null) {
+      acquireMetaData();
     }
 
-    return metadataFields;
+    return fieldNames;
   }
 
   /**
@@ -370,14 +338,14 @@ public class Database implements StorageObject {
     }
 
     // ask object store for object
-    if (StoreUtil.extendsStorableEntity(theEntityClass)) {
+    if (StoreUtil.extendsStorableEntity(entityClass)) {
       String uniqueId = id;
 
-      if (theEntityClass.equals(StorableObjectEntity.class)) {
+      if (entityClass.equals(StorableObjectEntity.class)) {
         uniqueId += ("@" + mainTable);
       }
 
-      StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
+      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);
@@ -388,7 +356,7 @@ public class Database implements StorageObject {
     }
 
     Statement stmt = null;
-    Connection con = getPooledCon();
+    Connection con = obtainConnection();
     Entity returnEntity = null;
 
     try {
@@ -401,10 +369,6 @@ public class Database implements StorageObject {
       rs = executeSql(stmt, selectSql);
 
       if (rs != null) {
-        if (evaluatedMetaData == false) {
-          evalMetaData(rs.getMetaData());
-        }
-
         if (rs.next()) {
           returnEntity = makeEntityFromResultSet(rs);
         }
@@ -448,25 +412,12 @@ public class Database implements StorageObject {
        return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, defaultLimit);
   }
 
-  /**
-   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
-   *   @param aField  Datenbankfeld der Bedingung.
-   *   @param aValue  Wert die der key anehmen muss.
-   *   @return EntityList mit den gematchten Entities
-   */
   public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
     return selectByFieldValue(aField, aValue, 0);
   }
 
-  /**
-   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
-   *   @param aField  Datenbankfeld der Bedingung.
-   *   @param aValue  Wert die der key anehmen muss.
-   *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
-   *   @return EntityList mit den gematchten Entities
-   */
   public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
-    return selectByWhereClause(aField + "=" + aValue, offset);
+    return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset);
   }
 
   /**
@@ -545,39 +496,40 @@ public class Database implements StorageObject {
    * 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
+   * @param anOffset ab welchem Datensatz
+   * @param aLimit wieviele Datens?tze
    * @return EntityList mit den gematchten Entities
    * @exception StorageObjectFailure
    */
-  public EntityList selectByWhereClause(String mainTablePrefix, List extraTables,
+  public EntityList selectByWhereClause(
+      String aMainTablePrefix, List anExtraTables,
       String aWhereClause, String anOrderByClause,
-                       int offset, int limit) throws StorageObjectFailure {
+                       int anOffset, int aLimit) throws StorageObjectFailure {
 
-    // TODO get rid of emtpy Strings in extraTables
-    // make extraTables null, if single empty String in it
+    // TODO get rid of emtpy Strings in anExtraTables
+    // make anExtraTables null, if single empty String in it
     // cause StringUtil.splitString puts in emptyString
-    if (extraTables != null && ((String)extraTables.get(0)).trim().equals(""))
-      {
-        logger.debug("+++ made extraTables to null!");
-        extraTables=null;
-      }
 
-      String useTable = mainTable;
-          String selectStar = "*";
-          if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
-            useTable+=" "+mainTablePrefix;
-            selectStar=mainTablePrefix.trim() + ".*";
-          }
+    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 (extraTables==null) {
-      if (StoreUtil.extendsStorableEntity(theEntityClass)) {
-         StoreIdentifier searchSid = new StoreIdentifier(theEntityClass,
+    if (anExtraTables==null) {
+      if (StoreUtil.extendsStorableEntity(entityClass)) {
+         StoreIdentifier searchSid = new StoreIdentifier(entityClass,
                StoreContainerType.STOC_TYPE_ENTITYLIST,
                StoreUtil.getEntityListUniqueIdentifierFor(mainTable,
-                aWhereClause, anOrderByClause, offset, limit));
+                aWhereClause, anOrderByClause, anOffset, aLimit));
          EntityList hit = (EntityList) o_store.use(searchSid);
 
          if (hit != null) {
@@ -588,11 +540,9 @@ public class Database implements StorageObject {
 
     // local
     EntityList theReturnList = null;
-    Connection con = null;
-    Statement stmt = null;
-    ResultSet rs;
-    int offsetCount = 0;
-    int count = 0;
+    Connection connection = null;
+    Statement statement = null;
+    ResultSet resultSet;
 
     // build sql-statement
 
@@ -600,97 +550,65 @@ public class Database implements StorageObject {
       aWhereClause = null;
     }
 
-    StringBuffer countSql =
-      new StringBuffer("select count(*) from ").append(useTable);
     StringBuffer selectSql =
-      new StringBuffer("select "+selectStar+" from ").append(useTable);
+      new StringBuffer("select "+selection+" 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));
-          selectSql.append( ", " + extraTables.get(i));
+    if (anExtraTables!=null) {
+      for (int i=0;i < anExtraTables.size();i++) {
+        if (!anExtraTables.get(i).equals("")) {
+          selectSql.append( ", " + anExtraTables.get(i));
         }
       }
     }
 
     if (aWhereClause != null) {
       selectSql.append(" where ").append(aWhereClause);
-      countSql.append(" where ").append(aWhereClause);
     }
 
     if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
       selectSql.append(" order by ").append(anOrderByClause);
     }
 
-    if ((limit > -1) && (offset > -1)) {
-      selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
+    if ((aLimit > -1) && (anOffset > -1)) {
+      selectSql.append(" LIMIT ").append(aLimit+1).append(" OFFSET ").append(anOffset);
     }
 
     // execute sql
     try {
-      con = getPooledCon();
-      stmt = con.createStatement();
+      connection = obtainConnection();
+      statement = connection.createStatement();
+      boolean hasMore = false;
 
       // selecting...
-      rs = executeSql(stmt, selectSql.toString());
-
-      if (rs != null) {
-        if (!evaluatedMetaData) {
-          evalMetaData(rs.getMetaData());
-        }
+      resultSet = executeSql(statement, selectSql.toString());
 
+      if (resultSet != null) {
         theReturnList = new EntityList();
         Entity theResultEntity;
-        while (rs.next()) {
-          theResultEntity = makeEntityFromResultSet(rs);
+        int position = 0;
+        while (((aLimit == -1) || (position<aLimit)) && resultSet.next()) {
+          theResultEntity = makeEntityFromResultSet(resultSet);
           theReturnList.add(theResultEntity);
-          offsetCount++;
+          position++;
         }
-        rs.close();
+        hasMore = resultSet.next();
+        resultSet.close();
       }
 
-      // making entitylist infos
-      count = offsetCount;
-
       if (theReturnList != null) {
         // now we decide if we have to know an overall count...
-        count = offsetCount;
-
-        if ((limit > -1) && (offset > -1)) {
-          if (offsetCount == limit) {
-            rs = executeSql(stmt, countSql.toString());
-
-            if (rs != null) {
-              if (rs.next()) {
-                count = rs.getInt(1);
-              }
-
-              rs.close();
-            }
-            else {
-              logger.error("Could not count: " + countSql);
-            }
-          }
-        }
-
-        theReturnList.setCount(count);
-        theReturnList.setOffset(offset);
+        theReturnList.setOffset(anOffset);
         theReturnList.setWhere(aWhereClause);
         theReturnList.setOrder(anOrderByClause);
         theReturnList.setStorage(this);
-        theReturnList.setLimit(limit);
-
-        if (offset >= limit) {
-          theReturnList.setPrevBatch(offset - limit);
-        }
+        theReturnList.setLimit(aLimit);
 
-        if ((offset + offsetCount) < count) {
-          theReturnList.setNextBatch(offset + limit);
+        if (hasMore) {
+          theReturnList.setNextBatch(anOffset + aLimit);
         }
 
-        if (extraTables==null && StoreUtil.extendsStorableEntity(theEntityClass)) {
+        if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
           StoreIdentifier sid = theReturnList.getStoreIdentifier();
           logger.debug("CACHE (add): " + sid.toString());
           o_store.add(sid);
@@ -702,8 +620,8 @@ public class Database implements StorageObject {
     }
     finally {
       try {
-        if (con != null) {
-          freeConnection(con, stmt);
+        if (connection != null) {
+          freeConnection(connection, statement);
         }
       } catch (Throwable t) {
       }
@@ -712,35 +630,26 @@ public class Database implements StorageObject {
     return theReturnList;
   }
 
-  /**
-   *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
-   *
-   *  @param rs Das ResultSetObjekt.
-   *  @return Entity Die Entity.
-   */
   private Entity makeEntityFromResultSet(ResultSet rs)
     throws StorageObjectFailure {
     Map theResultHash = new HashMap();
     String theResult = null;
-    int theType;
+    int type;
     Entity returnEntity = null;
 
     try {
-      if (StoreUtil.extendsStorableEntity(theEntityClass)) {
+      if (StoreUtil.extendsStorableEntity(entityClass)) {
          StoreIdentifier searchSid = StorableObjectEntity.getStoreIdentifier(this,
-               theEntityClass, rs);
+               entityClass, rs);
          Entity hit = (Entity) o_store.use(searchSid);
          if (hit != null) return hit;
       }
 
-
-      int size = metadataFields.size();
-
-      for (int i = 0; i < size; i++) {
+      for (int i = 0; i < getFieldNames().size(); i++) {
         // alle durchlaufen bis nix mehr da
-        theType = metadataTypes[i];
+        type = fieldTypes[i];
 
-        if (theType == java.sql.Types.LONGVARBINARY) {
+        if (type == java.sql.Types.LONGVARBINARY) {
           InputStreamReader is =
             (InputStreamReader) rs.getCharacterStream(i + 1);
 
@@ -755,21 +664,22 @@ public class Database implements StorageObject {
 
             is.close();
             theResult = theResultString.toString();
-          } else {
+          }
+          else {
             theResult = null;
           }
-        } else {
-          theResult = getValueAsString(rs, (i + 1), theType);
+        }
+        else {
+          theResult = getValueAsString(rs, (i + 1), type);
         }
 
         if (theResult != null) {
-          theResultHash.put(metadataFields.get(i), theResult);
+          theResultHash.put(getFieldNames().get(i), theResult);
         }
       }
 
-      if (theEntityClass != null) {
-        returnEntity = (Entity) theEntityClass.newInstance();
-        returnEntity.setStorage(this);
+      if (entityClass != null) {
+        returnEntity = createNewEntity();
         returnEntity.setFieldValues(theResultHash);
 
         if (returnEntity instanceof StorableObject) {
@@ -777,18 +687,12 @@ public class Database implements StorageObject {
           o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
         }
       } else {
-        throwStorageObjectException("Internal Error: theEntityClass not set!");
+        throwStorageObjectException("Internal Error: entityClass not set!");
       }
     }
-    catch (IllegalAccessException e) {
-      throwStorageObjectException("No access! -- " + e.getMessage());
-    }
     catch (IOException e) {
       throwStorageObjectException("IOException! -- " + e.getMessage());
     }
-    catch (InstantiationException e) {
-      throwStorageObjectException("No Instatiation! -- " + e.getMessage());
-    }
     catch (SQLException sqe) {
       throwSQLException(sqe, "makeEntityFromResultSet");
 
@@ -801,20 +705,11 @@ public class Database implements StorageObject {
   /**
    * Inserts an entity into the database.
    *
-   * @param theEntity
+   * @param anEntity
    * @return der Wert des Primary-keys der eingef?gten Entity
    */
-  public String insert(Entity theEntity) throws StorageObjectFailure {
-    //cache
-    invalidatePopupCache();
-
-    // invalidating all EntityLists corresponding with theEntityClass
-    if (StoreUtil.extendsStorableEntity(theEntityClass)) {
-      StoreContainerType stoc_type =
-        StoreContainerType.valueOf(theEntityClass,
-          StoreContainerType.STOC_TYPE_ENTITYLIST);
-      o_store.invalidate(stoc_type);
-    }
+  public String insert(Entity anEntity) throws StorageObjectFailure {
+    invalidateStore();
 
     String returnId = null;
     Connection con = null;
@@ -828,23 +723,23 @@ public class Database implements StorageObject {
       boolean firstField = true;
 
       // make sql-string
-      for (int i = 0; i < getFields().size(); i++) {
-        aField = (String) getFields().get(i);
+      for (int i = 0; i < getFieldNames().size(); i++) {
+        aField = (String) getFieldNames().get(i);
 
         if (!aField.equals(primaryKeyField)) {
           aValue = null;
 
           // exceptions
-          if (!theEntity.hasFieldValue(aField) && (
+          if (!anEntity.hasFieldValue(aField) && (
               aField.equals("webdb_create") ||
               aField.equals("webdb_lastchange"))) {
             aValue = "NOW()";
           }
           else {
-              if (theEntity.hasFieldValue(aField)) {
+              if (anEntity.hasFieldValue(aField)) {
                 aValue =
                   "'" +
-                   JDBCStringRoutines.escapeStringLiteral(theEntity.getFieldValue(aField)) + "'";
+                   JDBCStringRoutines.escapeStringLiteral(anEntity.getFieldValue(aField)) + "'";
               }
           }
 
@@ -871,8 +766,8 @@ public class Database implements StorageObject {
                                         .append(") values (").append(v).append(")");
       String sql = sqlBuf.toString();
 
-      logger.info("INSERT: " + sql);
-      con = getPooledCon();
+      logQueryBefore(sql);
+      con = obtainConnection();
       con.setAutoCommit(false);
       pstmt = con.prepareStatement(sql);
 
@@ -886,7 +781,7 @@ public class Database implements StorageObject {
 //      pstmt = con.prepareStatement("select currval('" +  + "_id_seq')");
 
       returnId = getLatestInsertedId(con);
-      theEntity.setId(returnId);
+      anEntity.setId(returnId);
     }
     catch (SQLException sqe) {
       throwSQLException(sqe, "insert");
@@ -920,27 +815,21 @@ public class Database implements StorageObject {
      *  that chooses to either insert or update depending if we
      *  have a primary key in the entity. i don't know if we
      *  still need the streamed input fields. // rk  */
+
     /** todo extension: check if Entity did change, otherwise we don't need
      *  the roundtrip to the database */
     /** invalidating corresponding entitylists in o_store*/
-    if (StoreUtil.extendsStorableEntity(theEntityClass)) {
-      StoreContainerType stoc_type =
-        StoreContainerType.valueOf(theEntityClass,
-          StoreContainerType.STOC_TYPE_ENTITYLIST);
-      o_store.invalidate(stoc_type);
-    }
+
+    invalidateStore();
 
     String id = theEntity.getId();
     String aField;
     StringBuffer fv = new StringBuffer();
     boolean firstField = true;
 
-    //cache
-    invalidatePopupCache();
-
     // build sql statement
-    for (int i = 0; i < getFields().size(); i++) {
-      aField = (String) metadataFields.get(i);
+    for (int i = 0; i < getFieldNames().size(); i++) {
+      aField = (String) getFieldNames().get(i);
 
       // only normal cases
       // todo if entity.hasFieldValue returns false, then the value should be stored as null
@@ -966,13 +855,13 @@ public class Database implements StorageObject {
       new StringBuffer("update ").append(mainTable).append(" set ").append(fv);
 
     // exceptions
-    if (metadataFields.contains("webdb_lastchange")) {
+    if (getFieldNames().contains("webdb_lastchange")) {
       sql.append(",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 (metadataFields.contains("webdb_create") &&
+    if (getFieldNames().contains("webdb_create") &&
         theEntity.hasFieldValue("webdb_create")) {
       // minimum of 10 (yyyy-mm-dd)...
       if (theEntity.getFieldValue("webdb_create").length() >= 10) {
@@ -996,10 +885,10 @@ public class Database implements StorageObject {
     }
 
     sql.append(" where id=").append(id);
-    logger.info("UPDATE: " + sql);
+    logQueryBefore(sql.toString());
 
     try {
-      con = getPooledCon();
+      con = obtainConnection();
       con.setAutoCommit(false);
       pstmt = con.prepareStatement(sql.toString());
 
@@ -1013,7 +902,8 @@ public class Database implements StorageObject {
         con.setAutoCommit(true);
       }
       catch (Exception e) {
-        ;
+        
+       
       }
 
       freeConnection(con, pstmt);
@@ -1026,20 +916,18 @@ public class Database implements StorageObject {
   *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
    */
   public boolean delete(String id) throws StorageObjectFailure {
-    invalidatePopupCache();
-
     // ostore send notification
-    if (StoreUtil.extendsStorableEntity(theEntityClass)) {
+    if (StoreUtil.extendsStorableEntity(entityClass)) {
       String uniqueId = id;
 
-      if (theEntityClass.equals(StorableObjectEntity.class)) {
+      if (entityClass.equals(StorableObjectEntity.class)) {
         uniqueId += ("@" + mainTable);
       }
 
       logger.debug("CACHE: (del) " + id);
 
       StoreIdentifier search_sid =
-        new StoreIdentifier(theEntityClass,
+        new StoreIdentifier(entityClass,
           StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
       o_store.invalidate(search_sid);
     }
@@ -1051,33 +939,29 @@ public class Database implements StorageObject {
     String sql =
       "delete from " + mainTable + " where " + primaryKeyField + "='" + id + "'";
 
-    //theLog.printInfo("DELETE " + sql);
+    logQueryBefore(sql);
     try {
-      con = getPooledCon();
+      con = obtainConnection();
       stmt = con.createStatement();
       res = stmt.executeUpdate(sql);
-    } catch (SQLException sqe) {
+    }
+    catch (SQLException sqe) {
       throwSQLException(sqe, "delete");
-    } finally {
+    }
+    finally {
       freeConnection(con, stmt);
     }
 
+    invalidateStore();
+
     return (res > 0) ? true : false;
   }
 
   /**
    * Deletes entities based on a where clause
-   *
-   * @param aWhereClause
-   * @return
-   * @throws StorageObjectFailure
    */
   public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
-    invalidatePopupCache();
-    if (StoreUtil.extendsStorableEntity(theEntityClass)) {
-      StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
-      o_store.invalidate(stoc_type);
-    }
+    invalidateStore();
 
     Statement stmt = null;
     Connection con = null;
@@ -1087,7 +971,7 @@ public class Database implements StorageObject {
 
     //theLog.printInfo("DELETE " + sql);
     try {
-      con = getPooledCon();
+      con = obtainConnection();
       stmt = con.createStatement();
       res = stmt.executeUpdate(sql);
     }
@@ -1105,15 +989,9 @@ public class Database implements StorageObject {
   * @return immer false
    */
   public boolean delete(EntityList theEntityList) {
-    invalidatePopupCache();
-
     return false;
   }
 
-  protected void invalidatePopupCache() {
-    /** todo  invalidates toooo much */
-  }
-
   /**
    * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
    * @param stmt Statemnt
@@ -1122,15 +1000,15 @@ public class Database implements StorageObject {
   public ResultSet executeSql(Statement stmt, String sql)
                             throws StorageObjectFailure, SQLException {
     ResultSet rs;
+    logQueryBefore(sql);
     long startTime = System.currentTimeMillis();
-
     try {
       rs = stmt.executeQuery(sql);
 
-      logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      logQueryAfter(sql, (System.currentTimeMillis() - startTime));
     }
     catch (SQLException e) {
-      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      logQueryError(sql, (System.currentTimeMillis() - startTime), e);
       throw e;
     }
 
@@ -1153,12 +1031,16 @@ public class Database implements StorageObject {
     }
   }
 
+  /**
+   * 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 StorageObjectFailure, StorageObjectExc {
     Connection connection = null;
     Statement statement = null;
     try {
-      List result = new Vector();
-      connection = getPooledCon();
+      List result = new ArrayList();
+      connection = obtainConnection();
       statement = connection.createStatement();
       ResultSet resultset = executeSql(statement, sql);
       try {
@@ -1180,16 +1062,19 @@ public class Database implements StorageObject {
         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 StorageObjectFailure, StorageObjectExc {
     try {
       List resultList = executeFreeSql(anSqlStatement, 1);
       try {
         if (resultList.size()>0)
           return (Map) resultList.get(0);
-        else
-          return null;
+                               return null;
       }
       finally {
       }
@@ -1197,8 +1082,12 @@ public class Database implements StorageObject {
     catch (Throwable t) {
       throw new StorageObjectFailure(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 StorageObjectFailure, StorageObjectExc {
     Map row = executeFreeSingleRowSql(sql);
 
@@ -1208,9 +1097,8 @@ public class Database implements StorageObject {
     Iterator i = row.values().iterator();
     if (i.hasNext())
       return (String) i.next();
-    else
-      return null;
-  };
+               return null;
+  }
 
   public int getSize(String where) throws SQLException, StorageObjectFailure {
     return getSize("", null, where);
@@ -1220,11 +1108,9 @@ public class Database implements StorageObject {
    */
   public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, StorageObjectFailure {
 
-    long startTime = System.currentTimeMillis();
-
     String useTable = mainTable;
     if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
-          useTable+=" "+mainTablePrefix;
+      useTable+=" "+mainTablePrefix;
     }
     StringBuffer countSql =
       new StringBuffer("select count(*) from ").append(useTable);
@@ -1244,9 +1130,11 @@ public class Database implements StorageObject {
     Connection con = null;
     Statement stmt = null;
     int result = 0;
+    logQueryBefore(countSql.toString());
+    long startTime = System.currentTimeMillis();
 
     try {
-      con = getPooledCon();
+      con = obtainConnection();
       stmt = con.createStatement();
 
       ResultSet rs = executeSql(stmt, countSql.toString());
@@ -1261,7 +1149,7 @@ public class Database implements StorageObject {
     finally {
       freeConnection(con, stmt);
     }
-    logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + countSql);
+    logQueryAfter(countSql.toString(), (System.currentTimeMillis() - startTime));
 
     return result;
   }
@@ -1269,15 +1157,17 @@ public class Database implements StorageObject {
   public int executeUpdate(Statement stmt, String sql)
     throws StorageObjectFailure, SQLException {
     int rs;
+
+    logQueryBefore(sql);
     long startTime = System.currentTimeMillis();
 
     try {
       rs = stmt.executeUpdate(sql);
 
-      logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      logQueryAfter(sql, (System.currentTimeMillis() - startTime));
     }
     catch (SQLException e) {
-      logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+      logQueryError(sql, (System.currentTimeMillis() - startTime), e);
       throw e;
     }
 
@@ -1287,109 +1177,101 @@ public class Database implements StorageObject {
   public int executeUpdate(String sql)
     throws StorageObjectFailure, SQLException {
     int result = -1;
-    long startTime = System.currentTimeMillis();
     Connection con = null;
     PreparedStatement pstmt = null;
 
+    logQueryBefore(sql);
+    long startTime = System.currentTimeMillis();
     try {
-      con = getPooledCon();
+      con = obtainConnection();
       pstmt = con.prepareStatement(sql);
       result = pstmt.executeUpdate();
+      logQueryAfter(sql, System.currentTimeMillis() - startTime);
     }
     catch (Throwable e) {
-      logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
+      logQueryError(sql, System.currentTimeMillis() - startTime, e);
       throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
     }
     finally {
       freeConnection(con, pstmt);
     }
-
-    logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
     return result;
   }
 
   /**
-   * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
-   * @param md ResultSetMetaData
+   * Processes the metadata for the table this Database object is responsible for.
    */
-  private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
-    this.evaluatedMetaData = true;
-    this.metadataFields = new ArrayList();
-    this.metadataLabels = new ArrayList();
-    this.metadataNotNullFields = new ArrayList();
+  private void processMetaData(ResultSetMetaData aMetaData) throws StorageObjectFailure {
+    fieldNames = new ArrayList();
+    fieldNameToType = new HashMap();
 
     try {
-      int numFields = md.getColumnCount();
-      this.metadataTypes = new int[numFields];
-
-      String aField;
-      int aType;
+      int numFields = aMetaData.getColumnCount();
+      fieldTypes = new int[numFields];
 
       for (int i = 1; i <= numFields; i++) {
-        aField = md.getColumnName(i);
-        metadataFields.add(aField);
-        metadataLabels.add(md.getColumnLabel(i));
-        aType = md.getColumnType(i);
-        metadataTypes[i - 1] = aType;
-
-        if (aField.equals(primaryKeyField)) {
-        }
-
-        if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
-          metadataNotNullFields.add(aField);
-        }
+        fieldNames.add(aMetaData.getColumnName(i));
+        fieldTypes[i - 1] = aMetaData.getColumnType(i);
+        fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i)));
       }
     }
     catch (SQLException e) {
-      throwSQLException(e, "evalMetaData");
+      throwSQLException(e, "processMetaData");
     }
   }
 
   /**
-   *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
-   *  um die alle Columns und Typen einer Tabelle zu ermitteln.
+   * Retrieves metadata from the table this Database object represents
    */
-  private void get_meta_data() throws StorageObjectFailure {
-    Connection con = null;
-    PreparedStatement pstmt = null;
+  private void acquireMetaData() throws StorageObjectFailure {
+    Connection connection = null;
+    PreparedStatement statement = null;
     String sql = "select * from " + mainTable + " where 0=1";
 
     try {
-      con = getPooledCon();
-      pstmt = con.prepareStatement(sql);
+      connection = obtainConnection();
+      statement = connection.prepareStatement(sql);
 
       logger.debug("METADATA: " + sql);
-      ResultSet rs = pstmt.executeQuery();
-      evalMetaData(rs.getMetaData());
-      rs.close();
+      ResultSet resultSet = statement.executeQuery();
+      try {
+        processMetaData(resultSet.getMetaData());
+      }
+      finally {
+        resultSet.close();
+      }
     }
     catch (SQLException e) {
-      throwSQLException(e, "get_meta_data");
+      throwSQLException(e, "acquireMetaData");
     }
     finally {
-      freeConnection(con, pstmt);
+      freeConnection(connection, statement);
     }
   }
 
-  public Connection getPooledCon() throws StorageObjectFailure {
-    Connection con = null;
-
+  public Connection obtainConnection() throws StorageObjectFailure {
     try {
-      con = SQLManager.getInstance().requestConnection();
+      return MirGlobal.getDatabaseEngine().obtainConnection();
     }
-    catch (SQLException e) {
-      logger.error("could not connect to the database " + e.getMessage());
-
-      throw new StorageObjectFailure("Could not connect to the database", e);
+    catch (Exception e) {
+      throw new StorageObjectFailure(e);
     }
-
-    return con;
   }
 
-  public void freeConnection(Connection con, Statement stmt)
-    throws StorageObjectFailure {
-    SQLManager.closeStatement(stmt);
-    SQLManager.getInstance().returnConnection(con);
+  public void freeConnection(Connection aConnection, Statement aStatement) throws StorageObjectFailure {
+    try {
+      aStatement.close();
+    }
+    catch (Throwable t) {
+      logger.warn("Can't close statemnet: " + t.toString());
+    }
+
+    try {
+      MirGlobal.getDatabaseEngine().releaseConnection(aConnection);
+    }
+    catch (Throwable t) {
+      logger.warn("Can't release connection: " + t.toString());
+    }
   }
 
   /**
@@ -1439,4 +1321,169 @@ public class Database implements StorageObject {
     logger.error(aMessage);
     throw new StorageObjectFailure(aMessage, null);
   }
+
+  /**
+   * 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 InputStream getBinaryField(String aQuery) throws StorageObjectFailure, SQLException {
+    Connection connection=null;
+    Statement statement=null;
+    InputStream inputStream;
+    InputStream imageInputStream = null;
+
+    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) {
+              byte[] data = resultSet.getBytes(1);
+              imageInputStream = new ByteArrayInputStream(data);
+            }
+            else {
+              inputStream = resultSet.getBlob(1).getBinaryStream();
+              imageInputStream = new BinaryFieldInputStream(inputStream, connection, statement);
+            }
+          }
+          resultSet.close();
+        }
+      }
+      finally {
+      }
+    }
+    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);
+    }
+
+    return imageInputStream;
+  }
+
+  /**
+   * 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 {
+    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);
+    }
+  }
+
+  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();
+  }
+
+
+  /**
+   * 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();
+    }
+  }
 }