2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with the com.oreilly.servlet library, any library
22 * licensed under the Apache Software License, The Sun (tm) Java Advanced
23 * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24 * the above that use the same license as the above), and distribute linked
25 * combinations including the two. You must obey the GNU General Public
26 * License in all respects for all of the code used other than the above
27 * mentioned libraries. If you modify this file, you may extend this exception
28 * to your version of the file, but you are not obligated to do so. If you do
29 * not wish to do so, delete this exception statement from your version.
38 import java.text.SimpleDateFormat;
39 import java.text.ParseException;
40 import freemarker.template.*;
41 import com.codestudio.sql.*;
42 import com.codestudio.util.*;
44 import mir.storage.StorageObject;
45 import mir.storage.store.*;
51 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
52 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
53 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
54 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
55 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
58 * @version $Revision: 1.21.2.4 $ $Date: 2002/12/20 03:01:01 $
59 * @author $Author: mh $
62 public class Database implements StorageObject {
64 protected String theTable;
65 protected String theCoreTable=null;
66 protected String thePKeyName="id";
67 protected int thePKeyType, thePKeyIndex;
68 protected boolean evaluatedMetaData=false;
69 protected ArrayList metadataFields,metadataLabels,
70 metadataNotNullFields;
71 protected int[] metadataTypes;
72 protected Class theEntityClass;
73 protected StorageObject myselfDatabase;
74 protected SimpleList popupCache=null;
75 protected boolean hasPopupCache = false;
76 protected SimpleHash hashCache=null;
77 protected boolean hasTimestamp=true;
78 private String database_driver, database_url;
79 private int defaultLimit;
80 protected DatabaseAdaptor theAdaptor;
81 protected Logfile theLog;
82 private static Class GENERIC_ENTITY_CLASS=null,
83 STORABLE_OBJECT_ENTITY_CLASS=null;
84 private static SimpleHash POPUP_EMTYLINE=new SimpleHash();
85 protected static final ObjectStore o_store=ObjectStore.getInstance();
86 private SimpleDateFormat _dateFormatterOut =
87 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
88 private SimpleDateFormat _dateFormatterIn =
89 new SimpleDateFormat("yyyy-MM-dd HH:mm");
90 private Calendar _cal = new GregorianCalendar();
92 private static final int _millisPerHour = 60 * 60 * 1000;
93 private static final int _millisPerMinute = 60 * 1000;
96 // always same object saves a little space
97 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
99 GENERIC_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
100 STORABLE_OBJECT_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
102 catch (Exception e) {
103 System.err.println("FATAL: Database.java could not initialize" + e.toString());
109 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
110 * Aus diesem file werden <code>Database.Logfile</code>,
111 * <code>Database.Username</code>,<code>Database.Password</code>,
112 * <code>Database.Host</code> und <code>Database.Adaptor</code>
113 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
116 * @param String confFilename Dateiname der Konfigurationsdatei
118 public Database() throws StorageObjectException {
119 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
120 MirConfig.getProp("Database.Logfile"));
121 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
122 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
124 theEntityClass = GENERIC_ENTITY_CLASS;
125 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
126 } catch (Exception e){
127 theLog.printError("Error in Database() constructor with "+
128 theAdaptorName + " -- " +e.toString());
129 throw new StorageObjectException("Error in Database() constructor with "
132 /*String database_username=MirConfig.getProp("Database.Username");
133 String database_password=MirConfig.getProp("Database.Password");
134 String database_host=MirConfig.getProp("Database.Host");
136 database_driver=theAdaptor.getDriver();
137 database_url=theAdaptor.getURL(database_username,database_password,
139 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
141 MirConfig.addBroker(database_driver,database_url);
142 //myBroker=MirConfig.getBroker();
147 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
148 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
149 * wird eine mir.entity.GenericEntity erzeugt.
151 * @return Class-Objekt der Entity
153 public java.lang.Class getEntityClass () {
154 return theEntityClass;
158 * Liefert die Standardbeschränkung von select-Statements zurück, also
159 * wieviel Datensätze per Default selektiert werden.
161 * @return Standard-Anzahl der Datensätze
163 public int getLimit () {
168 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
169 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
170 * @return Name des Primary-Keys
172 public String getIdName () {
177 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
179 * @return Name der Tabelle
181 public String getTableName () {
186 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
187 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
189 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
193 public String getCoreTable(){
194 if (theCoreTable!=null) return theCoreTable;
195 else return theTable;
199 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
200 * @return int-Array mit den Typen der Felder
201 * @exception StorageObjectException
203 public int[] getTypes () throws StorageObjectException {
204 if (metadataTypes == null)
206 return metadataTypes;
210 * Liefert eine Liste der Labels der Tabellenfelder
211 * @return ArrayListe mit Labeln
212 * @exception StorageObjectException
214 public ArrayList getLabels () throws StorageObjectException {
215 if (metadataLabels == null)
217 return metadataLabels;
221 * Liefert eine Liste der Felder der Tabelle
222 * @return ArrayList mit Feldern
223 * @exception StorageObjectException
225 public ArrayList getFields () throws StorageObjectException {
226 if (metadataFields == null)
228 return metadataFields;
233 * Gets value out of ResultSet according to type and converts to String
234 * @param inValue Wert aus ResultSet.
235 * @param aType Datenbanktyp.
236 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
237 * dann /unsupported value/
239 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
240 String outValue = null;
244 case java.sql.Types.BIT:
245 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
247 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
248 int out = rs.getInt(valueIndex);
250 outValue = new Integer(out).toString();
252 case java.sql.Types.NUMERIC:
253 /** @todo Numeric can be float or double depending upon
254 * metadata.getScale() / especially with oracle */
255 long outl = rs.getLong(valueIndex);
257 outValue = new Long(outl).toString();
259 case java.sql.Types.REAL:
260 float tempf = rs.getFloat(valueIndex);
264 int tempf_int = (int)tempf;
265 tempf = (float)tempf_int;
267 outValue = "" + tempf;
268 outValue = outValue.replace('.', ',');
271 case java.sql.Types.DOUBLE:
272 double tempd = rs.getDouble(valueIndex);
276 int tempd_int = (int)tempd;
277 tempd = (double)tempd_int;
279 outValue = "" + tempd;
280 outValue = outValue.replace('.', ',');
283 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
284 outValue = rs.getString(valueIndex);
286 case java.sql.Types.LONGVARBINARY:
287 outValue = rs.getString(valueIndex);
289 case java.sql.Types.TIMESTAMP:
290 // it's important to use Timestamp here as getting it
291 // as a string is undefined and is only there for debugging
292 // according to the API. we can make it a string through formatting.
294 Timestamp timestamp = (rs.getTimestamp(valueIndex));
296 java.util.Date date = new java.util.Date(timestamp.getTime());
297 outValue = _dateFormatterOut.format(date);
299 int offset = _cal.get(Calendar.ZONE_OFFSET)+
300 _cal.get(Calendar.DST_OFFSET);
301 String tzOffset = StringUtil.zeroPaddingNumber(
302 offset/_millisPerHour,2,2);
303 outValue = outValue+"+"+tzOffset;
307 outValue = "<unsupported value>";
308 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
311 } catch (SQLException e) {
312 throw new StorageObjectException("Could not get Value out of Resultset -- "
320 * select-Operator um einen Datensatz zu bekommen.
321 * @param id Primaerschluessel des Datensatzes.
322 * @return liefert EntityObject des gefundenen Datensatzes oder null.
324 public Entity selectById(String id) throws StorageObjectException
326 if (id==null||id.equals(""))
327 throw new StorageObjectException("id war null");
329 // ask object store for object
330 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
331 String uniqueId = id;
332 if ( theEntityClass.equals(StorableObjectEntity.class) )
333 uniqueId+="@"+theTable;
334 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
335 theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
336 Entity hit = (Entity)o_store.use(search_sid);
337 if ( hit!=null ) return hit;
340 Statement stmt=null;Connection con=getPooledCon();
341 Entity returnEntity=null;
344 /** @todo better prepared statement */
345 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
346 stmt = con.createStatement();
347 rs = executeSql(stmt, selectSql);
349 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
351 returnEntity = makeEntityFromResultSet(rs);
352 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
356 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
359 catch (SQLException sqe){
360 throwSQLException(sqe,"selectById"); return null;
362 catch (NumberFormatException e) {
363 theLog.printError("ID ist keine Zahl: " + id);
365 finally { freeConnection(con,stmt); }
367 /** @todo OS: Entity should be saved in ostore */
373 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
374 * @param key Datenbankfeld der Bedingung.
375 * @param value Wert die der key anehmen muss.
376 * @return EntityList mit den gematchten Entities
378 public EntityList selectByFieldValue(String aField, String aValue)
379 throws StorageObjectException
381 return selectByFieldValue(aField, aValue, 0);
385 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
386 * @param key Datenbankfeld der Bedingung.
387 * @param value Wert die der key anehmen muss.
388 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
389 * @return EntityList mit den gematchten Entities
391 public EntityList selectByFieldValue(String aField, String aValue, int offset)
392 throws StorageObjectException
394 return selectByWhereClause(aField + "=" + aValue, offset);
399 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
400 * Also offset wird der erste Datensatz genommen.
402 * @param wc where-Clause
403 * @return EntityList mit den gematchten Entities
404 * @exception StorageObjectException
406 public EntityList selectByWhereClause(String where)
407 throws StorageObjectException
409 return selectByWhereClause(where, 0);
414 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
415 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
417 * @param wc where-Clause
418 * @param offset ab welchem Datensatz.
419 * @return EntityList mit den gematchten Entities
420 * @exception StorageObjectException
422 public EntityList selectByWhereClause(String whereClause, int offset)
423 throws StorageObjectException
425 return selectByWhereClause(whereClause, null, offset);
430 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
431 * Also offset wird der erste Datensatz genommen.
432 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
434 * @param wc where-Clause
435 * @param ob orderBy-Clause
436 * @return EntityList mit den gematchten Entities
437 * @exception StorageObjectException
440 public EntityList selectByWhereClause(String where, String order)
441 throws StorageObjectException {
442 return selectByWhereClause(where, order, 0);
447 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
448 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
450 * @param wc where-Clause
451 * @param ob orderBy-Clause
452 * @param offset ab welchem Datensatz
453 * @return EntityList mit den gematchten Entities
454 * @exception StorageObjectException
457 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
458 throws StorageObjectException {
459 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
464 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
465 * @param wc where-Clause
466 * @param ob orderBy-Clause
467 * @param offset ab welchem Datensatz
468 * @param limit wieviele Datensätze
469 * @return EntityList mit den gematchten Entities
470 * @exception StorageObjectException
473 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
474 throws StorageObjectException
477 // check o_store for entitylist
478 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
479 StoreIdentifier search_sid =
480 new StoreIdentifier( theEntityClass,
481 StoreContainerType.STOC_TYPE_ENTITYLIST,
482 StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
483 EntityList hit = (EntityList)o_store.use(search_sid);
485 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
491 EntityList theReturnList=null;
492 Connection con=null; Statement stmt=null;
494 int offsetCount = 0, count=0;
496 // build sql-statement
498 /** @todo count sql string should only be assembled if we really count
499 * see below at the end of method //rk */
501 if (wc != null && wc.length() == 0) {
504 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
505 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
507 selectSql.append(" where ").append(wc);
508 countSql.append(" where ").append(wc);
510 if (ob != null && !(ob.length() == 0)) {
511 selectSql.append(" order by ").append(ob);
513 if (theAdaptor.hasLimit()) {
514 if (limit > -1 && offset > -1) {
515 selectSql.append(" limit ");
516 if (theAdaptor.reverseLimit()) {
517 selectSql.append(limit).append(",").append(offset);
520 selectSql.append(offset).append(",").append(limit);
527 con = getPooledCon();
528 stmt = con.createStatement();
531 rs = executeSql(stmt, selectSql.toString());
533 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
535 theReturnList = new EntityList();
536 Entity theResultEntity;
538 theResultEntity = makeEntityFromResultSet(rs);
539 theReturnList.add(theResultEntity);
545 // making entitylist infos
546 if (!(theAdaptor.hasLimit())) count = offsetCount;
548 if (theReturnList != null) {
549 // now we decide if we have to know an overall count...
551 if (limit > -1 && offset > -1) {
552 if (offsetCount==limit) {
553 /** @todo counting should be deffered to entitylist
554 * getSize() should be used */
555 rs = executeSql(stmt, countSql.toString());
557 if ( rs.next() ) count = rs.getInt(1);
560 else theLog.printError("Could not count: " + countSql);
563 theReturnList.setCount(count);
564 theReturnList.setOffset(offset);
565 theReturnList.setWhere(wc);
566 theReturnList.setOrder(ob);
567 theReturnList.setStorage(this);
568 theReturnList.setLimit(limit);
569 if ( offset >= limit )
570 theReturnList.setPrevBatch(offset - limit);
571 if ( offset+offsetCount < count )
572 theReturnList.setNextBatch(offset + limit);
573 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
574 StoreIdentifier sid=theReturnList.getStoreIdentifier();
575 theLog.printDebugInfo("CACHE (add): " + sid.toString());
580 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
581 finally { freeConnection(con, stmt); }
583 return theReturnList;
588 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
590 * @param rs Das ResultSetObjekt.
591 * @return Entity Die Entity.
593 private Entity makeEntityFromResultSet (ResultSet rs)
594 throws StorageObjectException
596 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
597 HashMap theResultHash = new HashMap();
598 String theResult = null;
600 Entity returnEntity = null;
602 int size = metadataFields.size();
603 for (int i = 0; i < size; i++) {
604 // alle durchlaufen bis nix mehr da
605 theType = metadataTypes[i];
606 if (theType == java.sql.Types.LONGVARBINARY) {
607 InputStreamReader is = (InputStreamReader)rs.getCharacterStream(i + 1);
609 char[] data = new char[32768];
610 StringBuffer theResultString = new StringBuffer();
612 while ((len = is.read(data)) > 0) {
613 theResultString.append(data, 0, len);
616 theResult = theResultString.toString();
623 theResult = getValueAsString(rs, (i + 1), theType);
625 if (theResult != null) {
626 theResultHash.put(metadataFields.get(i), theResult);
629 if (theEntityClass != null) {
630 returnEntity = (Entity)theEntityClass.newInstance();
631 returnEntity.setValues(theResultHash);
632 returnEntity.setStorage(myselfDatabase);
633 if ( returnEntity instanceof StorableObject ) {
634 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
635 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
638 throwStorageObjectException("Internal Error: theEntityClass not set!");
640 } catch (IllegalAccessException e) {
641 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
642 } catch (IOException e) {
643 throwStorageObjectException("IOException! -- " + e.toString());
644 } catch (InstantiationException e) {
645 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
646 } catch (SQLException sqe) {
647 throwSQLException(sqe, "makeEntityFromResultSet");
654 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
655 * wird automatisch mit dem aktuellen Datum gefuellt.
658 * @return der Wert des Primary-keys der eingefügten Entity
660 public String insert (Entity theEntity) throws StorageObjectException {
662 invalidatePopupCache();
664 // invalidating all EntityLists corresponding with theEntityClass
665 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
666 StoreContainerType stoc_type =
667 StoreContainerType.valueOf( theEntityClass,
668 StoreContainerType.STOC_TYPE_ENTITYLIST);
669 o_store.invalidate(stoc_type);
672 String returnId = null;
673 Connection con = null; PreparedStatement pstmt = null;
676 ArrayList streamedInput = theEntity.streamedInput();
677 StringBuffer f = new StringBuffer();
678 StringBuffer v = new StringBuffer();
679 String aField, aValue;
680 boolean firstField = true;
682 for (int i = 0; i < getFields().size(); i++) {
683 aField = (String)getFields().get(i);
684 if (!aField.equals(thePKeyName)) {
687 if (aField.equals("webdb_create") ||
688 aField.equals("webdb_lastchange")) {
692 if (streamedInput != null && streamedInput.contains(aField)) {
696 if (theEntity.hasValueForField(aField)) {
697 aValue = "'" + StringUtil.JDBCescapeStringLiteral((String)theEntity.getValue(aField))
702 // wenn Wert gegeben, dann einbauen
703 if (aValue != null) {
704 if (firstField == false) {
717 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
718 String sql = sqlBuf.toString();
719 //theLog.printInfo("INSERT: " + sql);
720 con = getPooledCon();
721 con.setAutoCommit(false);
722 pstmt = con.prepareStatement(sql);
723 if (streamedInput != null) {
724 for (int i = 0; i < streamedInput.size(); i++) {
725 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
726 pstmt.setBytes(i + 1, inputString.getBytes());
729 int ret = pstmt.executeUpdate();
734 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
735 ResultSet rs = pstmt.executeQuery();
737 returnId = rs.getString(1);
738 theEntity.setId(returnId);
739 } catch (SQLException sqe) {
740 throwSQLException(sqe, "insert");
743 con.setAutoCommit(true);
744 } catch (Exception e) {
747 freeConnection(con, pstmt);
749 /** @todo store entity in o_store */
754 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
755 * wird automatisch mit dem aktuellen Datum gefuellt.
759 public void update (Entity theEntity) throws StorageObjectException
761 Connection con = null; PreparedStatement pstmt = null;
762 /** @todo this is stupid: why do we prepare statement, when we
763 * throw it away afterwards. should be regular statement
764 * update/insert could better be one routine called save()
765 * that chooses to either insert or update depending if we
766 * have a primary key in the entity. i don't know if we
767 * still need the streamed input fields. // rk */
769 /** @todo extension: check if Entity did change, otherwise we don't need
770 * the roundtrip to the database */
772 /** invalidating corresponding entitylists in o_store*/
773 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
774 StoreContainerType stoc_type =
775 StoreContainerType.valueOf( theEntityClass,
776 StoreContainerType.STOC_TYPE_ENTITYLIST);
777 o_store.invalidate(stoc_type);
780 ArrayList streamedInput = theEntity.streamedInput();
781 String id = theEntity.getId();
783 StringBuffer fv = new StringBuffer();
784 boolean firstField = true;
786 invalidatePopupCache();
787 // build sql statement
788 for (int i = 0; i < getFields().size(); i++) {
789 aField = (String)metadataFields.get(i);
791 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
792 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
793 if (theEntity.hasValueForField(aField)) {
794 if (firstField == false) {
800 fv.append(aField).append("='").append(StringUtil.JDBCescapeStringLiteral((String)theEntity.getValue(aField))).append("'");
804 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
806 if (metadataFields.contains("webdb_lastchange")) {
807 sql.append(",webdb_lastchange=NOW()");
809 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
810 // format so anything extra will be ignored. -mh
811 if (metadataFields.contains("webdb_create") &&
812 theEntity.hasValueForField("webdb_create")) {
813 // minimum of 10 (yyyy-mm-dd)...
814 if (theEntity.getValue("webdb_create").length() >= 10) {
815 String dateString = theEntity.getValue("webdb_create");
816 // if only 10, then add 00:00 so it doesn't throw a ParseException
817 if (dateString.length() == 10)
818 dateString=dateString+" 00:00";
822 java.util.Date d = _dateFormatterIn.parse(dateString);
823 Timestamp tStamp = new Timestamp(d.getTime());
824 sql.append(",webdb_create='"+tStamp.toString()+"'");
825 } catch (ParseException e) {
826 throw new StorageObjectException(e.toString());
830 if (streamedInput != null) {
831 for (int i = 0; i < streamedInput.size(); i++) {
832 sql.append(",").append(streamedInput.get(i)).append("=?");
835 sql.append(" where id=").append(id);
836 //theLog.printInfo("UPDATE: " + sql);
839 con = getPooledCon();
840 con.setAutoCommit(false);
841 pstmt = con.prepareStatement(sql.toString());
842 if (streamedInput != null) {
843 for (int i = 0; i < streamedInput.size(); i++) {
844 String inputString = theEntity.getValue((String)streamedInput.get(i));
845 pstmt.setBytes(i + 1, inputString.getBytes());
848 pstmt.executeUpdate();
849 } catch (SQLException sqe) {
850 throwSQLException(sqe, "update");
853 con.setAutoCommit(true);
854 } catch (Exception e) {
857 freeConnection(con, pstmt);
863 * @param id des zu loeschenden Datensatzes
864 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
866 public boolean delete (String id) throws StorageObjectException {
868 invalidatePopupCache();
869 // ostore send notification
870 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
871 String uniqueId = id;
872 if ( theEntityClass.equals(StorableObjectEntity.class) )
873 uniqueId+="@"+theTable;
874 theLog.printInfo("CACHE: (del) " + id);
875 StoreIdentifier search_sid =
876 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
877 o_store.invalidate(search_sid);
880 /** @todo could be prepared Statement */
881 Statement stmt = null; Connection con = null;
883 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
884 //theLog.printInfo("DELETE " + sql);
886 con = getPooledCon(); stmt = con.createStatement();
887 res = stmt.executeUpdate(sql);
889 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
890 finally { freeConnection(con, stmt); }
892 return (res > 0) ? true : false;
895 /* noch nicht implementiert.
896 * @return immer false
898 public boolean delete (EntityList theEntityList) {
899 invalidatePopupCache();
904 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
905 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
908 public SimpleList getPopupData () throws StorageObjectException {
913 * Holt Daten fuer Popups.
914 * @param name Name des Feldes.
915 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
916 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
918 public SimpleList getPopupData (String name, boolean hasNullValue)
919 throws StorageObjectException {
920 return getPopupData(name, hasNullValue, null);
924 * Holt Daten fuer Popups.
925 * @param name Name des Feldes.
926 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
927 * @param where Schraenkt die Selektion der Datensaetze ein.
928 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
930 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
931 return getPopupData(name, hasNullValue, where, null);
935 * Holt Daten fuer Popups.
936 * @param name Name des Feldes.
937 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
938 * @param where Schraenkt die Selektion der Datensaetze ein.
939 * @param order Gibt ein Feld als Sortierkriterium an.
940 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
942 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
944 if (hasPopupCache && popupCache != null)
946 SimpleList simpleList = null;
947 Connection con = null;
948 Statement stmt = null;
950 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
951 .append(",").append(name).append(" from ")
953 if (where != null && !(where.length() == 0))
954 sql.append(" where ").append(where);
955 sql.append(" order by ");
956 if (order != null && !(order.length() == 0))
962 con = getPooledCon();
963 } catch (Exception e) {
964 throw new StorageObjectException(e.toString());
967 stmt = con.createStatement();
968 ResultSet rs = executeSql(stmt, sql.toString());
971 if (!evaluatedMetaData) get_meta_data();
972 simpleList = new SimpleList();
973 // if popup has null-selector
974 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
976 SimpleHash popupDict;
978 popupDict = new SimpleHash();
979 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
980 popupDict.put("value", rs.getString(2));
981 simpleList.add(popupDict);
985 } catch (Exception e) {
986 theLog.printError("getPopupData: "+e.toString());
987 throw new StorageObjectException(e.toString());
989 freeConnection(con, stmt);
992 if (hasPopupCache) popupCache = simpleList;
997 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
998 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
999 * Tabellen Verwendung finden.
1000 * @return SimpleHash mit den Tabellezeilen.
1002 public SimpleHash getHashData () {
1003 /** @todo dangerous! this should have a flag to be enabled, otherwise
1004 * very big Hashes could be returned */
1005 if (hashCache == null) {
1007 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
1009 } catch (StorageObjectException e) {
1010 theLog.printDebugInfo(e.toString());
1016 /* invalidates the popupCache
1018 protected void invalidatePopupCache () {
1019 /** @todo invalidates toooo much */
1025 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1026 * @param stmt Statemnt
1027 * @param sql Sql-String
1029 * @exception StorageObjectException
1031 public ResultSet executeSql (Statement stmt, String sql)
1032 throws StorageObjectException, SQLException
1034 long startTime = System.currentTimeMillis();
1037 rs = stmt.executeQuery(sql);
1038 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1041 catch (SQLException e)
1043 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
1044 - startTime) + "ms. for: "+ sql);
1052 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
1053 * getimed und geloggt.
1054 * @param stmt PreparedStatement mit der SQL-Anweisung
1055 * @return Liefert ResultSet des Statements zurueck.
1056 * @exception StorageObjectException, SQLException
1058 public ResultSet executeSql (PreparedStatement stmt)
1059 throws StorageObjectException, SQLException {
1061 long startTime = (new java.util.Date()).getTime();
1062 ResultSet rs = stmt.executeQuery();
1063 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1068 * returns the number of rows in the table
1070 public int getSize(String where)
1071 throws SQLException,StorageObjectException
1073 long startTime = System.currentTimeMillis();
1074 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
1075 Connection con = null;
1076 Statement stmt = null;
1080 con = getPooledCon();
1081 stmt = con.createStatement();
1082 ResultSet rs = executeSql(stmt,sql);
1084 result = rs.getInt(1);
1086 } catch (SQLException e) {
1087 theLog.printError(e.toString());
1089 freeConnection(con,stmt);
1091 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1092 //theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1096 public int executeUpdate(Statement stmt, String sql)
1097 throws StorageObjectException, SQLException
1100 long startTime = (new java.util.Date()).getTime();
1103 rs = stmt.executeUpdate(sql);
1104 //theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
1106 catch (SQLException e)
1108 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1109 - startTime) + "ms. for: "+ sql);
1115 public int executeUpdate(String sql)
1116 throws StorageObjectException, SQLException
1119 long startTime = (new java.util.Date()).getTime();
1120 Connection con=null;PreparedStatement pstmt=null;
1123 pstmt = con.prepareStatement(sql);
1124 result = pstmt.executeUpdate();
1126 catch (Exception e) {
1127 theLog.printDebugInfo("executeUpdate failed: "+e.toString());
1128 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1130 finally { freeConnection(con,pstmt); }
1131 //theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
1136 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1137 * @param md ResultSetMetaData
1138 * @exception StorageObjectException
1140 private void evalMetaData (ResultSetMetaData md)
1141 throws StorageObjectException {
1143 this.evaluatedMetaData = true;
1144 this.metadataFields = new ArrayList();
1145 this.metadataLabels = new ArrayList();
1146 this.metadataNotNullFields = new ArrayList();
1148 int numFields = md.getColumnCount();
1149 this.metadataTypes = new int[numFields];
1152 for (int i = 1; i <= numFields; i++) {
1153 aField = md.getColumnName(i);
1154 metadataFields.add(aField);
1155 metadataLabels.add(md.getColumnLabel(i));
1156 aType = md.getColumnType(i);
1157 metadataTypes[i - 1] = aType;
1158 if (aField.equals(thePKeyName)) {
1159 thePKeyType = aType; thePKeyIndex = i;
1161 if (md.isNullable(i) == md.columnNullable) {
1162 metadataNotNullFields.add(aField);
1165 } catch (SQLException e) {
1166 throwSQLException(e, "evalMetaData");
1171 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1172 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1174 private void get_meta_data () throws StorageObjectException {
1175 Connection con = null;
1176 PreparedStatement pstmt = null;
1177 String sql = "select * from " + theTable + " where 0=1";
1179 con = getPooledCon();
1180 pstmt = con.prepareStatement(sql);
1181 //theLog.printInfo("METADATA: " + sql);
1182 ResultSet rs = pstmt.executeQuery();
1183 evalMetaData(rs.getMetaData());
1185 } catch (SQLException e) {
1186 throwSQLException(e, "get_meta_data");
1188 freeConnection(con, pstmt);
1193 public Connection getPooledCon() throws StorageObjectException {
1194 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1196 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1197 } catch (Exception e){
1198 throw new StorageObjectException("Could not find the PoolMan Driver"
1201 Connection con = null;
1203 con = SQLManager.getInstance().requestConnection();
1204 } catch(SQLException e){
1205 theLog.printError("could not connect to the database "+e.toString());
1206 System.err.println("could not connect to the database "+e.toString());
1207 throw new StorageObjectException("Could not connect to the database"+
1213 public void freeConnection (Connection con, Statement stmt)
1214 throws StorageObjectException {
1215 SQLManager.getInstance().closeStatement(stmt);
1216 SQLManager.getInstance().returnConnection(con);
1220 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1221 * @param sqe SQLException
1222 * @param wo Funktonsname, in der die SQLException geworfen wurde
1223 * @exception StorageObjectException
1225 protected void throwSQLException (SQLException sqe, String wo)
1226 throws StorageObjectException {
1228 String message = "";
1231 state = sqe.getSQLState();
1232 message = sqe.getMessage();
1233 vendor = sqe.getErrorCode();
1235 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1237 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1241 protected void _throwStorageObjectException (Exception e, String wo)
1242 throws StorageObjectException {
1244 theLog.printError(e.toString()+ wo);
1245 throw new StorageObjectException(wo + e.toString());
1247 theLog.printError(wo);
1248 throw new StorageObjectException(wo);
1254 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1255 * eine StorageObjectException
1256 * @param message Nachricht mit dem Fehler
1257 * @exception StorageObjectException
1259 void throwStorageObjectException (String message)
1260 throws StorageObjectException {
1261 _throwStorageObjectException(null, message);