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;
42 /** @todo DatabaseCache will soon be replaced by
43 * ObjectStore. Points to interweave Database with
44 * ObjectStore are marked "todo: OS:" below */
45 protected DatabaseCache cache;
47 protected SimpleList popupCache=null;
48 protected boolean hasPopupCache = false;
49 protected SimpleHash hashCache=null;
50 protected boolean hasTimestamp=true;
51 private String database_driver;
52 private String database_url;
53 private int defaultLimit;
54 protected DatabaseAdaptor theAdaptor;
55 protected Logfile theLog;
56 protected static final SimpleHash POPUP_EMTYLINE=new SimpleHash();
59 // always same object saves a little space
60 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
62 /** @todo OS: init ObjectStore*/
66 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
67 * Aus diesem file werden <code>Database.Logfile</code>,
68 * <code>Database.Username</code>,<code>Database.Password</code>,
69 * <code>Database.Host</code> und <code>Database.Adaptor</code>
70 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
73 * @param String confFilename Dateiname der Konfigurationsdatei
75 public Database() throws StorageObjectException {
76 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
77 MirConfig.getProp("Database.Logfile"));
78 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
79 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
81 theEntityClass = Class.forName("mir.entity.GenericEntity");
82 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
83 } catch (Exception e){
84 theLog.printError("Error in Database() constructor with "+
85 theAdaptorName + " -- " +e.toString());
86 throw new StorageObjectException("Error in Database() constructor with "
89 /*String database_username=MirConfig.getProp("Database.Username");
90 String database_password=MirConfig.getProp("Database.Password");
91 String database_host=MirConfig.getProp("Database.Host");
93 database_driver=theAdaptor.getDriver();
94 database_url=theAdaptor.getURL(database_username,database_password,
96 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
98 MirConfig.addBroker(database_driver,database_url);
99 //myBroker=MirConfig.getBroker();
104 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
105 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
106 * wird eine mir.entity.GenericEntity erzeugt.
108 * @return Class-Objekt der Entity
110 public java.lang.Class getEntityClass () {
111 return theEntityClass;
115 * Liefert die Standardbeschränkung von select-Statements zurück, also
116 * wieviel Datensätze per Default selektiert werden.
118 * @return Standard-Anzahl der Datensätze
120 public int getLimit () {
125 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
126 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
127 * @return Name des Primary-Keys
129 public String getIdName () {
134 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
136 * @return Name der Tabelle
138 public String getTableName () {
143 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
144 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
146 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
150 public String getCoreTable(){
151 if (theCoreTable!=null) return theCoreTable;
152 else return theTable;
156 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
157 * @return int-Array mit den Typen der Felder
158 * @exception StorageObjectException
160 public int[] getTypes () throws StorageObjectException {
161 if (metadataTypes == null)
163 return metadataTypes;
167 * Liefert eine Liste der Labels der Tabellenfelder
168 * @return ArrayListe mit Labeln
169 * @exception StorageObjectException
171 public ArrayList getLabels () throws StorageObjectException {
172 if (metadataLabels == null)
174 return metadataLabels;
178 * Liefert eine Liste der Felder der Tabelle
179 * @return ArrayList mit Feldern
180 * @exception StorageObjectException
182 public ArrayList getFields () throws StorageObjectException {
183 if (metadataFields == null)
185 return metadataFields;
190 * Gets value out of ResultSet according to type and converts to String
191 * @param inValue Wert aus ResultSet.
192 * @param aType Datenbanktyp.
193 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
194 * dann /unsupported value/
196 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
197 String outValue = null;
201 case java.sql.Types.BIT:
202 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
204 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
205 int out = rs.getInt(valueIndex);
207 outValue = new Integer(out).toString();
209 case java.sql.Types.NUMERIC:
210 long outl = rs.getLong(valueIndex);
212 outValue = new Long(outl).toString();
214 case java.sql.Types.REAL:
215 float tempf = rs.getFloat(valueIndex);
219 int tempf_int = (int)tempf;
220 tempf = (float)tempf_int;
222 outValue = "" + tempf;
223 outValue = outValue.replace('.', ',');
226 case java.sql.Types.DOUBLE:
227 double tempd = rs.getDouble(valueIndex);
231 int tempd_int = (int)tempd;
232 tempd = (double)tempd_int;
234 outValue = "" + tempd;
235 outValue = outValue.replace('.', ',');
238 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
239 outValue = rs.getString(valueIndex);
240 //if (outValue != null)
241 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
243 case java.sql.Types.LONGVARBINARY:
244 outValue = rs.getString(valueIndex);
245 //if (outValue != null)
246 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
248 case java.sql.Types.TIMESTAMP:
249 Timestamp timestamp = (rs.getTimestamp(valueIndex));
251 outValue = timestamp.toString();
255 outValue = "<unsupported value>";
256 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
259 } catch (SQLException e) {
260 throw new StorageObjectException("Could not get Value out of Resultset -- "
268 * select-Operator um einen Datensatz zu bekommen.
269 * @param id Primaerschluessel des Datensatzes.
270 * @return liefert EntityObject des gefundenen Datensatzes oder null.
272 public Entity selectById(String id)
273 throws StorageObjectException {
275 if (id==null||id.equals(""))
276 throw new StorageObjectException("id war null");
278 /** @todo OS: build StoreIdenfier and check ObjectStore for StoreIdentifier */
279 if (cache != null && (cache.containsKey(id) > -1))
280 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
282 Statement stmt=null;Connection con=getPooledCon();
283 Entity returnEntity=null;
286 /** @todo better prepared statement */
287 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
288 stmt = con.createStatement();
289 rs = executeSql(stmt, selectSql);
291 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
293 returnEntity = makeEntityFromResultSet(rs);
294 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
298 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
301 catch (SQLException sqe){
302 throwSQLException(sqe,"selectById"); return null;
304 catch (NumberFormatException e) {
305 theLog.printError("ID ist keine Zahl: " + id);
307 finally { freeConnection(con,stmt); }
309 /** @todo OS: Entity should be saved in ostore */
315 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
316 * @param key Datenbankfeld der Bedingung.
317 * @param value Wert die der key anehmen muss.
318 * @return EntityList mit den gematchten Entities
320 public EntityList selectByFieldValue(String aField, String aValue)
321 throws StorageObjectException
323 return selectByFieldValue(aField, aValue, 0);
327 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
328 * @param key Datenbankfeld der Bedingung.
329 * @param value Wert die der key anehmen muss.
330 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
331 * @return EntityList mit den gematchten Entities
333 public EntityList selectByFieldValue(String aField, String aValue, int offset)
334 throws StorageObjectException
336 return selectByWhereClause(aField + "=" + aValue, offset);
341 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
342 * Also offset wird der erste Datensatz genommen.
344 * @param wc where-Clause
345 * @return EntityList mit den gematchten Entities
346 * @exception StorageObjectException
348 public EntityList selectByWhereClause(String where)
349 throws StorageObjectException
351 return selectByWhereClause(where, 0);
356 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
357 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
359 * @param wc where-Clause
360 * @param offset ab welchem Datensatz.
361 * @return EntityList mit den gematchten Entities
362 * @exception StorageObjectException
364 public EntityList selectByWhereClause(String whereClause, int offset)
365 throws StorageObjectException
367 return selectByWhereClause(whereClause, null, offset);
372 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
373 * Also offset wird der erste Datensatz genommen.
374 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
376 * @param wc where-Clause
377 * @param ob orderBy-Clause
378 * @return EntityList mit den gematchten Entities
379 * @exception StorageObjectException
382 public EntityList selectByWhereClause(String where, String order)
383 throws StorageObjectException {
384 return selectByWhereClause(where, order, 0);
389 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
390 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
392 * @param wc where-Clause
393 * @param ob orderBy-Clause
394 * @param offset ab welchem Datensatz
395 * @return EntityList mit den gematchten Entities
396 * @exception StorageObjectException
399 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
400 throws StorageObjectException {
401 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
406 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
407 * @param wc where-Clause
408 * @param ob orderBy-Clause
409 * @param offset ab welchem Datensatz
410 * @param limit wieviele Datensätze
411 * @return EntityList mit den gematchten Entities
412 * @exception StorageObjectException
415 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
416 throws StorageObjectException {
419 EntityList theReturnList=null;
423 int offsetCount = 0, count=0;
425 // build sql-statement
427 /** @todo count sql string should only be assembled if we really count
428 * see below at the end of method //rk */
430 if (wc != null && wc.length() == 0) {
433 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
434 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
436 selectSql.append(" where ").append(wc);
437 countSql.append(" where ").append(wc);
439 if (ob != null && !(ob.length() == 0)) {
440 selectSql.append(" order by ").append(ob);
442 if (theAdaptor.hasLimit()) {
443 if (limit > -1 && offset > -1) {
444 selectSql.append(" limit ");
445 if (theAdaptor.reverseLimit()) {
446 selectSql.append(limit).append(",").append(offset);
449 selectSql.append(offset).append(",").append(limit);
454 /** @todo OS: make StoreIdentifier and ask Ostore*/
458 con = getPooledCon();
459 stmt = con.createStatement();
462 rs = executeSql(stmt, selectSql.toString());
464 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
466 theReturnList = new EntityList();
467 Entity theResultEntity;
469 theResultEntity = makeEntityFromResultSet(rs);
470 theReturnList.add(theResultEntity);
476 // making entitylist infos
477 if (!(theAdaptor.hasLimit())) count = offsetCount;
479 if (theReturnList != null) {
480 // now we decide if we have to know an overall count...
482 if (limit > -1 && offset > -1) {
483 if (offsetCount==limit) {
484 /** @todo counting should be deffered to entitylist
485 * getSize() should be used */
486 rs = executeSql(stmt, countSql.toString());
488 if ( rs.next() ) count = rs.getInt(1);
491 else theLog.printError("Could not count: " + countSql);
494 theReturnList.setCount(count);
495 theReturnList.setOffset(offset);
496 theReturnList.setWhere(wc);
497 theReturnList.setOrder(ob);
498 if (offset >= limit) {
499 theReturnList.setPrevBatch(offset - limit);
501 if (offset + offsetCount < count) {
502 theReturnList.setNextBatch(offset + limit);
506 catch (SQLException sqe) {
507 throwSQLException(sqe, "selectByWhereClause");
510 freeConnection(con, stmt);
513 return theReturnList;
518 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
520 * @param rs Das ResultSetObjekt.
521 * @return Entity Die Entity.
523 private Entity makeEntityFromResultSet (ResultSet rs)
524 throws StorageObjectException
526 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
527 HashMap theResultHash = new HashMap();
528 String theResult = null;
530 Entity returnEntity = null;
532 int size = metadataFields.size();
533 for (int i = 0; i < size; i++) {
534 // alle durchlaufen bis nix mehr da
535 theType = metadataTypes[i];
536 if (theType == java.sql.Types.LONGVARBINARY) {
537 InputStream us = rs.getAsciiStream(i + 1);
539 InputStreamReader is = new InputStreamReader(us);
540 char[] data = new char[32768];
541 StringBuffer theResultString = new StringBuffer();
543 while ((len = is.read(data)) > 0) {
544 theResultString.append(data, 0, len);
547 theResult = theResultString.toString();
554 theResult = getValueAsString(rs, (i + 1), theType);
556 if (theResult != null) {
557 theResultHash.put(metadataFields.get(i), theResult);
561 /** @todo why fetching all data (above) and then consulting the
562 * cache? we should fetch pkeyname first // rk */
563 if (cache != null && theResultHash.containsKey(thePKeyName) &&
564 (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
565 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
567 if (theEntityClass != null) {
568 returnEntity = (Entity)theEntityClass.newInstance();
569 returnEntity.setValues(theResultHash);
570 returnEntity.setStorage(myselfDatabase);
572 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
573 /** @todo put element into ObjectStore */
574 cache.put(returnEntity.getId(), returnEntity);
577 throwStorageObjectException("Internal Error: theEntityClass not set!");
580 } catch (IllegalAccessException e) {
581 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
582 } catch (IOException e) {
583 throwStorageObjectException("IOException! -- " + e.toString());
584 } catch (InstantiationException e) {
585 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
586 } catch (SQLException sqe) {
587 throwSQLException(sqe, "makeEntityFromResultSet");
594 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
595 * wird automatisch mit dem aktuellen Datum gefuellt.
598 * @return der Wert des Primary-keys der eingefügten Entity
600 public String insert (Entity theEntity) throws StorageObjectException {
601 String returnId = null;
602 Connection con = null;
603 PreparedStatement pstmt = null;
605 invalidatePopupCache();
606 /** @todo OS: if Entity is StorableObject, invalidate in ObjectStore
607 * careful: Entity has no id yet! */
609 ArrayList streamedInput = theEntity.streamedInput();
610 StringBuffer f = new StringBuffer();
611 StringBuffer v = new StringBuffer();
612 String aField, aValue;
613 boolean firstField = true;
615 for (int i = 0; i < getFields().size(); i++) {
616 aField = (String)getFields().get(i);
617 if (!aField.equals(thePKeyName)) {
620 if (aField.equals("webdb_create")) {
624 if (streamedInput != null && streamedInput.contains(aField)) {
628 if (theEntity.hasValueForField(aField)) {
629 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
634 // wenn Wert gegeben, dann einbauen
635 if (aValue != null) {
636 if (firstField == false) {
649 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
650 String sql = sqlBuf.toString();
651 theLog.printInfo("INSERT: " + sql);
652 con = getPooledCon();
653 con.setAutoCommit(false);
654 pstmt = con.prepareStatement(sql);
655 if (streamedInput != null) {
656 for (int i = 0; i < streamedInput.size(); i++) {
657 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
658 pstmt.setBytes(i + 1, inputString.getBytes());
661 int ret = pstmt.executeUpdate();
666 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
667 ResultSet rs = pstmt.executeQuery();
669 returnId = rs.getString(1);
670 theEntity.setId(returnId);
671 } catch (SQLException sqe) {
672 throwSQLException(sqe, "insert");
675 con.setAutoCommit(true);
676 } catch (Exception e) {
679 freeConnection(con, pstmt);
685 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
686 * wird automatisch mit dem aktuellen Datum gefuellt.
690 public void update (Entity theEntity) throws StorageObjectException {
691 Connection con = null;
692 /** @todo this is stupid: why do we prepare statement, when we
693 * throw it away afterwards. should be regular statement
694 * update/insert could better be one routine called save()
695 * that chooses to either insert or update depending if we
696 * have a primary key in the entity. i don't know if we
697 * still need the streamed input fields. // rk */
698 /** @todo extension: check if Entity did change, otherwise we don't need */
699 /** @todo OS: invalidate in Ostore if Entity is StorableObject */
700 PreparedStatement pstmt = null;
701 ArrayList streamedInput = theEntity.streamedInput();
702 String id = theEntity.getId();
704 StringBuffer fv = new StringBuffer();
705 boolean firstField = true;
707 invalidatePopupCache();
708 // build sql statement
709 for (int i = 0; i < getFields().size(); i++) {
710 aField = (String)metadataFields.get(i);
712 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
713 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
714 if (theEntity.hasValueForField(aField)) {
715 if (firstField == false) {
721 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
725 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
727 if (metadataFields.contains("webdb_lastchange")) {
728 sql.append(",webdb_lastchange=NOW()");
730 if (streamedInput != null) {
731 for (int i = 0; i < streamedInput.size(); i++) {
732 sql.append(",").append(streamedInput.get(i)).append("=?");
735 sql.append(" where id=").append(id);
736 theLog.printInfo("UPDATE: " + sql);
739 con = getPooledCon();
740 con.setAutoCommit(false);
741 pstmt = con.prepareStatement(sql.toString());
742 if (streamedInput != null) {
743 for (int i = 0; i < streamedInput.size(); i++) {
744 String inputString = theEntity.getValue((String)streamedInput.get(i));
745 pstmt.setBytes(i + 1, inputString.getBytes());
748 pstmt.executeUpdate();
749 } catch (SQLException sqe) {
750 throwSQLException(sqe, "update");
753 con.setAutoCommit(true);
754 } catch (Exception e) {
757 freeConnection(con, pstmt);
763 * @param id des zu loeschenden Datensatzes
764 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
766 public boolean delete (String id) throws StorageObjectException {
767 Statement stmt = null;
768 Connection con = null;
771 // loeschen des caches
772 invalidatePopupCache();
773 /** @todo OS: invalidate if StorableObject */
774 /** @todo could be prepared Statement */
775 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
777 theLog.printInfo("DELETE " + sql);
779 con = getPooledCon();
780 stmt = con.createStatement();
781 res = stmt.executeUpdate(sql);
782 } catch (SQLException sqe) {
783 throwSQLException(sqe, "delete");
785 freeConnection(con, stmt);
787 /** @todo should take place before we delete */
789 theLog.printInfo("CACHE: deleted " + id);
792 return (res > 0) ? true : false;
795 /* noch nicht implementiert.
796 * @return immer false
798 public boolean delete (EntityList theEntityList) {
799 invalidatePopupCache();
804 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
805 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
808 public SimpleList getPopupData () throws StorageObjectException {
813 * Holt Daten fuer Popups.
814 * @param name Name des Feldes.
815 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
816 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
818 public SimpleList getPopupData (String name, boolean hasNullValue)
819 throws StorageObjectException {
820 return getPopupData(name, hasNullValue, null);
824 * Holt Daten fuer Popups.
825 * @param name Name des Feldes.
826 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
827 * @param where Schraenkt die Selektion der Datensaetze ein.
828 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
830 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
831 return getPopupData(name, hasNullValue, where, null);
835 * Holt Daten fuer Popups.
836 * @param name Name des Feldes.
837 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
838 * @param where Schraenkt die Selektion der Datensaetze ein.
839 * @param order Gibt ein Feld als Sortierkriterium an.
840 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
842 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
844 if (hasPopupCache && popupCache != null)
846 SimpleList simpleList = null;
847 Connection con = null;
848 Statement stmt = null;
850 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
851 .append(",").append(name).append(" from ")
853 if (where != null && !(where.length() == 0))
854 sql.append(" where ").append(where);
855 sql.append(" order by ");
856 if (order != null && !(order.length() == 0))
862 con = getPooledCon();
863 } catch (Exception e) {
864 throw new StorageObjectException(e.toString());
867 stmt = con.createStatement();
868 ResultSet rs = executeSql(stmt, sql.toString());
871 if (!evaluatedMetaData) get_meta_data();
872 simpleList = new SimpleList();
873 // if popup has null-selector
874 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
876 SimpleHash popupDict;
878 popupDict = new SimpleHash();
879 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
880 popupDict.put("value", rs.getString(2));
881 simpleList.add(popupDict);
885 } catch (Exception e) {
886 theLog.printError("getPopupData: "+e.toString());
887 throw new StorageObjectException(e.toString());
889 freeConnection(con, stmt);
892 if (hasPopupCache) popupCache = simpleList;
897 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
898 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
899 * Tabellen Verwendung finden.
900 * @return SimpleHash mit den Tabellezeilen.
902 public SimpleHash getHashData () {
903 /** @todo dangerous! this should have a flag to be enabled, otherwise
904 * very big Hashes could be returned */
905 if (hashCache == null) {
907 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
909 } catch (StorageObjectException e) {
910 theLog.printDebugInfo(e.toString());
916 /* invalidates the popupCache
918 protected void invalidatePopupCache () {
919 /** @todo invalidates toooo much */
925 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
926 * @param stmt Statemnt
927 * @param sql Sql-String
929 * @exception StorageObjectException
931 public ResultSet executeSql (Statement stmt, String sql)
932 throws StorageObjectException, SQLException
934 long startTime = System.currentTimeMillis();
937 rs = stmt.executeQuery(sql);
938 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
941 catch (SQLException e)
943 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
944 - startTime) + "ms. for: "+ sql);
952 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
953 * getimed und geloggt.
954 * @param stmt PreparedStatement mit der SQL-Anweisung
955 * @return Liefert ResultSet des Statements zurueck.
956 * @exception StorageObjectException, SQLException
958 public ResultSet executeSql (PreparedStatement stmt)
959 throws StorageObjectException, SQLException {
961 long startTime = (new java.util.Date()).getTime();
962 ResultSet rs = stmt.executeQuery();
963 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
968 * returns the number of rows in the table
970 public int getSize(String where)
971 throws SQLException,StorageObjectException
973 long startTime = System.currentTimeMillis();
974 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
975 Connection con = null;
976 Statement stmt = null;
980 con = getPooledCon();
981 stmt = con.createStatement();
982 ResultSet rs = executeSql(stmt,sql);
984 result = rs.getInt(1);
986 } catch (SQLException e) {
987 theLog.printError(e.toString());
989 freeConnection(con,stmt);
991 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
992 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
997 public int executeUpdate(Statement stmt, String sql)
998 throws StorageObjectException, SQLException
1001 long startTime = (new java.util.Date()).getTime();
1004 rs = stmt.executeUpdate(sql);
1005 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1008 catch (SQLException e)
1010 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1011 - startTime) + "ms. for: "+ sql);
1017 public int executeUpdate(String sql)
1018 throws StorageObjectException, SQLException
1021 long startTime = (new java.util.Date()).getTime();
1022 Connection con=null;PreparedStatement pstmt=null;
1025 pstmt = con.prepareStatement(sql);
1026 result = pstmt.executeUpdate();
1028 catch (Exception e) {
1029 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1030 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1032 finally { freeConnection(con,pstmt); }
1033 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1039 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1040 * @param md ResultSetMetaData
1041 * @exception StorageObjectException
1043 private void evalMetaData (ResultSetMetaData md)
1044 throws StorageObjectException {
1046 this.evaluatedMetaData = true;
1047 this.metadataFields = new ArrayList();
1048 this.metadataLabels = new ArrayList();
1049 this.metadataNotNullFields = new ArrayList();
1051 int numFields = md.getColumnCount();
1052 this.metadataTypes = new int[numFields];
1055 for (int i = 1; i <= numFields; i++) {
1056 aField = md.getColumnName(i);
1057 metadataFields.add(aField);
1058 metadataLabels.add(md.getColumnLabel(i));
1059 aType = md.getColumnType(i);
1060 metadataTypes[i - 1] = aType;
1061 if (aField.equals(thePKeyName)) {
1062 thePKeyType = aType;
1064 if (md.isNullable(i) == md.columnNullable) {
1065 metadataNotNullFields.add(aField);
1068 } catch (SQLException e) {
1069 throwSQLException(e, "evalMetaData");
1074 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1075 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1077 private void get_meta_data () throws StorageObjectException {
1078 Connection con = null;
1079 PreparedStatement pstmt = null;
1080 String sql = "select * from " + theTable + " where 0=1";
1082 con = getPooledCon();
1083 pstmt = con.prepareStatement(sql);
1084 theLog.printInfo("METADATA: " + sql);
1085 ResultSet rs = pstmt.executeQuery();
1086 evalMetaData(rs.getMetaData());
1088 } catch (SQLException e) {
1089 throwSQLException(e, "get_meta_data");
1091 freeConnection(con, pstmt);
1096 public Connection getPooledCon() throws StorageObjectException {
1097 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1099 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1100 } catch (Exception e){
1101 throw new StorageObjectException("Could not find the PoolMan Driver"
1104 Connection con = null;
1106 con = SQLManager.getInstance().requestConnection();
1107 } catch(SQLException e){
1108 theLog.printError("could not connect to the database "+e.toString());
1109 System.err.println("could not connect to the database "+e.toString());
1110 throw new StorageObjectException("Could not connect to the database"+
1116 public void freeConnection (Connection con, Statement stmt)
1117 throws StorageObjectException {
1118 SQLManager.getInstance().closeStatement(stmt);
1119 SQLManager.getInstance().returnConnection(con);
1123 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1124 * @param sqe SQLException
1125 * @param wo Funktonsname, in der die SQLException geworfen wurde
1126 * @exception StorageObjectException
1128 protected void throwSQLException (SQLException sqe, String wo)
1129 throws StorageObjectException {
1131 String message = "";
1134 state = sqe.getSQLState();
1135 message = sqe.getMessage();
1136 vendor = sqe.getErrorCode();
1138 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1140 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1144 protected void _throwStorageObjectException (Exception e, String wo)
1145 throws StorageObjectException {
1147 theLog.printError(e.toString()+ wo);
1148 throw new StorageObjectException(wo + e.toString());
1150 theLog.printError(wo);
1151 throw new StorageObjectException(wo);
1157 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1158 * eine StorageObjectException
1159 * @param message Nachricht mit dem Fehler
1160 * @exception StorageObjectException
1162 void throwStorageObjectException (String message)
1163 throws StorageObjectException {
1164 _throwStorageObjectException(null, message);