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