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();
586 theResult = getValueAsString(rs, (i + 1), theType);
588 if (theResult != null) {
589 theResultHash.put(metadataFields.get(i), theResult);
592 if (theEntityClass != null) {
593 returnEntity = (Entity)theEntityClass.newInstance();
594 returnEntity.setValues(theResultHash);
595 returnEntity.setStorage(myselfDatabase);
596 if ( returnEntity instanceof StorableObject ) {
597 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
598 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
601 throwStorageObjectException("Internal Error: theEntityClass not set!");
603 } catch (IllegalAccessException e) {
604 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
605 /* } catch (IOException e) {
606 throwStorageObjectException("IOException! -- " + e.toString());
607 */ } catch (InstantiationException e) {
608 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
609 /* } catch (SQLException sqe) {
610 throwSQLException(sqe, "makeEntityFromResultSet");
617 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
618 * wird automatisch mit dem aktuellen Datum gefuellt.
621 * @return der Wert des Primary-keys der eingefügten Entity
623 public String insert (Entity theEntity) throws StorageObjectException {
625 invalidatePopupCache();
627 // invalidating all EntityLists corresponding with theEntityClass
628 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
629 StoreContainerType stoc_type =
630 StoreContainerType.valueOf( theEntityClass,
631 StoreContainerType.STOC_TYPE_ENTITYLIST);
632 o_store.invalidate(stoc_type);
635 String returnId = null;
636 Connection con = null; PreparedStatement pstmt = null;
639 ArrayList streamedInput = theEntity.streamedInput();
640 StringBuffer f = new StringBuffer();
641 StringBuffer v = new StringBuffer();
642 String aField, aValue;
643 boolean firstField = true;
645 for (int i = 0; i < getFields().size(); i++) {
646 aField = (String)getFields().get(i);
647 if (!aField.equals(thePKeyName)) {
650 if (aField.equals("webdb_create")) {
654 if (streamedInput != null && streamedInput.contains(aField)) {
658 if (theEntity.hasValueForField(aField)) {
659 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
664 // wenn Wert gegeben, dann einbauen
665 if (aValue != null) {
666 if (firstField == false) {
679 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
680 String sql = sqlBuf.toString();
681 theLog.printInfo("INSERT: " + sql);
682 con = getPooledCon();
683 con.setAutoCommit(false);
684 pstmt = con.prepareStatement(sql);
685 if (streamedInput != null) {
686 for (int i = 0; i < streamedInput.size(); i++) {
687 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
688 pstmt.setBytes(i + 1, inputString.getBytes());
691 int ret = pstmt.executeUpdate();
696 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
697 ResultSet rs = pstmt.executeQuery();
699 returnId = rs.getString(1);
700 theEntity.setId(returnId);
701 } catch (SQLException sqe) {
702 throwSQLException(sqe, "insert");
705 con.setAutoCommit(true);
706 } catch (Exception e) {
709 freeConnection(con, pstmt);
711 /** @todo store entity in o_store */
716 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
717 * wird automatisch mit dem aktuellen Datum gefuellt.
721 public void update (Entity theEntity) throws StorageObjectException
723 Connection con = null; PreparedStatement pstmt = null;
724 /** @todo this is stupid: why do we prepare statement, when we
725 * throw it away afterwards. should be regular statement
726 * update/insert could better be one routine called save()
727 * that chooses to either insert or update depending if we
728 * have a primary key in the entity. i don't know if we
729 * still need the streamed input fields. // rk */
731 /** @todo extension: check if Entity did change, otherwise we don't need
732 * the roundtrip to the database */
734 /** invalidating corresponding entitylists in o_store*/
735 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
736 StoreContainerType stoc_type =
737 StoreContainerType.valueOf( theEntityClass,
738 StoreContainerType.STOC_TYPE_ENTITYLIST);
739 o_store.invalidate(stoc_type);
742 ArrayList streamedInput = theEntity.streamedInput();
743 String id = theEntity.getId();
745 StringBuffer fv = new StringBuffer();
746 boolean firstField = true;
748 invalidatePopupCache();
749 // build sql statement
750 for (int i = 0; i < getFields().size(); i++) {
751 aField = (String)metadataFields.get(i);
753 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
754 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
755 if (theEntity.hasValueForField(aField)) {
756 if (firstField == false) {
762 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
766 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
768 if (metadataFields.contains("webdb_lastchange")) {
769 sql.append(",webdb_lastchange=NOW()");
771 if (streamedInput != null) {
772 for (int i = 0; i < streamedInput.size(); i++) {
773 sql.append(",").append(streamedInput.get(i)).append("=?");
776 sql.append(" where id=").append(id);
777 theLog.printInfo("UPDATE: " + sql);
780 con = getPooledCon();
781 con.setAutoCommit(false);
782 pstmt = con.prepareStatement(sql.toString());
783 if (streamedInput != null) {
784 for (int i = 0; i < streamedInput.size(); i++) {
785 String inputString = theEntity.getValue((String)streamedInput.get(i));
786 pstmt.setBytes(i + 1, inputString.getBytes());
789 pstmt.executeUpdate();
790 } catch (SQLException sqe) {
791 throwSQLException(sqe, "update");
794 con.setAutoCommit(true);
795 } catch (Exception e) {
798 freeConnection(con, pstmt);
804 * @param id des zu loeschenden Datensatzes
805 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
807 public boolean delete (String id) throws StorageObjectException {
809 invalidatePopupCache();
810 // ostore send notification
811 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
812 String uniqueId = id;
813 if ( theEntityClass.equals(StorableObjectEntity.class) )
814 uniqueId+="@"+theTable;
815 theLog.printInfo("CACHE: (del) " + id);
816 StoreIdentifier search_sid =
817 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
818 o_store.invalidate(search_sid);
821 /** @todo could be prepared Statement */
822 Statement stmt = null; Connection con = null;
824 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
825 theLog.printInfo("DELETE " + sql);
827 con = getPooledCon(); stmt = con.createStatement();
828 res = stmt.executeUpdate(sql);
830 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
831 finally { freeConnection(con, stmt); }
833 return (res > 0) ? true : false;
836 /* noch nicht implementiert.
837 * @return immer false
839 public boolean delete (EntityList theEntityList) {
840 invalidatePopupCache();
845 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
846 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
849 public SimpleList getPopupData () throws StorageObjectException {
854 * Holt Daten fuer Popups.
855 * @param name Name des Feldes.
856 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
857 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
859 public SimpleList getPopupData (String name, boolean hasNullValue)
860 throws StorageObjectException {
861 return getPopupData(name, hasNullValue, null);
865 * Holt Daten fuer Popups.
866 * @param name Name des Feldes.
867 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
868 * @param where Schraenkt die Selektion der Datensaetze ein.
869 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
871 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
872 return getPopupData(name, hasNullValue, where, null);
876 * Holt Daten fuer Popups.
877 * @param name Name des Feldes.
878 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
879 * @param where Schraenkt die Selektion der Datensaetze ein.
880 * @param order Gibt ein Feld als Sortierkriterium an.
881 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
883 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
885 if (hasPopupCache && popupCache != null)
887 SimpleList simpleList = null;
888 Connection con = null;
889 Statement stmt = null;
891 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
892 .append(",").append(name).append(" from ")
894 if (where != null && !(where.length() == 0))
895 sql.append(" where ").append(where);
896 sql.append(" order by ");
897 if (order != null && !(order.length() == 0))
903 con = getPooledCon();
904 } catch (Exception e) {
905 throw new StorageObjectException(e.toString());
908 stmt = con.createStatement();
909 ResultSet rs = executeSql(stmt, sql.toString());
912 if (!evaluatedMetaData) get_meta_data();
913 simpleList = new SimpleList();
914 // if popup has null-selector
915 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
917 SimpleHash popupDict;
919 popupDict = new SimpleHash();
920 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
921 popupDict.put("value", rs.getString(2));
922 simpleList.add(popupDict);
926 } catch (Exception e) {
927 theLog.printError("getPopupData: "+e.toString());
928 throw new StorageObjectException(e.toString());
930 freeConnection(con, stmt);
933 if (hasPopupCache) popupCache = simpleList;
938 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
939 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
940 * Tabellen Verwendung finden.
941 * @return SimpleHash mit den Tabellezeilen.
943 public SimpleHash getHashData () {
944 /** @todo dangerous! this should have a flag to be enabled, otherwise
945 * very big Hashes could be returned */
946 if (hashCache == null) {
948 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
950 } catch (StorageObjectException e) {
951 theLog.printDebugInfo(e.toString());
957 /* invalidates the popupCache
959 protected void invalidatePopupCache () {
960 /** @todo invalidates toooo much */
966 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
967 * @param stmt Statemnt
968 * @param sql Sql-String
970 * @exception StorageObjectException
972 public ResultSet executeSql (Statement stmt, String sql)
973 throws StorageObjectException, SQLException
975 long startTime = System.currentTimeMillis();
978 rs = stmt.executeQuery(sql);
979 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
982 catch (SQLException e)
984 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
985 - startTime) + "ms. for: "+ sql);
993 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
994 * getimed und geloggt.
995 * @param stmt PreparedStatement mit der SQL-Anweisung
996 * @return Liefert ResultSet des Statements zurueck.
997 * @exception StorageObjectException, SQLException
999 public ResultSet executeSql (PreparedStatement stmt)
1000 throws StorageObjectException, SQLException {
1002 long startTime = (new java.util.Date()).getTime();
1003 ResultSet rs = stmt.executeQuery();
1004 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1009 * returns the number of rows in the table
1011 public int getSize(String where)
1012 throws SQLException,StorageObjectException
1014 long startTime = System.currentTimeMillis();
1015 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
1016 Connection con = null;
1017 Statement stmt = null;
1021 con = getPooledCon();
1022 stmt = con.createStatement();
1023 ResultSet rs = executeSql(stmt,sql);
1025 result = rs.getInt(1);
1027 } catch (SQLException e) {
1028 theLog.printError(e.toString());
1030 freeConnection(con,stmt);
1032 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1033 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1038 public int executeUpdate(Statement stmt, String sql)
1039 throws StorageObjectException, SQLException
1042 long startTime = (new java.util.Date()).getTime();
1045 rs = stmt.executeUpdate(sql);
1046 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1049 catch (SQLException e)
1051 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1052 - startTime) + "ms. for: "+ sql);
1058 public int executeUpdate(String sql)
1059 throws StorageObjectException, SQLException
1062 long startTime = (new java.util.Date()).getTime();
1063 Connection con=null;PreparedStatement pstmt=null;
1066 pstmt = con.prepareStatement(sql);
1067 result = pstmt.executeUpdate();
1069 catch (Exception e) {
1070 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1071 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1073 finally { freeConnection(con,pstmt); }
1074 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1080 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1081 * @param md ResultSetMetaData
1082 * @exception StorageObjectException
1084 private void evalMetaData (ResultSetMetaData md)
1085 throws StorageObjectException {
1087 this.evaluatedMetaData = true;
1088 this.metadataFields = new ArrayList();
1089 this.metadataLabels = new ArrayList();
1090 this.metadataNotNullFields = new ArrayList();
1092 int numFields = md.getColumnCount();
1093 this.metadataTypes = new int[numFields];
1096 for (int i = 1; i <= numFields; i++) {
1097 aField = md.getColumnName(i);
1098 metadataFields.add(aField);
1099 metadataLabels.add(md.getColumnLabel(i));
1100 aType = md.getColumnType(i);
1101 metadataTypes[i - 1] = aType;
1102 if (aField.equals(thePKeyName)) {
1103 thePKeyType = aType; thePKeyIndex = i;
1105 if (md.isNullable(i) == md.columnNullable) {
1106 metadataNotNullFields.add(aField);
1109 } catch (SQLException e) {
1110 throwSQLException(e, "evalMetaData");
1115 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1116 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1118 private void get_meta_data () throws StorageObjectException {
1119 Connection con = null;
1120 PreparedStatement pstmt = null;
1121 String sql = "select * from " + theTable + " where 0=1";
1123 con = getPooledCon();
1124 pstmt = con.prepareStatement(sql);
1125 theLog.printInfo("METADATA: " + sql);
1126 ResultSet rs = pstmt.executeQuery();
1127 evalMetaData(rs.getMetaData());
1129 } catch (SQLException e) {
1130 throwSQLException(e, "get_meta_data");
1132 freeConnection(con, pstmt);
1137 public Connection getPooledCon() throws StorageObjectException {
1138 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1140 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1141 } catch (Exception e){
1142 throw new StorageObjectException("Could not find the PoolMan Driver"
1145 Connection con = null;
1147 con = SQLManager.getInstance().requestConnection();
1148 } catch(SQLException e){
1149 theLog.printError("could not connect to the database "+e.toString());
1150 System.err.println("could not connect to the database "+e.toString());
1151 throw new StorageObjectException("Could not connect to the database"+
1157 public void freeConnection (Connection con, Statement stmt)
1158 throws StorageObjectException {
1159 SQLManager.getInstance().closeStatement(stmt);
1160 SQLManager.getInstance().returnConnection(con);
1164 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1165 * @param sqe SQLException
1166 * @param wo Funktonsname, in der die SQLException geworfen wurde
1167 * @exception StorageObjectException
1169 protected void throwSQLException (SQLException sqe, String wo)
1170 throws StorageObjectException {
1172 String message = "";
1175 state = sqe.getSQLState();
1176 message = sqe.getMessage();
1177 vendor = sqe.getErrorCode();
1179 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1181 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1185 protected void _throwStorageObjectException (Exception e, String wo)
1186 throws StorageObjectException {
1188 theLog.printError(e.toString()+ wo);
1189 throw new StorageObjectException(wo + e.toString());
1191 theLog.printError(wo);
1192 throw new StorageObjectException(wo);
1198 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1199 * eine StorageObjectException
1200 * @param message Nachricht mit dem Fehler
1201 * @exception StorageObjectException
1203 void throwStorageObjectException (String message)
1204 throws StorageObjectException {
1205 _throwStorageObjectException(null, message);