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 any library licensed under the Apache Software License,
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23 * (or with modified versions of the above that use the same license as the above),
24 * and distribute linked combinations including the two. You must obey the
25 * GNU General Public License in all respects for all of the code used other than
26 * the above mentioned libraries. If you modify this file, you may extend this
27 * exception to your version of the file, but you are not obligated to do so.
28 * If you do not wish to do so, delete this exception statement from your version.
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.sql.Connection;
35 import java.sql.PreparedStatement;
36 import java.sql.ResultSet;
37 import java.sql.ResultSetMetaData;
38 import java.sql.SQLException;
39 import java.sql.Statement;
40 import java.sql.Timestamp;
41 import java.text.ParseException;
42 import java.text.SimpleDateFormat;
43 import java.util.ArrayList;
44 import java.util.Calendar;
45 import java.util.GregorianCalendar;
46 import java.util.HashMap;
50 import com.codestudio.util.SQLManager;
52 import freemarker.template.SimpleHash;
53 import freemarker.template.SimpleList;
55 import mir.config.MirPropertiesConfiguration;
56 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
57 import mir.entity.Entity;
58 import mir.entity.EntityList;
59 import mir.entity.StorableObjectEntity;
60 import mir.log.LoggerWrapper;
61 import mir.misc.HTMLTemplateProcessor;
62 import mir.misc.StringUtil;
63 import mir.storage.store.ObjectStore;
64 import mir.storage.store.StorableObject;
65 import mir.storage.store.StoreContainerType;
66 import mir.storage.store.StoreIdentifier;
67 import mir.storage.store.StoreUtil;
68 import mir.util.JDBCStringRoutines;
72 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
73 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
74 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
75 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
76 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
79 * @version $Id: Database.java,v 1.41 2003/05/02 01:02:45 zapata Exp $
83 public class Database implements StorageObject {
84 private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
85 private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
88 private static SimpleHash POPUP_EMPTYLINE = new SimpleHash();
89 protected static final ObjectStore o_store = ObjectStore.getInstance();
90 private static final int _millisPerHour = 60 * 60 * 1000;
91 private static final int _millisPerMinute = 60 * 1000;
94 // always same object saves a little space
95 POPUP_EMPTYLINE.put("key", "");
96 POPUP_EMPTYLINE.put("value", "--");
99 protected LoggerWrapper logger;
100 protected MirPropertiesConfiguration configuration;
101 protected String theTable;
102 protected String theCoreTable = null;
103 protected String thePKeyName = "id";
104 protected int thePKeyType;
105 protected int thePKeyIndex;
106 protected boolean evaluatedMetaData = false;
107 protected ArrayList metadataFields;
108 protected ArrayList metadataLabels;
109 protected ArrayList metadataNotNullFields;
110 protected int[] metadataTypes;
111 protected Class theEntityClass;
112 protected StorageObject myselfDatabase;
113 protected SimpleList popupCache = null;
114 protected boolean hasPopupCache = false;
115 protected SimpleHash hashCache = null;
116 protected boolean hasTimestamp = true;
117 private String database_driver;
118 private String database_url;
119 private int defaultLimit;
120 protected DatabaseAdaptor theAdaptor;
121 private SimpleDateFormat _dateFormatterOut =
122 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
123 private SimpleDateFormat _dateFormatterIn =
124 new SimpleDateFormat("yyyy-MM-dd HH:mm");
125 private Calendar _cal = new GregorianCalendar();
128 * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
129 * Aus diesem file werden <code>Database.Logfile</code>,
130 * <code>Database.Username</code>,<code>Database.Password</code>,
131 * <code>Database.Host</code> und <code>Database.Adaptor</code>
132 * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
135 * @param String confFilename Dateiname der Konfigurationsdatei
137 public Database() throws StorageObjectFailure {
139 configuration = MirPropertiesConfiguration.instance();
141 catch (PropertiesConfigExc e) {
142 throw new StorageObjectFailure(e);
144 logger = new LoggerWrapper("Database");
146 String theAdaptorName = configuration.getString("Database.Adaptor");
147 defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
150 theEntityClass = GENERIC_ENTITY_CLASS;
151 theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance();
153 catch (Throwable e) {
154 logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
155 throw new StorageObjectFailure("Error in Database() constructor.", e);
160 * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
161 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
162 * wird eine mir.entity.GenericEntity erzeugt.
164 * @return Class-Objekt der Entity
166 public java.lang.Class getEntityClass() {
167 return theEntityClass;
171 * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
172 * wieviel Datens?tze per Default selektiert werden.
174 * @return Standard-Anzahl der Datens?tze
176 public int getLimit() {
181 * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
182 * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
183 * @return Name des Primary-Keys
185 public String getIdName() {
190 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
192 * @return Name der Tabelle
194 public String getTableName() {
199 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
200 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
202 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
205 public String getCoreTable() {
206 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) throws StorageObjectFailure {
481 return selectByWhereClause(where, 0);
485 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
486 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
488 * @param wc where-Clause
489 * @param offset ab welchem Datensatz.
490 * @return EntityList mit den gematchten Entities
491 * @exception StorageObjectException
493 public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
494 return selectByWhereClause(whereClause, null, offset);
498 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
499 * Also offset wird der erste Datensatz genommen.
500 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
502 * @param wc where-Clause
503 * @param ob orderBy-Clause
504 * @return EntityList mit den gematchten Entities
505 * @exception StorageObjectException
507 public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
508 return selectByWhereClause(where, order, 0);
512 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
513 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
515 * @param wc where-Clause
516 * @param ob orderBy-Clause
517 * @param offset ab welchem Datensatz
518 * @return EntityList mit den gematchten Entities
519 * @exception StorageObjectException
521 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
522 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
526 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
527 * @param aWhereClause where-Clause
528 * @param anOrderByClause orderBy-Clause
529 * @param offset ab welchem Datensatz
530 * @param limit wieviele Datens?tze
531 * @return EntityList mit den gematchten Entities
532 * @exception StorageObjectException
534 public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
535 int offset, int limit) throws StorageObjectFailure {
537 // check o_store for entitylist
538 if (StoreUtil.implementsStorableObject(theEntityClass)) {
539 StoreIdentifier search_sid =
541 theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
542 StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));
543 EntityList hit = (EntityList) o_store.use(search_sid);
546 logger.debug("CACHE (hit): " + search_sid.toString());
553 EntityList theReturnList = null;
554 Connection con = null;
555 Statement stmt = null;
560 // build sql-statement
562 /** @todo count sql string should only be assembled if we really count
563 * see below at the end of method //rk */
564 if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
568 StringBuffer countSql =
569 new StringBuffer("select count(*) from ").append(theTable);
570 StringBuffer selectSql =
571 new StringBuffer("select * from ").append(theTable);
573 if (aWhereClause != null) {
574 selectSql.append(" where ").append(aWhereClause);
575 countSql.append(" where ").append(aWhereClause);
578 if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
579 selectSql.append(" order by ").append(anOrderByClause);
582 if (theAdaptor.hasLimit()) {
583 if ((limit > -1) && (offset > -1)) {
584 selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
590 con = getPooledCon();
591 stmt = con.createStatement();
594 rs = executeSql(stmt, selectSql.toString());
597 if (!evaluatedMetaData) {
598 evalMetaData(rs.getMetaData());
601 theReturnList = new EntityList();
603 Entity theResultEntity;
606 theResultEntity = makeEntityFromResultSet(rs);
607 theReturnList.add(theResultEntity);
614 // making entitylist infos
615 if (!(theAdaptor.hasLimit())) {
619 if (theReturnList != null) {
620 // now we decide if we have to know an overall count...
623 if ((limit > -1) && (offset > -1)) {
624 if (offsetCount == limit) {
625 /** @todo counting should be deffered to entitylist
626 * getSize() should be used */
627 rs = executeSql(stmt, countSql.toString());
631 count = rs.getInt(1);
637 logger.error("Could not count: " + countSql);
642 theReturnList.setCount(count);
643 theReturnList.setOffset(offset);
644 theReturnList.setWhere(aWhereClause);
645 theReturnList.setOrder(anOrderByClause);
646 theReturnList.setStorage(this);
647 theReturnList.setLimit(limit);
649 if (offset >= limit) {
650 theReturnList.setPrevBatch(offset - limit);
653 if ((offset + offsetCount) < count) {
654 theReturnList.setNextBatch(offset + limit);
657 if (StoreUtil.implementsStorableObject(theEntityClass)) {
658 StoreIdentifier sid = theReturnList.getStoreIdentifier();
659 logger.debug("CACHE (add): " + sid.toString());
663 } catch (SQLException sqe) {
664 throwSQLException(sqe, "selectByWhereClause");
668 freeConnection(con, stmt);
670 } catch (Throwable t) {
674 return theReturnList;
678 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
680 * @param rs Das ResultSetObjekt.
681 * @return Entity Die Entity.
683 private Entity makeEntityFromResultSet(ResultSet rs)
684 throws StorageObjectFailure {
685 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
686 Map theResultHash = new HashMap();
687 String theResult = null;
689 Entity returnEntity = null;
692 int size = metadataFields.size();
694 for (int i = 0; i < size; i++) {
695 // alle durchlaufen bis nix mehr da
696 theType = metadataTypes[i];
698 if (theType == java.sql.Types.LONGVARBINARY) {
699 InputStreamReader is =
700 (InputStreamReader) rs.getCharacterStream(i + 1);
703 char[] data = new char[32768];
704 StringBuffer theResultString = new StringBuffer();
707 while ((len = is.read(data)) > 0) {
708 theResultString.append(data, 0, len);
712 theResult = theResultString.toString();
717 theResult = getValueAsString(rs, (i + 1), theType);
720 if (theResult != null) {
721 theResultHash.put(metadataFields.get(i), theResult);
725 if (theEntityClass != null) {
726 returnEntity = (Entity) theEntityClass.newInstance();
727 returnEntity.setValues(theResultHash);
728 returnEntity.setStorage(myselfDatabase);
730 if (returnEntity instanceof StorableObject) {
731 logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
732 o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
735 throwStorageObjectException("Internal Error: theEntityClass not set!");
738 catch (IllegalAccessException e) {
739 throwStorageObjectException("No access! -- " + e.getMessage());
741 catch (IOException e) {
742 throwStorageObjectException("IOException! -- " + e.getMessage());
744 catch (InstantiationException e) {
745 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);
1235 public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
1236 long startTime = System.currentTimeMillis();
1239 Connection connection = getPooledCon();
1240 Statement statement = connection.createStatement();
1243 result = statement.executeQuery(sql);
1245 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1248 catch (Throwable e) {
1249 logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1250 throw new StorageObjectFailure(e);
1254 private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
1256 Map result = new HashMap();
1257 ResultSetMetaData metaData = aResultSet.getMetaData();
1258 int nrColumns = metaData.getColumnCount();
1259 for (int i=0; i<nrColumns; i++) {
1260 result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
1265 catch (Throwable e) {
1266 throw new StorageObjectFailure(e);
1270 public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
1272 ResultSet resultset = executeSql(sql);
1273 List result = new Vector();
1275 while (resultset.next() && result.size() < aLimit) {
1276 result.add(processRow(resultset));
1281 catch (Throwable e) {
1282 throw new StorageObjectFailure(e);
1286 public Map executeFreeSingleRowSql(String sql) throws StorageObjectFailure, StorageObjectExc {
1288 ResultSet resultset = executeSql(sql);
1290 if (resultset.next())
1291 return processRow(resultset);
1295 catch (Throwable t) {
1296 throw new StorageObjectFailure(t);
1300 public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
1301 Map row = executeFreeSingleRowSql(sql);
1306 Iterator i = row.values().iterator();
1308 return (String) i.next();
1314 * returns the number of rows in the table
1316 public int getSize(String where) throws SQLException, StorageObjectFailure {
1317 long startTime = System.currentTimeMillis();
1318 String sql = "SELECT Count(*) FROM " + theTable;
1320 if ((where != null) && (where.length() != 0)) {
1321 sql = sql + " where " + where;
1324 Connection con = null;
1325 Statement stmt = null;
1329 con = getPooledCon();
1330 stmt = con.createStatement();
1332 ResultSet rs = executeSql(stmt, sql);
1335 result = rs.getInt(1);
1338 catch (SQLException e) {
1339 logger.error("Database.getSize: " + e.getMessage());
1342 freeConnection(con, stmt);
1345 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1346 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1351 public int executeUpdate(Statement stmt, String sql)
1352 throws StorageObjectFailure, SQLException {
1354 long startTime = System.currentTimeMillis();
1357 rs = stmt.executeUpdate(sql);
1359 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1361 catch (SQLException e) {
1362 logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1369 public int executeUpdate(String sql)
1370 throws StorageObjectFailure, SQLException {
1372 long startTime = System.currentTimeMillis();
1373 Connection con = null;
1374 PreparedStatement pstmt = null;
1377 con = getPooledCon();
1378 pstmt = con.prepareStatement(sql);
1379 result = pstmt.executeUpdate();
1381 catch (Throwable e) {
1382 logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
1383 throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
1386 freeConnection(con, pstmt);
1389 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1394 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1395 * @param md ResultSetMetaData
1396 * @exception StorageObjectException
1398 private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
1399 this.evaluatedMetaData = true;
1400 this.metadataFields = new ArrayList();
1401 this.metadataLabels = new ArrayList();
1402 this.metadataNotNullFields = new ArrayList();
1405 int numFields = md.getColumnCount();
1406 this.metadataTypes = new int[numFields];
1411 for (int i = 1; i <= numFields; i++) {
1412 aField = md.getColumnName(i);
1413 metadataFields.add(aField);
1414 metadataLabels.add(md.getColumnLabel(i));
1415 aType = md.getColumnType(i);
1416 metadataTypes[i - 1] = aType;
1418 if (aField.equals(thePKeyName)) {
1419 thePKeyType = aType;
1423 if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
1424 metadataNotNullFields.add(aField);
1428 catch (SQLException e) {
1429 throwSQLException(e, "evalMetaData");
1434 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1435 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1437 private void get_meta_data() throws StorageObjectFailure {
1438 Connection con = null;
1439 PreparedStatement pstmt = null;
1440 String sql = "select * from " + theTable + " where 0=1";
1443 con = getPooledCon();
1444 pstmt = con.prepareStatement(sql);
1446 logger.debug("METADATA: " + sql);
1447 ResultSet rs = pstmt.executeQuery();
1448 evalMetaData(rs.getMetaData());
1451 catch (SQLException e) {
1452 throwSQLException(e, "get_meta_data");
1455 freeConnection(con, pstmt);
1459 public Connection getPooledCon() throws StorageObjectFailure {
1460 Connection con = null;
1463 con = SQLManager.getInstance().requestConnection();
1465 catch (SQLException e) {
1466 logger.error("could not connect to the database " + e.getMessage());
1468 throw new StorageObjectFailure("Could not connect to the database", e);
1474 public void freeConnection(Connection con, Statement stmt)
1475 throws StorageObjectFailure {
1476 SQLManager.closeStatement(stmt);
1477 SQLManager.getInstance().returnConnection(con);
1481 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1482 * @param sqe SQLException
1483 * @param wo Funktonsname, in der die SQLException geworfen wurde
1484 * @exception StorageObjectException
1486 protected void throwSQLException(SQLException sqe, String aFunction)
1487 throws StorageObjectFailure {
1489 String message = "";
1493 state = sqe.getSQLState();
1494 message = sqe.getMessage();
1495 vendor = sqe.getErrorCode();
1498 String information =
1501 ", vendor= " + vendor +
1502 ", message=" + message +
1503 ", function= " + aFunction;
1505 logger.error(information);
1507 throw new StorageObjectFailure(information, sqe);
1510 protected void _throwStorageObjectException(Exception e, String aFunction)
1511 throws StorageObjectFailure {
1514 logger.error(e.getMessage() + aFunction);
1515 throw new StorageObjectFailure(aFunction, e);
1520 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1521 * eine StorageObjectException
1522 * @param message Nachricht mit dem Fehler
1523 * @exception StorageObjectException
1525 void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
1526 logger.error(aMessage);
1527 throw new StorageObjectFailure(aMessage, null);