2 * put your module comment here
10 import freemarker.template.*;
11 import com.codestudio.sql.*;
12 import com.codestudio.util.*;
14 import mir.storage.StorageObject;
15 import mir.storage.store.*;
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
31 public class Database implements StorageObject {
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();
57 // always same object saves a little space
58 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
60 GENERIC_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
61 STORABLE_OBJECT_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
64 System.err.println("FATAL: Database.java could not initialize" + e.toString());
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
77 * @param String confFilename Dateiname der Konfigurationsdatei
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"));
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 "
93 /*String database_username=MirConfig.getProp("Database.Username");
94 String database_password=MirConfig.getProp("Database.Password");
95 String database_host=MirConfig.getProp("Database.Host");
97 database_driver=theAdaptor.getDriver();
98 database_url=theAdaptor.getURL(database_username,database_password,
100 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
102 MirConfig.addBroker(database_driver,database_url);
103 //myBroker=MirConfig.getBroker();
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.
112 * @return Class-Objekt der Entity
114 public java.lang.Class getEntityClass () {
115 return theEntityClass;
119 * Liefert die Standardbeschränkung von select-Statements zurück, also
120 * wieviel Datensätze per Default selektiert werden.
122 * @return Standard-Anzahl der Datensätze
124 public int getLimit () {
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
133 public String getIdName () {
138 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
140 * @return Name der Tabelle
142 public String getTableName () {
147 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
148 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
150 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
154 public String getCoreTable(){
155 if (theCoreTable!=null) return theCoreTable;
156 else return theTable;
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
164 public int[] getTypes () throws StorageObjectException {
165 if (metadataTypes == null)
167 return metadataTypes;
171 * Liefert eine Liste der Labels der Tabellenfelder
172 * @return ArrayListe mit Labeln
173 * @exception StorageObjectException
175 public ArrayList getLabels () throws StorageObjectException {
176 if (metadataLabels == null)
178 return metadataLabels;
182 * Liefert eine Liste der Felder der Tabelle
183 * @return ArrayList mit Feldern
184 * @exception StorageObjectException
186 public ArrayList getFields () throws StorageObjectException {
187 if (metadataFields == null)
189 return metadataFields;
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/
200 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
201 String outValue = null;
205 case java.sql.Types.BIT:
206 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
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);
211 outValue = new Integer(out).toString();
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);
218 outValue = new Long(outl).toString();
220 case java.sql.Types.REAL:
221 float tempf = rs.getFloat(valueIndex);
225 int tempf_int = (int)tempf;
226 tempf = (float)tempf_int;
228 outValue = "" + tempf;
229 outValue = outValue.replace('.', ',');
232 case java.sql.Types.DOUBLE:
233 double tempd = rs.getDouble(valueIndex);
237 int tempd_int = (int)tempd;
238 tempd = (double)tempd_int;
240 outValue = "" + tempd;
241 outValue = outValue.replace('.', ',');
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));
249 case java.sql.Types.LONGVARBINARY:
250 outValue = rs.getString(valueIndex);
251 //if (outValue != null)
252 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
254 case java.sql.Types.TIMESTAMP:
255 Timestamp timestamp = (rs.getTimestamp(valueIndex));
257 outValue = timestamp.toString();
261 outValue = "<unsupported value>";
262 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
265 } catch (SQLException e) {
266 throw new StorageObjectException("Could not get Value out of Resultset -- "
274 * select-Operator um einen Datensatz zu bekommen.
275 * @param id Primaerschluessel des Datensatzes.
276 * @return liefert EntityObject des gefundenen Datensatzes oder null.
278 public Entity selectById(String id) throws StorageObjectException
280 if (id==null||id.equals(""))
281 throw new StorageObjectException("id war null");
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;
294 Statement stmt=null;Connection con=getPooledCon();
295 Entity returnEntity=null;
298 /** @todo better prepared statement */
299 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
300 stmt = con.createStatement();
301 rs = executeSql(stmt, selectSql);
303 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
305 returnEntity = makeEntityFromResultSet(rs);
306 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
310 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
313 catch (SQLException sqe){
314 throwSQLException(sqe,"selectById"); return null;
316 catch (NumberFormatException e) {
317 theLog.printError("ID ist keine Zahl: " + id);
319 finally { freeConnection(con,stmt); }
321 /** @todo OS: Entity should be saved in ostore */
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
332 public EntityList selectByFieldValue(String aField, String aValue)
333 throws StorageObjectException
335 return selectByFieldValue(aField, aValue, 0);
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
345 public EntityList selectByFieldValue(String aField, String aValue, int offset)
346 throws StorageObjectException
348 return selectByWhereClause(aField + "=" + aValue, offset);
353 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
354 * Also offset wird der erste Datensatz genommen.
356 * @param wc where-Clause
357 * @return EntityList mit den gematchten Entities
358 * @exception StorageObjectException
360 public EntityList selectByWhereClause(String where)
361 throws StorageObjectException
363 return selectByWhereClause(where, 0);
368 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
369 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
371 * @param wc where-Clause
372 * @param offset ab welchem Datensatz.
373 * @return EntityList mit den gematchten Entities
374 * @exception StorageObjectException
376 public EntityList selectByWhereClause(String whereClause, int offset)
377 throws StorageObjectException
379 return selectByWhereClause(whereClause, null, offset);
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.
388 * @param wc where-Clause
389 * @param ob orderBy-Clause
390 * @return EntityList mit den gematchten Entities
391 * @exception StorageObjectException
394 public EntityList selectByWhereClause(String where, String order)
395 throws StorageObjectException {
396 return selectByWhereClause(where, order, 0);
401 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
402 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
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
411 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
412 throws StorageObjectException {
413 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
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
427 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
428 throws StorageObjectException
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(theTable,wc,ob,offset,limit) );
437 EntityList hit = (EntityList)o_store.use(search_sid);
439 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
445 EntityList theReturnList=null;
446 Connection con=null; Statement stmt=null;
448 int offsetCount = 0, count=0;
450 // build sql-statement
452 /** @todo count sql string should only be assembled if we really count
453 * see below at the end of method //rk */
455 if (wc != null && wc.length() == 0) {
458 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
459 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
461 selectSql.append(" where ").append(wc);
462 countSql.append(" where ").append(wc);
464 if (ob != null && !(ob.length() == 0)) {
465 selectSql.append(" order by ").append(ob);
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);
474 selectSql.append(offset).append(",").append(limit);
481 con = getPooledCon();
482 stmt = con.createStatement();
485 rs = executeSql(stmt, selectSql.toString());
487 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
489 theReturnList = new EntityList();
490 Entity theResultEntity;
492 theResultEntity = makeEntityFromResultSet(rs);
493 theReturnList.add(theResultEntity);
499 // making entitylist infos
500 if (!(theAdaptor.hasLimit())) count = offsetCount;
502 if (theReturnList != null) {
503 // now we decide if we have to know an overall count...
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());
511 if ( rs.next() ) count = rs.getInt(1);
514 else theLog.printError("Could not count: " + countSql);
517 theReturnList.setCount(count);
518 theReturnList.setOffset(offset);
519 theReturnList.setWhere(wc);
520 theReturnList.setOrder(ob);
521 theReturnList.setStorage(this);
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());
534 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
535 finally { freeConnection(con, stmt); }
537 return theReturnList;
542 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
544 * @param rs Das ResultSetObjekt.
545 * @return Entity Die Entity.
547 private Entity makeEntityFromResultSet (ResultSet rs)
548 throws StorageObjectException
550 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
551 HashMap theResultHash = new HashMap();
552 String theResult = null;
554 Entity returnEntity = null;
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);
563 InputStreamReader is = new InputStreamReader(us);
564 char[] data = new char[32768];
565 StringBuffer theResultString = new StringBuffer();
567 while ((len = is.read(data)) > 0) {
568 theResultString.append(data, 0, len);
571 theResult = theResultString.toString();
578 theResult = getValueAsString(rs, (i + 1), theType);
580 if (theResult != null) {
581 theResultHash.put(metadataFields.get(i), theResult);
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());
593 throwStorageObjectException("Internal Error: theEntityClass not set!");
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");
609 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
610 * wird automatisch mit dem aktuellen Datum gefuellt.
613 * @return der Wert des Primary-keys der eingefügten Entity
615 public String insert (Entity theEntity) throws StorageObjectException {
617 invalidatePopupCache();
619 // invalidating all EntityLists corresponding with theEntityClass
620 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
621 StoreContainerType stoc_type =
622 StoreContainerType.valueOf( theEntityClass,
623 StoreContainerType.STOC_TYPE_ENTITYLIST);
624 o_store.invalidate(stoc_type);
627 String returnId = null;
628 Connection con = null; PreparedStatement pstmt = null;
631 ArrayList streamedInput = theEntity.streamedInput();
632 StringBuffer f = new StringBuffer();
633 StringBuffer v = new StringBuffer();
634 String aField, aValue;
635 boolean firstField = true;
637 for (int i = 0; i < getFields().size(); i++) {
638 aField = (String)getFields().get(i);
639 if (!aField.equals(thePKeyName)) {
642 if (aField.equals("webdb_create")) {
646 if (streamedInput != null && streamedInput.contains(aField)) {
650 if (theEntity.hasValueForField(aField)) {
651 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
656 // wenn Wert gegeben, dann einbauen
657 if (aValue != null) {
658 if (firstField == false) {
671 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
672 String sql = sqlBuf.toString();
673 theLog.printInfo("INSERT: " + sql);
674 con = getPooledCon();
675 con.setAutoCommit(false);
676 pstmt = con.prepareStatement(sql);
677 if (streamedInput != null) {
678 for (int i = 0; i < streamedInput.size(); i++) {
679 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
680 pstmt.setBytes(i + 1, inputString.getBytes());
683 int ret = pstmt.executeUpdate();
688 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
689 ResultSet rs = pstmt.executeQuery();
691 returnId = rs.getString(1);
692 theEntity.setId(returnId);
693 } catch (SQLException sqe) {
694 throwSQLException(sqe, "insert");
697 con.setAutoCommit(true);
698 } catch (Exception e) {
701 freeConnection(con, pstmt);
703 /** @todo store entity in o_store */
708 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
709 * wird automatisch mit dem aktuellen Datum gefuellt.
713 public void update (Entity theEntity) throws StorageObjectException
715 Connection con = null; PreparedStatement pstmt = null;
716 /** @todo this is stupid: why do we prepare statement, when we
717 * throw it away afterwards. should be regular statement
718 * update/insert could better be one routine called save()
719 * that chooses to either insert or update depending if we
720 * have a primary key in the entity. i don't know if we
721 * still need the streamed input fields. // rk */
723 /** @todo extension: check if Entity did change, otherwise we don't need
724 * the roundtrip to the database */
726 /** invalidating corresponding entitylists in o_store*/
727 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
728 StoreContainerType stoc_type =
729 StoreContainerType.valueOf( theEntityClass,
730 StoreContainerType.STOC_TYPE_ENTITYLIST);
731 o_store.invalidate(stoc_type);
734 ArrayList streamedInput = theEntity.streamedInput();
735 String id = theEntity.getId();
737 StringBuffer fv = new StringBuffer();
738 boolean firstField = true;
740 invalidatePopupCache();
741 // build sql statement
742 for (int i = 0; i < getFields().size(); i++) {
743 aField = (String)metadataFields.get(i);
745 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
746 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
747 if (theEntity.hasValueForField(aField)) {
748 if (firstField == false) {
754 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
758 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
760 if (metadataFields.contains("webdb_lastchange")) {
761 sql.append(",webdb_lastchange=NOW()");
763 if (streamedInput != null) {
764 for (int i = 0; i < streamedInput.size(); i++) {
765 sql.append(",").append(streamedInput.get(i)).append("=?");
768 sql.append(" where id=").append(id);
769 theLog.printInfo("UPDATE: " + sql);
772 con = getPooledCon();
773 con.setAutoCommit(false);
774 pstmt = con.prepareStatement(sql.toString());
775 if (streamedInput != null) {
776 for (int i = 0; i < streamedInput.size(); i++) {
777 String inputString = theEntity.getValue((String)streamedInput.get(i));
778 pstmt.setBytes(i + 1, inputString.getBytes());
781 pstmt.executeUpdate();
782 } catch (SQLException sqe) {
783 throwSQLException(sqe, "update");
786 con.setAutoCommit(true);
787 } catch (Exception e) {
790 freeConnection(con, pstmt);
796 * @param id des zu loeschenden Datensatzes
797 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
799 public boolean delete (String id) throws StorageObjectException {
801 invalidatePopupCache();
802 // ostore send notification
803 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
804 String uniqueId = id;
805 if ( theEntityClass.equals(StorableObjectEntity.class) )
806 uniqueId+="@"+theTable;
807 theLog.printInfo("CACHE: (del) " + id);
808 StoreIdentifier search_sid =
809 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
810 o_store.invalidate(search_sid);
813 /** @todo could be prepared Statement */
814 Statement stmt = null; Connection con = null;
816 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
817 theLog.printInfo("DELETE " + sql);
819 con = getPooledCon(); stmt = con.createStatement();
820 res = stmt.executeUpdate(sql);
822 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
823 finally { freeConnection(con, stmt); }
825 return (res > 0) ? true : false;
828 /* noch nicht implementiert.
829 * @return immer false
831 public boolean delete (EntityList theEntityList) {
832 invalidatePopupCache();
837 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
838 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
841 public SimpleList getPopupData () throws StorageObjectException {
846 * Holt Daten fuer Popups.
847 * @param name Name des Feldes.
848 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
849 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
851 public SimpleList getPopupData (String name, boolean hasNullValue)
852 throws StorageObjectException {
853 return getPopupData(name, hasNullValue, null);
857 * Holt Daten fuer Popups.
858 * @param name Name des Feldes.
859 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
860 * @param where Schraenkt die Selektion der Datensaetze ein.
861 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
863 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
864 return getPopupData(name, hasNullValue, where, null);
868 * Holt Daten fuer Popups.
869 * @param name Name des Feldes.
870 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
871 * @param where Schraenkt die Selektion der Datensaetze ein.
872 * @param order Gibt ein Feld als Sortierkriterium an.
873 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
875 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
877 if (hasPopupCache && popupCache != null)
879 SimpleList simpleList = null;
880 Connection con = null;
881 Statement stmt = null;
883 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
884 .append(",").append(name).append(" from ")
886 if (where != null && !(where.length() == 0))
887 sql.append(" where ").append(where);
888 sql.append(" order by ");
889 if (order != null && !(order.length() == 0))
895 con = getPooledCon();
896 } catch (Exception e) {
897 throw new StorageObjectException(e.toString());
900 stmt = con.createStatement();
901 ResultSet rs = executeSql(stmt, sql.toString());
904 if (!evaluatedMetaData) get_meta_data();
905 simpleList = new SimpleList();
906 // if popup has null-selector
907 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
909 SimpleHash popupDict;
911 popupDict = new SimpleHash();
912 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
913 popupDict.put("value", rs.getString(2));
914 simpleList.add(popupDict);
918 } catch (Exception e) {
919 theLog.printError("getPopupData: "+e.toString());
920 throw new StorageObjectException(e.toString());
922 freeConnection(con, stmt);
925 if (hasPopupCache) popupCache = simpleList;
930 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
931 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
932 * Tabellen Verwendung finden.
933 * @return SimpleHash mit den Tabellezeilen.
935 public SimpleHash getHashData () {
936 /** @todo dangerous! this should have a flag to be enabled, otherwise
937 * very big Hashes could be returned */
938 if (hashCache == null) {
940 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
942 } catch (StorageObjectException e) {
943 theLog.printDebugInfo(e.toString());
949 /* invalidates the popupCache
951 protected void invalidatePopupCache () {
952 /** @todo invalidates toooo much */
958 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
959 * @param stmt Statemnt
960 * @param sql Sql-String
962 * @exception StorageObjectException
964 public ResultSet executeSql (Statement stmt, String sql)
965 throws StorageObjectException, SQLException
967 long startTime = System.currentTimeMillis();
970 rs = stmt.executeQuery(sql);
971 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
974 catch (SQLException e)
976 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
977 - startTime) + "ms. for: "+ sql);
985 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
986 * getimed und geloggt.
987 * @param stmt PreparedStatement mit der SQL-Anweisung
988 * @return Liefert ResultSet des Statements zurueck.
989 * @exception StorageObjectException, SQLException
991 public ResultSet executeSql (PreparedStatement stmt)
992 throws StorageObjectException, SQLException {
994 long startTime = (new java.util.Date()).getTime();
995 ResultSet rs = stmt.executeQuery();
996 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1001 * returns the number of rows in the table
1003 public int getSize(String where)
1004 throws SQLException,StorageObjectException
1006 long startTime = System.currentTimeMillis();
1007 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
1008 Connection con = null;
1009 Statement stmt = null;
1013 con = getPooledCon();
1014 stmt = con.createStatement();
1015 ResultSet rs = executeSql(stmt,sql);
1017 result = rs.getInt(1);
1019 } catch (SQLException e) {
1020 theLog.printError(e.toString());
1022 freeConnection(con,stmt);
1024 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1025 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1030 public int executeUpdate(Statement stmt, String sql)
1031 throws StorageObjectException, SQLException
1034 long startTime = (new java.util.Date()).getTime();
1037 rs = stmt.executeUpdate(sql);
1038 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1041 catch (SQLException e)
1043 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1044 - startTime) + "ms. for: "+ sql);
1050 public int executeUpdate(String sql)
1051 throws StorageObjectException, SQLException
1054 long startTime = (new java.util.Date()).getTime();
1055 Connection con=null;PreparedStatement pstmt=null;
1058 pstmt = con.prepareStatement(sql);
1059 result = pstmt.executeUpdate();
1061 catch (Exception e) {
1062 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1063 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1065 finally { freeConnection(con,pstmt); }
1066 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1072 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1073 * @param md ResultSetMetaData
1074 * @exception StorageObjectException
1076 private void evalMetaData (ResultSetMetaData md)
1077 throws StorageObjectException {
1079 this.evaluatedMetaData = true;
1080 this.metadataFields = new ArrayList();
1081 this.metadataLabels = new ArrayList();
1082 this.metadataNotNullFields = new ArrayList();
1084 int numFields = md.getColumnCount();
1085 this.metadataTypes = new int[numFields];
1088 for (int i = 1; i <= numFields; i++) {
1089 aField = md.getColumnName(i);
1090 metadataFields.add(aField);
1091 metadataLabels.add(md.getColumnLabel(i));
1092 aType = md.getColumnType(i);
1093 metadataTypes[i - 1] = aType;
1094 if (aField.equals(thePKeyName)) {
1095 thePKeyType = aType; thePKeyIndex = i;
1097 if (md.isNullable(i) == md.columnNullable) {
1098 metadataNotNullFields.add(aField);
1101 } catch (SQLException e) {
1102 throwSQLException(e, "evalMetaData");
1107 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1108 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1110 private void get_meta_data () throws StorageObjectException {
1111 Connection con = null;
1112 PreparedStatement pstmt = null;
1113 String sql = "select * from " + theTable + " where 0=1";
1115 con = getPooledCon();
1116 pstmt = con.prepareStatement(sql);
1117 theLog.printInfo("METADATA: " + sql);
1118 ResultSet rs = pstmt.executeQuery();
1119 evalMetaData(rs.getMetaData());
1121 } catch (SQLException e) {
1122 throwSQLException(e, "get_meta_data");
1124 freeConnection(con, pstmt);
1129 public Connection getPooledCon() throws StorageObjectException {
1130 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1132 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1133 } catch (Exception e){
1134 throw new StorageObjectException("Could not find the PoolMan Driver"
1137 Connection con = null;
1139 con = SQLManager.getInstance().requestConnection();
1140 } catch(SQLException e){
1141 theLog.printError("could not connect to the database "+e.toString());
1142 System.err.println("could not connect to the database "+e.toString());
1143 throw new StorageObjectException("Could not connect to the database"+
1149 public void freeConnection (Connection con, Statement stmt)
1150 throws StorageObjectException {
1151 SQLManager.getInstance().closeStatement(stmt);
1152 SQLManager.getInstance().returnConnection(con);
1156 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1157 * @param sqe SQLException
1158 * @param wo Funktonsname, in der die SQLException geworfen wurde
1159 * @exception StorageObjectException
1161 protected void throwSQLException (SQLException sqe, String wo)
1162 throws StorageObjectException {
1164 String message = "";
1167 state = sqe.getSQLState();
1168 message = sqe.getMessage();
1169 vendor = sqe.getErrorCode();
1171 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1173 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1177 protected void _throwStorageObjectException (Exception e, String wo)
1178 throws StorageObjectException {
1180 theLog.printError(e.toString()+ wo);
1181 throw new StorageObjectException(wo + e.toString());
1183 theLog.printError(wo);
1184 throw new StorageObjectException(wo);
1190 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1191 * eine StorageObjectException
1192 * @param message Nachricht mit dem Fehler
1193 * @exception StorageObjectException
1195 void throwStorageObjectException (String message)
1196 throws StorageObjectException {
1197 _throwStorageObjectException(null, message);