count optimizaton moved
[mir.git] / source / mir / storage / Database.java
1 /*
2  * put your module comment here
3  */
4 package mir.storage;
5
6 import  java.sql.*;
7 import  java.lang.*;
8 import  java.io.*;
9 import  java.util.*;
10 import  freemarker.template.*;
11 import  com.javaexchange.dbConnectionBroker.*;
12 import  mir.storage.StorageObject;
13 import  mir.entity.*;
14 import  mir.misc.*;
15
16
17 /**
18  * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
19  * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
20  * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
21  * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
22  * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
23  * Datenbank erfolgt.
24  *
25  * @author RK
26  * @version 16.7.1999
27  */
28 public class Database implements StorageObject {
29
30   protected DbConnectionBroker        myBroker;
31   protected String                    theTable;
32   protected String                    theCoreTable=null;
33   protected String                    thePKeyName="id";
34   protected int                       thePKeyType;
35   protected boolean                   evaluatedMetaData=false;
36   protected ArrayList                 metadataFields,metadataLabels,metadataNotNullFields;
37   protected int[]                     metadataTypes;
38   protected Class                     theEntityClass;
39   protected StorageObject             myselfDatabase;
40   protected DatabaseCache             cache;
41   protected SimpleList                popupCache=null;
42   protected boolean                   hasPopupCache = false;
43   protected SimpleHash                hashCache=null;
44   protected boolean                   hasTimestamp=true;
45   private       String                database_driver;
46   private       String                database_url;
47   private int                         defaultLimit;
48   protected DatabaseAdaptor             theAdaptor;
49   protected Logfile                   theLog;
50
51   /**
52    * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
53    * Aus diesem file werden <code>Database.Logfile</code>,
54    * <code>Database.Username</code>,<code>Database.Password</code>,
55    * <code>Database.Host</code> und <code>Database.Adaptor</code>
56    * ausgelesen und ein Broker für die Verbindugen zur Datenbank
57    * erzeugt.
58    *
59    * @param   String confFilename Dateiname der Konfigurationsdatei
60    */
61   public Database() throws StorageObjectException {
62     theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
63     String database_username=MirConfig.getProp("Database.Username");
64     String database_password=MirConfig.getProp("Database.Password");
65     String database_host=MirConfig.getProp("Database.Host");
66     String theAdaptorName=MirConfig.getProp("Database.Adaptor");
67     try {
68       theEntityClass = Class.forName("mir.entity.GenericEntity");
69       theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
70       defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
71       database_driver=theAdaptor.getDriver();
72       database_url=theAdaptor.getURL(database_username,database_password,database_host);
73       theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url  );
74       MirConfig.addBroker(database_driver,database_url);
75       myBroker=MirConfig.getBroker();
76     }
77     catch (Exception e){
78       theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
79       throw new StorageObjectException(e.toString());
80     }
81   }
82
83   /**
84    * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
85    * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
86    * wird eine mir.entity.GenericEntity erzeugt.
87    *
88    * @return Class-Objekt der Entity
89    */
90   public java.lang.Class getEntityClass () {
91     return  theEntityClass;
92   }
93
94   /**
95    * Liefert die Standardbeschränkung von select-Statements zurück, also
96    * wieviel Datensätze per Default selektiert werden.
97    *
98    * @return Standard-Anzahl der Datensätze
99    */
100   public int getLimit () {
101     return  defaultLimit;
102   }
103
104   /**
105    * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
106    * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
107    * @return Name des Primary-Keys
108    */
109   public String getIdName () {
110     return  thePKeyName;
111   }
112
113   /**
114    * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
115    *
116    * @return Name der Tabelle
117    */
118   public String getTableName () {
119     return  theTable;
120   }
121
122   /*
123    *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
124    *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
125    *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
126    *    the Table
127    */
128
129   public String getCoreTable(){
130     if (theCoreTable!=null) return theCoreTable;
131     else return theTable;
132   }
133
134   /**
135    * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
136    * @return int-Array mit den Typen der Felder
137    * @exception StorageObjectException
138    */
139   public int[] getTypes () throws StorageObjectException {
140     if (metadataTypes == null)
141       get_meta_data();
142     return  metadataTypes;
143   }
144
145   /**
146    * Liefert eine Liste der Labels der Tabellenfelder
147    * @return ArrayListe mit Labeln
148    * @exception StorageObjectException
149    */
150   public ArrayList getLabels () throws StorageObjectException {
151     if (metadataLabels == null)
152       get_meta_data();
153     return  metadataLabels;
154   }
155
156   /**
157    * Liefert eine Liste der Felder der Tabelle
158    * @return ArrayList mit Feldern
159    * @exception StorageObjectException
160    */
161   public ArrayList getFields () throws StorageObjectException {
162     if (metadataFields == null)
163       get_meta_data();
164     return  metadataFields;
165   }
166
167
168   /*
169    *   Gets value out of ResultSet according to type and converts to String
170    *   @param inValue  Wert aus ResultSet.
171    *   @param aType  Datenbanktyp.
172    *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
173    *           dann /unsupported value/
174    */
175   private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
176     String outValue = null;
177     if (rs != null) {
178       try {
179         switch (aType) {
180           case java.sql.Types.BIT:
181             outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
182             break;
183           case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
184             int out = rs.getInt(valueIndex);
185             if (!rs.wasNull())
186               outValue = new Integer(out).toString();
187             break;
188           case java.sql.Types.NUMERIC:
189             long outl = rs.getLong(valueIndex);
190             if (!rs.wasNull())
191               outValue = new Long(outl).toString();
192             break;
193           case java.sql.Types.REAL:
194             float tempf = rs.getFloat(valueIndex);
195             if (!rs.wasNull()) {
196               tempf *= 10;
197               tempf += 0.5;
198               int tempf_int = (int)tempf;
199               tempf = (float)tempf_int;
200               tempf /= 10;
201               outValue = "" + tempf;
202               outValue = outValue.replace('.', ',');
203             }
204             break;
205           case java.sql.Types.DOUBLE:
206             double tempd = rs.getDouble(valueIndex);
207             if (!rs.wasNull()) {
208               tempd *= 10;
209               tempd += 0.5;
210               int tempd_int = (int)tempd;
211               tempd = (double)tempd_int;
212               tempd /= 10;
213               outValue = "" + tempd;
214               outValue = outValue.replace('.', ',');
215             }
216             break;
217           case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
218             outValue = rs.getString(valueIndex);
219             //if (outValue != null)
220               //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
221             break;
222           case java.sql.Types.LONGVARBINARY:
223             outValue = rs.getString(valueIndex);
224             //if (outValue != null)
225               //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
226             break;
227           case java.sql.Types.TIMESTAMP:
228             Timestamp timestamp = (rs.getTimestamp(valueIndex));
229             if (!rs.wasNull()) {
230               outValue = timestamp.toString();
231             }
232             break;
233           default:
234             outValue = "<unsupported value>";
235             theLog.printWarning("Unsupported Datatype: at " + valueIndex +
236                 " (" + aType + ")");
237         }
238       } catch (SQLException e) {
239         throw  new StorageObjectException("Could not get Value out of Resultset -- "
240             + e.toString());
241       }
242     }
243     return  outValue;
244   }
245
246   /*
247    *   select-Operator um einen Datensatz zu bekommen.
248    *   @param id Primaerschluessel des Datensatzes.
249    *   @return liefert EntityObject des gefundenen Datensatzes oder null.
250    */
251   public Entity selectById(String id)
252     throws StorageObjectException {
253
254     if (id==null||id.equals(""))
255       throw new StorageObjectException("id war null");
256     if (cache != null && (cache.containsKey(id) > -1))
257       return (Entity)cache.get(id);  // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
258
259     Statement stmt=null;Connection con=getPooledCon();
260     Entity returnEntity=null;
261     try {
262       ResultSet rs;
263       String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
264       stmt = con.createStatement();
265       rs = executeSql(stmt, selectSql);
266       if (rs != null) {
267         if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
268         if (rs.next())
269           returnEntity = makeEntityFromResultSet(rs);
270         else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
271         rs.close();
272       } else {
273         theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
274       }
275     } catch (SQLException sqe){
276       throwSQLException(sqe,"selectById"); return null;
277     } catch (NumberFormatException e) {
278       theLog.printError("ID ist keine Zahl: " + id);
279     } finally {
280       freeConnection(con,stmt);
281     }
282
283     return returnEntity;
284   }
285
286   /**
287    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
288    *   @param key  Datenbankfeld der Bedingung.
289    *   @param value  Wert die der key anehmen muss.
290    *   @return EntityList mit den gematchten Entities
291    */
292
293   public EntityList selectByFieldValue(String aField, String aValue)
294     throws StorageObjectException {
295
296     return selectByFieldValue(aField, aValue, 0);
297   }
298
299   /**
300    *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
301    *   @param key  Datenbankfeld der Bedingung.
302    *   @param value  Wert die der key anehmen muss.
303    *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
304    *   @return EntityList mit den gematchten Entities
305    */
306
307   public EntityList selectByFieldValue(String aField, String aValue, int offset)
308     throws StorageObjectException {
309
310     return selectByWhereClause(aField + "=" + aValue, offset);
311   }
312
313
314   /**
315    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
316    * Also offset wird der erste Datensatz genommen.
317    *
318    * @param wc where-Clause
319    * @return EntityList mit den gematchten Entities
320    * @exception StorageObjectException
321    */
322   public EntityList selectByWhereClause(String where)
323     throws StorageObjectException {
324
325     return selectByWhereClause(where, 0);
326   }
327
328
329   /**
330    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
331    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
332    *
333    * @param wc where-Clause
334    * @param offset ab welchem Datensatz.
335    * @return EntityList mit den gematchten Entities
336    * @exception StorageObjectException
337    */
338   public EntityList selectByWhereClause(String whereClause, int offset)
339     throws StorageObjectException {
340
341     return selectByWhereClause(whereClause, null, offset);
342   }
343
344   /**
345    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
346    * Also offset wird der erste Datensatz genommen.
347    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
348    *
349    * @param wc where-Clause
350    * @param ob orderBy-Clause
351    * @return EntityList mit den gematchten Entities
352    * @exception StorageObjectException
353    */
354
355   public EntityList selectByWhereClause(String where, String order)
356     throws StorageObjectException {
357
358     return selectByWhereClause(where, order, 0);
359   }
360   /**
361    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
362    * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
363    *
364    * @param wc where-Clause
365    * @param ob orderBy-Clause
366    * @param offset ab welchem Datensatz
367    * @return EntityList mit den gematchten Entities
368    * @exception StorageObjectException
369    */
370
371   public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
372     throws StorageObjectException {
373
374     return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
375   }
376
377
378   /**
379    * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
380    * @param wc where-Clause
381    * @param ob orderBy-Clause
382    * @param offset ab welchem Datensatz
383    * @param limit wieviele Datensätze
384    * @return EntityList mit den gematchten Entities
385    * @exception StorageObjectException
386    */
387
388   public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
389     throws StorageObjectException   {
390
391     // local
392     EntityList    theReturnList=null;
393     Connection    con=null;
394     Statement     stmt=null;
395     ResultSet     rs;
396     int       offsetCount = 0;
397     int           count=0;
398
399
400     // build sql-statement
401     if (wc != null && wc.length() == 0) {
402       wc = null;
403     }
404     StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
405     StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
406     if (wc != null) {
407       selectSql.append(" where ").append(wc);
408       countSql.append(" where ").append(wc);
409     }
410     if (ob != null && !(ob.length() == 0)) {
411       selectSql.append(" order by ").append(ob);
412     }
413     if (theAdaptor.hasLimit()) {
414       if (limit > -1 && offset > -1) {
415         selectSql.append(" limit ");
416         if (theAdaptor.reverseLimit()) {
417           selectSql.append(limit).append(",").append(offset);
418         }
419         else {
420           selectSql.append(offset).append(",").append(limit);
421         }
422       }
423     }
424
425       // execute sql
426     try {
427       con = getPooledCon();
428       stmt = con.createStatement();
429       // counting rows
430       if (theAdaptor.hasLimit()) {
431         rs = executeSql(stmt, countSql.toString());
432         if (rs != null) {
433           if (rs.next())
434             count = rs.getInt(1);
435           rs.close();
436           //nothing in the table: return null
437           if(count<=0){
438             freeConnection(con, stmt);
439             return null;
440           }
441         } else {
442           theLog.printError("Could not count: " + countSql);
443         }
444       }
445
446       // hier select
447       rs = executeSql(stmt, selectSql.toString());
448       if (rs != null) {
449         theReturnList = new EntityList();
450         if (evaluatedMetaData == false) {
451           evalMetaData(rs.getMetaData());
452         }
453         Entity theResultEntity;
454         while (rs.next()) {
455           theResultEntity = makeEntityFromResultSet(rs);
456           theReturnList.add(theResultEntity);
457           offsetCount++;
458         }
459         rs.close();
460       }
461       // making entitylist
462       if (!(theAdaptor.hasLimit()))
463         count = offsetCount;
464       if (theReturnList != null) {
465         theReturnList.setCount(count);
466         theReturnList.setOffset(offset);
467         theReturnList.setWhere(wc);
468         theReturnList.setOrder(ob);
469         if (offset >= limit) {
470           theReturnList.setPrevBatch(offset - limit);
471         }
472         if (offset + offsetCount < count) {
473           theReturnList.setNextBatch(offset + limit);
474         }
475       }
476     } catch (SQLException sqe) {
477       throwSQLException(sqe, "selectByWhereClause");
478     } finally {
479       freeConnection(con, stmt);
480     }
481     return  theReturnList;
482   }
483
484   /**
485    *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
486    *
487    *  @param rs Das ResultSetObjekt.
488    *  @return Entity Die Entity.
489    */
490
491   public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
492     HashMap theResultHash = new HashMap();
493     String theResult = null;
494     int theType;
495     Entity returnEntity = null;
496     try {
497       int size = metadataFields.size();
498       for (int i = 0; i < size; i++) {
499         // alle durchlaufen bis nix mehr da
500         theType = metadataTypes[i];
501         if (theType == java.sql.Types.LONGVARBINARY) {
502           InputStream us = rs.getAsciiStream(i + 1);
503           if (us != null) {
504             InputStreamReader is = new InputStreamReader(us);
505             char[] data = new char[32768];
506             StringBuffer theResultString = new StringBuffer();
507             int len;
508             while ((len = is.read(data)) > 0) {
509               theResultString.append(data, 0, len);
510             }
511             is.close();
512             theResult = theResultString.toString();
513           }
514           else {
515             theResult = null;
516           }
517         }
518         else {
519           theResult = getValueAsString(rs, (i + 1), theType);
520         }
521         if (theResult != null) {
522           theResultHash.put(metadataFields.get(i), theResult);
523         }
524       }
525       if (cache != null && theResultHash.containsKey(thePKeyName) &&
526             (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
527         //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
528         returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
529       }
530       else {
531         if (theEntityClass != null) {
532           returnEntity = (Entity)theEntityClass.newInstance();
533           returnEntity.setValues(theResultHash);
534           returnEntity.setStorage(myselfDatabase);
535           if (cache != null) {
536             //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
537             cache.put(returnEntity.getId(), returnEntity);
538           }
539         }
540         else {
541           throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
542         }
543       }
544     }           // try
545     catch (IllegalAccessException e) {
546       throwStorageObjectException("Kein Zugriff! -- " + e.toString());
547     } catch (IOException e) {
548       throwStorageObjectException("IOException! -- " + e.toString());
549     } catch (InstantiationException e) {
550       throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
551     } catch (SQLException sqe) {
552       throwSQLException(sqe, "makeEntityFromResultSet");
553       return  null;
554     }
555     return  returnEntity;
556   }
557
558   /**
559    * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
560    * wird automatisch mit dem aktuellen Datum gefuellt.
561    *
562    * @param theEntity
563    * @return der Wert des Primary-keys der eingefügten Entity
564    */
565   public String insert (Entity theEntity) throws StorageObjectException {
566     String returnId = null;
567     Connection con = null;
568     PreparedStatement pstmt = null;
569     //cache
570     invalidatePopupCache();
571     try {
572       ArrayList streamedInput = theEntity.streamedInput();
573       StringBuffer f = new StringBuffer();
574       StringBuffer v = new StringBuffer();
575       String aField, aValue;
576       boolean firstField = true;
577       // make sql-string
578       for (int i = 0; i < getFields().size(); i++) {
579         aField = (String)getFields().get(i);
580         if (!aField.equals(thePKeyName)) {
581           aValue = null;
582           // sonderfaelle
583           if (aField.equals("webdb_create")) {
584             aValue = "NOW()";
585           }
586           else {
587             if (streamedInput != null && streamedInput.contains(aField)) {
588               aValue = "?";
589             }
590             else {
591               if (theEntity.hasValueForField(aField)) {
592                 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
593                     + "'";
594               }
595             }
596           }
597           // wenn Wert gegeben, dann einbauen
598           if (aValue != null) {
599             if (firstField == false) {
600               f.append(",");
601               v.append(",");
602             }
603             else {
604               firstField = false;
605             }
606             f.append(aField);
607             v.append(aValue);
608           }
609         }
610       }         // end for
611       // insert into db
612       StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
613       String sql = sqlBuf.toString();
614       theLog.printInfo("INSERT: " + sql);
615       con = getPooledCon();
616       con.setAutoCommit(false);
617       pstmt = con.prepareStatement(sql);
618       if (streamedInput != null) {
619         for (int i = 0; i < streamedInput.size(); i++) {
620           String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
621           pstmt.setBytes(i + 1, inputString.getBytes());
622         }
623       }
624       int ret = pstmt.executeUpdate();
625       if(ret == 0){
626         //insert failed
627         return null;
628       }
629       pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
630       ResultSet rs = pstmt.executeQuery();
631       rs.next();
632       returnId = rs.getString(1);
633       theEntity.setId(returnId);
634     } catch (SQLException sqe) {
635       throwSQLException(sqe, "insert");
636     } finally {
637       try {
638         con.setAutoCommit(true);
639       } catch (Exception e) {
640         ;
641       }
642       freeConnection(con, pstmt);
643     }
644     return  returnId;
645   }
646
647   /**
648    * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
649    * wird automatisch mit dem aktuellen Datum gefuellt.
650    *
651    * @param theEntity
652    */
653   public void update (Entity theEntity) throws StorageObjectException {
654     Connection con = null;
655     PreparedStatement pstmt = null;
656     ArrayList streamedInput = theEntity.streamedInput();
657     String id = theEntity.getId();
658     String aField;
659     StringBuffer fv = new StringBuffer();
660     boolean firstField = true;
661     //cache
662     invalidatePopupCache();
663     // build sql statement
664     for (int i = 0; i < getFields().size(); i++) {
665       aField = (String)metadataFields.get(i);
666       // only normal cases
667       if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
668           aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
669         if (theEntity.hasValueForField(aField)) {
670           if (firstField == false) {
671             fv.append(", ");
672           }
673           else {
674             firstField = false;
675           }
676           fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
677         }
678       }
679     }
680     StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
681     // exceptions
682     if (metadataFields.contains("webdb_lastchange")) {
683       sql.append(",webdb_lastchange=NOW()");
684     }
685     if (streamedInput != null) {
686       for (int i = 0; i < streamedInput.size(); i++) {
687         sql.append(",").append(streamedInput.get(i)).append("=?");
688       }
689     }
690     sql.append(" where id=").append(id);
691     theLog.printInfo("UPDATE: " + sql);
692     // execute sql
693     try {
694       con = getPooledCon();
695       con.setAutoCommit(false);
696       pstmt = con.prepareStatement(sql.toString());
697       if (streamedInput != null) {
698         for (int i = 0; i < streamedInput.size(); i++) {
699           String inputString = theEntity.getValue((String)streamedInput.get(i));
700           pstmt.setBytes(i + 1, inputString.getBytes());
701         }
702       }
703       pstmt.executeUpdate();
704     } catch (SQLException sqe) {
705       throwSQLException(sqe, "update");
706     } finally {
707       try {
708         con.setAutoCommit(true);
709       } catch (Exception e) {
710         ;
711       }
712       freeConnection(con, pstmt);
713     }
714   }
715
716   /*
717    *   delete-Operator
718    *   @param id des zu loeschenden Datensatzes
719    *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
720    */
721   public boolean delete (String id) throws StorageObjectException {
722     Statement stmt = null;
723     Connection con = null;
724     String sql;
725     int res = 0;
726     // loeschen des caches
727     invalidatePopupCache();
728     sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
729         "'";
730     theLog.printInfo("DELETE " + sql);
731     try {
732       con = getPooledCon();
733       stmt = con.createStatement();
734       res = stmt.executeUpdate(sql);
735     } catch (SQLException sqe) {
736       throwSQLException(sqe, "delete");
737     } finally {
738       freeConnection(con, stmt);
739     }
740     if (cache != null) {
741       theLog.printInfo("CACHE: deleted " + id);
742       cache.remove(id);
743     }
744     return  (res > 0) ? true : false;
745   }
746
747   /* noch nicht implementiert.
748    * @return immer false
749    */
750   public boolean delete (EntityList theEntityList) {
751     invalidatePopupCache();
752     return  false;
753   }
754
755   /**
756    * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
757    * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
758    * @return null
759    */
760   public SimpleList getPopupData () throws StorageObjectException {
761     return  null;
762   }
763
764   /**
765    *  Holt Daten fuer Popups.
766    *  @param name  Name des Feldes.
767    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
768    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
769    */
770   public SimpleList getPopupData (String name, boolean hasNullValue)
771     throws StorageObjectException {
772     return  getPopupData(name, hasNullValue, null);
773   }
774
775   /**
776    *  Holt Daten fuer Popups.
777    *  @param name  Name des Feldes.
778    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
779    *  @param where  Schraenkt die Selektion der Datensaetze ein.
780    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
781    */
782   public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
783    return  getPopupData(name, hasNullValue, where, null);
784   }
785
786   /**
787    *  Holt Daten fuer Popups.
788    *  @param name  Name des Feldes.
789    *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
790    *  @param where  Schraenkt die Selektion der Datensaetze ein.
791    *  @param order  Gibt ein Feld als Sortierkriterium an.
792    *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
793    */
794   public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
795     // caching
796     if (hasPopupCache && popupCache != null)
797       return  popupCache;
798     SimpleList simpleList = null;
799     Connection con = null;
800     Statement stmt = null;
801     // build sql
802     StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
803     if (where != null && !(where.length() == 0))
804       sql.append(" where ").append(where);
805     sql.append(" order by ");
806     if (order != null && !(order.length() == 0))
807       sql.append(order);
808     else
809       sql.append(name);
810     // execute sql
811     try {
812       con = getPooledCon();
813       stmt = con.createStatement();
814       ResultSet rs = executeSql(stmt, sql.toString());
815       if (rs != null) {
816         if (evaluatedMetaData == false)
817           get_meta_data();
818         simpleList = new SimpleList();
819         SimpleHash popupDict;
820         if (hasNullValue) {
821           popupDict = new SimpleHash();
822           popupDict.put("key", "");
823           popupDict.put("value", "--");
824           simpleList.add(popupDict);
825         }
826         while (rs.next()) {
827           popupDict = new SimpleHash();
828           popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
829           popupDict.put("value", rs.getString(2));
830           simpleList.add(popupDict);
831         }
832         rs.close();
833       }
834     } catch (Exception e) {
835       theLog.printDebugInfo(e.toString());
836       throw new StorageObjectException(e.toString());
837     } finally {
838       freeConnection(con, stmt);
839     }
840     if (hasPopupCache) {
841       popupCache = simpleList;
842     }
843     return  simpleList;
844   }
845
846   /**
847    * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
848    * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
849    * Tabellen Verwendung finden.
850    * @return SimpleHash mit den Tabellezeilen.
851    */
852   public SimpleHash getHashData () {
853     if (hashCache == null) {
854       try {
855         hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
856             -1));
857       } catch (StorageObjectException e) {
858         theLog.printDebugInfo(e.toString());
859       }
860     }
861     return  hashCache;
862   }
863
864   /* invalidates the popupCache
865    */
866   protected void invalidatePopupCache () {
867
868     /** @todo  invalidates toooo much */
869     popupCache = null;
870     hashCache = null;
871   }
872
873   /**
874    * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
875    * @param stmt Statemnt
876    * @param sql Sql-String
877    * @return ResultSet
878    * @exception StorageObjectException
879    */
880   public ResultSet executeSql (Statement stmt, String sql)
881     throws StorageObjectException, SQLException
882   {
883     ResultSet rs;
884     long startTime = (new java.util.Date()).getTime();
885     try {
886       rs = stmt.executeQuery(sql);
887       theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
888         + sql);
889     }
890     catch (SQLException e)
891     {
892       theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
893         + sql);
894       throw e;
895     }
896
897     return  rs;
898   }
899
900   /**
901    * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
902    * getimed und geloggt.
903    * @param stmt PreparedStatement mit der SQL-Anweisung
904    * @return Liefert ResultSet des Statements zurueck.
905    * @exception StorageObjectException, SQLException
906    */
907   public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
908       SQLException {
909
910     long startTime = (new java.util.Date()).getTime();
911     ResultSet rs = stmt.executeQuery();
912     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
913     return  rs;
914   }
915
916     /**
917    * returns the number of rows in the table
918    */
919   public int getSize(String where)
920     throws SQLException,StorageObjectException
921   {
922     long  startTime = (new java.util.Date()).getTime();
923     String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
924     //theLog.printDebugInfo("trying: "+ sql);
925     Connection con = null;
926     Statement stmt = null;
927     int result = 0;
928
929     try {
930       con = getPooledCon();
931       stmt = con.createStatement();
932       ResultSet rs = executeSql(stmt,sql);
933       while(rs.next()){
934         result = rs.getInt(1);
935       }
936     } catch (SQLException e) {
937       theLog.printError(e.toString());
938     } finally {
939       freeConnection(con,stmt);
940     }
941     theLog.printInfo(theTable + " has "+ result +" rows where " + where);
942     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
943     return result;
944   }
945
946   public int executeUpdate(Statement stmt, String sql)
947     throws StorageObjectException, SQLException
948   {
949     int rs;
950     long  startTime = (new java.util.Date()).getTime();
951     try
952     {
953       rs = stmt.executeUpdate(sql);
954       theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
955     }
956     catch (SQLException e)
957     {
958       theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
959         + sql);
960       throw e;
961     }
962     return rs;
963   }
964
965   public int executeUpdate(String sql)
966     throws StorageObjectException, SQLException
967   {
968     int result=-1;
969     long  startTime = (new java.util.Date()).getTime();
970     Connection con=null;PreparedStatement pstmt=null;
971     try {
972       con=getPooledCon();
973       pstmt = con.prepareStatement(sql);
974       result = pstmt.executeUpdate();
975     }
976     catch (Exception e) {
977       theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
978       throw new StorageObjectException("executeUpdate failed: "+e.toString());
979     }
980     finally { freeConnection(con,pstmt); }
981     theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
982     return result;
983   }
984
985   /**
986    * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
987    * @param md ResultSetMetaData
988    * @exception StorageObjectException
989    */
990   private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
991     this.evaluatedMetaData = true;
992     this.metadataFields = new ArrayList();
993     this.metadataLabels = new ArrayList();
994     this.metadataNotNullFields = new ArrayList();
995     try {
996       int numFields = md.getColumnCount();
997       this.metadataTypes = new int[numFields];
998       String aField;
999       int aType;
1000       for (int i = 1; i <= numFields; i++) {
1001         aField = md.getColumnName(i);
1002         metadataFields.add(aField);
1003         metadataLabels.add(md.getColumnLabel(i));
1004         aType = md.getColumnType(i);
1005         metadataTypes[i - 1] = aType;
1006         if (aField.equals(thePKeyName)) {
1007           thePKeyType = aType;
1008         }
1009         if (md.isNullable(i) == md.columnNullable) {
1010           metadataNotNullFields.add(aField);
1011         }
1012       }
1013     } catch (SQLException e) {
1014       throwSQLException(e, "evalMetaData");
1015     }
1016   }
1017
1018   /**
1019    *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1020    *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1021    */
1022   private void get_meta_data () throws StorageObjectException {
1023     Connection con = null;
1024     PreparedStatement pstmt = null;
1025     String sql = "select * from " + theTable + " where 0=1";
1026     try {
1027       con = getPooledCon();
1028       pstmt = con.prepareStatement(sql);
1029       theLog.printInfo("METADATA: " + sql);
1030       ResultSet rs = pstmt.executeQuery();
1031       evalMetaData(rs.getMetaData());
1032       rs.close();
1033     } catch (SQLException e) {
1034       throwSQLException(e, "get_meta_data");
1035     } finally {
1036       freeConnection(con, pstmt);
1037     }
1038   }
1039
1040   /**
1041    * Datenbankverbindung wird geschlossen
1042    */
1043   public void disconnectPool () throws StorageObjectException {
1044     try {
1045       myBroker.destroy(100);
1046     } catch (SQLException sqe) {
1047       throwSQLException(sqe, "disconnectPool");
1048     }
1049   }
1050
1051   /**
1052    * Returns Connection-Object out of the PoolBroker.
1053    *
1054    * @return Connection Object.
1055    */
1056   public Connection getPooledCon () throws StorageObjectException {
1057     if (myBroker != null) {
1058       Connection con = myBroker.getConnection();
1059       if (con != null)
1060         return  con;
1061     }
1062     throw  new StorageObjectException("No connection to database!");
1063   }
1064
1065   /**
1066    * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1067    * zurückgeben
1068    * @param con Connection zur Datenbank
1069    * @param stmt Statement-Objekt
1070    */
1071   public void freeConnection (Connection con, Statement stmt)
1072     throws StorageObjectException {
1073     try {
1074       if (stmt != null)
1075         stmt.close();
1076     } catch (SQLException e1) {
1077       theLog.printDebugInfo(e1.toString());
1078       throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1079     }
1080     if (con != null)
1081       myBroker.freeConnection(con);
1082     else {
1083       theLog.printDebugInfo("Con was null!");
1084       throw new StorageObjectException("Con was null!");
1085     }
1086   }
1087
1088   /**
1089    * Wertet SQLException aus und wirft dannach eine StorageObjectException
1090    * @param sqe SQLException
1091    * @param wo Funktonsname, in der die SQLException geworfen wurde
1092    * @exception StorageObjectException
1093    */
1094   protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1095     String state = "";
1096     String message = "";
1097     int vendor = 0;
1098     if (sqe != null) {
1099       state = sqe.getSQLState();
1100       message = sqe.getMessage();
1101       vendor = sqe.getErrorCode();
1102     }
1103     theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1104         + wo);
1105     throw  new StorageObjectException((sqe == null) ? "undefined sql exception" :
1106         sqe.toString());
1107   }
1108
1109   protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1110     if (e != null) {
1111         theLog.printError(e.toString()+ wo);
1112         throw  new StorageObjectException(wo + e.toString());
1113     } else {
1114         theLog.printError(wo);
1115         throw  new StorageObjectException(wo);
1116     }
1117
1118   }
1119
1120   /**
1121    * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1122    * @param message Nachricht mit dem Fehler
1123    * @exception StorageObjectException
1124    */
1125   void throwStorageObjectException (String message) throws StorageObjectException {
1126     _throwStorageObjectException(null, message);
1127   }
1128
1129 }
1130
1131
1132