2 * put your module comment here
10 import freemarker.template.*;
11 import com.javaexchange.dbConnectionBroker.*;
12 import mir.storage.StorageObject;
18 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
19 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
20 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
21 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
22 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
28 public class Database implements StorageObject {
30 protected DbConnectionBroker myBroker;
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,metadataNotNullFields;
37 protected int[] metadataTypes;
38 protected Class theEntityClass;
39 protected StorageObject myselfDatabase;
40 protected DatabaseCache cache;
41 protected SimpleList popupCache=null;
42 protected boolean hasPopupCache = false;
43 protected SimpleHash hashCache=null;
44 protected boolean hasTimestamp=true;
45 private String database_driver;
46 private String database_url;
47 private int defaultLimit;
48 protected DatabaseAdaptor theAdaptor;
49 protected Logfile theLog;
52 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
53 * Aus diesem file werden <code>Database.Logfile</code>,
54 * <code>Database.Username</code>,<code>Database.Password</code>,
55 * <code>Database.Host</code> und <code>Database.Adaptor</code>
56 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
59 * @param String confFilename Dateiname der Konfigurationsdatei
61 public Database() throws StorageObjectException {
62 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
63 String database_username=MirConfig.getProp("Database.Username");
64 String database_password=MirConfig.getProp("Database.Password");
65 String database_host=MirConfig.getProp("Database.Host");
66 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
68 theEntityClass = Class.forName("mir.entity.GenericEntity");
69 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
70 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
71 database_driver=theAdaptor.getDriver();
72 database_url=theAdaptor.getURL(database_username,database_password,database_host);
73 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
74 MirConfig.addBroker(database_driver,database_url);
75 myBroker=MirConfig.getBroker();
78 theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
79 throw new StorageObjectException(e.toString());
84 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
85 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
86 * wird eine mir.entity.GenericEntity erzeugt.
88 * @return Class-Objekt der Entity
90 public java.lang.Class getEntityClass () {
91 return theEntityClass;
95 * Liefert die Standardbeschränkung von select-Statements zurück, also
96 * wieviel Datensätze per Default selektiert werden.
98 * @return Standard-Anzahl der Datensätze
100 public int getLimit () {
105 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
106 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
107 * @return Name des Primary-Keys
109 public String getIdName () {
114 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
116 * @return Name der Tabelle
118 public String getTableName () {
123 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
124 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
125 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
129 public String getCoreTable(){
130 if (theCoreTable!=null) return theCoreTable;
131 else return theTable;
135 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
136 * @return int-Array mit den Typen der Felder
137 * @exception StorageObjectException
139 public int[] getTypes () throws StorageObjectException {
140 if (metadataTypes == null)
142 return metadataTypes;
146 * Liefert eine Liste der Labels der Tabellenfelder
147 * @return ArrayListe mit Labeln
148 * @exception StorageObjectException
150 public ArrayList getLabels () throws StorageObjectException {
151 if (metadataLabels == null)
153 return metadataLabels;
157 * Liefert eine Liste der Felder der Tabelle
158 * @return ArrayList mit Feldern
159 * @exception StorageObjectException
161 public ArrayList getFields () throws StorageObjectException {
162 if (metadataFields == null)
164 return metadataFields;
169 * Gets value out of ResultSet according to type and converts to String
170 * @param inValue Wert aus ResultSet.
171 * @param aType Datenbanktyp.
172 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
173 * dann /unsupported value/
175 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
176 String outValue = null;
180 case java.sql.Types.BIT:
181 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
183 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
184 int out = rs.getInt(valueIndex);
186 outValue = new Integer(out).toString();
188 case java.sql.Types.NUMERIC:
189 long outl = rs.getLong(valueIndex);
191 outValue = new Long(outl).toString();
193 case java.sql.Types.REAL:
194 float tempf = rs.getFloat(valueIndex);
198 int tempf_int = (int)tempf;
199 tempf = (float)tempf_int;
201 outValue = "" + tempf;
202 outValue = outValue.replace('.', ',');
205 case java.sql.Types.DOUBLE:
206 double tempd = rs.getDouble(valueIndex);
210 int tempd_int = (int)tempd;
211 tempd = (double)tempd_int;
213 outValue = "" + tempd;
214 outValue = outValue.replace('.', ',');
217 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
218 outValue = rs.getString(valueIndex);
219 //if (outValue != null)
220 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
222 case java.sql.Types.LONGVARBINARY:
223 outValue = rs.getString(valueIndex);
224 //if (outValue != null)
225 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
227 case java.sql.Types.TIMESTAMP:
228 Timestamp timestamp = (rs.getTimestamp(valueIndex));
230 outValue = timestamp.toString();
234 outValue = "<unsupported value>";
235 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
238 } catch (SQLException e) {
239 throw new StorageObjectException("Could not get Value out of Resultset -- "
247 * select-Operator um einen Datensatz zu bekommen.
248 * @param id Primaerschluessel des Datensatzes.
249 * @return liefert EntityObject des gefundenen Datensatzes oder null.
251 public Entity selectById(String id)
252 throws StorageObjectException {
254 if (id==null||id.equals(""))
255 throw new StorageObjectException("id war null");
256 if (cache != null && (cache.containsKey(id) > -1))
257 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
259 Statement stmt=null;Connection con=getPooledCon();
260 Entity returnEntity=null;
263 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
264 stmt = con.createStatement();
265 rs = executeSql(stmt, selectSql);
267 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
269 returnEntity = makeEntityFromResultSet(rs);
270 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
273 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
275 } catch (SQLException sqe){
276 throwSQLException(sqe,"selectById"); return null;
277 } catch (NumberFormatException e) {
278 theLog.printError("ID ist keine Zahl: " + id);
280 freeConnection(con,stmt);
287 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
288 * @param key Datenbankfeld der Bedingung.
289 * @param value Wert die der key anehmen muss.
290 * @return EntityList mit den gematchten Entities
293 public EntityList selectByFieldValue(String aField, String aValue)
294 throws StorageObjectException {
296 return selectByFieldValue(aField, aValue, 0);
300 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
301 * @param key Datenbankfeld der Bedingung.
302 * @param value Wert die der key anehmen muss.
303 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
304 * @return EntityList mit den gematchten Entities
307 public EntityList selectByFieldValue(String aField, String aValue, int offset)
308 throws StorageObjectException {
310 return selectByWhereClause(aField + "=" + aValue, offset);
315 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
316 * Also offset wird der erste Datensatz genommen.
318 * @param wc where-Clause
319 * @return EntityList mit den gematchten Entities
320 * @exception StorageObjectException
322 public EntityList selectByWhereClause(String where)
323 throws StorageObjectException {
325 return selectByWhereClause(where, 0);
330 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
331 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
333 * @param wc where-Clause
334 * @param offset ab welchem Datensatz.
335 * @return EntityList mit den gematchten Entities
336 * @exception StorageObjectException
338 public EntityList selectByWhereClause(String whereClause, int offset)
339 throws StorageObjectException {
341 return selectByWhereClause(whereClause, null, offset);
345 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
346 * Also offset wird der erste Datensatz genommen.
347 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
349 * @param wc where-Clause
350 * @param ob orderBy-Clause
351 * @return EntityList mit den gematchten Entities
352 * @exception StorageObjectException
355 public EntityList selectByWhereClause(String where, String order)
356 throws StorageObjectException {
358 return selectByWhereClause(where, order, 0);
361 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
362 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
364 * @param wc where-Clause
365 * @param ob orderBy-Clause
366 * @param offset ab welchem Datensatz
367 * @return EntityList mit den gematchten Entities
368 * @exception StorageObjectException
371 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
372 throws StorageObjectException {
374 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
379 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
380 * @param wc where-Clause
381 * @param ob orderBy-Clause
382 * @param offset ab welchem Datensatz
383 * @param limit wieviele Datensätze
384 * @return EntityList mit den gematchten Entities
385 * @exception StorageObjectException
388 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
389 throws StorageObjectException {
392 EntityList theReturnList=null;
400 // build sql-statement
401 if (wc != null && wc.length() == 0) {
404 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
405 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
407 selectSql.append(" where ").append(wc);
408 countSql.append(" where ").append(wc);
410 if (ob != null && !(ob.length() == 0)) {
411 selectSql.append(" order by ").append(ob);
413 if (theAdaptor.hasLimit()) {
414 if (limit > -1 && offset > -1) {
415 selectSql.append(" limit ");
416 if (theAdaptor.reverseLimit()) {
417 selectSql.append(limit).append(",").append(offset);
420 selectSql.append(offset).append(",").append(limit);
427 con = getPooledCon();
428 stmt = con.createStatement();
430 if (theAdaptor.hasLimit()) {
431 rs = executeSql(stmt, countSql.toString());
434 count = rs.getInt(1);
437 theLog.printError("Mh. Konnte nicht zaehlen: " + countSql);
440 //nothing in the table: return null
445 rs = executeSql(stmt, selectSql.toString());
447 theReturnList = new EntityList();
448 if (evaluatedMetaData == false) {
449 evalMetaData(rs.getMetaData());
451 Entity theResultEntity;
453 theResultEntity = makeEntityFromResultSet(rs);
454 theReturnList.add(theResultEntity);
460 if (!(theAdaptor.hasLimit()))
462 if (theReturnList != null) {
463 theReturnList.setCount(count);
464 theReturnList.setOffset(offset);
465 theReturnList.setWhere(wc);
466 theReturnList.setOrder(ob);
467 if (offset >= limit) {
468 theReturnList.setPrevBatch(offset - limit);
470 if (offset + offsetCount < count) {
471 theReturnList.setNextBatch(offset + limit);
474 } catch (SQLException sqe) {
475 throwSQLException(sqe, "selectByWhereClause");
477 freeConnection(con, stmt);
479 return theReturnList;
483 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
485 * @param rs Das ResultSetObjekt.
486 * @return Entity Die Entity.
489 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
490 HashMap theResultHash = new HashMap();
491 String theResult = null;
493 Entity returnEntity = null;
495 int size = metadataFields.size();
496 for (int i = 0; i < size; i++) {
497 // alle durchlaufen bis nix mehr da
498 theType = metadataTypes[i];
499 if (theType == java.sql.Types.LONGVARBINARY) {
500 InputStream us = rs.getAsciiStream(i + 1);
502 InputStreamReader is = new InputStreamReader(us);
503 char[] data = new char[32768];
504 StringBuffer theResultString = new StringBuffer();
506 while ((len = is.read(data)) > 0) {
507 theResultString.append(data, 0, len);
510 theResult = theResultString.toString();
517 theResult = getValueAsString(rs, (i + 1), theType);
519 if (theResult != null) {
520 theResultHash.put(metadataFields.get(i), theResult);
523 if (cache != null && theResultHash.containsKey(thePKeyName) &&
524 (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
525 //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
526 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
529 if (theEntityClass != null) {
530 returnEntity = (Entity)theEntityClass.newInstance();
531 returnEntity.setValues(theResultHash);
532 returnEntity.setStorage(myselfDatabase);
534 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
535 cache.put(returnEntity.getId(), returnEntity);
539 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
543 catch (IllegalAccessException e) {
544 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
545 } catch (IOException e) {
546 throwStorageObjectException("IOException! -- " + e.toString());
547 } catch (InstantiationException e) {
548 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
549 } catch (SQLException sqe) {
550 throwSQLException(sqe, "makeEntityFromResultSet");
557 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
558 * wird automatisch mit dem aktuellen Datum gefuellt.
561 * @return der Wert des Primary-keys der eingefügten Entity
563 public String insert (Entity theEntity) throws StorageObjectException {
564 String returnId = null;
565 Connection con = null;
566 PreparedStatement pstmt = null;
568 invalidatePopupCache();
570 ArrayList streamedInput = theEntity.streamedInput();
571 StringBuffer f = new StringBuffer();
572 StringBuffer v = new StringBuffer();
573 String aField, aValue;
574 boolean firstField = true;
576 for (int i = 0; i < getFields().size(); i++) {
577 aField = (String)getFields().get(i);
578 if (!aField.equals(thePKeyName)) {
581 if (aField.equals("webdb_create")) {
585 if (streamedInput != null && streamedInput.contains(aField)) {
589 if (theEntity.hasValueForField(aField)) {
590 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
595 // wenn Wert gegeben, dann einbauen
596 if (aValue != null) {
597 if (firstField == false) {
610 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
611 String sql = sqlBuf.toString();
612 theLog.printInfo("INSERT: " + sql);
613 con = getPooledCon();
614 con.setAutoCommit(false);
615 pstmt = con.prepareStatement(sql);
616 if (streamedInput != null) {
617 for (int i = 0; i < streamedInput.size(); i++) {
618 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
619 pstmt.setBytes(i + 1, inputString.getBytes());
622 int ret = pstmt.executeUpdate();
627 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
628 ResultSet rs = pstmt.executeQuery();
630 returnId = rs.getString(1);
631 theEntity.setId(returnId);
632 } catch (SQLException sqe) {
633 throwSQLException(sqe, "insert");
636 con.setAutoCommit(true);
637 } catch (Exception e) {
640 freeConnection(con, pstmt);
646 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
647 * wird automatisch mit dem aktuellen Datum gefuellt.
651 public void update (Entity theEntity) throws StorageObjectException {
652 Connection con = null;
653 PreparedStatement pstmt = null;
654 ArrayList streamedInput = theEntity.streamedInput();
655 String id = theEntity.getId();
657 StringBuffer fv = new StringBuffer();
658 boolean firstField = true;
660 invalidatePopupCache();
661 // build sql statement
662 for (int i = 0; i < getFields().size(); i++) {
663 aField = (String)metadataFields.get(i);
665 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
666 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
667 if (theEntity.hasValueForField(aField)) {
668 if (firstField == false) {
674 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
678 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
680 if (metadataFields.contains("webdb_lastchange")) {
681 sql.append(",webdb_lastchange=NOW()");
683 if (streamedInput != null) {
684 for (int i = 0; i < streamedInput.size(); i++) {
685 sql.append(",").append(streamedInput.get(i)).append("=?");
688 sql.append(" where id=").append(id);
689 theLog.printInfo("UPDATE: " + sql);
692 con = getPooledCon();
693 con.setAutoCommit(false);
694 pstmt = con.prepareStatement(sql.toString());
695 if (streamedInput != null) {
696 for (int i = 0; i < streamedInput.size(); i++) {
697 String inputString = theEntity.getValue((String)streamedInput.get(i));
698 pstmt.setBytes(i + 1, inputString.getBytes());
701 pstmt.executeUpdate();
702 } catch (SQLException sqe) {
703 throwSQLException(sqe, "update");
706 con.setAutoCommit(true);
707 } catch (Exception e) {
710 freeConnection(con, pstmt);
716 * @param id des zu loeschenden Datensatzes
717 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
719 public boolean delete (String id) throws StorageObjectException {
720 Statement stmt = null;
721 Connection con = null;
724 // loeschen des caches
725 invalidatePopupCache();
726 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
728 theLog.printInfo("DELETE " + sql);
730 con = getPooledCon();
731 stmt = con.createStatement();
732 res = stmt.executeUpdate(sql);
733 } catch (SQLException sqe) {
734 throwSQLException(sqe, "delete");
736 freeConnection(con, stmt);
739 theLog.printInfo("CACHE: deleted " + id);
742 return (res > 0) ? true : false;
745 /* noch nicht implementiert.
746 * @return immer false
748 public boolean delete (EntityList theEntityList) {
749 invalidatePopupCache();
754 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
755 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
758 public SimpleList getPopupData () throws StorageObjectException {
763 * Holt Daten fuer Popups.
764 * @param name Name des Feldes.
765 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
766 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
768 public SimpleList getPopupData (String name, boolean hasNullValue)
769 throws StorageObjectException {
770 return getPopupData(name, hasNullValue, null);
774 * Holt Daten fuer Popups.
775 * @param name Name des Feldes.
776 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
777 * @param where Schraenkt die Selektion der Datensaetze ein.
778 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
780 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
781 return getPopupData(name, hasNullValue, where, null);
785 * Holt Daten fuer Popups.
786 * @param name Name des Feldes.
787 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
788 * @param where Schraenkt die Selektion der Datensaetze ein.
789 * @param order Gibt ein Feld als Sortierkriterium an.
790 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
792 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
794 if (hasPopupCache && popupCache != null)
796 SimpleList simpleList = null;
797 Connection con = null;
798 Statement stmt = null;
800 StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
801 if (where != null && !(where.length() == 0))
802 sql.append(" where ").append(where);
803 sql.append(" order by ");
804 if (order != null && !(order.length() == 0))
810 con = getPooledCon();
811 stmt = con.createStatement();
812 ResultSet rs = executeSql(stmt, sql.toString());
814 if (evaluatedMetaData == false)
816 simpleList = new SimpleList();
817 SimpleHash popupDict;
819 popupDict = new SimpleHash();
820 popupDict.put("key", "");
821 popupDict.put("value", "--");
822 simpleList.add(popupDict);
825 popupDict = new SimpleHash();
826 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
827 popupDict.put("value", rs.getString(2));
828 simpleList.add(popupDict);
832 } catch (Exception e) {
833 theLog.printDebugInfo(e.toString());
834 throw new StorageObjectException(e.toString());
836 freeConnection(con, stmt);
839 popupCache = simpleList;
845 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
846 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
847 * Tabellen Verwendung finden.
848 * @return SimpleHash mit den Tabellezeilen.
850 public SimpleHash getHashData () {
851 if (hashCache == null) {
853 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
855 } catch (StorageObjectException e) {
856 theLog.printDebugInfo(e.toString());
862 /* invalidates the popupCache
864 protected void invalidatePopupCache () {
866 /** @todo invalidates toooo much */
872 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
873 * @param stmt Statemnt
874 * @param sql Sql-String
876 * @exception StorageObjectException
878 public ResultSet executeSql (Statement stmt, String sql)
879 throws StorageObjectException, SQLException
882 long startTime = (new java.util.Date()).getTime();
884 rs = stmt.executeQuery(sql);
885 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
888 catch (SQLException e)
890 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
899 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
900 * getimed und geloggt.
901 * @param stmt PreparedStatement mit der SQL-Anweisung
902 * @return Liefert ResultSet des Statements zurueck.
903 * @exception StorageObjectException, SQLException
905 public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
908 long startTime = (new java.util.Date()).getTime();
909 ResultSet rs = stmt.executeQuery();
910 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
915 * returns the number of rows in the table
917 public int getSize(String where)
918 throws SQLException,StorageObjectException
920 long startTime = (new java.util.Date()).getTime();
921 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
922 //theLog.printDebugInfo("trying: "+ sql);
923 Connection con = null;
924 Statement stmt = null;
928 con = getPooledCon();
929 stmt = con.createStatement();
930 ResultSet rs = executeSql(stmt,sql);
932 result = rs.getInt(1);
934 } catch (SQLException e) {
935 theLog.printError(e.toString());
937 freeConnection(con,stmt);
939 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
940 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
944 public int executeUpdate(Statement stmt, String sql)
945 throws StorageObjectException, SQLException
948 long startTime = (new java.util.Date()).getTime();
951 rs = stmt.executeUpdate(sql);
952 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
954 catch (SQLException e)
956 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
963 public int executeUpdate(String sql)
964 throws StorageObjectException, SQLException
967 long startTime = (new java.util.Date()).getTime();
968 Connection con=null;PreparedStatement pstmt=null;
971 pstmt = con.prepareStatement(sql);
972 result = pstmt.executeUpdate();
974 catch (Exception e) {
975 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
976 throw new StorageObjectException("executeUpdate failed: "+e.toString());
978 finally { freeConnection(con,pstmt); }
979 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
984 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
985 * @param md ResultSetMetaData
986 * @exception StorageObjectException
988 private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
989 this.evaluatedMetaData = true;
990 this.metadataFields = new ArrayList();
991 this.metadataLabels = new ArrayList();
992 this.metadataNotNullFields = new ArrayList();
994 int numFields = md.getColumnCount();
995 this.metadataTypes = new int[numFields];
998 for (int i = 1; i <= numFields; i++) {
999 aField = md.getColumnName(i);
1000 metadataFields.add(aField);
1001 metadataLabels.add(md.getColumnLabel(i));
1002 aType = md.getColumnType(i);
1003 metadataTypes[i - 1] = aType;
1004 if (aField.equals(thePKeyName)) {
1005 thePKeyType = aType;
1007 if (md.isNullable(i) == md.columnNullable) {
1008 metadataNotNullFields.add(aField);
1011 } catch (SQLException e) {
1012 throwSQLException(e, "evalMetaData");
1017 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1018 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1020 private void get_meta_data () throws StorageObjectException {
1021 Connection con = null;
1022 PreparedStatement pstmt = null;
1023 String sql = "select * from " + theTable + " where 0=1";
1025 con = getPooledCon();
1026 pstmt = con.prepareStatement(sql);
1027 theLog.printInfo("METADATA: " + sql);
1028 ResultSet rs = pstmt.executeQuery();
1029 evalMetaData(rs.getMetaData());
1031 } catch (SQLException e) {
1032 throwSQLException(e, "get_meta_data");
1034 freeConnection(con, pstmt);
1039 * Datenbankverbindung wird geschlossen
1041 public void disconnectPool () throws StorageObjectException {
1043 myBroker.destroy(100);
1044 } catch (SQLException sqe) {
1045 throwSQLException(sqe, "disconnectPool");
1050 * Returns Connection-Object out of the PoolBroker.
1052 * @return Connection Object.
1054 public Connection getPooledCon () throws StorageObjectException {
1055 if (myBroker != null) {
1056 Connection con = myBroker.getConnection();
1060 throw new StorageObjectException("No connection to database!");
1064 * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1066 * @param con Connection zur Datenbank
1067 * @param stmt Statement-Objekt
1069 public void freeConnection (Connection con, Statement stmt)
1070 throws StorageObjectException {
1074 } catch (SQLException e1) {
1075 theLog.printDebugInfo(e1.toString());
1076 throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1079 myBroker.freeConnection(con);
1081 theLog.printDebugInfo("Con was null!");
1082 throw new StorageObjectException("Con was null!");
1087 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1088 * @param sqe SQLException
1089 * @param wo Funktonsname, in der die SQLException geworfen wurde
1090 * @exception StorageObjectException
1092 protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1094 String message = "";
1097 state = sqe.getSQLState();
1098 message = sqe.getMessage();
1099 vendor = sqe.getErrorCode();
1101 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1103 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1107 protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1109 theLog.printError(e.toString()+ wo);
1110 throw new StorageObjectException(wo + e.toString());
1112 theLog.printError(wo);
1113 throw new StorageObjectException(wo);
1119 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1120 * @param message Nachricht mit dem Fehler
1121 * @exception StorageObjectException
1123 void throwStorageObjectException (String message) throws StorageObjectException {
1124 _throwStorageObjectException(null, message);