update new style :)
[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.GenericEntity");
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                                                 if (!rs.wasNull()) {
257                                                         outValue = timestamp.toString();
258                                                 }
259                                                 break;
260                                         default:
261                                                 outValue = "<unsupported value>";
262                                                 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
263                                                                 " (" + aType + ")");
264                                 }
265                         } catch (SQLException e) {
266                                 throw  new StorageObjectException("Could not get Value out of Resultset -- "
267                                                 + e.toString());
268                         }
269                 }
270                 return  outValue;
271         }
272
273         /*
274          *   select-Operator um einen Datensatz zu bekommen.
275          *   @param id Primaerschluessel des Datensatzes.
276          *   @return liefert EntityObject des gefundenen Datensatzes oder null.
277          */
278         public Entity selectById(String id)     throws StorageObjectException
279   {
280                 if (id==null||id.equals(""))
281                         throw new StorageObjectException("id war null");
282
283     // ask object store for object
284     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
285       String uniqueId = id;
286       if ( theEntityClass.equals(StorableObjectEntity.class) )
287         uniqueId+="@"+theTable;
288       StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
289       theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
290       Entity hit = (Entity)o_store.use(search_sid);
291       if ( hit!=null ) return hit;
292     }
293
294                 Statement stmt=null;Connection con=getPooledCon();
295                 Entity returnEntity=null;
296                 try {
297                         ResultSet rs;
298                         /** @todo better prepared statement */
299                         String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
300                         stmt = con.createStatement();
301                         rs = executeSql(stmt, selectSql);
302                         if (rs != null) {
303                                 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
304                                 if (rs.next())
305                                         returnEntity = makeEntityFromResultSet(rs);
306                                 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
307                                 rs.close();
308                         }
309                         else {
310                                 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
311                         }
312                 }
313                 catch (SQLException sqe){
314                         throwSQLException(sqe,"selectById"); return null;
315                 }
316                 catch (NumberFormatException e) {
317                         theLog.printError("ID ist keine Zahl: " + id);
318                 }
319                 finally { freeConnection(con,stmt); }
320
321                 /** @todo OS: Entity should be saved in ostore */
322                 return returnEntity;
323         }
324
325
326         /**
327          *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
328          *   @param key  Datenbankfeld der Bedingung.
329          *   @param value  Wert die der key anehmen muss.
330          *   @return EntityList mit den gematchten Entities
331          */
332         public EntityList selectByFieldValue(String aField, String aValue)
333                 throws StorageObjectException
334         {
335                 return selectByFieldValue(aField, aValue, 0);
336         }
337
338         /**
339          *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
340          *   @param key  Datenbankfeld der Bedingung.
341          *   @param value  Wert die der key anehmen muss.
342          *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
343          *   @return EntityList mit den gematchten Entities
344          */
345         public EntityList selectByFieldValue(String aField, String aValue, int offset)
346                 throws StorageObjectException
347         {
348                 return selectByWhereClause(aField + "=" + aValue, offset);
349         }
350
351
352         /**
353          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
354          * Also offset wird der erste Datensatz genommen.
355          *
356          * @param wc where-Clause
357          * @return EntityList mit den gematchten Entities
358          * @exception StorageObjectException
359          */
360         public EntityList selectByWhereClause(String where)
361                 throws StorageObjectException
362         {
363                 return selectByWhereClause(where, 0);
364         }
365
366
367         /**
368          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
369          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
370          *
371          * @param wc where-Clause
372          * @param offset ab welchem Datensatz.
373          * @return EntityList mit den gematchten Entities
374          * @exception StorageObjectException
375          */
376         public EntityList selectByWhereClause(String whereClause, int offset)
377                 throws StorageObjectException
378         {
379                 return selectByWhereClause(whereClause, null, offset);
380         }
381
382
383         /**
384          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
385          * Also offset wird der erste Datensatz genommen.
386          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
387          *
388          * @param wc where-Clause
389          * @param ob orderBy-Clause
390          * @return EntityList mit den gematchten Entities
391          * @exception StorageObjectException
392          */
393
394         public EntityList selectByWhereClause(String where, String order)
395                 throws StorageObjectException {
396                 return selectByWhereClause(where, order, 0);
397         }
398
399
400         /**
401          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
402          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
403          *
404          * @param wc where-Clause
405          * @param ob orderBy-Clause
406          * @param offset ab welchem Datensatz
407          * @return EntityList mit den gematchten Entities
408          * @exception StorageObjectException
409          */
410
411         public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
412                 throws StorageObjectException {
413                 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
414         }
415
416
417         /**
418          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
419          * @param wc where-Clause
420          * @param ob orderBy-Clause
421          * @param offset ab welchem Datensatz
422          * @param limit wieviele Datensätze
423          * @return EntityList mit den gematchten Entities
424          * @exception StorageObjectException
425          */
426
427         public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
428                 throws StorageObjectException
429   {
430
431     // check o_store for entitylist
432     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
433       StoreIdentifier search_sid =
434         new StoreIdentifier( theEntityClass,
435                              StoreContainerType.STOC_TYPE_ENTITYLIST,
436                              StoreUtil.getEntityListUniqueIdentifierFor(wc,ob,offset,limit) );
437       EntityList hit = (EntityList)o_store.use(search_sid);
438       if ( hit!=null ) {
439         theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
440         return hit;
441       }
442     }
443
444                 // local
445                 EntityList    theReturnList=null;
446                 Connection    con=null; Statement stmt=null;
447                 ResultSet     rs;
448                 int           offsetCount = 0, count=0;
449
450                 // build sql-statement
451
452                 /** @todo count sql string should only be assembled if we really count
453                  *  see below at the end of method //rk */
454
455                 if (wc != null && wc.length() == 0) {
456                         wc = null;
457                 }
458                 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
459                 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
460                 if (wc != null) {
461                         selectSql.append(" where ").append(wc);
462                         countSql.append(" where ").append(wc);
463                 }
464                 if (ob != null && !(ob.length() == 0)) {
465                         selectSql.append(" order by ").append(ob);
466                 }
467                 if (theAdaptor.hasLimit()) {
468                         if (limit > -1 && offset > -1) {
469                                 selectSql.append(" limit ");
470                                 if (theAdaptor.reverseLimit()) {
471                                         selectSql.append(limit).append(",").append(offset);
472                                 }
473                                 else {
474                                         selectSql.append(offset).append(",").append(limit);
475                                 }
476                         }
477                 }
478
479                 // execute sql
480                 try {
481                         con = getPooledCon();
482                         stmt = con.createStatement();
483
484                         // selecting...
485                         rs = executeSql(stmt, selectSql.toString());
486                         if (rs != null) {
487                                 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
488
489                                 theReturnList = new EntityList();
490                                 Entity theResultEntity;
491                                 while (rs.next()) {
492                                         theResultEntity = makeEntityFromResultSet(rs);
493                                         theReturnList.add(theResultEntity);
494                                         offsetCount++;
495                                 }
496                                 rs.close();
497                         }
498
499                         // making entitylist infos
500                         if (!(theAdaptor.hasLimit())) count = offsetCount;
501
502                         if (theReturnList != null) {
503                                 // now we decide if we have to know an overall count...
504                                 count=offsetCount;
505                                 if (limit > -1 && offset > -1) {
506                                         if (offsetCount==limit) {
507                                                 /** @todo counting should be deffered to entitylist
508                                                  *  getSize() should be used */
509                                                 rs = executeSql(stmt, countSql.toString());
510                                                 if (rs != null) {
511                                                         if ( rs.next() ) count = rs.getInt(1);
512                                                         rs.close();
513                                                 }
514                                                 else theLog.printError("Could not count: " + countSql);
515                                         }
516                                 }
517                                 theReturnList.setCount(count);
518                                 theReturnList.setOffset(offset);
519                                 theReturnList.setWhere(wc);
520                                 theReturnList.setOrder(ob);
521         theReturnList.setEntityClass(theEntityClass);
522         theReturnList.setLimit(limit);
523                                 if ( offset >= limit )
524                                         theReturnList.setPrevBatch(offset - limit);
525                                 if ( offset+offsetCount < count )
526                                         theReturnList.setNextBatch(offset + limit);
527         if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
528           StoreIdentifier sid=theReturnList.getStoreIdentifier();
529           theLog.printDebugInfo("CACHE (add): " + sid.toString());
530           o_store.add(sid);
531         }
532                         }
533                 }
534                 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
535                 finally { freeConnection(con, stmt); }
536
537                 return  theReturnList;
538         }
539
540
541         /**
542          *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
543          *
544          *  @param rs Das ResultSetObjekt.
545          *  @return Entity Die Entity.
546          */
547         private Entity makeEntityFromResultSet (ResultSet rs)
548                 throws StorageObjectException
549         {
550                 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
551                 HashMap theResultHash = new HashMap();
552                 String theResult = null;
553                 int theType;
554                 Entity returnEntity = null;
555                 try {
556                         int size = metadataFields.size();
557                         for (int i = 0; i < size; i++) {
558                                 // alle durchlaufen bis nix mehr da
559                                 theType = metadataTypes[i];
560                                 if (theType == java.sql.Types.LONGVARBINARY) {
561                                         InputStream us = rs.getAsciiStream(i + 1);
562                                         if (us != null) {
563                                                 InputStreamReader is = new InputStreamReader(us);
564                                                 char[] data = new char[32768];
565                                                 StringBuffer theResultString = new StringBuffer();
566                                                 int len;
567                                                 while ((len = is.read(data)) > 0) {
568                                                         theResultString.append(data, 0, len);
569                                                 }
570                                                 is.close();
571                                                 theResult = theResultString.toString();
572                                         }
573                                         else {
574                                                 theResult = null;
575                                         }
576                                 }
577                                 else {
578                                         theResult = getValueAsString(rs, (i + 1), theType);
579                                 }
580                                 if (theResult != null) {
581                                         theResultHash.put(metadataFields.get(i), theResult);
582                                 }
583                         }
584       if (theEntityClass != null) {
585         returnEntity = (Entity)theEntityClass.newInstance();
586         returnEntity.setValues(theResultHash);
587         returnEntity.setStorage(myselfDatabase);
588         if ( returnEntity instanceof StorableObject ) {
589           theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
590           o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
591         }
592       } else {
593         throwStorageObjectException("Internal Error: theEntityClass not set!");
594       }
595                 } catch (IllegalAccessException e) {
596                         throwStorageObjectException("Kein Zugriff! -- " + e.toString());
597                 } catch (IOException e) {
598                         throwStorageObjectException("IOException! -- " + e.toString());
599                 } catch (InstantiationException e) {
600                         throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
601                 } catch (SQLException sqe) {
602                         throwSQLException(sqe, "makeEntityFromResultSet");
603                         return  null;
604                 }
605                 return  returnEntity;
606         }
607
608         /**
609          * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
610          * wird automatisch mit dem aktuellen Datum gefuellt.
611          *
612          * @param theEntity
613          * @return der Wert des Primary-keys der eingefügten Entity
614          */
615         public String insert (Entity theEntity) throws StorageObjectException {
616                 String returnId = null;
617                 Connection con = null;
618                 PreparedStatement pstmt = null;
619                 //cache
620                 invalidatePopupCache();
621                 /** @todo OS: if Entity is StorableObject, invalidate in ObjectStore
622                  *  careful: Entity has no id yet! */
623                 try {
624                         ArrayList streamedInput = theEntity.streamedInput();
625                         StringBuffer f = new StringBuffer();
626                         StringBuffer v = new StringBuffer();
627                         String aField, aValue;
628                         boolean firstField = true;
629                         // make sql-string
630                         for (int i = 0; i < getFields().size(); i++) {
631                                 aField = (String)getFields().get(i);
632                                 if (!aField.equals(thePKeyName)) {
633                                         aValue = null;
634                                         // sonderfaelle
635                                         if (aField.equals("webdb_create")) {
636                                                 aValue = "NOW()";
637                                         }
638                                         else {
639                                                 if (streamedInput != null && streamedInput.contains(aField)) {
640                                                         aValue = "?";
641                                                 }
642                                                 else {
643                                                         if (theEntity.hasValueForField(aField)) {
644                                                                 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
645                                                                                 + "'";
646                                                         }
647                                                 }
648                                         }
649                                         // wenn Wert gegeben, dann einbauen
650                                         if (aValue != null) {
651                                                 if (firstField == false) {
652                                                         f.append(",");
653                                                         v.append(",");
654                                                 }
655                                                 else {
656                                                         firstField = false;
657                                                 }
658                                                 f.append(aField);
659                                                 v.append(aValue);
660                                         }
661                                 }
662                         }         // end for
663                         // insert into db
664                         StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
665                         String sql = sqlBuf.toString();
666                         theLog.printInfo("INSERT: " + sql);
667                         con = getPooledCon();
668                         con.setAutoCommit(false);
669                         pstmt = con.prepareStatement(sql);
670                         if (streamedInput != null) {
671                                 for (int i = 0; i < streamedInput.size(); i++) {
672                                         String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
673                                         pstmt.setBytes(i + 1, inputString.getBytes());
674                                 }
675                         }
676                         int ret = pstmt.executeUpdate();
677                         if(ret == 0){
678                                 //insert failed
679                                 return null;
680                         }
681                         pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
682                         ResultSet rs = pstmt.executeQuery();
683                         rs.next();
684                         returnId = rs.getString(1);
685                         theEntity.setId(returnId);
686                 } catch (SQLException sqe) {
687                         throwSQLException(sqe, "insert");
688                 } finally {
689                         try {
690                                 con.setAutoCommit(true);
691                         } catch (Exception e) {
692                                 ;
693                         }
694                         freeConnection(con, pstmt);
695                 }
696                 return  returnId;
697         }
698
699         /**
700          * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
701          * wird automatisch mit dem aktuellen Datum gefuellt.
702          *
703          * @param theEntity
704          */
705         public void update (Entity theEntity) throws StorageObjectException
706   {
707                 Connection con = null; PreparedStatement pstmt = null;
708                 /** @todo this is stupid: why do we prepare statement, when we
709                  *  throw it away afterwards. should be regular statement
710                  *  update/insert could better be one routine called save()
711                  *  that chooses to either insert or update depending if we
712                  *  have a primary key in the entity. i don't know if we
713                  *  still need the streamed input fields. // rk  */
714
715                 /** @todo extension: check if Entity did change, otherwise we don't need */
716                 /** @todo OS: invalidate in Ostore if Entity is StorableObject */
717
718                 ArrayList streamedInput = theEntity.streamedInput();
719                 String id = theEntity.getId();
720                 String aField;
721                 StringBuffer fv = new StringBuffer();
722                 boolean firstField = true;
723                 //cache
724                 invalidatePopupCache();
725                 // build sql statement
726                 for (int i = 0; i < getFields().size(); i++) {
727                         aField = (String)metadataFields.get(i);
728                         // only normal cases
729                         if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
730                                         aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
731                                 if (theEntity.hasValueForField(aField)) {
732                                         if (firstField == false) {
733                                                 fv.append(", ");
734                                         }
735                                         else {
736                                                 firstField = false;
737                                         }
738                                         fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
739                                 }
740                         }
741                 }
742                 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
743                 // exceptions
744                 if (metadataFields.contains("webdb_lastchange")) {
745                         sql.append(",webdb_lastchange=NOW()");
746                 }
747                 if (streamedInput != null) {
748                         for (int i = 0; i < streamedInput.size(); i++) {
749                                 sql.append(",").append(streamedInput.get(i)).append("=?");
750                         }
751                 }
752                 sql.append(" where id=").append(id);
753                 theLog.printInfo("UPDATE: " + sql);
754                 // execute sql
755                 try {
756                         con = getPooledCon();
757                         con.setAutoCommit(false);
758                         pstmt = con.prepareStatement(sql.toString());
759                         if (streamedInput != null) {
760                                 for (int i = 0; i < streamedInput.size(); i++) {
761                                         String inputString = theEntity.getValue((String)streamedInput.get(i));
762                                         pstmt.setBytes(i + 1, inputString.getBytes());
763                                 }
764                         }
765                         pstmt.executeUpdate();
766                 } catch (SQLException sqe) {
767                         throwSQLException(sqe, "update");
768                 } finally {
769                         try {
770                                 con.setAutoCommit(true);
771                         } catch (Exception e) {
772                                 ;
773                         }
774                         freeConnection(con, pstmt);
775                 }
776         }
777
778         /*
779          *   delete-Operator
780          *   @param id des zu loeschenden Datensatzes
781          *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
782          */
783         public boolean delete (String id) throws StorageObjectException {
784
785                 invalidatePopupCache();
786     // ostore send notification
787     if (StoreUtil.implementsStorableObject(theEntityClass) ) {
788                         theLog.printInfo("CACHE: (del) " + id);
789                         StoreIdentifier search_sid =
790         new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, id);
791       o_store.invalidate(search_sid);
792                 }
793
794                 /** @todo could be prepared Statement */
795                 Statement stmt = null; Connection con = null;
796                 int res = 0;
797                 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
798                 theLog.printInfo("DELETE " + sql);
799                 try {
800                         con = getPooledCon(); stmt = con.createStatement();
801                         res = stmt.executeUpdate(sql);
802                 }
803     catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
804     finally { freeConnection(con, stmt); }
805
806                 return  (res > 0) ? true : false;
807         }
808
809         /* noch nicht implementiert.
810          * @return immer false
811          */
812         public boolean delete (EntityList theEntityList) {
813                 invalidatePopupCache();
814                 return  false;
815         }
816
817         /**
818          * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
819          * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
820          * @return null
821          */
822         public SimpleList getPopupData () throws StorageObjectException {
823                 return  null;
824         }
825
826         /**
827          *  Holt Daten fuer Popups.
828          *  @param name  Name des Feldes.
829          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
830          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
831          */
832         public SimpleList getPopupData (String name, boolean hasNullValue)
833                 throws StorageObjectException {
834                 return  getPopupData(name, hasNullValue, null);
835         }
836
837         /**
838          *  Holt Daten fuer Popups.
839          *  @param name  Name des Feldes.
840          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
841          *  @param where  Schraenkt die Selektion der Datensaetze ein.
842          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
843          */
844         public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
845          return  getPopupData(name, hasNullValue, where, null);
846         }
847
848         /**
849          *  Holt Daten fuer Popups.
850          *  @param name  Name des Feldes.
851          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
852          *  @param where  Schraenkt die Selektion der Datensaetze ein.
853          *  @param order  Gibt ein Feld als Sortierkriterium an.
854          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
855          */
856         public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
857                 // caching
858                 if (hasPopupCache && popupCache != null)
859                         return  popupCache;
860                 SimpleList simpleList = null;
861                 Connection con = null;
862                 Statement stmt = null;
863                 // build sql
864                 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
865                                                                                                                                                                 .append(",").append(name).append(" from ")
866                                                                                                                                                                 .append(theTable);
867                 if (where != null && !(where.length() == 0))
868                         sql.append(" where ").append(where);
869                 sql.append(" order by ");
870                 if (order != null && !(order.length() == 0))
871                         sql.append(order);
872                 else
873                         sql.append(name);
874                 // execute sql
875                 try {
876                         con = getPooledCon();
877                 } catch (Exception e) {
878                         throw new StorageObjectException(e.toString());
879                 }
880                 try {
881                         stmt = con.createStatement();
882                         ResultSet rs = executeSql(stmt, sql.toString());
883
884                         if (rs != null) {
885                                 if (!evaluatedMetaData) get_meta_data();
886                                 simpleList = new SimpleList();
887                                 // if popup has null-selector
888                                 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
889
890                                 SimpleHash popupDict;
891                                 while (rs.next()) {
892                                         popupDict = new SimpleHash();
893                                         popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
894                                         popupDict.put("value", rs.getString(2));
895                                         simpleList.add(popupDict);
896                                 }
897                                 rs.close();
898                         }
899                 } catch (Exception e) {
900                         theLog.printError("getPopupData: "+e.toString());
901                         throw new StorageObjectException(e.toString());
902                 } finally {
903                         freeConnection(con, stmt);
904                 }
905
906                 if (hasPopupCache) popupCache = simpleList;
907                 return  simpleList;
908         }
909
910         /**
911          * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
912          * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
913          * Tabellen Verwendung finden.
914          * @return SimpleHash mit den Tabellezeilen.
915          */
916         public SimpleHash getHashData () {
917                 /** @todo dangerous! this should have a flag to be enabled, otherwise
918                  *  very big Hashes could be returned */
919                 if (hashCache == null) {
920                         try {
921                                 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
922                                                 -1));
923                         } catch (StorageObjectException e) {
924                                 theLog.printDebugInfo(e.toString());
925                         }
926                 }
927                 return  hashCache;
928         }
929
930         /* invalidates the popupCache
931          */
932         protected void invalidatePopupCache () {
933                 /** @todo  invalidates toooo much */
934                 popupCache = null;
935                 hashCache = null;
936         }
937
938         /**
939          * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
940          * @param stmt Statemnt
941          * @param sql Sql-String
942          * @return ResultSet
943          * @exception StorageObjectException
944          */
945         public ResultSet executeSql (Statement stmt, String sql)
946                 throws StorageObjectException, SQLException
947         {
948                 long startTime = System.currentTimeMillis();
949                 ResultSet rs;
950                 try {
951                         rs = stmt.executeQuery(sql);
952                         theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
953                                 + sql);
954                 }
955                 catch (SQLException e)
956                 {
957                         theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
958                                                                                                                 - startTime) + "ms. for: "+ sql);
959                         throw e;
960                 }
961
962                 return  rs;
963         }
964
965         /**
966          * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
967          * getimed und geloggt.
968          * @param stmt PreparedStatement mit der SQL-Anweisung
969          * @return Liefert ResultSet des Statements zurueck.
970          * @exception StorageObjectException, SQLException
971          */
972         public ResultSet executeSql (PreparedStatement stmt)
973                 throws StorageObjectException, SQLException {
974
975                 long startTime = (new java.util.Date()).getTime();
976                 ResultSet rs = stmt.executeQuery();
977                 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
978                 return  rs;
979         }
980
981                 /**
982          * returns the number of rows in the table
983          */
984         public int getSize(String where)
985                 throws SQLException,StorageObjectException
986         {
987                 long  startTime = System.currentTimeMillis();
988                 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
989                 Connection con = null;
990                 Statement stmt = null;
991                 int result = 0;
992
993                 try {
994                         con = getPooledCon();
995                         stmt = con.createStatement();
996                         ResultSet rs = executeSql(stmt,sql);
997                         while(rs.next()){
998                                 result = rs.getInt(1);
999                         }
1000                 } catch (SQLException e) {
1001                         theLog.printError(e.toString());
1002                 } finally {
1003                         freeConnection(con,stmt);
1004                 }
1005                 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1006                 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1007                                                                                 + sql);
1008                 return result;
1009         }
1010
1011         public int executeUpdate(Statement stmt, String sql)
1012                 throws StorageObjectException, SQLException
1013         {
1014                 int rs;
1015                 long  startTime = (new java.util.Date()).getTime();
1016                 try
1017                 {
1018                         rs = stmt.executeUpdate(sql);
1019                         theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1020                                                                                                 + sql);
1021                 }
1022                 catch (SQLException e)
1023                 {
1024                         theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1025                                                                                                                 - startTime) + "ms. for: "+ sql);
1026                         throw e;
1027                 }
1028                 return rs;
1029         }
1030
1031         public int executeUpdate(String sql)
1032                 throws StorageObjectException, SQLException
1033         {
1034                 int result=-1;
1035                 long  startTime = (new java.util.Date()).getTime();
1036                 Connection con=null;PreparedStatement pstmt=null;
1037                 try {
1038                         con=getPooledCon();
1039                         pstmt = con.prepareStatement(sql);
1040                         result = pstmt.executeUpdate();
1041                 }
1042                 catch (Exception e) {
1043                         theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1044                         throw new StorageObjectException("executeUpdate failed: "+e.toString());
1045                 }
1046                 finally { freeConnection(con,pstmt); }
1047                 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1048                                                                                 + sql);
1049                 return result;
1050         }
1051
1052         /**
1053          * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1054          * @param md ResultSetMetaData
1055          * @exception StorageObjectException
1056          */
1057         private void evalMetaData (ResultSetMetaData md)
1058                 throws StorageObjectException {
1059
1060                 this.evaluatedMetaData = true;
1061                 this.metadataFields = new ArrayList();
1062                 this.metadataLabels = new ArrayList();
1063                 this.metadataNotNullFields = new ArrayList();
1064                 try {
1065                         int numFields = md.getColumnCount();
1066                         this.metadataTypes = new int[numFields];
1067                         String aField;
1068                         int aType;
1069                         for (int i = 1; i <= numFields; i++) {
1070                                 aField = md.getColumnName(i);
1071                                 metadataFields.add(aField);
1072                                 metadataLabels.add(md.getColumnLabel(i));
1073                                 aType = md.getColumnType(i);
1074                                 metadataTypes[i - 1] = aType;
1075                                 if (aField.equals(thePKeyName)) {
1076                                         thePKeyType = aType; thePKeyIndex = i;
1077                                 }
1078                                 if (md.isNullable(i) == md.columnNullable) {
1079                                         metadataNotNullFields.add(aField);
1080                                 }
1081                         }
1082                 } catch (SQLException e) {
1083                         throwSQLException(e, "evalMetaData");
1084                 }
1085         }
1086
1087         /**
1088          *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1089          *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1090          */
1091         private void get_meta_data () throws StorageObjectException {
1092                 Connection con = null;
1093                 PreparedStatement pstmt = null;
1094                 String sql = "select * from " + theTable + " where 0=1";
1095                 try {
1096                         con = getPooledCon();
1097                         pstmt = con.prepareStatement(sql);
1098                         theLog.printInfo("METADATA: " + sql);
1099                         ResultSet rs = pstmt.executeQuery();
1100                         evalMetaData(rs.getMetaData());
1101                         rs.close();
1102                 } catch (SQLException e) {
1103                         throwSQLException(e, "get_meta_data");
1104                 } finally {
1105                         freeConnection(con, pstmt);
1106                 }
1107         }
1108
1109
1110         public Connection getPooledCon() throws StorageObjectException {
1111                 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1112                         try{
1113                         Class.forName("com.codestudio.sql.PoolMan").newInstance();
1114                 } catch (Exception e){
1115                         throw new StorageObjectException("Could not find the PoolMan Driver"
1116                                                                                                                                                                 +e.toString());
1117                 }*/
1118                 Connection con = null;
1119                 try{
1120                         con = SQLManager.getInstance().requestConnection();
1121                 } catch(SQLException e){
1122                         theLog.printError("could not connect to the database "+e.toString());
1123                         System.err.println("could not connect to the database "+e.toString());
1124                         throw new StorageObjectException("Could not connect to the database"+
1125                                                                                                                                                                 e.toString());
1126                 }
1127                 return con;
1128         }
1129
1130         public void freeConnection (Connection con, Statement stmt)
1131                 throws StorageObjectException {
1132                 SQLManager.getInstance().closeStatement(stmt);
1133                 SQLManager.getInstance().returnConnection(con);
1134         }
1135
1136         /**
1137          * Wertet SQLException aus und wirft dannach eine StorageObjectException
1138          * @param sqe SQLException
1139          * @param wo Funktonsname, in der die SQLException geworfen wurde
1140          * @exception StorageObjectException
1141          */
1142         protected void throwSQLException (SQLException sqe, String wo)
1143                 throws StorageObjectException {
1144                 String state = "";
1145                 String message = "";
1146                 int vendor = 0;
1147                 if (sqe != null) {
1148                         state = sqe.getSQLState();
1149                         message = sqe.getMessage();
1150                         vendor = sqe.getErrorCode();
1151                 }
1152                 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1153                                 + wo);
1154                 throw  new StorageObjectException((sqe == null) ? "undefined sql exception" :
1155                                 sqe.toString());
1156         }
1157
1158         protected void _throwStorageObjectException (Exception e, String wo)
1159                 throws StorageObjectException {
1160                 if (e != null) {
1161                                 theLog.printError(e.toString()+ wo);
1162                                 throw  new StorageObjectException(wo + e.toString());
1163                 } else {
1164                                 theLog.printError(wo);
1165                                 throw  new StorageObjectException(wo);
1166                 }
1167
1168         }
1169
1170         /**
1171          * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1172          * eine StorageObjectException
1173          * @param message Nachricht mit dem Fehler
1174          * @exception StorageObjectException
1175          */
1176         void throwStorageObjectException (String message)
1177                 throws StorageObjectException {
1178                 _throwStorageObjectException(null, message);
1179         }
1180
1181 }
1182
1183
1184