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 $Id: Database.java,v 1.24 2002/11/04 04:35:21 mh Exp $
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);
285 //if (outValue != null)
286 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
288 case java.sql.Types.LONGVARBINARY:
289 outValue = rs.getString(valueIndex);
290 //if (outValue != null)
291 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
293 case java.sql.Types.TIMESTAMP:
294 // it's important to use Timestamp here as getting it
295 // as a string is undefined and is only there for debugging
296 // according to the API. we can make it a string through formatting.
298 Timestamp timestamp = (rs.getTimestamp(valueIndex));
300 java.util.Date date = new java.util.Date(timestamp.getTime());
301 outValue = _dateFormatterOut.format(date);
303 int offset = _cal.get(Calendar.ZONE_OFFSET)+
304 _cal.get(Calendar.DST_OFFSET);
305 String tzOffset = StringUtil.zeroPaddingNumber(
306 offset/_millisPerHour,2,2);
307 outValue = outValue+"+"+tzOffset;
311 outValue = "<unsupported value>";
312 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
315 } catch (SQLException e) {
316 throw new StorageObjectException("Could not get Value out of Resultset -- "
324 * select-Operator um einen Datensatz zu bekommen.
325 * @param id Primaerschluessel des Datensatzes.
326 * @return liefert EntityObject des gefundenen Datensatzes oder null.
328 public Entity selectById(String id) throws StorageObjectException
330 if (id==null||id.equals(""))
331 throw new StorageObjectException("id war null");
333 // ask object store for object
334 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
335 String uniqueId = id;
336 if ( theEntityClass.equals(StorableObjectEntity.class) )
337 uniqueId+="@"+theTable;
338 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
339 theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
340 Entity hit = (Entity)o_store.use(search_sid);
341 if ( hit!=null ) return hit;
344 Statement stmt=null;Connection con=getPooledCon();
345 Entity returnEntity=null;
348 /** @todo better prepared statement */
349 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
350 stmt = con.createStatement();
351 rs = executeSql(stmt, selectSql);
353 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
355 returnEntity = makeEntityFromResultSet(rs);
356 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
360 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
363 catch (SQLException sqe){
364 throwSQLException(sqe,"selectById"); return null;
366 catch (NumberFormatException e) {
367 theLog.printError("ID ist keine Zahl: " + id);
369 finally { freeConnection(con,stmt); }
371 /** @todo OS: Entity should be saved in ostore */
377 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
378 * @param key Datenbankfeld der Bedingung.
379 * @param value Wert die der key anehmen muss.
380 * @return EntityList mit den gematchten Entities
382 public EntityList selectByFieldValue(String aField, String aValue)
383 throws StorageObjectException
385 return selectByFieldValue(aField, aValue, 0);
389 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
390 * @param key Datenbankfeld der Bedingung.
391 * @param value Wert die der key anehmen muss.
392 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
393 * @return EntityList mit den gematchten Entities
395 public EntityList selectByFieldValue(String aField, String aValue, int offset)
396 throws StorageObjectException
398 return selectByWhereClause(aField + "=" + aValue, offset);
403 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
404 * Also offset wird der erste Datensatz genommen.
406 * @param wc where-Clause
407 * @return EntityList mit den gematchten Entities
408 * @exception StorageObjectException
410 public EntityList selectByWhereClause(String where)
411 throws StorageObjectException
413 return selectByWhereClause(where, 0);
418 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
419 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
421 * @param wc where-Clause
422 * @param offset ab welchem Datensatz.
423 * @return EntityList mit den gematchten Entities
424 * @exception StorageObjectException
426 public EntityList selectByWhereClause(String whereClause, int offset)
427 throws StorageObjectException
429 return selectByWhereClause(whereClause, null, offset);
434 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
435 * Also offset wird der erste Datensatz genommen.
436 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
438 * @param wc where-Clause
439 * @param ob orderBy-Clause
440 * @return EntityList mit den gematchten Entities
441 * @exception StorageObjectException
444 public EntityList selectByWhereClause(String where, String order)
445 throws StorageObjectException {
446 return selectByWhereClause(where, order, 0);
451 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
452 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
454 * @param wc where-Clause
455 * @param ob orderBy-Clause
456 * @param offset ab welchem Datensatz
457 * @return EntityList mit den gematchten Entities
458 * @exception StorageObjectException
461 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
462 throws StorageObjectException {
463 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
468 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
469 * @param wc where-Clause
470 * @param ob orderBy-Clause
471 * @param offset ab welchem Datensatz
472 * @param limit wieviele Datensätze
473 * @return EntityList mit den gematchten Entities
474 * @exception StorageObjectException
477 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
478 throws StorageObjectException
481 // check o_store for entitylist
482 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
483 StoreIdentifier search_sid =
484 new StoreIdentifier( theEntityClass,
485 StoreContainerType.STOC_TYPE_ENTITYLIST,
486 StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
487 EntityList hit = (EntityList)o_store.use(search_sid);
489 theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
495 EntityList theReturnList=null;
496 Connection con=null; Statement stmt=null;
498 int offsetCount = 0, count=0;
500 // build sql-statement
502 /** @todo count sql string should only be assembled if we really count
503 * see below at the end of method //rk */
505 if (wc != null && wc.length() == 0) {
508 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
509 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
511 selectSql.append(" where ").append(wc);
512 countSql.append(" where ").append(wc);
514 if (ob != null && !(ob.length() == 0)) {
515 selectSql.append(" order by ").append(ob);
517 if (theAdaptor.hasLimit()) {
518 if (limit > -1 && offset > -1) {
519 selectSql.append(" limit ");
520 if (theAdaptor.reverseLimit()) {
521 selectSql.append(limit).append(",").append(offset);
524 selectSql.append(offset).append(",").append(limit);
531 con = getPooledCon();
532 stmt = con.createStatement();
535 rs = executeSql(stmt, selectSql.toString());
537 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
539 theReturnList = new EntityList();
540 Entity theResultEntity;
542 theResultEntity = makeEntityFromResultSet(rs);
543 theReturnList.add(theResultEntity);
549 // making entitylist infos
550 if (!(theAdaptor.hasLimit())) count = offsetCount;
552 if (theReturnList != null) {
553 // now we decide if we have to know an overall count...
555 if (limit > -1 && offset > -1) {
556 if (offsetCount==limit) {
557 /** @todo counting should be deffered to entitylist
558 * getSize() should be used */
559 rs = executeSql(stmt, countSql.toString());
561 if ( rs.next() ) count = rs.getInt(1);
564 else theLog.printError("Could not count: " + countSql);
567 theReturnList.setCount(count);
568 theReturnList.setOffset(offset);
569 theReturnList.setWhere(wc);
570 theReturnList.setOrder(ob);
571 theReturnList.setStorage(this);
572 theReturnList.setLimit(limit);
573 if ( offset >= limit )
574 theReturnList.setPrevBatch(offset - limit);
575 if ( offset+offsetCount < count )
576 theReturnList.setNextBatch(offset + limit);
577 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
578 StoreIdentifier sid=theReturnList.getStoreIdentifier();
579 theLog.printDebugInfo("CACHE (add): " + sid.toString());
584 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
585 finally { freeConnection(con, stmt); }
587 return theReturnList;
592 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
594 * @param rs Das ResultSetObjekt.
595 * @return Entity Die Entity.
597 private Entity makeEntityFromResultSet (ResultSet rs)
598 throws StorageObjectException
600 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
601 HashMap theResultHash = new HashMap();
602 String theResult = null;
604 Entity returnEntity = null;
606 int size = metadataFields.size();
607 for (int i = 0; i < size; i++) {
608 // alle durchlaufen bis nix mehr da
610 theType = metadataTypes[i];
611 if (theType == java.sql.Types.LONGVARBINARY) {
612 InputStreamReader is = (InputStreamReader)rs.getCharacterStream(i + 1);
614 char[] data = new char[32768];
615 StringBuffer theResultString = new StringBuffer();
617 while ((len = is.read(data)) > 0) {
618 theResultString.append(data, 0, len);
621 theResult = theResultString.toString();
628 theResult = getValueAsString(rs, (i + 1), theType);
630 if (theResult != null) {
631 theResultHash.put(metadataFields.get(i), theResult);
634 if (theEntityClass != null) {
635 returnEntity = (Entity)theEntityClass.newInstance();
636 returnEntity.setValues(theResultHash);
637 returnEntity.setStorage(myselfDatabase);
638 if ( returnEntity instanceof StorableObject ) {
639 theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
640 o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
643 throwStorageObjectException("Internal Error: theEntityClass not set!");
645 } catch (IllegalAccessException e) {
646 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
647 } catch (IOException e) {
648 throwStorageObjectException("IOException! -- " + e.toString());
649 } catch (InstantiationException e) {
650 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
651 } catch (SQLException sqe) {
652 throwSQLException(sqe, "makeEntityFromResultSet");
659 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
660 * wird automatisch mit dem aktuellen Datum gefuellt.
663 * @return der Wert des Primary-keys der eingefügten Entity
665 public String insert (Entity theEntity) throws StorageObjectException {
667 invalidatePopupCache();
669 // invalidating all EntityLists corresponding with theEntityClass
670 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
671 StoreContainerType stoc_type =
672 StoreContainerType.valueOf( theEntityClass,
673 StoreContainerType.STOC_TYPE_ENTITYLIST);
674 o_store.invalidate(stoc_type);
677 String returnId = null;
678 Connection con = null; PreparedStatement pstmt = null;
681 ArrayList streamedInput = theEntity.streamedInput();
682 StringBuffer f = new StringBuffer();
683 StringBuffer v = new StringBuffer();
684 String aField, aValue;
685 boolean firstField = true;
687 for (int i = 0; i < getFields().size(); i++) {
688 aField = (String)getFields().get(i);
689 if (!aField.equals(thePKeyName)) {
692 if (aField.equals("webdb_create") ||
693 aField.equals("webdb_lastchange")) {
697 if (streamedInput != null && streamedInput.contains(aField)) {
701 if (theEntity.hasValueForField(aField)) {
702 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
707 // wenn Wert gegeben, dann einbauen
708 if (aValue != null) {
709 if (firstField == false) {
722 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
723 String sql = sqlBuf.toString();
724 theLog.printInfo("INSERT: " + sql);
725 con = getPooledCon();
726 con.setAutoCommit(false);
727 pstmt = con.prepareStatement(sql);
728 if (streamedInput != null) {
729 for (int i = 0; i < streamedInput.size(); i++) {
730 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
731 pstmt.setBytes(i + 1, inputString.getBytes());
734 int ret = pstmt.executeUpdate();
739 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
740 ResultSet rs = pstmt.executeQuery();
742 returnId = rs.getString(1);
743 theEntity.setId(returnId);
744 } catch (SQLException sqe) {
745 throwSQLException(sqe, "insert");
748 con.setAutoCommit(true);
749 } catch (Exception e) {
752 freeConnection(con, pstmt);
754 /** @todo store entity in o_store */
759 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
760 * wird automatisch mit dem aktuellen Datum gefuellt.
764 public void update (Entity theEntity) throws StorageObjectException
766 Connection con = null; PreparedStatement pstmt = null;
767 /** @todo this is stupid: why do we prepare statement, when we
768 * throw it away afterwards. should be regular statement
769 * update/insert could better be one routine called save()
770 * that chooses to either insert or update depending if we
771 * have a primary key in the entity. i don't know if we
772 * still need the streamed input fields. // rk */
774 /** @todo extension: check if Entity did change, otherwise we don't need
775 * the roundtrip to the database */
777 /** invalidating corresponding entitylists in o_store*/
778 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
779 StoreContainerType stoc_type =
780 StoreContainerType.valueOf( theEntityClass,
781 StoreContainerType.STOC_TYPE_ENTITYLIST);
782 o_store.invalidate(stoc_type);
785 ArrayList streamedInput = theEntity.streamedInput();
786 String id = theEntity.getId();
788 StringBuffer fv = new StringBuffer();
789 boolean firstField = true;
791 invalidatePopupCache();
792 // build sql statement
793 for (int i = 0; i < getFields().size(); i++) {
794 aField = (String)metadataFields.get(i);
796 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
797 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
798 if (theEntity.hasValueForField(aField)) {
799 if (firstField == false) {
805 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
809 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
811 if (metadataFields.contains("webdb_lastchange")) {
812 sql.append(",webdb_lastchange=NOW()");
814 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
815 // format so anything extra will be ignored. -mh
816 if (metadataFields.contains("webdb_create") &&
817 theEntity.hasValueForField("webdb_create")) {
818 // minimum of 10 (yyyy-mm-dd)...
819 if (theEntity.getValue("webdb_create").length() >= 10) {
820 String dateString = theEntity.getValue("webdb_create");
821 // if only 10, then add 00:00 so it doesn't throw a ParseException
822 if (dateString.length() == 10)
823 dateString=dateString+" 00:00";
827 java.util.Date d = _dateFormatterIn.parse(dateString);
828 Timestamp tStamp = new Timestamp(d.getTime());
829 sql.append(",webdb_create='"+tStamp.toString()+"'");
830 } catch (ParseException e) {
831 throw new StorageObjectException(e.toString());
835 if (streamedInput != null) {
836 for (int i = 0; i < streamedInput.size(); i++) {
837 sql.append(",").append(streamedInput.get(i)).append("=?");
840 sql.append(" where id=").append(id);
841 theLog.printInfo("UPDATE: " + sql);
844 con = getPooledCon();
845 con.setAutoCommit(false);
846 pstmt = con.prepareStatement(sql.toString());
847 if (streamedInput != null) {
848 for (int i = 0; i < streamedInput.size(); i++) {
849 String inputString = theEntity.getValue((String)streamedInput.get(i));
850 pstmt.setBytes(i + 1, inputString.getBytes());
853 pstmt.executeUpdate();
854 } catch (SQLException sqe) {
855 throwSQLException(sqe, "update");
858 con.setAutoCommit(true);
859 } catch (Exception e) {
862 freeConnection(con, pstmt);
868 * @param id des zu loeschenden Datensatzes
869 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
871 public boolean delete (String id) throws StorageObjectException {
873 invalidatePopupCache();
874 // ostore send notification
875 if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
876 String uniqueId = id;
877 if ( theEntityClass.equals(StorableObjectEntity.class) )
878 uniqueId+="@"+theTable;
879 theLog.printInfo("CACHE: (del) " + id);
880 StoreIdentifier search_sid =
881 new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
882 o_store.invalidate(search_sid);
885 /** @todo could be prepared Statement */
886 Statement stmt = null; Connection con = null;
888 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
889 theLog.printInfo("DELETE " + sql);
891 con = getPooledCon(); stmt = con.createStatement();
892 res = stmt.executeUpdate(sql);
894 catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
895 finally { freeConnection(con, stmt); }
897 return (res > 0) ? true : false;
900 /* noch nicht implementiert.
901 * @return immer false
903 public boolean delete (EntityList theEntityList) {
904 invalidatePopupCache();
909 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
910 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
913 public SimpleList getPopupData () throws StorageObjectException {
918 * Holt Daten fuer Popups.
919 * @param name Name des Feldes.
920 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
921 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
923 public SimpleList getPopupData (String name, boolean hasNullValue)
924 throws StorageObjectException {
925 return getPopupData(name, hasNullValue, null);
929 * Holt Daten fuer Popups.
930 * @param name Name des Feldes.
931 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
932 * @param where Schraenkt die Selektion der Datensaetze ein.
933 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
935 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
936 return getPopupData(name, hasNullValue, where, null);
940 * Holt Daten fuer Popups.
941 * @param name Name des Feldes.
942 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
943 * @param where Schraenkt die Selektion der Datensaetze ein.
944 * @param order Gibt ein Feld als Sortierkriterium an.
945 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
947 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
949 if (hasPopupCache && popupCache != null)
951 SimpleList simpleList = null;
952 Connection con = null;
953 Statement stmt = null;
955 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
956 .append(",").append(name).append(" from ")
958 if (where != null && !(where.length() == 0))
959 sql.append(" where ").append(where);
960 sql.append(" order by ");
961 if (order != null && !(order.length() == 0))
967 con = getPooledCon();
968 } catch (Exception e) {
969 throw new StorageObjectException(e.toString());
972 stmt = con.createStatement();
973 ResultSet rs = executeSql(stmt, sql.toString());
976 if (!evaluatedMetaData) get_meta_data();
977 simpleList = new SimpleList();
978 // if popup has null-selector
979 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
981 SimpleHash popupDict;
983 popupDict = new SimpleHash();
984 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
985 popupDict.put("value", rs.getString(2));
986 simpleList.add(popupDict);
990 } catch (Exception e) {
991 theLog.printError("getPopupData: "+e.toString());
992 throw new StorageObjectException(e.toString());
994 freeConnection(con, stmt);
997 if (hasPopupCache) popupCache = simpleList;
1002 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
1003 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
1004 * Tabellen Verwendung finden.
1005 * @return SimpleHash mit den Tabellezeilen.
1007 public SimpleHash getHashData () {
1008 /** @todo dangerous! this should have a flag to be enabled, otherwise
1009 * very big Hashes could be returned */
1010 if (hashCache == null) {
1012 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
1014 } catch (StorageObjectException e) {
1015 theLog.printDebugInfo(e.toString());
1021 /* invalidates the popupCache
1023 protected void invalidatePopupCache () {
1024 /** @todo invalidates toooo much */
1030 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1031 * @param stmt Statemnt
1032 * @param sql Sql-String
1034 * @exception StorageObjectException
1036 public ResultSet executeSql (Statement stmt, String sql)
1037 throws StorageObjectException, SQLException
1039 long startTime = System.currentTimeMillis();
1042 rs = stmt.executeQuery(sql);
1043 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1046 catch (SQLException e)
1048 theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
1049 - startTime) + "ms. for: "+ sql);
1057 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
1058 * getimed und geloggt.
1059 * @param stmt PreparedStatement mit der SQL-Anweisung
1060 * @return Liefert ResultSet des Statements zurueck.
1061 * @exception StorageObjectException, SQLException
1063 public ResultSet executeSql (PreparedStatement stmt)
1064 throws StorageObjectException, SQLException {
1066 long startTime = (new java.util.Date()).getTime();
1067 ResultSet rs = stmt.executeQuery();
1068 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1073 * returns the number of rows in the table
1075 public int getSize(String where)
1076 throws SQLException,StorageObjectException
1078 long startTime = System.currentTimeMillis();
1079 String sql = "SELECT Count(*) FROM "+ theTable;
1080 if (where != null && !(where.length() == 0))
1081 sql = sql + " where " + where;
1082 Connection con = null;
1083 Statement stmt = null;
1087 con = getPooledCon();
1088 stmt = con.createStatement();
1089 ResultSet rs = executeSql(stmt,sql);
1091 result = rs.getInt(1);
1093 } catch (SQLException e) {
1094 theLog.printError(e.toString());
1096 freeConnection(con,stmt);
1098 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1099 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1104 public int executeUpdate(Statement stmt, String sql)
1105 throws StorageObjectException, SQLException
1108 long startTime = (new java.util.Date()).getTime();
1111 rs = stmt.executeUpdate(sql);
1112 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1115 catch (SQLException e)
1117 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1118 - startTime) + "ms. for: "+ sql);
1124 public int executeUpdate(String sql)
1125 throws StorageObjectException, SQLException
1128 long startTime = (new java.util.Date()).getTime();
1129 Connection con=null;PreparedStatement pstmt=null;
1132 pstmt = con.prepareStatement(sql);
1133 result = pstmt.executeUpdate();
1135 catch (Exception e) {
1136 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1137 throw new StorageObjectException("executeUpdate failed: "+e.toString());
1139 finally { freeConnection(con,pstmt); }
1140 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1146 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1147 * @param md ResultSetMetaData
1148 * @exception StorageObjectException
1150 private void evalMetaData (ResultSetMetaData md)
1151 throws StorageObjectException {
1153 this.evaluatedMetaData = true;
1154 this.metadataFields = new ArrayList();
1155 this.metadataLabels = new ArrayList();
1156 this.metadataNotNullFields = new ArrayList();
1158 int numFields = md.getColumnCount();
1159 this.metadataTypes = new int[numFields];
1162 for (int i = 1; i <= numFields; i++) {
1163 aField = md.getColumnName(i);
1164 metadataFields.add(aField);
1165 metadataLabels.add(md.getColumnLabel(i));
1166 aType = md.getColumnType(i);
1167 metadataTypes[i - 1] = aType;
1168 if (aField.equals(thePKeyName)) {
1169 thePKeyType = aType; thePKeyIndex = i;
1171 if (md.isNullable(i) == md.columnNullable) {
1172 metadataNotNullFields.add(aField);
1175 } catch (SQLException e) {
1176 throwSQLException(e, "evalMetaData");
1181 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1182 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1184 private void get_meta_data () throws StorageObjectException {
1185 Connection con = null;
1186 PreparedStatement pstmt = null;
1187 String sql = "select * from " + theTable + " where 0=1";
1189 con = getPooledCon();
1190 pstmt = con.prepareStatement(sql);
1191 theLog.printInfo("METADATA: " + sql);
1192 ResultSet rs = pstmt.executeQuery();
1193 evalMetaData(rs.getMetaData());
1195 } catch (SQLException e) {
1196 throwSQLException(e, "get_meta_data");
1198 freeConnection(con, pstmt);
1203 public Connection getPooledCon() throws StorageObjectException {
1204 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1206 Class.forName("com.codestudio.sql.PoolMan").newInstance();
1207 } catch (Exception e){
1208 throw new StorageObjectException("Could not find the PoolMan Driver"
1211 Connection con = null;
1213 con = SQLManager.getInstance().requestConnection();
1214 } catch(SQLException e){
1215 theLog.printError("could not connect to the database "+e.toString());
1216 System.err.println("could not connect to the database "+e.toString());
1217 throw new StorageObjectException("Could not connect to the database"+
1223 public void freeConnection (Connection con, Statement stmt)
1224 throws StorageObjectException {
1225 SQLManager.getInstance().closeStatement(stmt);
1226 SQLManager.getInstance().returnConnection(con);
1230 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1231 * @param sqe SQLException
1232 * @param wo Funktonsname, in der die SQLException geworfen wurde
1233 * @exception StorageObjectException
1235 protected void throwSQLException (SQLException sqe, String wo)
1236 throws StorageObjectException {
1238 String message = "";
1241 state = sqe.getSQLState();
1242 message = sqe.getMessage();
1243 vendor = sqe.getErrorCode();
1245 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1247 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1251 protected void _throwStorageObjectException (Exception e, String wo)
1252 throws StorageObjectException {
1254 theLog.printError(e.toString()+ wo);
1255 throw new StorageObjectException(wo + e.toString());
1257 theLog.printError(wo);
1258 throw new StorageObjectException(wo);
1264 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1265 * eine StorageObjectException
1266 * @param message Nachricht mit dem Fehler
1267 * @exception StorageObjectException
1269 void throwStorageObjectException (String message)
1270 throws StorageObjectException {
1271 _throwStorageObjectException(null, message);