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
409 if (wc != null && wc.length() == 0) {
412 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
413 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
415 selectSql.append(" where ").append(wc);
416 countSql.append(" where ").append(wc);
418 if (ob != null && !(ob.length() == 0)) {
419 selectSql.append(" order by ").append(ob);
421 if (theAdaptor.hasLimit()) {
422 if (limit > -1 && offset > -1) {
423 selectSql.append(" limit ");
424 if (theAdaptor.reverseLimit()) {
425 selectSql.append(limit).append(",").append(offset);
428 selectSql.append(offset).append(",").append(limit);
435 con = getPooledCon();
436 stmt = con.createStatement();
438 if (theAdaptor.hasLimit()) {
439 rs = executeSql(stmt, countSql.toString());
442 count = rs.getInt(1);
444 //nothing in the table: return null
446 freeConnection(con, stmt);
450 theLog.printError("Could not count: " + countSql);
455 rs = executeSql(stmt, selectSql.toString());
457 theReturnList = new EntityList();
458 if (evaluatedMetaData == false) {
459 evalMetaData(rs.getMetaData());
461 Entity theResultEntity;
463 theResultEntity = makeEntityFromResultSet(rs);
464 theReturnList.add(theResultEntity);
470 if (!(theAdaptor.hasLimit()))
472 if (theReturnList != null) {
473 theReturnList.setCount(count);
474 theReturnList.setOffset(offset);
475 theReturnList.setWhere(wc);
476 theReturnList.setOrder(ob);
477 if (offset >= limit) {
478 theReturnList.setPrevBatch(offset - limit);
480 if (offset + offsetCount < count) {
481 theReturnList.setNextBatch(offset + limit);
484 } catch (SQLException sqe) {
485 throwSQLException(sqe, "selectByWhereClause");
487 freeConnection(con, stmt);
489 return theReturnList;
493 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
495 * @param rs Das ResultSetObjekt.
496 * @return Entity Die Entity.
499 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
500 HashMap theResultHash = new HashMap();
501 String theResult = null;
503 Entity returnEntity = null;
505 int size = metadataFields.size();
506 for (int i = 0; i < size; i++) {
507 // alle durchlaufen bis nix mehr da
508 theType = metadataTypes[i];
509 if (theType == java.sql.Types.LONGVARBINARY) {
510 InputStream us = rs.getAsciiStream(i + 1);
512 InputStreamReader is = new InputStreamReader(us);
513 char[] data = new char[32768];
514 StringBuffer theResultString = new StringBuffer();
516 while ((len = is.read(data)) > 0) {
517 theResultString.append(data, 0, len);
520 theResult = theResultString.toString();
527 theResult = getValueAsString(rs, (i + 1), theType);
529 if (theResult != null) {
530 theResultHash.put(metadataFields.get(i), theResult);
533 if (cache != null && theResultHash.containsKey(thePKeyName) &&
534 (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
535 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
537 if (theEntityClass != null) {
538 returnEntity = (Entity)theEntityClass.newInstance();
539 returnEntity.setValues(theResultHash);
540 returnEntity.setStorage(myselfDatabase);
542 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
543 cache.put(returnEntity.getId(), returnEntity);
546 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
549 } catch (IllegalAccessException e) {
550 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
551 } catch (IOException e) {
552 throwStorageObjectException("IOException! -- " + e.toString());
553 } catch (InstantiationException e) {
554 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
555 } catch (SQLException sqe) {
556 throwSQLException(sqe, "makeEntityFromResultSet");
563 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
564 * wird automatisch mit dem aktuellen Datum gefuellt.
567 * @return der Wert des Primary-keys der eingefügten Entity
569 public String insert (Entity theEntity) throws StorageObjectException {
570 String returnId = null;
571 Connection con = null;
572 PreparedStatement pstmt = null;
574 invalidatePopupCache();
576 ArrayList streamedInput = theEntity.streamedInput();
577 StringBuffer f = new StringBuffer();
578 StringBuffer v = new StringBuffer();
579 String aField, aValue;
580 boolean firstField = true;
582 for (int i = 0; i < getFields().size(); i++) {
583 aField = (String)getFields().get(i);
584 if (!aField.equals(thePKeyName)) {
587 if (aField.equals("webdb_create")) {
591 if (streamedInput != null && streamedInput.contains(aField)) {
595 if (theEntity.hasValueForField(aField)) {
596 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
601 // wenn Wert gegeben, dann einbauen
602 if (aValue != null) {
603 if (firstField == false) {
616 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
617 String sql = sqlBuf.toString();
618 theLog.printInfo("INSERT: " + sql);
619 con = getPooledCon();
620 con.setAutoCommit(false);
621 pstmt = con.prepareStatement(sql);
622 if (streamedInput != null) {
623 for (int i = 0; i < streamedInput.size(); i++) {
624 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
625 pstmt.setBytes(i + 1, inputString.getBytes());
628 int ret = pstmt.executeUpdate();
633 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
634 ResultSet rs = pstmt.executeQuery();
636 returnId = rs.getString(1);
637 theEntity.setId(returnId);
638 } catch (SQLException sqe) {
639 throwSQLException(sqe, "insert");
642 con.setAutoCommit(true);
643 } catch (Exception e) {
646 freeConnection(con, pstmt);
652 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
653 * wird automatisch mit dem aktuellen Datum gefuellt.
657 public void update (Entity theEntity) throws StorageObjectException {
658 Connection con = null;
659 PreparedStatement pstmt = null;
660 ArrayList streamedInput = theEntity.streamedInput();
661 String id = theEntity.getId();
663 StringBuffer fv = new StringBuffer();
664 boolean firstField = true;
666 invalidatePopupCache();
667 // build sql statement
668 for (int i = 0; i < getFields().size(); i++) {
669 aField = (String)metadataFields.get(i);
671 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
672 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
673 if (theEntity.hasValueForField(aField)) {
674 if (firstField == false) {
680 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
684 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
686 if (metadataFields.contains("webdb_lastchange")) {
687 sql.append(",webdb_lastchange=NOW()");
689 if (streamedInput != null) {
690 for (int i = 0; i < streamedInput.size(); i++) {
691 sql.append(",").append(streamedInput.get(i)).append("=?");
694 sql.append(" where id=").append(id);
695 theLog.printInfo("UPDATE: " + sql);
698 con = getPooledCon();
699 con.setAutoCommit(false);
700 pstmt = con.prepareStatement(sql.toString());
701 if (streamedInput != null) {
702 for (int i = 0; i < streamedInput.size(); i++) {
703 String inputString = theEntity.getValue((String)streamedInput.get(i));
704 pstmt.setBytes(i + 1, inputString.getBytes());
707 pstmt.executeUpdate();
708 } catch (SQLException sqe) {
709 throwSQLException(sqe, "update");
712 con.setAutoCommit(true);
713 } catch (Exception e) {
716 freeConnection(con, pstmt);
722 * @param id des zu loeschenden Datensatzes
723 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
725 public boolean delete (String id) throws StorageObjectException {
726 Statement stmt = null;
727 Connection con = null;
730 // loeschen des caches
731 invalidatePopupCache();
732 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
734 theLog.printInfo("DELETE " + sql);
736 con = getPooledCon();
737 stmt = con.createStatement();
738 res = stmt.executeUpdate(sql);
739 } catch (SQLException sqe) {
740 throwSQLException(sqe, "delete");
742 freeConnection(con, stmt);
745 theLog.printInfo("CACHE: deleted " + id);
748 return (res > 0) ? true : false;
751 /* noch nicht implementiert.
752 * @return immer false
754 public boolean delete (EntityList theEntityList) {
755 invalidatePopupCache();
760 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
761 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
764 public SimpleList getPopupData () throws StorageObjectException {
769 * Holt Daten fuer Popups.
770 * @param name Name des Feldes.
771 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
772 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
774 public SimpleList getPopupData (String name, boolean hasNullValue)
775 throws StorageObjectException {
776 return getPopupData(name, hasNullValue, null);
780 * Holt Daten fuer Popups.
781 * @param name Name des Feldes.
782 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
783 * @param where Schraenkt die Selektion der Datensaetze ein.
784 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
786 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
787 return getPopupData(name, hasNullValue, where, null);
791 * Holt Daten fuer Popups.
792 * @param name Name des Feldes.
793 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
794 * @param where Schraenkt die Selektion der Datensaetze ein.
795 * @param order Gibt ein Feld als Sortierkriterium an.
796 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
798 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
800 if (hasPopupCache && popupCache != null)
802 SimpleList simpleList = null;
803 Connection con = null;
804 Statement stmt = null;
806 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
807 .append(",").append(name).append(" from ")
809 if (where != null && !(where.length() == 0))
810 sql.append(" where ").append(where);
811 sql.append(" order by ");
812 if (order != null && !(order.length() == 0))
818 con = getPooledCon();
819 } catch (Exception e) {
820 throw new StorageObjectException(e.toString());
823 stmt = con.createStatement();
824 ResultSet rs = executeSql(stmt, sql.toString());
826 if (evaluatedMetaData == false)
828 simpleList = new SimpleList();
829 SimpleHash popupDict;
831 popupDict = new SimpleHash();
832 popupDict.put("key", "");
833 popupDict.put("value", "--");
834 simpleList.add(popupDict);
837 popupDict = new SimpleHash();
838 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
839 popupDict.put("value", rs.getString(2));
840 simpleList.add(popupDict);
844 } catch (Exception e) {
845 theLog.printError("getPopupData: "+e.toString());
846 throw new StorageObjectException(e.toString());
848 freeConnection(con, stmt);
851 popupCache = simpleList;
857 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
858 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
859 * Tabellen Verwendung finden.
860 * @return SimpleHash mit den Tabellezeilen.
862 public SimpleHash getHashData () {
863 if (hashCache == null) {
865 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
867 } catch (StorageObjectException e) {
868 theLog.printDebugInfo(e.toString());
874 /* invalidates the popupCache
876 protected void invalidatePopupCache () {
878 /** @todo invalidates toooo much */
884 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
885 * @param stmt Statemnt
886 * @param sql Sql-String
888 * @exception StorageObjectException
890 public ResultSet executeSql (Statement stmt, String sql)
891 throws StorageObjectException, SQLException
894 long startTime = (new java.util.Date()).getTime();
896 rs = stmt.executeQuery(sql);
897 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
900 catch (SQLException e)
902 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
903 - startTime) + "ms. for: "+ sql);
911 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
912 * getimed und geloggt.
913 * @param stmt PreparedStatement mit der SQL-Anweisung
914 * @return Liefert ResultSet des Statements zurueck.
915 * @exception StorageObjectException, SQLException
917 public ResultSet executeSql (PreparedStatement stmt)
918 throws StorageObjectException, SQLException {
920 long startTime = (new java.util.Date()).getTime();
921 ResultSet rs = stmt.executeQuery();
922 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
927 * returns the number of rows in the table
929 public int getSize(String where)
930 throws SQLException,StorageObjectException
932 long startTime = (new java.util.Date()).getTime();
933 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
934 //theLog.printDebugInfo("trying: "+ sql);
935 Connection con = null;
936 Statement stmt = null;
940 con = getPooledCon();
941 stmt = con.createStatement();
942 ResultSet rs = executeSql(stmt,sql);
944 result = rs.getInt(1);
946 } catch (SQLException e) {
947 theLog.printError(e.toString());
949 freeConnection(con,stmt);
951 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
952 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
957 public int executeUpdate(Statement stmt, String sql)
958 throws StorageObjectException, SQLException
961 long startTime = (new java.util.Date()).getTime();
964 rs = stmt.executeUpdate(sql);
965 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
968 catch (SQLException e)
970 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
971 - startTime) + "ms. for: "+ sql);
977 public int executeUpdate(String sql)
978 throws StorageObjectException, SQLException
981 long startTime = (new java.util.Date()).getTime();
982 Connection con=null;PreparedStatement pstmt=null;
985 pstmt = con.prepareStatement(sql);
986 result = pstmt.executeUpdate();
988 catch (Exception e) {
989 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
990 throw new StorageObjectException("executeUpdate failed: "+e.toString());
992 finally { freeConnection(con,pstmt); }
993 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
999 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1000 * @param md ResultSetMetaData
1001 * @exception StorageObjectException
1003 private void evalMetaData (ResultSetMetaData md)
1004 throws StorageObjectException {
1006 this.evaluatedMetaData = true;
1007 this.metadataFields = new ArrayList();
1008 this.metadataLabels = new ArrayList();
1009 this.metadataNotNullFields = new ArrayList();
1011 int numFields = md.getColumnCount();
1012 this.metadataTypes = new int[numFields];
1015 for (int i = 1; i <= numFields; i++) {
1016 aField = md.getColumnName(i);
1017 metadataFields.add(aField);
1018 metadataLabels.add(md.getColumnLabel(i));
1019 aType = md.getColumnType(i);
1020 metadataTypes[i - 1] = aType;
1021 if (aField.equals(thePKeyName)) {
1022 thePKeyType = aType;
1024 if (md.isNullable(i) == md.columnNullable) {
1025 metadataNotNullFields.add(aField);
1028 } catch (SQLException e) {
1029 throwSQLException(e, "evalMetaData");
1034 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1035 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1037 private void get_meta_data () throws StorageObjectException {
1038 Connection con = null;
1039 PreparedStatement pstmt = null;
1040 String sql = "select * from " + theTable + " where 0=1";
1042 con = getPooledCon();
1043 pstmt = con.prepareStatement(sql);
1044 theLog.printInfo("METADATA: " + sql);
1045 ResultSet rs = pstmt.executeQuery();
1046 evalMetaData(rs.getMetaData());
1048 } catch (SQLException e) {
1049 throwSQLException(e, "get_meta_data");
1051 freeConnection(con, pstmt);
1056 public Connection getPooledCon() throws StorageObjectException {
1057 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1059 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1060 } catch (Exception e){
1061 throw new StorageObjectException("Could not find the PoolMan Driver"
1064 Connection con = null;
1066 con = SQLManager.getInstance().requestConnection();
1067 } catch(SQLException e){
1068 theLog.printError("could not connect to the database "+e.toString());
1069 System.err.println("could not connect to the database "+e.toString());
1070 throw new StorageObjectException("Could not connect to the database"+
1076 public void freeConnection (Connection con, Statement stmt)
1077 throws StorageObjectException {
1078 SQLManager.getInstance().closeStatement(stmt);
1079 SQLManager.getInstance().returnConnection(con);
1083 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1084 * @param sqe SQLException
1085 * @param wo Funktonsname, in der die SQLException geworfen wurde
1086 * @exception StorageObjectException
1088 protected void throwSQLException (SQLException sqe, String wo)
1089 throws StorageObjectException {
1091 String message = "";
1094 state = sqe.getSQLState();
1095 message = sqe.getMessage();
1096 vendor = sqe.getErrorCode();
1098 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1100 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1104 protected void _throwStorageObjectException (Exception e, String wo)
1105 throws StorageObjectException {
1107 theLog.printError(e.toString()+ wo);
1108 throw new StorageObjectException(wo + e.toString());
1110 theLog.printError(wo);
1111 throw new StorageObjectException(wo);
1117 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1118 * eine StorageObjectException
1119 * @param message Nachricht mit dem Fehler
1120 * @exception StorageObjectException
1122 void throwStorageObjectException (String message)
1123 throws StorageObjectException {
1124 _throwStorageObjectException(null, message);