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.
33 import java.io.IOException;
34 import java.io.InputStreamReader;
35 import java.sql.Connection;
36 import java.sql.PreparedStatement;
37 import java.sql.ResultSet;
38 import java.sql.ResultSetMetaData;
39 import java.sql.SQLException;
40 import java.sql.Statement;
41 import java.sql.Timestamp;
42 import java.text.ParseException;
43 import java.text.SimpleDateFormat;
44 import java.util.ArrayList;
45 import java.util.Calendar;
46 import java.util.GregorianCalendar;
47 import java.util.HashMap;
48 import java.util.List;
51 import mir.config.MirPropertiesConfiguration;
52 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
53 import mir.entity.Entity;
54 import mir.entity.EntityList;
55 import mir.entity.StorableObjectEntity;
56 import mir.log.LoggerWrapper;
57 import mir.misc.HTMLTemplateProcessor;
58 import mir.misc.StringUtil;
59 import mir.storage.store.ObjectStore;
60 import mir.storage.store.StorableObject;
61 import mir.storage.store.StoreContainerType;
62 import mir.storage.store.StoreIdentifier;
63 import mir.storage.store.StoreUtil;
64 import mir.util.JDBCStringRoutines;
66 import com.codestudio.util.SQLManager;
68 import freemarker.template.SimpleHash;
69 import freemarker.template.SimpleList;
73 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
74 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
75 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
76 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
77 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
80 * @version $Id: Database.java,v 1.38 2003/04/16 03:26:45 zapata Exp $
84 public class Database implements StorageObject {
85 private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
86 private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
89 private static SimpleHash POPUP_EMPTYLINE = new SimpleHash();
90 protected static final ObjectStore o_store = ObjectStore.getInstance();
91 private static final int _millisPerHour = 60 * 60 * 1000;
92 private static final int _millisPerMinute = 60 * 1000;
95 // always same object saves a little space
96 POPUP_EMPTYLINE.put("key", "");
97 POPUP_EMPTYLINE.put("value", "--");
100 protected LoggerWrapper logger;
101 protected MirPropertiesConfiguration configuration;
102 protected String theTable;
103 protected String theCoreTable = null;
104 protected String thePKeyName = "id";
105 protected int thePKeyType;
106 protected int thePKeyIndex;
107 protected boolean evaluatedMetaData = false;
108 protected ArrayList metadataFields;
109 protected ArrayList metadataLabels;
110 protected ArrayList metadataNotNullFields;
111 protected int[] metadataTypes;
112 protected Class theEntityClass;
113 protected StorageObject myselfDatabase;
114 protected SimpleList popupCache = null;
115 protected boolean hasPopupCache = false;
116 protected SimpleHash hashCache = null;
117 protected boolean hasTimestamp = true;
118 private String database_driver;
119 private String database_url;
120 private int defaultLimit;
121 protected DatabaseAdaptor theAdaptor;
122 private SimpleDateFormat _dateFormatterOut =
123 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
124 private SimpleDateFormat _dateFormatterIn =
125 new SimpleDateFormat("yyyy-MM-dd HH:mm");
126 private Calendar _cal = new GregorianCalendar();
129 * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
130 * Aus diesem file werden <code>Database.Logfile</code>,
131 * <code>Database.Username</code>,<code>Database.Password</code>,
132 * <code>Database.Host</code> und <code>Database.Adaptor</code>
133 * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
136 * @param String confFilename Dateiname der Konfigurationsdatei
138 public Database() throws StorageObjectFailure {
140 configuration = MirPropertiesConfiguration.instance();
142 catch (PropertiesConfigExc e) {
143 throw new StorageObjectFailure(e);
145 logger = new LoggerWrapper("Database");
147 String theAdaptorName = configuration.getString("Database.Adaptor");
148 defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
151 theEntityClass = GENERIC_ENTITY_CLASS;
152 theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance();
154 catch (Throwable e) {
155 logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
156 throw new StorageObjectFailure("Error in Database() constructor.", e);
161 * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
162 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
163 * wird eine mir.entity.GenericEntity erzeugt.
165 * @return Class-Objekt der Entity
167 public java.lang.Class getEntityClass() {
168 return theEntityClass;
172 * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
173 * wieviel Datens?tze per Default selektiert werden.
175 * @return Standard-Anzahl der Datens?tze
177 public int getLimit() {
182 * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
183 * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
184 * @return Name des Primary-Keys
186 public String getIdName() {
191 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
193 * @return Name der Tabelle
195 public String getTableName() {
200 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
201 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
203 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
206 public String getCoreTable() {
207 if (theCoreTable != null) {
215 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
216 * @return int-Array mit den Typen der Felder
217 * @exception StorageObjectException
219 public int[] getTypes() throws StorageObjectFailure {
220 if (metadataTypes == null) {
224 return metadataTypes;
228 * Liefert eine Liste der Labels der Tabellenfelder
229 * @return ArrayListe mit Labeln
230 * @exception StorageObjectException
232 public List getLabels() throws StorageObjectFailure {
233 if (metadataLabels == null) {
237 return metadataLabels;
241 * Liefert eine Liste der Felder der Tabelle
242 * @return ArrayList mit Feldern
243 * @exception StorageObjectException
245 public List getFields() throws StorageObjectFailure {
246 if (metadataFields == null) {
250 return metadataFields;
254 * Gets value out of ResultSet according to type and converts to String
255 * @param inValue Wert aus ResultSet.
256 * @param aType Datenbanktyp.
257 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
258 * dann /unsupported value/
260 private String getValueAsString(ResultSet rs, int valueIndex, int aType)
261 throws StorageObjectFailure {
262 String outValue = null;
267 case java.sql.Types.BIT:
268 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
272 case java.sql.Types.INTEGER:
273 case java.sql.Types.SMALLINT:
274 case java.sql.Types.TINYINT:
275 case java.sql.Types.BIGINT:
277 int out = rs.getInt(valueIndex);
280 outValue = new Integer(out).toString();
285 case java.sql.Types.NUMERIC:
287 /** @todo Numeric can be float or double depending upon
288 * metadata.getScale() / especially with oracle */
289 long outl = rs.getLong(valueIndex);
292 outValue = new Long(outl).toString();
297 case java.sql.Types.REAL:
299 float tempf = rs.getFloat(valueIndex);
305 int tempf_int = (int) tempf;
306 tempf = (float) tempf_int;
308 outValue = "" + tempf;
309 outValue = outValue.replace('.', ',');
314 case java.sql.Types.DOUBLE:
316 double tempd = rs.getDouble(valueIndex);
322 int tempd_int = (int) tempd;
323 tempd = (double) tempd_int;
325 outValue = "" + tempd;
326 outValue = outValue.replace('.', ',');
331 case java.sql.Types.CHAR:
332 case java.sql.Types.VARCHAR:
333 case java.sql.Types.LONGVARCHAR:
334 outValue = rs.getString(valueIndex);
338 case java.sql.Types.LONGVARBINARY:
339 outValue = rs.getString(valueIndex);
343 case java.sql.Types.TIMESTAMP:
345 // it's important to use Timestamp here as getting it
346 // as a string is undefined and is only there for debugging
347 // according to the API. we can make it a string through formatting.
349 Timestamp timestamp = (rs.getTimestamp(valueIndex));
352 java.util.Date date = new java.util.Date(timestamp.getTime());
353 outValue = _dateFormatterOut.format(date);
357 _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET);
359 StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2);
360 outValue = outValue + "+" + tzOffset;
366 outValue = "<unsupported value>";
367 logger.warn( "Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
369 } catch (SQLException e) {
370 throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
379 * select-Operator um einen Datensatz zu bekommen.
380 * @param id Primaerschluessel des Datensatzes.
381 * @return liefert EntityObject des gefundenen Datensatzes oder null.
383 public Entity selectById(String id) throws StorageObjectExc {
384 if ((id == null) || id.equals("")) {
385 throw new StorageObjectExc("Database.selectById: Missing id");
388 // ask object store for object
389 if (StoreUtil.implementsStorableObject(theEntityClass)) {
390 String uniqueId = id;
392 if (theEntityClass.equals(StorableObjectEntity.class)) {
393 uniqueId += ("@" + theTable);
396 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
397 logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
399 Entity hit = (Entity) o_store.use(search_sid);
406 Statement stmt = null;
407 Connection con = getPooledCon();
408 Entity returnEntity = null;
413 /** @todo better prepared statement */
415 "select * from " + theTable + " where " + thePKeyName + "=" + id;
416 stmt = con.createStatement();
417 rs = executeSql(stmt, selectSql);
420 if (evaluatedMetaData == false) {
421 evalMetaData(rs.getMetaData());
425 returnEntity = makeEntityFromResultSet(rs);
428 logger.debug("No data for id: " + id + " in table " + theTable);
434 logger.debug("No Data for Id " + id + " in Table " + theTable);
437 catch (SQLException sqe) {
438 throwSQLException(sqe, "selectById");
441 catch (NumberFormatException e) {
442 logger.error("ID is no number: " + id);
445 freeConnection(con, stmt);
452 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
453 * @param key Datenbankfeld der Bedingung.
454 * @param value Wert die der key anehmen muss.
455 * @return EntityList mit den gematchten Entities
457 public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
458 return selectByFieldValue(aField, aValue, 0);
462 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
463 * @param key Datenbankfeld der Bedingung.
464 * @param value Wert die der key anehmen muss.
465 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
466 * @return EntityList mit den gematchten Entities
468 public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
469 return selectByWhereClause(aField + "=" + aValue, offset);
473 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
474 * Also offset wird der erste Datensatz genommen.
476 * @param wc where-Clause
477 * @return EntityList mit den gematchten Entities
478 * @exception StorageObjectException
480 public EntityList selectByWhereClause(String where)
481 throws StorageObjectFailure {
482 return selectByWhereClause(where, 0);
486 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
487 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
489 * @param wc where-Clause
490 * @param offset ab welchem Datensatz.
491 * @return EntityList mit den gematchten Entities
492 * @exception StorageObjectException
494 public EntityList selectByWhereClause(String whereClause, int offset)
495 throws StorageObjectFailure {
496 return selectByWhereClause(whereClause, null, offset);
500 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
501 * Also offset wird der erste Datensatz genommen.
502 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
504 * @param wc where-Clause
505 * @param ob orderBy-Clause
506 * @return EntityList mit den gematchten Entities
507 * @exception StorageObjectException
509 public EntityList selectByWhereClause(String where, String order)
510 throws StorageObjectFailure {
511 return selectByWhereClause(where, order, 0);
515 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
516 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
518 * @param wc where-Clause
519 * @param ob orderBy-Clause
520 * @param offset ab welchem Datensatz
521 * @return EntityList mit den gematchten Entities
522 * @exception StorageObjectException
524 public EntityList selectByWhereClause(String whereClause, String orderBy,
525 int offset) throws StorageObjectFailure {
526 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
530 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
531 * @param wc where-Clause
532 * @param ob orderBy-Clause
533 * @param offset ab welchem Datensatz
534 * @param limit wieviele Datens?tze
535 * @return EntityList mit den gematchten Entities
536 * @exception StorageObjectException
538 public EntityList selectByWhereClause(String wc, String ob, int offset,
539 int limit) throws StorageObjectFailure {
540 // check o_store for entitylist
541 if (StoreUtil.implementsStorableObject(theEntityClass)) {
542 StoreIdentifier search_sid =
543 new StoreIdentifier(theEntityClass,
544 StoreContainerType.STOC_TYPE_ENTITYLIST,
545 StoreUtil.getEntityListUniqueIdentifierFor(theTable, wc, ob, offset,
547 EntityList hit = (EntityList) o_store.use(search_sid);
550 logger.debug("CACHE (hit): " + search_sid.toString());
557 EntityList theReturnList = null;
558 Connection con = null;
559 Statement stmt = null;
564 // build sql-statement
566 /** @todo count sql string should only be assembled if we really count
567 * see below at the end of method //rk */
568 if ((wc != null) && (wc.trim().length() == 0)) {
572 StringBuffer countSql =
573 new StringBuffer("select count(*) from ").append(theTable);
574 StringBuffer selectSql =
575 new StringBuffer("select * from ").append(theTable);
578 selectSql.append(" where ").append(wc);
579 countSql.append(" where ").append(wc);
582 if ((ob != null) && !(ob.trim().length() == 0)) {
583 selectSql.append(" order by ").append(ob);
586 if (theAdaptor.hasLimit()) {
587 if ((limit > -1) && (offset > -1)) {
588 selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
594 con = getPooledCon();
595 stmt = con.createStatement();
598 rs = executeSql(stmt, selectSql.toString());
601 if (!evaluatedMetaData) {
602 evalMetaData(rs.getMetaData());
605 theReturnList = new EntityList();
607 Entity theResultEntity;
610 theResultEntity = makeEntityFromResultSet(rs);
611 theReturnList.add(theResultEntity);
618 // making entitylist infos
619 if (!(theAdaptor.hasLimit())) {
623 if (theReturnList != null) {
624 // now we decide if we have to know an overall count...
627 if ((limit > -1) && (offset > -1)) {
628 if (offsetCount == limit) {
629 /** @todo counting should be deffered to entitylist
630 * getSize() should be used */
631 rs = executeSql(stmt, countSql.toString());
635 count = rs.getInt(1);
641 logger.error("Could not count: " + countSql);
646 theReturnList.setCount(count);
647 theReturnList.setOffset(offset);
648 theReturnList.setWhere(wc);
649 theReturnList.setOrder(ob);
650 theReturnList.setStorage(this);
651 theReturnList.setLimit(limit);
653 if (offset >= limit) {
654 theReturnList.setPrevBatch(offset - limit);
657 if ((offset + offsetCount) < count) {
658 theReturnList.setNextBatch(offset + limit);
661 if (StoreUtil.implementsStorableObject(theEntityClass)) {
662 StoreIdentifier sid = theReturnList.getStoreIdentifier();
663 logger.debug("CACHE (add): " + sid.toString());
667 } catch (SQLException sqe) {
668 throwSQLException(sqe, "selectByWhereClause");
672 freeConnection(con, stmt);
674 } catch (Throwable t) {
678 return theReturnList;
682 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
684 * @param rs Das ResultSetObjekt.
685 * @return Entity Die Entity.
687 private Entity makeEntityFromResultSet(ResultSet rs)
688 throws StorageObjectFailure {
689 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
690 Map theResultHash = new HashMap();
691 String theResult = null;
693 Entity returnEntity = null;
696 int size = metadataFields.size();
698 for (int i = 0; i < size; i++) {
699 // alle durchlaufen bis nix mehr da
700 theType = metadataTypes[i];
702 if (theType == java.sql.Types.LONGVARBINARY) {
703 InputStreamReader is =
704 (InputStreamReader) rs.getCharacterStream(i + 1);
707 char[] data = new char[32768];
708 StringBuffer theResultString = new StringBuffer();
711 while ((len = is.read(data)) > 0) {
712 theResultString.append(data, 0, len);
716 theResult = theResultString.toString();
721 theResult = getValueAsString(rs, (i + 1), theType);
724 if (theResult != null) {
725 theResultHash.put(metadataFields.get(i), theResult);
729 if (theEntityClass != null) {
730 returnEntity = (Entity) theEntityClass.newInstance();
731 returnEntity.setValues(theResultHash);
732 returnEntity.setStorage(myselfDatabase);
734 if (returnEntity instanceof StorableObject) {
735 logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
736 o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
739 throwStorageObjectException("Internal Error: theEntityClass not set!");
741 } catch (IllegalAccessException e) {
742 throwStorageObjectException("No access! -- " + e.getMessage());
743 } catch (IOException e) {
744 throwStorageObjectException("IOException! -- " + e.getMessage());
745 } catch (InstantiationException e) {
746 throwStorageObjectException("No Instatiation! -- " + e.getMessage());
747 } catch (SQLException sqe) {
748 throwSQLException(sqe, "makeEntityFromResultSet");
757 * insert-Operator: f?gt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
758 * wird automatisch mit dem aktuellen Datum gefuellt.
761 * @return der Wert des Primary-keys der eingef?gten Entity
763 public String insert(Entity theEntity) throws StorageObjectFailure {
765 invalidatePopupCache();
767 // invalidating all EntityLists corresponding with theEntityClass
768 if (StoreUtil.implementsStorableObject(theEntityClass)) {
769 StoreContainerType stoc_type =
770 StoreContainerType.valueOf(theEntityClass,
771 StoreContainerType.STOC_TYPE_ENTITYLIST);
772 o_store.invalidate(stoc_type);
775 String returnId = null;
776 Connection con = null;
777 PreparedStatement pstmt = null;
780 List streamedInput = theEntity.streamedInput();
781 StringBuffer f = new StringBuffer();
782 StringBuffer v = new StringBuffer();
785 boolean firstField = true;
788 for (int i = 0; i < getFields().size(); i++) {
789 aField = (String) getFields().get(i);
791 if (!aField.equals(thePKeyName)) {
795 if (aField.equals("webdb_create") ||
796 aField.equals("webdb_lastchange")) {
799 if ((streamedInput != null) && streamedInput.contains(aField)) {
802 if (theEntity.hasValueForField(aField)) {
805 JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(
811 // wenn Wert gegeben, dann einbauen
812 if (aValue != null) {
813 if (firstField == false) {
829 StringBuffer sqlBuf =
830 new StringBuffer("insert into ").append(theTable).append("(").append(f)
831 .append(") values (").append(v).append(")");
832 String sql = sqlBuf.toString();
834 logger.debug("INSERT: " + sql);
835 con = getPooledCon();
836 con.setAutoCommit(false);
837 pstmt = con.prepareStatement(sql);
839 if (streamedInput != null) {
840 for (int i = 0; i < streamedInput.size(); i++) {
842 (String) theEntity.getValue((String) streamedInput.get(i));
843 pstmt.setBytes(i + 1, inputString.getBytes());
847 int ret = pstmt.executeUpdate();
855 con.prepareStatement(theAdaptor.getLastInsertSQL(
856 (Database) myselfDatabase));
858 ResultSet rs = pstmt.executeQuery();
860 returnId = rs.getString(1);
861 theEntity.setId(returnId);
863 catch (SQLException sqe) {
864 throwSQLException(sqe, "insert");
868 con.setAutoCommit(true);
870 catch (Exception e) {
873 freeConnection(con, pstmt);
876 /** @todo store entity in o_store */
881 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
882 * wird automatisch mit dem aktuellen Datum gefuellt.
886 public void update(Entity theEntity) throws StorageObjectFailure {
887 Connection con = null;
888 PreparedStatement pstmt = null;
890 /** @todo this is stupid: why do we prepare statement, when we
891 * throw it away afterwards. should be regular statement
892 * update/insert could better be one routine called save()
893 * that chooses to either insert or update depending if we
894 * have a primary key in the entity. i don't know if we
895 * still need the streamed input fields. // rk */
896 /** @todo extension: check if Entity did change, otherwise we don't need
897 * the roundtrip to the database */
898 /** invalidating corresponding entitylists in o_store*/
899 if (StoreUtil.implementsStorableObject(theEntityClass)) {
900 StoreContainerType stoc_type =
901 StoreContainerType.valueOf(theEntityClass,
902 StoreContainerType.STOC_TYPE_ENTITYLIST);
903 o_store.invalidate(stoc_type);
906 List streamedInput = theEntity.streamedInput();
907 String id = theEntity.getId();
909 StringBuffer fv = new StringBuffer();
910 boolean firstField = true;
913 invalidatePopupCache();
915 // build sql statement
916 for (int i = 0; i < getFields().size(); i++) {
917 aField = (String) metadataFields.get(i);
920 if ( !(aField.equals(thePKeyName) ||
921 aField.equals("webdb_create") ||
922 aField.equals("webdb_lastchange") ||
923 ((streamedInput != null) && streamedInput.contains(aField)))) {
924 if (theEntity.hasValueForField(aField)) {
925 if (firstField == false) {
932 fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
934 // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
940 new StringBuffer("update ").append(theTable).append(" set ").append(fv);
943 if (metadataFields.contains("webdb_lastchange")) {
944 sql.append(",webdb_lastchange=NOW()");
947 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
948 // format so anything extra will be ignored. -mh
949 if (metadataFields.contains("webdb_create") &&
950 theEntity.hasValueForField("webdb_create")) {
951 // minimum of 10 (yyyy-mm-dd)...
952 if (theEntity.getValue("webdb_create").length() >= 10) {
953 String dateString = theEntity.getValue("webdb_create");
955 // if only 10, then add 00:00 so it doesn't throw a ParseException
956 if (dateString.length() == 10) {
957 dateString = dateString + " 00:00";
962 java.util.Date d = _dateFormatterIn.parse(dateString);
963 Timestamp tStamp = new Timestamp(d.getTime());
964 sql.append(",webdb_create='" + tStamp.toString() + "'");
965 } catch (ParseException e) {
966 throw new StorageObjectFailure(e);
971 if (streamedInput != null) {
972 for (int i = 0; i < streamedInput.size(); i++) {
973 sql.append(",").append(streamedInput.get(i)).append("=?");
977 sql.append(" where id=").append(id);
979 //theLog.printInfo("UPDATE: " + sql);
982 con = getPooledCon();
983 con.setAutoCommit(false);
984 pstmt = con.prepareStatement(sql.toString());
986 if (streamedInput != null) {
987 for (int i = 0; i < streamedInput.size(); i++) {
989 theEntity.getValue((String) streamedInput.get(i));
990 pstmt.setBytes(i + 1, inputString.getBytes());
994 pstmt.executeUpdate();
995 } catch (SQLException sqe) {
996 throwSQLException(sqe, "update");
999 con.setAutoCommit(true);
1000 } catch (Exception e) {
1004 freeConnection(con, pstmt);
1010 * @param id des zu loeschenden Datensatzes
1011 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
1013 public boolean delete(String id) throws StorageObjectFailure {
1014 invalidatePopupCache();
1016 // ostore send notification
1017 if (StoreUtil.implementsStorableObject(theEntityClass)) {
1018 String uniqueId = id;
1020 if (theEntityClass.equals(StorableObjectEntity.class)) {
1021 uniqueId += ("@" + theTable);
1024 logger.debug("CACHE: (del) " + id);
1026 StoreIdentifier search_sid =
1027 new StoreIdentifier(theEntityClass,
1028 StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
1029 o_store.invalidate(search_sid);
1032 /** @todo could be prepared Statement */
1033 Statement stmt = null;
1034 Connection con = null;
1037 "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
1039 //theLog.printInfo("DELETE " + sql);
1041 con = getPooledCon();
1042 stmt = con.createStatement();
1043 res = stmt.executeUpdate(sql);
1044 } catch (SQLException sqe) {
1045 throwSQLException(sqe, "delete");
1047 freeConnection(con, stmt);
1050 return (res > 0) ? true : false;
1053 /* noch nicht implementiert.
1054 * @return immer false
1056 public boolean delete(EntityList theEntityList) {
1057 invalidatePopupCache();
1063 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
1064 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
1067 public SimpleList getPopupData() throws StorageObjectFailure {
1072 * Holt Daten fuer Popups.
1073 * @param name Name des Feldes.
1074 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
1075 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
1077 public SimpleList getPopupData(String name, boolean hasNullValue)
1078 throws StorageObjectFailure {
1079 return getPopupData(name, hasNullValue, null);
1083 * Holt Daten fuer Popups.
1084 * @param name Name des Feldes.
1085 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
1086 * @param where Schraenkt die Selektion der Datensaetze ein.
1087 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
1089 public SimpleList getPopupData(String name, boolean hasNullValue, String where)
1090 throws StorageObjectFailure {
1091 return getPopupData(name, hasNullValue, where, null);
1095 * Holt Daten fuer Popups.
1096 * @param name Name des Feldes.
1097 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
1098 * @param where Schraenkt die Selektion der Datensaetze ein.
1099 * @param order Gibt ein Feld als Sortierkriterium an.
1100 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
1102 public SimpleList getPopupData(String name, boolean hasNullValue,
1103 String where, String order) throws StorageObjectFailure {
1105 if (hasPopupCache && (popupCache != null)) {
1109 SimpleList simpleList = null;
1110 Connection con = null;
1111 Statement stmt = null;
1115 new StringBuffer("select ").append(thePKeyName).append(",").append(name)
1116 .append(" from ").append(theTable);
1118 if ((where != null) && !(where.length() == 0)) {
1119 sql.append(" where ").append(where);
1122 sql.append(" order by ");
1124 if ((order != null) && !(order.length() == 0)) {
1132 con = getPooledCon();
1133 } catch (Exception e) {
1134 throw new StorageObjectFailure(e);
1138 stmt = con.createStatement();
1140 ResultSet rs = executeSql(stmt, sql.toString());
1143 if (!evaluatedMetaData) {
1147 simpleList = new SimpleList();
1149 // if popup has null-selector
1151 simpleList.add(POPUP_EMPTYLINE);
1154 SimpleHash popupDict;
1157 popupDict = new SimpleHash();
1158 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
1159 popupDict.put("value", rs.getString(2));
1160 simpleList.add(popupDict);
1166 catch (Exception e) {
1167 logger.error("getPopupData: " + e.getMessage());
1168 throw new StorageObjectFailure(e);
1170 freeConnection(con, stmt);
1173 if (hasPopupCache) {
1174 popupCache = simpleList;
1181 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
1182 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
1183 * Tabellen Verwendung finden.
1184 * @return SimpleHash mit den Tabellezeilen.
1186 public SimpleHash getHashData() {
1187 /** @todo dangerous! this should have a flag to be enabled, otherwise
1188 * very big Hashes could be returned */
1189 if (hashCache == null) {
1192 HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1));
1194 catch (StorageObjectFailure e) {
1195 logger.debug(e.getMessage());
1202 /* invalidates the popupCache
1204 protected void invalidatePopupCache() {
1205 /** @todo invalidates toooo much */
1211 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1212 * @param stmt Statemnt
1213 * @param sql Sql-String
1215 * @exception StorageObjectException
1217 public ResultSet executeSql(Statement stmt, String sql)
1218 throws StorageObjectFailure, SQLException {
1220 long startTime = System.currentTimeMillis();
1223 rs = stmt.executeQuery(sql);
1225 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1227 catch (SQLException e) {
1228 logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1236 * returns the number of rows in the table
1238 public int getSize(String where) throws SQLException, StorageObjectFailure {
1239 long startTime = System.currentTimeMillis();
1240 String sql = "SELECT Count(*) FROM " + theTable;
1242 if ((where != null) && !(where.length() == 0)) {
1243 sql = sql + " where " + where;
1246 Connection con = null;
1247 Statement stmt = null;
1251 con = getPooledCon();
1252 stmt = con.createStatement();
1254 ResultSet rs = executeSql(stmt, sql);
1257 result = rs.getInt(1);
1260 catch (SQLException e) {
1261 logger.error("Database.getSize: " + e.getMessage());
1264 freeConnection(con, stmt);
1267 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1268 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1273 public int executeUpdate(Statement stmt, String sql)
1274 throws StorageObjectFailure, SQLException {
1276 long startTime = System.currentTimeMillis();
1279 rs = stmt.executeUpdate(sql);
1281 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1283 catch (SQLException e) {
1284 logger.debug("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1291 public int executeUpdate(String sql)
1292 throws StorageObjectFailure, SQLException {
1294 long startTime = System.currentTimeMillis();
1295 Connection con = null;
1296 PreparedStatement pstmt = null;
1299 con = getPooledCon();
1300 pstmt = con.prepareStatement(sql);
1301 result = pstmt.executeUpdate();
1303 catch (Throwable e) {
1304 logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
1305 throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
1308 freeConnection(con, pstmt);
1311 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1316 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1317 * @param md ResultSetMetaData
1318 * @exception StorageObjectException
1320 private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
1321 this.evaluatedMetaData = true;
1322 this.metadataFields = new ArrayList();
1323 this.metadataLabels = new ArrayList();
1324 this.metadataNotNullFields = new ArrayList();
1327 int numFields = md.getColumnCount();
1328 this.metadataTypes = new int[numFields];
1333 for (int i = 1; i <= numFields; i++) {
1334 aField = md.getColumnName(i);
1335 metadataFields.add(aField);
1336 metadataLabels.add(md.getColumnLabel(i));
1337 aType = md.getColumnType(i);
1338 metadataTypes[i - 1] = aType;
1340 if (aField.equals(thePKeyName)) {
1341 thePKeyType = aType;
1345 if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
1346 metadataNotNullFields.add(aField);
1350 catch (SQLException e) {
1351 throwSQLException(e, "evalMetaData");
1356 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1357 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1359 private void get_meta_data() throws StorageObjectFailure {
1360 Connection con = null;
1361 PreparedStatement pstmt = null;
1362 String sql = "select * from " + theTable + " where 0=1";
1365 con = getPooledCon();
1366 pstmt = con.prepareStatement(sql);
1368 logger.debug("METADATA: " + sql);
1369 ResultSet rs = pstmt.executeQuery();
1370 evalMetaData(rs.getMetaData());
1373 catch (SQLException e) {
1374 throwSQLException(e, "get_meta_data");
1377 freeConnection(con, pstmt);
1381 public Connection getPooledCon() throws StorageObjectFailure {
1382 Connection con = null;
1385 con = SQLManager.getInstance().requestConnection();
1387 catch (SQLException e) {
1388 logger.error("could not connect to the database " + e.getMessage());
1390 throw new StorageObjectFailure("Could not connect to the database", e);
1396 public void freeConnection(Connection con, Statement stmt)
1397 throws StorageObjectFailure {
1398 SQLManager.closeStatement(stmt);
1399 SQLManager.getInstance().returnConnection(con);
1403 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1404 * @param sqe SQLException
1405 * @param wo Funktonsname, in der die SQLException geworfen wurde
1406 * @exception StorageObjectException
1408 protected void throwSQLException(SQLException sqe, String aFunction)
1409 throws StorageObjectFailure {
1411 String message = "";
1415 state = sqe.getSQLState();
1416 message = sqe.getMessage();
1417 vendor = sqe.getErrorCode();
1420 String information =
1423 ", vendor= " + vendor +
1424 ", message=" + message +
1425 ", function= " + aFunction;
1427 logger.error(information);
1429 throw new StorageObjectFailure(information, sqe);
1432 protected void _throwStorageObjectException(Exception e, String aFunction)
1433 throws StorageObjectFailure {
1436 logger.error(e.getMessage() + aFunction);
1437 throw new StorageObjectFailure(aFunction, e);
1442 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1443 * eine StorageObjectException
1444 * @param message Nachricht mit dem Fehler
1445 * @exception StorageObjectException
1447 void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
1448 logger.error(aMessage);
1449 throw new StorageObjectFailure(aMessage, null);