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
563 theType = metadataTypes[i];
564 if (theType == java.sql.Types.LONGVARBINARY) {
565 InputStream us = rs.getAsciiStream(i + 1);
567 InputStreamReader is = new InputStreamReader(us);
568 char[] data = new char[32768];
569 StringBuffer theResultString = new StringBuffer();
571 while ((len = is.read(data)) > 0) {
572 theResultString.append(data, 0, len);
575 theResult = theResultString.toString();
582 theResult = getValueAsString(rs, (i + 1), theType);
584 if (theResult != null) {
585 theResultHash.put(metadataFields.get(i), theResult);
588 if (theEntityClass != null) {
589 returnEntity = (Entity)theEntityClass.newInstance();
590 returnEntity.setValues(theResultHash);
591 returnEntity.setStorage(myselfDatabase);
592 if ( returnEntity instanceof StorableObject ) {
593 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
594 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
597 throwStorageObjectException("Internal Error: theEntityClass not set!");
599 } catch (IllegalAccessException e) {
600 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
601 } catch (IOException e) {
602 throwStorageObjectException("IOException! -- " + e.toString());
603 } catch (InstantiationException e) {
604 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
605 } catch (SQLException sqe) {
606 throwSQLException(sqe, "makeEntityFromResultSet");
613 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
614 * wird automatisch mit dem aktuellen Datum gefuellt.
617 * @return der Wert des Primary-keys der eingefügten Entity
619 public String insert (Entity theEntity) throws StorageObjectException {
621 invalidatePopupCache();
623 // invalidating all EntityLists corresponding with theEntityClass
624 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
625 StoreContainerType stoc_type =
626 StoreContainerType.valueOf( theEntityClass,
627 StoreContainerType.STOC_TYPE_ENTITYLIST);
628 o_store.invalidate(stoc_type);
631 String returnId = null;
632 Connection con = null; PreparedStatement pstmt = null;
635 ArrayList streamedInput = theEntity.streamedInput();
636 StringBuffer f = new StringBuffer();
637 StringBuffer v = new StringBuffer();
638 String aField, aValue;
639 boolean firstField = true;
641 for (int i = 0; i < getFields().size(); i++) {
642 aField = (String)getFields().get(i);
643 if (!aField.equals(thePKeyName)) {
646 if (aField.equals("webdb_create")) {
650 if (streamedInput != null && streamedInput.contains(aField)) {
654 if (theEntity.hasValueForField(aField)) {
655 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
660 // wenn Wert gegeben, dann einbauen
661 if (aValue != null) {
662 if (firstField == false) {
675 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
676 String sql = sqlBuf.toString();
677 theLog.printInfo("INSERT: " + sql);
678 con = getPooledCon();
679 con.setAutoCommit(false);
680 pstmt = con.prepareStatement(sql);
681 if (streamedInput != null) {
682 for (int i = 0; i < streamedInput.size(); i++) {
683 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
684 pstmt.setBytes(i + 1, inputString.getBytes());
687 int ret = pstmt.executeUpdate();
692 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
693 ResultSet rs = pstmt.executeQuery();
695 returnId = rs.getString(1);
696 theEntity.setId(returnId);
697 } catch (SQLException sqe) {
698 throwSQLException(sqe, "insert");
701 con.setAutoCommit(true);
702 } catch (Exception e) {
705 freeConnection(con, pstmt);
707 /** @todo store entity in o_store */
712 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
713 * wird automatisch mit dem aktuellen Datum gefuellt.
717 public void update (Entity theEntity) throws StorageObjectException
719 Connection con = null; PreparedStatement pstmt = null;
720 /** @todo this is stupid: why do we prepare statement, when we
721 * throw it away afterwards. should be regular statement
722 * update/insert could better be one routine called save()
723 * that chooses to either insert or update depending if we
724 * have a primary key in the entity. i don't know if we
725 * still need the streamed input fields. // rk */
727 /** @todo extension: check if Entity did change, otherwise we don't need
728 * the roundtrip to the database */
730 /** invalidating corresponding entitylists in o_store*/
731 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
732 StoreContainerType stoc_type =
733 StoreContainerType.valueOf( theEntityClass,
734 StoreContainerType.STOC_TYPE_ENTITYLIST);
735 o_store.invalidate(stoc_type);
738 ArrayList streamedInput = theEntity.streamedInput();
739 String id = theEntity.getId();
741 StringBuffer fv = new StringBuffer();
742 boolean firstField = true;
744 invalidatePopupCache();
745 // build sql statement
746 for (int i = 0; i < getFields().size(); i++) {
747 aField = (String)metadataFields.get(i);
749 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
750 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
751 if (theEntity.hasValueForField(aField)) {
752 if (firstField == false) {
758 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
762 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
764 if (metadataFields.contains("webdb_lastchange")) {
765 sql.append(",webdb_lastchange=NOW()");
767 if (streamedInput != null) {
768 for (int i = 0; i < streamedInput.size(); i++) {
769 sql.append(",").append(streamedInput.get(i)).append("=?");
772 sql.append(" where id=").append(id);
773 theLog.printInfo("UPDATE: " + sql);
776 con = getPooledCon();
777 con.setAutoCommit(false);
778 pstmt = con.prepareStatement(sql.toString());
779 if (streamedInput != null) {
780 for (int i = 0; i < streamedInput.size(); i++) {
781 String inputString = theEntity.getValue((String)streamedInput.get(i));
782 pstmt.setBytes(i + 1, inputString.getBytes());
785 pstmt.executeUpdate();
786 } catch (SQLException sqe) {
787 throwSQLException(sqe, "update");
790 con.setAutoCommit(true);
791 } catch (Exception e) {
794 freeConnection(con, pstmt);
800 * @param id des zu loeschenden Datensatzes
801 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
803 public boolean delete (String id) throws StorageObjectException {
805 invalidatePopupCache();
806 // ostore send notification
807 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
808 String uniqueId = id;
809 if ( theEntityClass.equals(StorableObjectEntity.class) )
810 uniqueId+="@"+theTable;
811 theLog.printInfo("CACHE: (del) " + id);
812 StoreIdentifier search_sid =
813 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
814 o_store.invalidate(search_sid);
817 /** @todo could be prepared Statement */
818 Statement stmt = null; Connection con = null;
820 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
821 theLog.printInfo("DELETE " + sql);
823 con = getPooledCon(); stmt = con.createStatement();
824 res = stmt.executeUpdate(sql);
826 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
827 finally { freeConnection(con, stmt); }
829 return (res > 0) ? true : false;
832 /* noch nicht implementiert.
833 * @return immer false
835 public boolean delete (EntityList theEntityList) {
836 invalidatePopupCache();
841 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
842 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
845 public SimpleList getPopupData () throws StorageObjectException {
850 * Holt Daten fuer Popups.
851 * @param name Name des Feldes.
852 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
853 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
855 public SimpleList getPopupData (String name, boolean hasNullValue)
856 throws StorageObjectException {
857 return getPopupData(name, hasNullValue, null);
861 * Holt Daten fuer Popups.
862 * @param name Name des Feldes.
863 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
864 * @param where Schraenkt die Selektion der Datensaetze ein.
865 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
867 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
868 return getPopupData(name, hasNullValue, where, null);
872 * Holt Daten fuer Popups.
873 * @param name Name des Feldes.
874 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
875 * @param where Schraenkt die Selektion der Datensaetze ein.
876 * @param order Gibt ein Feld als Sortierkriterium an.
877 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
879 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
881 if (hasPopupCache && popupCache != null)
883 SimpleList simpleList = null;
884 Connection con = null;
885 Statement stmt = null;
887 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
888 .append(",").append(name).append(" from ")
890 if (where != null && !(where.length() == 0))
891 sql.append(" where ").append(where);
892 sql.append(" order by ");
893 if (order != null && !(order.length() == 0))
899 con = getPooledCon();
900 } catch (Exception e) {
901 throw new StorageObjectException(e.toString());
904 stmt = con.createStatement();
905 ResultSet rs = executeSql(stmt, sql.toString());
908 if (!evaluatedMetaData) get_meta_data();
909 simpleList = new SimpleList();
910 // if popup has null-selector
911 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
913 SimpleHash popupDict;
915 popupDict = new SimpleHash();
916 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
917 popupDict.put("value", rs.getString(2));
918 simpleList.add(popupDict);
922 } catch (Exception e) {
923 theLog.printError("getPopupData: "+e.toString());
924 throw new StorageObjectException(e.toString());
926 freeConnection(con, stmt);
929 if (hasPopupCache) popupCache = simpleList;
934 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
935 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
936 * Tabellen Verwendung finden.
937 * @return SimpleHash mit den Tabellezeilen.
939 public SimpleHash getHashData () {
940 /** @todo dangerous! this should have a flag to be enabled, otherwise
941 * very big Hashes could be returned */
942 if (hashCache == null) {
944 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
946 } catch (StorageObjectException e) {
947 theLog.printDebugInfo(e.toString());
953 /* invalidates the popupCache
955 protected void invalidatePopupCache () {
956 /** @todo invalidates toooo much */
962 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
963 * @param stmt Statemnt
964 * @param sql Sql-String
966 * @exception StorageObjectException
968 public ResultSet executeSql (Statement stmt, String sql)
969 throws StorageObjectException, SQLException
971 long startTime = System.currentTimeMillis();
974 rs = stmt.executeQuery(sql);
975 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
978 catch (SQLException e)
980 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
981 - startTime) + "ms. for: "+ sql);
989 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
990 * getimed und geloggt.
991 * @param stmt PreparedStatement mit der SQL-Anweisung
992 * @return Liefert ResultSet des Statements zurueck.
993 * @exception StorageObjectException, SQLException
995 public ResultSet executeSql (PreparedStatement stmt)
996 throws StorageObjectException, SQLException {
998 long startTime = (new java.util.Date()).getTime();
999 ResultSet rs = stmt.executeQuery();
1000 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1005 * returns the number of rows in the table
1007 public int getSize(String where)
1008 throws SQLException,StorageObjectException
1010 long startTime = System.currentTimeMillis();
1011 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
1012 Connection con = null;
1013 Statement stmt = null;
1017 con = getPooledCon();
1018 stmt = con.createStatement();
1019 ResultSet rs = executeSql(stmt,sql);
1021 result = rs.getInt(1);
1023 } catch (SQLException e) {
1024 theLog.printError(e.toString());
1026 freeConnection(con,stmt);
1028 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1029 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1034 public int executeUpdate(Statement stmt, String sql)
1035 throws StorageObjectException, SQLException
1038 long startTime = (new java.util.Date()).getTime();
1041 rs = stmt.executeUpdate(sql);
1042 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1045 catch (SQLException e)
1047 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1048 - startTime) + "ms. for: "+ sql);
1054 public int executeUpdate(String sql)
1055 throws StorageObjectException, SQLException
1058 long startTime = (new java.util.Date()).getTime();
1059 Connection con=null;PreparedStatement pstmt=null;
1062 pstmt = con.prepareStatement(sql);
1063 result = pstmt.executeUpdate();
1065 catch (Exception e) {
1066 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1067 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1069 finally { freeConnection(con,pstmt); }
1070 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1076 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1077 * @param md ResultSetMetaData
1078 * @exception StorageObjectException
1080 private void evalMetaData (ResultSetMetaData md)
1081 throws StorageObjectException {
1083 this.evaluatedMetaData = true;
1084 this.metadataFields = new ArrayList();
1085 this.metadataLabels = new ArrayList();
1086 this.metadataNotNullFields = new ArrayList();
1088 int numFields = md.getColumnCount();
1089 this.metadataTypes = new int[numFields];
1092 for (int i = 1; i <= numFields; i++) {
1093 aField = md.getColumnName(i);
1094 metadataFields.add(aField);
1095 metadataLabels.add(md.getColumnLabel(i));
1096 aType = md.getColumnType(i);
1097 metadataTypes[i - 1] = aType;
1098 if (aField.equals(thePKeyName)) {
1099 thePKeyType = aType; thePKeyIndex = i;
1101 if (md.isNullable(i) == md.columnNullable) {
1102 metadataNotNullFields.add(aField);
1105 } catch (SQLException e) {
1106 throwSQLException(e, "evalMetaData");
1111 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1112 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1114 private void get_meta_data () throws StorageObjectException {
1115 Connection con = null;
1116 PreparedStatement pstmt = null;
1117 String sql = "select * from " + theTable + " where 0=1";
1119 con = getPooledCon();
1120 pstmt = con.prepareStatement(sql);
1121 theLog.printInfo("METADATA: " + sql);
1122 ResultSet rs = pstmt.executeQuery();
1123 evalMetaData(rs.getMetaData());
1125 } catch (SQLException e) {
1126 throwSQLException(e, "get_meta_data");
1128 freeConnection(con, pstmt);
1133 public Connection getPooledCon() throws StorageObjectException {
1134 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1136 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1137 } catch (Exception e){
1138 throw new StorageObjectException("Could not find the PoolMan Driver"
1141 Connection con = null;
1143 con = SQLManager.getInstance().requestConnection();
1144 } catch(SQLException e){
1145 theLog.printError("could not connect to the database "+e.toString());
1146 System.err.println("could not connect to the database "+e.toString());
1147 throw new StorageObjectException("Could not connect to the database"+
1153 public void freeConnection (Connection con, Statement stmt)
1154 throws StorageObjectException {
1155 SQLManager.getInstance().closeStatement(stmt);
1156 SQLManager.getInstance().returnConnection(con);
1160 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1161 * @param sqe SQLException
1162 * @param wo Funktonsname, in der die SQLException geworfen wurde
1163 * @exception StorageObjectException
1165 protected void throwSQLException (SQLException sqe, String wo)
1166 throws StorageObjectException {
1168 String message = "";
1171 state = sqe.getSQLState();
1172 message = sqe.getMessage();
1173 vendor = sqe.getErrorCode();
1175 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1177 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1181 protected void _throwStorageObjectException (Exception e, String wo)
1182 throws StorageObjectException {
1184 theLog.printError(e.toString()+ wo);
1185 throw new StorageObjectException(wo + e.toString());
1187 theLog.printError(wo);
1188 throw new StorageObjectException(wo);
1194 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1195 * eine StorageObjectException
1196 * @param message Nachricht mit dem Fehler
1197 * @exception StorageObjectException
1199 void throwStorageObjectException (String message)
1200 throws StorageObjectException {
1201 _throwStorageObjectException(null, message);