2 * put your module comment here
10 import freemarker.template.*;
11 import mir.storage.StorageObject;
14 import com.codestudio.sql.*;
15 import com.codestudio.util.*;
19 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
20 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
21 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
22 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
23 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
29 public class Database implements StorageObject {
31 protected String theTable;
32 protected String theCoreTable=null;
33 protected String thePKeyName="id";
34 protected int thePKeyType;
35 protected boolean evaluatedMetaData=false;
36 protected ArrayList metadataFields,metadataLabels,
37 metadataNotNullFields;
38 protected int[] metadataTypes;
39 protected Class theEntityClass;
40 protected StorageObject myselfDatabase;
41 protected DatabaseCache cache;
42 protected SimpleList popupCache=null;
43 protected boolean hasPopupCache = false;
44 protected SimpleHash hashCache=null;
45 protected boolean hasTimestamp=true;
46 private String database_driver;
47 private String database_url;
48 private int defaultLimit;
49 protected DatabaseAdaptor theAdaptor;
50 protected Logfile theLog;
53 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
54 * Aus diesem file werden <code>Database.Logfile</code>,
55 * <code>Database.Username</code>,<code>Database.Password</code>,
56 * <code>Database.Host</code> und <code>Database.Adaptor</code>
57 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
60 * @param String confFilename Dateiname der Konfigurationsdatei
62 public Database() throws StorageObjectException {
63 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
64 MirConfig.getProp("Database.Logfile"));
65 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
66 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
68 theEntityClass = Class.forName("mir.entity.GenericEntity");
69 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
70 } catch (Exception e){
71 theLog.printError("Error in Database() constructor with "+
72 theAdaptorName + " -- " +e.toString());
73 throw new StorageObjectException("Error in Database() constructor with "
76 /*String database_username=MirConfig.getProp("Database.Username");
77 String database_password=MirConfig.getProp("Database.Password");
78 String database_host=MirConfig.getProp("Database.Host");
80 database_driver=theAdaptor.getDriver();
81 database_url=theAdaptor.getURL(database_username,database_password,
83 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
85 MirConfig.addBroker(database_driver,database_url);
86 //myBroker=MirConfig.getBroker();
91 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
92 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
93 * wird eine mir.entity.GenericEntity erzeugt.
95 * @return Class-Objekt der Entity
97 public java.lang.Class getEntityClass () {
98 return theEntityClass;
102 * Liefert die Standardbeschränkung von select-Statements zurück, also
103 * wieviel Datensätze per Default selektiert werden.
105 * @return Standard-Anzahl der Datensätze
107 public int getLimit () {
112 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
113 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
114 * @return Name des Primary-Keys
116 public String getIdName () {
121 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
123 * @return Name der Tabelle
125 public String getTableName () {
130 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
131 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
133 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
137 public String getCoreTable(){
138 if (theCoreTable!=null) return theCoreTable;
139 else return theTable;
143 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
144 * @return int-Array mit den Typen der Felder
145 * @exception StorageObjectException
147 public int[] getTypes () throws StorageObjectException {
148 if (metadataTypes == null)
150 return metadataTypes;
154 * Liefert eine Liste der Labels der Tabellenfelder
155 * @return ArrayListe mit Labeln
156 * @exception StorageObjectException
158 public ArrayList getLabels () throws StorageObjectException {
159 if (metadataLabels == null)
161 return metadataLabels;
165 * Liefert eine Liste der Felder der Tabelle
166 * @return ArrayList mit Feldern
167 * @exception StorageObjectException
169 public ArrayList getFields () throws StorageObjectException {
170 if (metadataFields == null)
172 return metadataFields;
177 * Gets value out of ResultSet according to type and converts to String
178 * @param inValue Wert aus ResultSet.
179 * @param aType Datenbanktyp.
180 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
181 * dann /unsupported value/
183 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
184 String outValue = null;
188 case java.sql.Types.BIT:
189 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
191 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
192 int out = rs.getInt(valueIndex);
194 outValue = new Integer(out).toString();
196 case java.sql.Types.NUMERIC:
197 long outl = rs.getLong(valueIndex);
199 outValue = new Long(outl).toString();
201 case java.sql.Types.REAL:
202 float tempf = rs.getFloat(valueIndex);
206 int tempf_int = (int)tempf;
207 tempf = (float)tempf_int;
209 outValue = "" + tempf;
210 outValue = outValue.replace('.', ',');
213 case java.sql.Types.DOUBLE:
214 double tempd = rs.getDouble(valueIndex);
218 int tempd_int = (int)tempd;
219 tempd = (double)tempd_int;
221 outValue = "" + tempd;
222 outValue = outValue.replace('.', ',');
225 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
226 outValue = rs.getString(valueIndex);
227 //if (outValue != null)
228 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
230 case java.sql.Types.LONGVARBINARY:
231 outValue = rs.getString(valueIndex);
232 //if (outValue != null)
233 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
235 case java.sql.Types.TIMESTAMP:
236 Timestamp timestamp = (rs.getTimestamp(valueIndex));
238 outValue = timestamp.toString();
242 outValue = "<unsupported value>";
243 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
246 } catch (SQLException e) {
247 throw new StorageObjectException("Could not get Value out of Resultset -- "
255 * select-Operator um einen Datensatz zu bekommen.
256 * @param id Primaerschluessel des Datensatzes.
257 * @return liefert EntityObject des gefundenen Datensatzes oder null.
259 public Entity selectById(String id)
260 throws StorageObjectException {
262 if (id==null||id.equals(""))
263 throw new StorageObjectException("id war null");
264 if (cache != null && (cache.containsKey(id) > -1))
265 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
267 Statement stmt=null;Connection con=getPooledCon();
268 Entity returnEntity=null;
271 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
272 stmt = con.createStatement();
273 rs = executeSql(stmt, selectSql);
275 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
277 returnEntity = makeEntityFromResultSet(rs);
278 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
281 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
283 } catch (SQLException sqe){
284 throwSQLException(sqe,"selectById"); return null;
285 } catch (NumberFormatException e) {
286 theLog.printError("ID ist keine Zahl: " + id);
288 freeConnection(con,stmt);
295 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
296 * @param key Datenbankfeld der Bedingung.
297 * @param value Wert die der key anehmen muss.
298 * @return EntityList mit den gematchten Entities
301 public EntityList selectByFieldValue(String aField, String aValue)
302 throws StorageObjectException {
304 return selectByFieldValue(aField, aValue, 0);
308 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
309 * @param key Datenbankfeld der Bedingung.
310 * @param value Wert die der key anehmen muss.
311 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
312 * @return EntityList mit den gematchten Entities
315 public EntityList selectByFieldValue(String aField, String aValue, int offset)
316 throws StorageObjectException {
318 return selectByWhereClause(aField + "=" + aValue, offset);
323 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
324 * Also offset wird der erste Datensatz genommen.
326 * @param wc where-Clause
327 * @return EntityList mit den gematchten Entities
328 * @exception StorageObjectException
330 public EntityList selectByWhereClause(String where)
331 throws StorageObjectException {
333 return selectByWhereClause(where, 0);
338 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
339 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
341 * @param wc where-Clause
342 * @param offset ab welchem Datensatz.
343 * @return EntityList mit den gematchten Entities
344 * @exception StorageObjectException
346 public EntityList selectByWhereClause(String whereClause, int offset)
347 throws StorageObjectException {
349 return selectByWhereClause(whereClause, null, offset);
353 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
354 * Also offset wird der erste Datensatz genommen.
355 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
357 * @param wc where-Clause
358 * @param ob orderBy-Clause
359 * @return EntityList mit den gematchten Entities
360 * @exception StorageObjectException
363 public EntityList selectByWhereClause(String where, String order)
364 throws StorageObjectException {
366 return selectByWhereClause(where, order, 0);
369 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
370 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
372 * @param wc where-Clause
373 * @param ob orderBy-Clause
374 * @param offset ab welchem Datensatz
375 * @return EntityList mit den gematchten Entities
376 * @exception StorageObjectException
379 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
380 throws StorageObjectException {
382 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
387 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
388 * @param wc where-Clause
389 * @param ob orderBy-Clause
390 * @param offset ab welchem Datensatz
391 * @param limit wieviele Datensätze
392 * @return EntityList mit den gematchten Entities
393 * @exception StorageObjectException
396 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
397 throws StorageObjectException {
400 EntityList theReturnList=null;
408 // build sql-statement
410 /** @todo count sql string should only be assembled if we really count
411 * see below at the end of method //rk */
413 if (wc != null && wc.length() == 0) {
416 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
417 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
419 selectSql.append(" where ").append(wc);
420 countSql.append(" where ").append(wc);
422 if (ob != null && !(ob.length() == 0)) {
423 selectSql.append(" order by ").append(ob);
425 if (theAdaptor.hasLimit()) {
426 if (limit > -1 && offset > -1) {
427 selectSql.append(" limit ");
428 if (theAdaptor.reverseLimit()) {
429 selectSql.append(limit).append(",").append(offset);
432 selectSql.append(offset).append(",").append(limit);
439 con = getPooledCon();
440 stmt = con.createStatement();
443 rs = executeSql(stmt, selectSql.toString());
445 theReturnList = new EntityList();
446 if (evaluatedMetaData == false) {
447 evalMetaData(rs.getMetaData());
449 Entity theResultEntity;
451 theResultEntity = makeEntityFromResultSet(rs);
452 theReturnList.add(theResultEntity);
458 // making entitylist infos
459 if (!(theAdaptor.hasLimit())) count = offsetCount;
461 if (theReturnList != null) {
462 // now we decide if we have to know an overall count...
464 if (limit > -1 && offset > -1) {
465 if (offsetCount==limit) {
466 rs = executeSql(stmt, countSql.toString());
468 if ( rs.next() ) count = rs.getInt(1);
471 else theLog.printError("Could not count: " + countSql);
475 theReturnList.setCount(count);
477 theReturnList.setOffset(offset);
478 theReturnList.setWhere(wc);
479 theReturnList.setOrder(ob);
480 if (offset >= limit) {
481 theReturnList.setPrevBatch(offset - limit);
483 if (offset + offsetCount < count) {
484 theReturnList.setNextBatch(offset + limit);
490 } catch (SQLException sqe) {
491 throwSQLException(sqe, "selectByWhereClause");
493 freeConnection(con, stmt);
495 return theReturnList;
500 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
502 * @param rs Das ResultSetObjekt.
503 * @return Entity Die Entity.
506 private Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
507 HashMap theResultHash = new HashMap();
508 String theResult = null;
510 Entity returnEntity = null;
512 int size = metadataFields.size();
513 for (int i = 0; i < size; i++) {
514 // alle durchlaufen bis nix mehr da
515 theType = metadataTypes[i];
516 if (theType == java.sql.Types.LONGVARBINARY) {
517 InputStream us = rs.getAsciiStream(i + 1);
519 InputStreamReader is = new InputStreamReader(us);
520 char[] data = new char[32768];
521 StringBuffer theResultString = new StringBuffer();
523 while ((len = is.read(data)) > 0) {
524 theResultString.append(data, 0, len);
527 theResult = theResultString.toString();
534 theResult = getValueAsString(rs, (i + 1), theType);
536 if (theResult != null) {
537 theResultHash.put(metadataFields.get(i), theResult);
540 if (cache != null && theResultHash.containsKey(thePKeyName) &&
541 (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
542 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
544 if (theEntityClass != null) {
545 returnEntity = (Entity)theEntityClass.newInstance();
546 returnEntity.setValues(theResultHash);
547 returnEntity.setStorage(myselfDatabase);
549 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
550 cache.put(returnEntity.getId(), returnEntity);
553 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
556 } catch (IllegalAccessException e) {
557 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
558 } catch (IOException e) {
559 throwStorageObjectException("IOException! -- " + e.toString());
560 } catch (InstantiationException e) {
561 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
562 } catch (SQLException sqe) {
563 throwSQLException(sqe, "makeEntityFromResultSet");
570 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
571 * wird automatisch mit dem aktuellen Datum gefuellt.
574 * @return der Wert des Primary-keys der eingefügten Entity
576 public String insert (Entity theEntity) throws StorageObjectException {
577 String returnId = null;
578 Connection con = null;
579 PreparedStatement pstmt = null;
581 invalidatePopupCache();
583 ArrayList streamedInput = theEntity.streamedInput();
584 StringBuffer f = new StringBuffer();
585 StringBuffer v = new StringBuffer();
586 String aField, aValue;
587 boolean firstField = true;
589 for (int i = 0; i < getFields().size(); i++) {
590 aField = (String)getFields().get(i);
591 if (!aField.equals(thePKeyName)) {
594 if (aField.equals("webdb_create")) {
598 if (streamedInput != null && streamedInput.contains(aField)) {
602 if (theEntity.hasValueForField(aField)) {
603 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
608 // wenn Wert gegeben, dann einbauen
609 if (aValue != null) {
610 if (firstField == false) {
623 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
624 String sql = sqlBuf.toString();
625 theLog.printInfo("INSERT: " + sql);
626 con = getPooledCon();
627 con.setAutoCommit(false);
628 pstmt = con.prepareStatement(sql);
629 if (streamedInput != null) {
630 for (int i = 0; i < streamedInput.size(); i++) {
631 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
632 pstmt.setBytes(i + 1, inputString.getBytes());
635 int ret = pstmt.executeUpdate();
640 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
641 ResultSet rs = pstmt.executeQuery();
643 returnId = rs.getString(1);
644 theEntity.setId(returnId);
645 } catch (SQLException sqe) {
646 throwSQLException(sqe, "insert");
649 con.setAutoCommit(true);
650 } catch (Exception e) {
653 freeConnection(con, pstmt);
659 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
660 * wird automatisch mit dem aktuellen Datum gefuellt.
664 public void update (Entity theEntity) throws StorageObjectException {
665 Connection con = null;
666 PreparedStatement pstmt = null;
667 ArrayList streamedInput = theEntity.streamedInput();
668 String id = theEntity.getId();
670 StringBuffer fv = new StringBuffer();
671 boolean firstField = true;
673 invalidatePopupCache();
674 // build sql statement
675 for (int i = 0; i < getFields().size(); i++) {
676 aField = (String)metadataFields.get(i);
678 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
679 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
680 if (theEntity.hasValueForField(aField)) {
681 if (firstField == false) {
687 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
691 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
693 if (metadataFields.contains("webdb_lastchange")) {
694 sql.append(",webdb_lastchange=NOW()");
696 if (streamedInput != null) {
697 for (int i = 0; i < streamedInput.size(); i++) {
698 sql.append(",").append(streamedInput.get(i)).append("=?");
701 sql.append(" where id=").append(id);
702 theLog.printInfo("UPDATE: " + sql);
705 con = getPooledCon();
706 con.setAutoCommit(false);
707 pstmt = con.prepareStatement(sql.toString());
708 if (streamedInput != null) {
709 for (int i = 0; i < streamedInput.size(); i++) {
710 String inputString = theEntity.getValue((String)streamedInput.get(i));
711 pstmt.setBytes(i + 1, inputString.getBytes());
714 pstmt.executeUpdate();
715 } catch (SQLException sqe) {
716 throwSQLException(sqe, "update");
719 con.setAutoCommit(true);
720 } catch (Exception e) {
723 freeConnection(con, pstmt);
729 * @param id des zu loeschenden Datensatzes
730 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
732 public boolean delete (String id) throws StorageObjectException {
733 Statement stmt = null;
734 Connection con = null;
737 // loeschen des caches
738 invalidatePopupCache();
739 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
741 theLog.printInfo("DELETE " + sql);
743 con = getPooledCon();
744 stmt = con.createStatement();
745 res = stmt.executeUpdate(sql);
746 } catch (SQLException sqe) {
747 throwSQLException(sqe, "delete");
749 freeConnection(con, stmt);
752 theLog.printInfo("CACHE: deleted " + id);
755 return (res > 0) ? true : false;
758 /* noch nicht implementiert.
759 * @return immer false
761 public boolean delete (EntityList theEntityList) {
762 invalidatePopupCache();
767 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
768 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
771 public SimpleList getPopupData () throws StorageObjectException {
776 * Holt Daten fuer Popups.
777 * @param name Name des Feldes.
778 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
779 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
781 public SimpleList getPopupData (String name, boolean hasNullValue)
782 throws StorageObjectException {
783 return getPopupData(name, hasNullValue, null);
787 * Holt Daten fuer Popups.
788 * @param name Name des Feldes.
789 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
790 * @param where Schraenkt die Selektion der Datensaetze ein.
791 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
793 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
794 return getPopupData(name, hasNullValue, where, null);
798 * Holt Daten fuer Popups.
799 * @param name Name des Feldes.
800 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
801 * @param where Schraenkt die Selektion der Datensaetze ein.
802 * @param order Gibt ein Feld als Sortierkriterium an.
803 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
805 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
807 if (hasPopupCache && popupCache != null)
809 SimpleList simpleList = null;
810 Connection con = null;
811 Statement stmt = null;
813 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
814 .append(",").append(name).append(" from ")
816 if (where != null && !(where.length() == 0))
817 sql.append(" where ").append(where);
818 sql.append(" order by ");
819 if (order != null && !(order.length() == 0))
825 con = getPooledCon();
826 } catch (Exception e) {
827 throw new StorageObjectException(e.toString());
830 stmt = con.createStatement();
831 ResultSet rs = executeSql(stmt, sql.toString());
833 if (evaluatedMetaData == false)
835 simpleList = new SimpleList();
836 SimpleHash popupDict;
838 popupDict = new SimpleHash();
839 popupDict.put("key", "");
840 popupDict.put("value", "--");
841 simpleList.add(popupDict);
844 popupDict = new SimpleHash();
845 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
846 popupDict.put("value", rs.getString(2));
847 simpleList.add(popupDict);
851 } catch (Exception e) {
852 theLog.printError("getPopupData: "+e.toString());
853 throw new StorageObjectException(e.toString());
855 freeConnection(con, stmt);
858 popupCache = simpleList;
864 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
865 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
866 * Tabellen Verwendung finden.
867 * @return SimpleHash mit den Tabellezeilen.
869 public SimpleHash getHashData () {
870 if (hashCache == null) {
872 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
874 } catch (StorageObjectException e) {
875 theLog.printDebugInfo(e.toString());
881 /* invalidates the popupCache
883 protected void invalidatePopupCache () {
885 /** @todo invalidates toooo much */
891 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
892 * @param stmt Statemnt
893 * @param sql Sql-String
895 * @exception StorageObjectException
897 public ResultSet executeSql (Statement stmt, String sql)
898 throws StorageObjectException, SQLException
901 long startTime = (new java.util.Date()).getTime();
903 rs = stmt.executeQuery(sql);
904 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
907 catch (SQLException e)
909 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
910 - startTime) + "ms. for: "+ sql);
918 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
919 * getimed und geloggt.
920 * @param stmt PreparedStatement mit der SQL-Anweisung
921 * @return Liefert ResultSet des Statements zurueck.
922 * @exception StorageObjectException, SQLException
924 public ResultSet executeSql (PreparedStatement stmt)
925 throws StorageObjectException, SQLException {
927 long startTime = (new java.util.Date()).getTime();
928 ResultSet rs = stmt.executeQuery();
929 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
934 * returns the number of rows in the table
936 public int getSize(String where)
937 throws SQLException,StorageObjectException
939 long startTime = (new java.util.Date()).getTime();
940 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
941 //theLog.printDebugInfo("trying: "+ sql);
942 Connection con = null;
943 Statement stmt = null;
947 con = getPooledCon();
948 stmt = con.createStatement();
949 ResultSet rs = executeSql(stmt,sql);
951 result = rs.getInt(1);
953 } catch (SQLException e) {
954 theLog.printError(e.toString());
956 freeConnection(con,stmt);
958 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
959 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
964 public int executeUpdate(Statement stmt, String sql)
965 throws StorageObjectException, SQLException
968 long startTime = (new java.util.Date()).getTime();
971 rs = stmt.executeUpdate(sql);
972 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
975 catch (SQLException e)
977 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
978 - startTime) + "ms. for: "+ sql);
984 public int executeUpdate(String sql)
985 throws StorageObjectException, SQLException
988 long startTime = (new java.util.Date()).getTime();
989 Connection con=null;PreparedStatement pstmt=null;
992 pstmt = con.prepareStatement(sql);
993 result = pstmt.executeUpdate();
995 catch (Exception e) {
996 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
997 throw new StorageObjectException("executeUpdate failed: "+e.toString());
999 finally { freeConnection(con,pstmt); }
1000 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1006 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1007 * @param md ResultSetMetaData
1008 * @exception StorageObjectException
1010 private void evalMetaData (ResultSetMetaData md)
1011 throws StorageObjectException {
1013 this.evaluatedMetaData = true;
1014 this.metadataFields = new ArrayList();
1015 this.metadataLabels = new ArrayList();
1016 this.metadataNotNullFields = new ArrayList();
1018 int numFields = md.getColumnCount();
1019 this.metadataTypes = new int[numFields];
1022 for (int i = 1; i <= numFields; i++) {
1023 aField = md.getColumnName(i);
1024 metadataFields.add(aField);
1025 metadataLabels.add(md.getColumnLabel(i));
1026 aType = md.getColumnType(i);
1027 metadataTypes[i - 1] = aType;
1028 if (aField.equals(thePKeyName)) {
1029 thePKeyType = aType;
1031 if (md.isNullable(i) == md.columnNullable) {
1032 metadataNotNullFields.add(aField);
1035 } catch (SQLException e) {
1036 throwSQLException(e, "evalMetaData");
1041 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1042 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1044 private void get_meta_data () throws StorageObjectException {
1045 Connection con = null;
1046 PreparedStatement pstmt = null;
1047 String sql = "select * from " + theTable + " where 0=1";
1049 con = getPooledCon();
1050 pstmt = con.prepareStatement(sql);
1051 theLog.printInfo("METADATA: " + sql);
1052 ResultSet rs = pstmt.executeQuery();
1053 evalMetaData(rs.getMetaData());
1055 } catch (SQLException e) {
1056 throwSQLException(e, "get_meta_data");
1058 freeConnection(con, pstmt);
1063 public Connection getPooledCon() throws StorageObjectException {
1064 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1066 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1067 } catch (Exception e){
1068 throw new StorageObjectException("Could not find the PoolMan Driver"
1071 Connection con = null;
1073 con = SQLManager.getInstance().requestConnection();
1074 } catch(SQLException e){
1075 theLog.printError("could not connect to the database "+e.toString());
1076 System.err.println("could not connect to the database "+e.toString());
1077 throw new StorageObjectException("Could not connect to the database"+
1083 public void freeConnection (Connection con, Statement stmt)
1084 throws StorageObjectException {
1085 SQLManager.getInstance().closeStatement(stmt);
1086 SQLManager.getInstance().returnConnection(con);
1090 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1091 * @param sqe SQLException
1092 * @param wo Funktonsname, in der die SQLException geworfen wurde
1093 * @exception StorageObjectException
1095 protected void throwSQLException (SQLException sqe, String wo)
1096 throws StorageObjectException {
1098 String message = "";
1101 state = sqe.getSQLState();
1102 message = sqe.getMessage();
1103 vendor = sqe.getErrorCode();
1105 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1107 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1111 protected void _throwStorageObjectException (Exception e, String wo)
1112 throws StorageObjectException {
1114 theLog.printError(e.toString()+ wo);
1115 throw new StorageObjectException(wo + e.toString());
1117 theLog.printError(wo);
1118 throw new StorageObjectException(wo);
1124 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1125 * eine StorageObjectException
1126 * @param message Nachricht mit dem Fehler
1127 * @exception StorageObjectException
1129 void throwStorageObjectException (String message)
1130 throws StorageObjectException {
1131 _throwStorageObjectException(null, message);