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));
256 //jbdc drops time zone info,
257 //so just get the string from
259 String timestamp = (rs.getString(valueIndex));
261 outValue = timestamp;
265 outValue = "<unsupported value>";
266 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
269 } catch (SQLException e) {
270 throw new StorageObjectException("Could not get Value out of Resultset -- "
278 * select-Operator um einen Datensatz zu bekommen.
279 * @param id Primaerschluessel des Datensatzes.
280 * @return liefert EntityObject des gefundenen Datensatzes oder null.
282 public Entity selectById(String id) throws StorageObjectException
284 if (id==null||id.equals(""))
285 throw new StorageObjectException("id war null");
287 // ask object store for object
288 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
289 String uniqueId = id;
290 if ( theEntityClass.equals(StorableObjectEntity.class) )
291 uniqueId+="@"+theTable;
292 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
293 theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
294 Entity hit = (Entity)o_store.use(search_sid);
295 if ( hit!=null ) return hit;
298 Statement stmt=null;Connection con=getPooledCon();
299 Entity returnEntity=null;
302 /** @todo better prepared statement */
303 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
304 stmt = con.createStatement();
305 rs = executeSql(stmt, selectSql);
307 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
309 returnEntity = makeEntityFromResultSet(rs);
310 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
314 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
317 catch (SQLException sqe){
318 throwSQLException(sqe,"selectById"); return null;
320 catch (NumberFormatException e) {
321 theLog.printError("ID ist keine Zahl: " + id);
323 finally { freeConnection(con,stmt); }
325 /** @todo OS: Entity should be saved in ostore */
331 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
332 * @param key Datenbankfeld der Bedingung.
333 * @param value Wert die der key anehmen muss.
334 * @return EntityList mit den gematchten Entities
336 public EntityList selectByFieldValue(String aField, String aValue)
337 throws StorageObjectException
339 return selectByFieldValue(aField, aValue, 0);
343 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
344 * @param key Datenbankfeld der Bedingung.
345 * @param value Wert die der key anehmen muss.
346 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
347 * @return EntityList mit den gematchten Entities
349 public EntityList selectByFieldValue(String aField, String aValue, int offset)
350 throws StorageObjectException
352 return selectByWhereClause(aField + "=" + aValue, offset);
357 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
358 * Also offset wird der erste Datensatz genommen.
360 * @param wc where-Clause
361 * @return EntityList mit den gematchten Entities
362 * @exception StorageObjectException
364 public EntityList selectByWhereClause(String where)
365 throws StorageObjectException
367 return selectByWhereClause(where, 0);
372 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
373 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
375 * @param wc where-Clause
376 * @param offset ab welchem Datensatz.
377 * @return EntityList mit den gematchten Entities
378 * @exception StorageObjectException
380 public EntityList selectByWhereClause(String whereClause, int offset)
381 throws StorageObjectException
383 return selectByWhereClause(whereClause, null, offset);
388 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
389 * Also offset wird der erste Datensatz genommen.
390 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
392 * @param wc where-Clause
393 * @param ob orderBy-Clause
394 * @return EntityList mit den gematchten Entities
395 * @exception StorageObjectException
398 public EntityList selectByWhereClause(String where, String order)
399 throws StorageObjectException {
400 return selectByWhereClause(where, order, 0);
405 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
406 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
408 * @param wc where-Clause
409 * @param ob orderBy-Clause
410 * @param offset ab welchem Datensatz
411 * @return EntityList mit den gematchten Entities
412 * @exception StorageObjectException
415 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
416 throws StorageObjectException {
417 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
422 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
423 * @param wc where-Clause
424 * @param ob orderBy-Clause
425 * @param offset ab welchem Datensatz
426 * @param limit wieviele Datensätze
427 * @return EntityList mit den gematchten Entities
428 * @exception StorageObjectException
431 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
432 throws StorageObjectException
435 // check o_store for entitylist
436 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
437 StoreIdentifier search_sid =
438 new StoreIdentifier( theEntityClass,
439 StoreContainerType.STOC_TYPE_ENTITYLIST,
440 StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
441 EntityList hit = (EntityList)o_store.use(search_sid);
443 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
449 EntityList theReturnList=null;
450 Connection con=null; Statement stmt=null;
452 int offsetCount = 0, count=0;
454 // build sql-statement
456 /** @todo count sql string should only be assembled if we really count
457 * see below at the end of method //rk */
459 if (wc != null && wc.length() == 0) {
462 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
463 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
465 selectSql.append(" where ").append(wc);
466 countSql.append(" where ").append(wc);
468 if (ob != null && !(ob.length() == 0)) {
469 selectSql.append(" order by ").append(ob);
471 if (theAdaptor.hasLimit()) {
472 if (limit > -1 && offset > -1) {
473 selectSql.append(" limit ");
474 if (theAdaptor.reverseLimit()) {
475 selectSql.append(limit).append(",").append(offset);
478 selectSql.append(offset).append(",").append(limit);
485 con = getPooledCon();
486 stmt = con.createStatement();
489 rs = executeSql(stmt, selectSql.toString());
491 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
493 theReturnList = new EntityList();
494 Entity theResultEntity;
496 theResultEntity = makeEntityFromResultSet(rs);
497 theReturnList.add(theResultEntity);
503 // making entitylist infos
504 if (!(theAdaptor.hasLimit())) count = offsetCount;
506 if (theReturnList != null) {
507 // now we decide if we have to know an overall count...
509 if (limit > -1 && offset > -1) {
510 if (offsetCount==limit) {
511 /** @todo counting should be deffered to entitylist
512 * getSize() should be used */
513 rs = executeSql(stmt, countSql.toString());
515 if ( rs.next() ) count = rs.getInt(1);
518 else theLog.printError("Could not count: " + countSql);
521 theReturnList.setCount(count);
522 theReturnList.setOffset(offset);
523 theReturnList.setWhere(wc);
524 theReturnList.setOrder(ob);
525 theReturnList.setStorage(this);
526 theReturnList.setLimit(limit);
527 if ( offset >= limit )
528 theReturnList.setPrevBatch(offset - limit);
529 if ( offset+offsetCount < count )
530 theReturnList.setNextBatch(offset + limit);
531 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
532 StoreIdentifier sid=theReturnList.getStoreIdentifier();
533 theLog.printDebugInfo("CACHE (add): " + sid.toString());
538 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
539 finally { freeConnection(con, stmt); }
541 return theReturnList;
546 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
548 * @param rs Das ResultSetObjekt.
549 * @return Entity Die Entity.
551 private Entity makeEntityFromResultSet (ResultSet rs)
552 throws StorageObjectException
554 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
555 HashMap theResultHash = new HashMap();
556 String theResult = null;
558 Entity returnEntity = null;
560 int size = metadataFields.size();
561 for (int i = 0; i < size; i++) {
562 // alle durchlaufen bis nix mehr da
564 theType = metadataTypes[i];
565 if (theType == java.sql.Types.LONGVARBINARY) {
566 InputStream us = rs.getAsciiStream(i + 1);
568 InputStreamReader is = new InputStreamReader(us);
569 char[] data = new char[32768];
570 StringBuffer theResultString = new StringBuffer();
572 while ((len = is.read(data)) > 0) {
573 theResultString.append(data, 0, len);
576 theResult = theResultString.toString();
585 theResult = getValueAsString(rs, (i + 1), theType);
587 if (theResult != null) {
588 theResultHash.put(metadataFields.get(i), theResult);
591 if (theEntityClass != null) {
592 returnEntity = (Entity)theEntityClass.newInstance();
593 returnEntity.setValues(theResultHash);
594 returnEntity.setStorage(myselfDatabase);
595 if ( returnEntity instanceof StorableObject ) {
596 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
597 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
600 throwStorageObjectException("Internal Error: theEntityClass not set!");
602 } catch (IllegalAccessException e) {
603 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
604 } catch (IOException e) {
605 throwStorageObjectException("IOException! -- " + e.toString());
606 } catch (InstantiationException e) {
607 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
608 } catch (SQLException sqe) {
609 throwSQLException(sqe, "makeEntityFromResultSet");
616 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
617 * wird automatisch mit dem aktuellen Datum gefuellt.
620 * @return der Wert des Primary-keys der eingefügten Entity
622 public String insert (Entity theEntity) throws StorageObjectException {
624 invalidatePopupCache();
626 // invalidating all EntityLists corresponding with theEntityClass
627 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
628 StoreContainerType stoc_type =
629 StoreContainerType.valueOf( theEntityClass,
630 StoreContainerType.STOC_TYPE_ENTITYLIST);
631 o_store.invalidate(stoc_type);
634 String returnId = null;
635 Connection con = null; PreparedStatement pstmt = null;
638 ArrayList streamedInput = theEntity.streamedInput();
639 StringBuffer f = new StringBuffer();
640 StringBuffer v = new StringBuffer();
641 String aField, aValue;
642 boolean firstField = true;
644 for (int i = 0; i < getFields().size(); i++) {
645 aField = (String)getFields().get(i);
646 if (!aField.equals(thePKeyName)) {
649 if (aField.equals("webdb_create")) {
653 if (streamedInput != null && streamedInput.contains(aField)) {
657 if (theEntity.hasValueForField(aField)) {
658 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
663 // wenn Wert gegeben, dann einbauen
664 if (aValue != null) {
665 if (firstField == false) {
678 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
679 String sql = sqlBuf.toString();
680 theLog.printInfo("INSERT: " + sql);
681 con = getPooledCon();
682 con.setAutoCommit(false);
683 pstmt = con.prepareStatement(sql);
684 if (streamedInput != null) {
685 for (int i = 0; i < streamedInput.size(); i++) {
686 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
687 pstmt.setBytes(i + 1, inputString.getBytes());
690 int ret = pstmt.executeUpdate();
695 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
696 ResultSet rs = pstmt.executeQuery();
698 returnId = rs.getString(1);
699 theEntity.setId(returnId);
700 } catch (SQLException sqe) {
701 throwSQLException(sqe, "insert");
704 con.setAutoCommit(true);
705 } catch (Exception e) {
708 freeConnection(con, pstmt);
710 /** @todo store entity in o_store */
715 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
716 * wird automatisch mit dem aktuellen Datum gefuellt.
720 public void update (Entity theEntity) throws StorageObjectException
722 Connection con = null; PreparedStatement pstmt = null;
723 /** @todo this is stupid: why do we prepare statement, when we
724 * throw it away afterwards. should be regular statement
725 * update/insert could better be one routine called save()
726 * that chooses to either insert or update depending if we
727 * have a primary key in the entity. i don't know if we
728 * still need the streamed input fields. // rk */
730 /** @todo extension: check if Entity did change, otherwise we don't need
731 * the roundtrip to the database */
733 /** invalidating corresponding entitylists in o_store*/
734 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
735 StoreContainerType stoc_type =
736 StoreContainerType.valueOf( theEntityClass,
737 StoreContainerType.STOC_TYPE_ENTITYLIST);
738 o_store.invalidate(stoc_type);
741 ArrayList streamedInput = theEntity.streamedInput();
742 String id = theEntity.getId();
744 StringBuffer fv = new StringBuffer();
745 boolean firstField = true;
747 invalidatePopupCache();
748 // build sql statement
749 for (int i = 0; i < getFields().size(); i++) {
750 aField = (String)metadataFields.get(i);
752 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
753 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
754 if (theEntity.hasValueForField(aField)) {
755 if (firstField == false) {
761 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
765 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
767 if (metadataFields.contains("webdb_lastchange")) {
768 sql.append(",webdb_lastchange=NOW()");
770 if (streamedInput != null) {
771 for (int i = 0; i < streamedInput.size(); i++) {
772 sql.append(",").append(streamedInput.get(i)).append("=?");
775 sql.append(" where id=").append(id);
776 theLog.printInfo("UPDATE: " + sql);
779 con = getPooledCon();
780 con.setAutoCommit(false);
781 pstmt = con.prepareStatement(sql.toString());
782 if (streamedInput != null) {
783 for (int i = 0; i < streamedInput.size(); i++) {
784 String inputString = theEntity.getValue((String)streamedInput.get(i));
785 pstmt.setBytes(i + 1, inputString.getBytes());
788 pstmt.executeUpdate();
789 } catch (SQLException sqe) {
790 throwSQLException(sqe, "update");
793 con.setAutoCommit(true);
794 } catch (Exception e) {
797 freeConnection(con, pstmt);
803 * @param id des zu loeschenden Datensatzes
804 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
806 public boolean delete (String id) throws StorageObjectException {
808 invalidatePopupCache();
809 // ostore send notification
810 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
811 String uniqueId = id;
812 if ( theEntityClass.equals(StorableObjectEntity.class) )
813 uniqueId+="@"+theTable;
814 theLog.printInfo("CACHE: (del) " + id);
815 StoreIdentifier search_sid =
816 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
817 o_store.invalidate(search_sid);
820 /** @todo could be prepared Statement */
821 Statement stmt = null; Connection con = null;
823 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
824 theLog.printInfo("DELETE " + sql);
826 con = getPooledCon(); stmt = con.createStatement();
827 res = stmt.executeUpdate(sql);
829 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
830 finally { freeConnection(con, stmt); }
832 return (res > 0) ? true : false;
835 /* noch nicht implementiert.
836 * @return immer false
838 public boolean delete (EntityList theEntityList) {
839 invalidatePopupCache();
844 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
845 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
848 public SimpleList getPopupData () throws StorageObjectException {
853 * Holt Daten fuer Popups.
854 * @param name Name des Feldes.
855 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
856 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
858 public SimpleList getPopupData (String name, boolean hasNullValue)
859 throws StorageObjectException {
860 return getPopupData(name, hasNullValue, null);
864 * Holt Daten fuer Popups.
865 * @param name Name des Feldes.
866 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
867 * @param where Schraenkt die Selektion der Datensaetze ein.
868 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
870 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
871 return getPopupData(name, hasNullValue, where, null);
875 * Holt Daten fuer Popups.
876 * @param name Name des Feldes.
877 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
878 * @param where Schraenkt die Selektion der Datensaetze ein.
879 * @param order Gibt ein Feld als Sortierkriterium an.
880 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
882 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
884 if (hasPopupCache && popupCache != null)
886 SimpleList simpleList = null;
887 Connection con = null;
888 Statement stmt = null;
890 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
891 .append(",").append(name).append(" from ")
893 if (where != null && !(where.length() == 0))
894 sql.append(" where ").append(where);
895 sql.append(" order by ");
896 if (order != null && !(order.length() == 0))
902 con = getPooledCon();
903 } catch (Exception e) {
904 throw new StorageObjectException(e.toString());
907 stmt = con.createStatement();
908 ResultSet rs = executeSql(stmt, sql.toString());
911 if (!evaluatedMetaData) get_meta_data();
912 simpleList = new SimpleList();
913 // if popup has null-selector
914 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
916 SimpleHash popupDict;
918 popupDict = new SimpleHash();
919 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
920 popupDict.put("value", rs.getString(2));
921 simpleList.add(popupDict);
925 } catch (Exception e) {
926 theLog.printError("getPopupData: "+e.toString());
927 throw new StorageObjectException(e.toString());
929 freeConnection(con, stmt);
932 if (hasPopupCache) popupCache = simpleList;
937 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
938 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
939 * Tabellen Verwendung finden.
940 * @return SimpleHash mit den Tabellezeilen.
942 public SimpleHash getHashData () {
943 /** @todo dangerous! this should have a flag to be enabled, otherwise
944 * very big Hashes could be returned */
945 if (hashCache == null) {
947 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
949 } catch (StorageObjectException e) {
950 theLog.printDebugInfo(e.toString());
956 /* invalidates the popupCache
958 protected void invalidatePopupCache () {
959 /** @todo invalidates toooo much */
965 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
966 * @param stmt Statemnt
967 * @param sql Sql-String
969 * @exception StorageObjectException
971 public ResultSet executeSql (Statement stmt, String sql)
972 throws StorageObjectException, SQLException
974 long startTime = System.currentTimeMillis();
977 rs = stmt.executeQuery(sql);
978 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
981 catch (SQLException e)
983 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
984 - startTime) + "ms. for: "+ sql);
992 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
993 * getimed und geloggt.
994 * @param stmt PreparedStatement mit der SQL-Anweisung
995 * @return Liefert ResultSet des Statements zurueck.
996 * @exception StorageObjectException, SQLException
998 public ResultSet executeSql (PreparedStatement stmt)
999 throws StorageObjectException, SQLException {
1001 long startTime = (new java.util.Date()).getTime();
1002 ResultSet rs = stmt.executeQuery();
1003 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1008 * returns the number of rows in the table
1010 public int getSize(String where)
1011 throws SQLException,StorageObjectException
1013 long startTime = System.currentTimeMillis();
1014 String sql = "SELECT Count(*) FROM "+ theTable;
1015 if (where != null && !(where.length() == 0))
1016 sql = sql + " where " + where;
1017 Connection con = null;
1018 Statement stmt = null;
1022 con = getPooledCon();
1023 stmt = con.createStatement();
1024 ResultSet rs = executeSql(stmt,sql);
1026 result = rs.getInt(1);
1028 } catch (SQLException e) {
1029 theLog.printError(e.toString());
1031 freeConnection(con,stmt);
1033 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1034 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1039 public int executeUpdate(Statement stmt, String sql)
1040 throws StorageObjectException, SQLException
1043 long startTime = (new java.util.Date()).getTime();
1046 rs = stmt.executeUpdate(sql);
1047 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1050 catch (SQLException e)
1052 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1053 - startTime) + "ms. for: "+ sql);
1059 public int executeUpdate(String sql)
1060 throws StorageObjectException, SQLException
1063 long startTime = (new java.util.Date()).getTime();
1064 Connection con=null;PreparedStatement pstmt=null;
1067 pstmt = con.prepareStatement(sql);
1068 result = pstmt.executeUpdate();
1070 catch (Exception e) {
1071 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1072 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1074 finally { freeConnection(con,pstmt); }
1075 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1081 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1082 * @param md ResultSetMetaData
1083 * @exception StorageObjectException
1085 private void evalMetaData (ResultSetMetaData md)
1086 throws StorageObjectException {
1088 this.evaluatedMetaData = true;
1089 this.metadataFields = new ArrayList();
1090 this.metadataLabels = new ArrayList();
1091 this.metadataNotNullFields = new ArrayList();
1093 int numFields = md.getColumnCount();
1094 this.metadataTypes = new int[numFields];
1097 for (int i = 1; i <= numFields; i++) {
1098 aField = md.getColumnName(i);
1099 metadataFields.add(aField);
1100 metadataLabels.add(md.getColumnLabel(i));
1101 aType = md.getColumnType(i);
1102 metadataTypes[i - 1] = aType;
1103 if (aField.equals(thePKeyName)) {
1104 thePKeyType = aType; thePKeyIndex = i;
1106 if (md.isNullable(i) == md.columnNullable) {
1107 metadataNotNullFields.add(aField);
1110 } catch (SQLException e) {
1111 throwSQLException(e, "evalMetaData");
1116 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1117 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1119 private void get_meta_data () throws StorageObjectException {
1120 Connection con = null;
1121 PreparedStatement pstmt = null;
1122 String sql = "select * from " + theTable + " where 0=1";
1124 con = getPooledCon();
1125 pstmt = con.prepareStatement(sql);
1126 theLog.printInfo("METADATA: " + sql);
1127 ResultSet rs = pstmt.executeQuery();
1128 evalMetaData(rs.getMetaData());
1130 } catch (SQLException e) {
1131 throwSQLException(e, "get_meta_data");
1133 freeConnection(con, pstmt);
1138 public Connection getPooledCon() throws StorageObjectException {
1139 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1141 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1142 } catch (Exception e){
1143 throw new StorageObjectException("Could not find the PoolMan Driver"
1146 Connection con = null;
1148 con = SQLManager.getInstance().requestConnection();
1149 } catch(SQLException e){
1150 theLog.printError("could not connect to the database "+e.toString());
1151 System.err.println("could not connect to the database "+e.toString());
1152 throw new StorageObjectException("Could not connect to the database"+
1158 public void freeConnection (Connection con, Statement stmt)
1159 throws StorageObjectException {
1160 SQLManager.getInstance().closeStatement(stmt);
1161 SQLManager.getInstance().returnConnection(con);
1165 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1166 * @param sqe SQLException
1167 * @param wo Funktonsname, in der die SQLException geworfen wurde
1168 * @exception StorageObjectException
1170 protected void throwSQLException (SQLException sqe, String wo)
1171 throws StorageObjectException {
1173 String message = "";
1176 state = sqe.getSQLState();
1177 message = sqe.getMessage();
1178 vendor = sqe.getErrorCode();
1180 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1182 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1186 protected void _throwStorageObjectException (Exception e, String wo)
1187 throws StorageObjectException {
1189 theLog.printError(e.toString()+ wo);
1190 throw new StorageObjectException(wo + e.toString());
1192 theLog.printError(wo);
1193 throw new StorageObjectException(wo);
1199 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1200 * eine StorageObjectException
1201 * @param message Nachricht mit dem Fehler
1202 * @exception StorageObjectException
1204 void throwStorageObjectException (String message)
1205 throws StorageObjectException {
1206 _throwStorageObjectException(null, message);