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;
47 import java.util.Iterator;
48 import java.util.List;
50 import java.util.TimeZone;
51 import java.util.Vector;
53 import mir.config.MirPropertiesConfiguration;
54 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
55 import mir.entity.Entity;
56 import mir.entity.EntityList;
57 import mir.entity.StorableObjectEntity;
58 import mir.log.LoggerWrapper;
59 import mir.misc.StringUtil;
60 import mir.storage.store.ObjectStore;
61 import mir.storage.store.StorableObject;
62 import mir.storage.store.StoreContainerType;
63 import mir.storage.store.StoreIdentifier;
64 import mir.storage.store.StoreUtil;
65 import mir.util.JDBCStringRoutines;
67 import com.codestudio.util.SQLManager;
71 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
72 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
73 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
74 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
75 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
78 * @version $Id: Database.java,v 1.44.2.16 2003/11/27 14:50:57 rk Exp $
82 public class Database implements StorageObject {
83 private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
84 private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
87 private static Map POPUP_EMPTYLINE = new HashMap();
88 protected static final ObjectStore o_store = ObjectStore.getInstance();
89 private static final int _millisPerHour = 60 * 60 * 1000;
90 private static final int _millisPerMinute = 60 * 1000;
93 // always same object saves a little space
94 POPUP_EMPTYLINE.put("key", "");
95 POPUP_EMPTYLINE.put("value", "--");
98 protected LoggerWrapper logger;
99 protected MirPropertiesConfiguration configuration;
100 protected String theTable;
101 protected String theCoreTable = null;
102 protected String thePKeyName = "id";
103 protected int thePKeyType;
104 protected int thePKeyIndex;
105 protected boolean evaluatedMetaData = false;
106 protected ArrayList metadataFields;
107 protected ArrayList metadataLabels;
108 protected ArrayList metadataNotNullFields;
109 protected int[] metadataTypes;
110 protected Class theEntityClass;
111 protected List popupCache = null;
112 protected boolean hasPopupCache = false;
113 protected Map hashCache = null;
114 protected boolean hasTimestamp = true;
115 private String database_driver;
116 private String database_url;
117 private int defaultLimit;
120 SimpleDateFormat internalDateFormat;
121 SimpleDateFormat userInputDateFormat;
123 private SimpleDateFormat _dateFormatterOut;
124 private SimpleDateFormat _dateFormatterIn;
125 _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
126 _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");
130 * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
131 * Aus diesem file werden <code>Database.Logfile</code>,
132 * <code>Database.Username</code>,<code>Database.Password</code>,
133 * <code>Database.Host</code> und <code>Database.Adaptor</code>
134 * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
137 * @param String confFilename Dateiname der Konfigurationsdatei
139 public Database() throws StorageObjectFailure {
141 configuration = MirPropertiesConfiguration.instance();
143 catch (PropertiesConfigExc e) {
144 throw new StorageObjectFailure(e);
146 logger = new LoggerWrapper("Database");
147 timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
148 internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
149 internalDateFormat.setTimeZone(timezone);
151 userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
152 userInputDateFormat.setTimeZone(timezone);
155 String theAdaptorName = configuration.getString("Database.Adaptor");
156 defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
159 theEntityClass = GENERIC_ENTITY_CLASS;
161 catch (Throwable e) {
162 logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
163 throw new StorageObjectFailure("Error in Database() constructor.", e);
168 * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
169 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
170 * wird eine mir.entity.GenericEntity erzeugt.
172 * @return Class-Objekt der Entity
174 public java.lang.Class getEntityClass() {
175 return theEntityClass;
179 * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
180 * wieviel Datens?tze per Default selektiert werden.
182 * @return Standard-Anzahl der Datens?tze
184 public int getLimit() {
189 * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
190 * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
191 * @return Name des Primary-Keys
193 public String getIdName() {
198 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
200 * @return Name der Tabelle
202 public String getTableName() {
207 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
208 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
210 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
213 public String getCoreTable() {
214 if (theCoreTable != null) {
223 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
224 * @return int-Array mit den Typen der Felder
225 * @exception StorageObjectException
227 public int[] getTypes() throws StorageObjectFailure {
228 if (metadataTypes == null) {
232 return metadataTypes;
236 * Liefert eine Liste der Labels der Tabellenfelder
237 * @return ArrayListe mit Labeln
238 * @exception StorageObjectException
240 public List getLabels() throws StorageObjectFailure {
241 if (metadataLabels == null) {
245 return metadataLabels;
249 * Liefert eine Liste der Felder der Tabelle
250 * @return ArrayList mit Feldern
251 * @exception StorageObjectException
253 public List getFields() throws StorageObjectFailure {
254 if (metadataFields == null) {
258 return metadataFields;
262 * Gets value out of ResultSet according to type and converts to String
263 * @param rs ResultSet.
264 * @param aType a type from java.sql.Types.*
265 * @param index index in ResultSet
266 * @return returns the value as String. If no conversion is possible
267 * /unsupported value/ is returned
269 private String getValueAsString(ResultSet rs, int valueIndex, int aType)
270 throws StorageObjectFailure {
271 String outValue = null;
276 case java.sql.Types.BIT:
277 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
281 case java.sql.Types.INTEGER:
282 case java.sql.Types.SMALLINT:
283 case java.sql.Types.TINYINT:
284 case java.sql.Types.BIGINT:
286 int out = rs.getInt(valueIndex);
289 outValue = new Integer(out).toString();
294 case java.sql.Types.NUMERIC:
296 /** @todo Numeric can be float or double depending upon
297 * metadata.getScale() / especially with oracle */
298 long outl = rs.getLong(valueIndex);
301 outValue = new Long(outl).toString();
306 case java.sql.Types.REAL:
308 float tempf = rs.getFloat(valueIndex);
314 int tempf_int = (int) tempf;
315 tempf = (float) tempf_int;
317 outValue = "" + tempf;
318 outValue = outValue.replace('.', ',');
323 case java.sql.Types.DOUBLE:
325 double tempd = rs.getDouble(valueIndex);
331 int tempd_int = (int) tempd;
332 tempd = (double) tempd_int;
334 outValue = "" + tempd;
335 outValue = outValue.replace('.', ',');
340 case java.sql.Types.CHAR:
341 case java.sql.Types.VARCHAR:
342 case java.sql.Types.LONGVARCHAR:
343 outValue = rs.getString(valueIndex);
347 case java.sql.Types.LONGVARBINARY:
348 outValue = rs.getString(valueIndex);
352 case java.sql.Types.TIMESTAMP:
354 // it's important to use Timestamp here as getting it
355 // as a string is undefined and is only there for debugging
356 // according to the API. we can make it a string through formatting.
358 Timestamp timestamp = (rs.getTimestamp(valueIndex));
361 java.util.Date date = new java.util.Date(timestamp.getTime());
363 Calendar calendar = new GregorianCalendar();
364 calendar.setTime(date);
365 calendar.setTimeZone(timezone);
366 outValue = internalDateFormat.format(date);
368 int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
369 String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
372 outValue = outValue + "-";
374 outValue = outValue + "+";
375 outValue = outValue + tzOffset;
381 outValue = "<unsupported value>";
382 logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
384 } catch (SQLException e) {
385 throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
394 * select-Operator um einen Datensatz zu bekommen.
395 * @param id Primaerschluessel des Datensatzes.
396 * @return liefert EntityObject des gefundenen Datensatzes oder null.
398 public Entity selectById(String id) throws StorageObjectExc {
399 if ((id == null) || id.equals("")) {
400 throw new StorageObjectExc("Database.selectById: Missing id");
403 // ask object store for object
404 if (StoreUtil.implementsStorableObject(theEntityClass)) {
405 String uniqueId = id;
407 if (theEntityClass.equals(StorableObjectEntity.class)) {
408 uniqueId += ("@" + theTable);
411 StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
412 logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
414 Entity hit = (Entity) o_store.use(search_sid);
421 Statement stmt = null;
422 Connection con = getPooledCon();
423 Entity returnEntity = null;
428 /** @todo better prepared statement */
430 "select * from " + theTable + " where " + thePKeyName + "=" + id;
431 stmt = con.createStatement();
432 rs = executeSql(stmt, selectSql);
435 if (evaluatedMetaData == false) {
436 evalMetaData(rs.getMetaData());
440 returnEntity = makeEntityFromResultSet(rs);
443 logger.debug("No data for id: " + id + " in table " + theTable);
449 logger.debug("No Data for Id " + id + " in Table " + theTable);
452 catch (SQLException sqe) {
453 throwSQLException(sqe, "selectById");
456 catch (NumberFormatException e) {
457 logger.error("ID is no number: " + id);
460 freeConnection(con, stmt);
467 * This method makes it possible to make selects across multiple tables
469 * @param mainTablePrefix prefix for the mainTable
470 * @param extraTables a vector of tables for relational select
471 * @param aWhereClause whereClause
472 * @return EntityList of selected Objects
473 * @throws StorageObjectFailure
476 public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix,
477 List extraTables, String aWhereClause )
478 throws StorageObjectFailure {
479 return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, defaultLimit);
483 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
484 * @param key Datenbankfeld der Bedingung.
485 * @param value Wert die der key anehmen muss.
486 * @return EntityList mit den gematchten Entities
488 public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
489 return selectByFieldValue(aField, aValue, 0);
493 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
494 * @param key Datenbankfeld der Bedingung.
495 * @param value Wert die der key anehmen muss.
496 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
497 * @return EntityList mit den gematchten Entities
499 public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
500 return selectByWhereClause(aField + "=" + aValue, offset);
504 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
505 * Also offset wird der erste Datensatz genommen.
507 * @param wc where-Clause
508 * @return EntityList mit den gematchten Entities
509 * @exception StorageObjectException
511 public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
512 return selectByWhereClause(where, 0);
516 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
517 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
519 * @param wc where-Clause
520 * @param offset ab welchem Datensatz.
521 * @return EntityList mit den gematchten Entities
522 * @exception StorageObjectException
524 public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
525 return selectByWhereClause(whereClause, null, offset);
529 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
530 * Also offset wird der erste Datensatz genommen.
531 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
533 * @param wc where-Clause
534 * @param ob orderBy-Clause
535 * @return EntityList mit den gematchten Entities
536 * @exception StorageObjectException
538 public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
539 return selectByWhereClause(where, order, 0);
542 public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws StorageObjectFailure {
543 return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, defaultLimit);
547 * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
548 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
550 * @param wc where-Clause
551 * @param ob orderBy-Clause
552 * @param offset ab welchem Datensatz
553 * @return EntityList mit den gematchten Entities
554 * @exception StorageObjectException
556 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
557 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
561 * select-Operator returns EntityList with matching rows in Database.
562 * @param aWhereClause where-Clause
563 * @param anOrderByClause orderBy-Clause
564 * @param offset ab welchem Datensatz
565 * @param limit wieviele Datens?tze
566 * @return EntityList mit den gematchten Entities
567 * @exception StorageObjectException
569 public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
570 int offset, int limit) throws StorageObjectFailure {
571 return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
576 * select-Operator returns EntityList with matching rows in Database.
577 * @param aWhereClause where-Clause
578 * @param anOrderByClause orderBy-Clause
579 * @param offset ab welchem Datensatz
580 * @param limit wieviele Datens?tze
581 * @return EntityList mit den gematchten Entities
582 * @exception StorageObjectException
584 public EntityList selectByWhereClause(String mainTablePrefix, List extraTables,
585 String aWhereClause, String anOrderByClause,
586 int offset, int limit) throws StorageObjectFailure {
588 // TODO get rid of emtpy Strings in extraTables
589 // make extraTables null, if single empty String in it
590 if (extraTables != null && ((String)extraTables.get(0)).trim().equals(""))
592 logger.debug("+++ made extraTables to null!");
596 String useTable = theTable;
597 String selectStar = "*";
598 if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
599 useTable+=" "+mainTablePrefix;
600 selectStar=mainTablePrefix.trim() + ".*";
603 // check o_store for entitylist
604 // only if no relational select
605 if (extraTables==null) {
606 if (StoreUtil.implementsStorableObject(theEntityClass)) {
607 StoreIdentifier search_sid =
609 theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
610 StoreUtil.getEntityListUniqueIdentifierFor(useTable, aWhereClause, anOrderByClause, offset, limit));
611 EntityList hit = (EntityList) o_store.use(search_sid);
614 logger.debug("CACHE (hit): " + search_sid.toString());
622 EntityList theReturnList = null;
623 Connection con = null;
624 Statement stmt = null;
629 // build sql-statement
631 if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
635 StringBuffer countSql =
636 new StringBuffer("select count(*) from ").append(useTable);
637 StringBuffer selectSql =
638 new StringBuffer("select "+selectStar+" from ").append(useTable);
640 // append extratables, if necessary
641 if (extraTables!=null) {
642 for (int i=0;i < extraTables.size();i++) {
643 if (!extraTables.get(i).equals("")) {
644 countSql.append( ", " + extraTables.get(i));
645 selectSql.append( ", " + extraTables.get(i));
650 if (aWhereClause != null) {
651 selectSql.append(" where ").append(aWhereClause);
652 countSql.append(" where ").append(aWhereClause);
655 if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
656 selectSql.append(" order by ").append(anOrderByClause);
659 if ((limit > -1) && (offset > -1)) {
660 selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
665 con = getPooledCon();
666 stmt = con.createStatement();
669 rs = executeSql(stmt, selectSql.toString());
672 if (!evaluatedMetaData) {
673 evalMetaData(rs.getMetaData());
676 theReturnList = new EntityList();
677 Entity theResultEntity;
679 theResultEntity = makeEntityFromResultSet(rs);
680 theReturnList.add(theResultEntity);
686 // making entitylist infos
689 if (theReturnList != null) {
690 // now we decide if we have to know an overall count...
693 if ((limit > -1) && (offset > -1)) {
694 if (offsetCount == limit) {
695 rs = executeSql(stmt, countSql.toString());
699 count = rs.getInt(1);
705 logger.error("Could not count: " + countSql);
710 theReturnList.setCount(count);
711 theReturnList.setOffset(offset);
712 theReturnList.setWhere(aWhereClause);
713 theReturnList.setOrder(anOrderByClause);
714 theReturnList.setStorage(this);
715 theReturnList.setLimit(limit);
717 if (offset >= limit) {
718 theReturnList.setPrevBatch(offset - limit);
721 if ((offset + offsetCount) < count) {
722 theReturnList.setNextBatch(offset + limit);
725 if (extraTables==null && StoreUtil.implementsStorableObject(theEntityClass)) {
726 StoreIdentifier sid = theReturnList.getStoreIdentifier();
727 logger.debug("CACHE (add): " + sid.toString());
732 catch (SQLException sqe) {
733 throwSQLException(sqe, "selectByWhereClause");
738 freeConnection(con, stmt);
740 } catch (Throwable t) {
744 return theReturnList;
748 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
750 * @param rs Das ResultSetObjekt.
751 * @return Entity Die Entity.
753 private Entity makeEntityFromResultSet(ResultSet rs)
754 throws StorageObjectFailure {
755 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
756 Map theResultHash = new HashMap();
757 String theResult = null;
759 Entity returnEntity = null;
762 int size = metadataFields.size();
764 for (int i = 0; i < size; i++) {
765 // alle durchlaufen bis nix mehr da
766 theType = metadataTypes[i];
768 if (theType == java.sql.Types.LONGVARBINARY) {
769 InputStreamReader is =
770 (InputStreamReader) rs.getCharacterStream(i + 1);
773 char[] data = new char[32768];
774 StringBuffer theResultString = new StringBuffer();
777 while ((len = is.read(data)) > 0) {
778 theResultString.append(data, 0, len);
782 theResult = theResultString.toString();
787 theResult = getValueAsString(rs, (i + 1), theType);
790 if (theResult != null) {
791 theResultHash.put(metadataFields.get(i), theResult);
795 if (theEntityClass != null) {
796 returnEntity = (Entity) theEntityClass.newInstance();
797 returnEntity.setStorage(this);
798 returnEntity.setValues(theResultHash);
800 if (returnEntity instanceof StorableObject) {
801 logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
802 o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
805 throwStorageObjectException("Internal Error: theEntityClass not set!");
808 catch (IllegalAccessException e) {
809 throwStorageObjectException("No access! -- " + e.getMessage());
811 catch (IOException e) {
812 throwStorageObjectException("IOException! -- " + e.getMessage());
814 catch (InstantiationException e) {
815 throwStorageObjectException("No Instatiation! -- " + e.getMessage());
817 catch (SQLException sqe) {
818 throwSQLException(sqe, "makeEntityFromResultSet");
827 * Inserts an entity into the database.
830 * @return der Wert des Primary-keys der eingef?gten Entity
832 public String insert(Entity theEntity) throws StorageObjectFailure {
834 invalidatePopupCache();
836 // invalidating all EntityLists corresponding with theEntityClass
837 if (StoreUtil.implementsStorableObject(theEntityClass)) {
838 StoreContainerType stoc_type =
839 StoreContainerType.valueOf(theEntityClass,
840 StoreContainerType.STOC_TYPE_ENTITYLIST);
841 o_store.invalidate(stoc_type);
844 String returnId = null;
845 Connection con = null;
846 PreparedStatement pstmt = null;
849 List streamedInput = theEntity.streamedInput();
850 StringBuffer f = new StringBuffer();
851 StringBuffer v = new StringBuffer();
854 boolean firstField = true;
857 for (int i = 0; i < getFields().size(); i++) {
858 aField = (String) getFields().get(i);
860 if (!aField.equals(thePKeyName)) {
864 if (!theEntity.hasValueForField(aField) && (
865 aField.equals("webdb_create") ||
866 aField.equals("webdb_lastchange"))) {
870 if ((streamedInput != null) && streamedInput.contains(aField)) {
874 if (theEntity.hasValueForField(aField)) {
877 JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";
882 // wenn Wert gegeben, dann einbauen
883 if (aValue != null) {
884 if (firstField == false) {
900 StringBuffer sqlBuf =
901 new StringBuffer("insert into ").append(theTable).append("(").append(f)
902 .append(") values (").append(v).append(")");
903 String sql = sqlBuf.toString();
905 logger.debug("INSERT: " + sql);
906 con = getPooledCon();
907 con.setAutoCommit(false);
908 pstmt = con.prepareStatement(sql);
910 if (streamedInput != null) {
911 for (int i = 0; i < streamedInput.size(); i++) {
913 (String) theEntity.getValue((String) streamedInput.get(i));
914 pstmt.setBytes(i + 1, inputString.getBytes());
918 int ret = pstmt.executeUpdate();
925 pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");
927 ResultSet rs = pstmt.executeQuery();
929 returnId = rs.getString(1);
930 theEntity.setId(returnId);
932 catch (SQLException sqe) {
933 throwSQLException(sqe, "insert");
937 con.setAutoCommit(true);
939 catch (Exception e) {
942 freeConnection(con, pstmt);
945 /** @todo store entity in o_store */
950 * Updates an entity in the database
954 public void update(Entity theEntity) throws StorageObjectFailure {
955 Connection con = null;
956 PreparedStatement pstmt = null;
958 /** @todo this is stupid: why do we prepare statement, when we
959 * throw it away afterwards. should be regular statement
960 * update/insert could better be one routine called save()
961 * that chooses to either insert or update depending if we
962 * have a primary key in the entity. i don't know if we
963 * still need the streamed input fields. // rk */
964 /** @todo extension: check if Entity did change, otherwise we don't need
965 * the roundtrip to the database */
966 /** invalidating corresponding entitylists in o_store*/
967 if (StoreUtil.implementsStorableObject(theEntityClass)) {
968 StoreContainerType stoc_type =
969 StoreContainerType.valueOf(theEntityClass,
970 StoreContainerType.STOC_TYPE_ENTITYLIST);
971 o_store.invalidate(stoc_type);
974 List streamedInput = theEntity.streamedInput();
975 String id = theEntity.getId();
977 StringBuffer fv = new StringBuffer();
978 boolean firstField = true;
981 invalidatePopupCache();
983 // build sql statement
984 for (int i = 0; i < getFields().size(); i++) {
985 aField = (String) metadataFields.get(i);
988 if ( !(aField.equals(thePKeyName) ||
989 aField.equals("webdb_create") ||
990 aField.equals("webdb_lastchange") ||
991 ((streamedInput != null) && streamedInput.contains(aField)))) {
992 if (theEntity.hasValueForField(aField)) {
993 if (firstField == false) {
1000 fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
1002 // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
1008 new StringBuffer("update ").append(theTable).append(" set ").append(fv);
1011 if (metadataFields.contains("webdb_lastchange")) {
1012 sql.append(",webdb_lastchange=NOW()");
1015 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
1016 // format so anything extra will be ignored. -mh
1017 if (metadataFields.contains("webdb_create") &&
1018 theEntity.hasValueForField("webdb_create")) {
1019 // minimum of 10 (yyyy-mm-dd)...
1020 if (theEntity.getValue("webdb_create").length() >= 10) {
1021 String dateString = theEntity.getValue("webdb_create");
1023 // if only 10, then add 00:00 so it doesn't throw a ParseException
1024 if (dateString.length() == 10) {
1025 dateString = dateString + " 00:00";
1030 java.util.Date d = userInputDateFormat.parse(dateString);
1031 // Timestamp tStamp = new Timestamp(d.getTime());
1032 sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
1034 catch (ParseException e) {
1035 throw new StorageObjectFailure(e);
1040 if (streamedInput != null) {
1041 for (int i = 0; i < streamedInput.size(); i++) {
1042 sql.append(",").append(streamedInput.get(i)).append("=?");
1046 sql.append(" where id=").append(id);
1047 logger.debug("UPDATE: " + sql);
1050 con = getPooledCon();
1051 con.setAutoCommit(false);
1052 pstmt = con.prepareStatement(sql.toString());
1054 if (streamedInput != null) {
1055 for (int i = 0; i < streamedInput.size(); i++) {
1056 String inputString =
1057 theEntity.getValue((String) streamedInput.get(i));
1058 pstmt.setBytes(i + 1, inputString.getBytes());
1062 pstmt.executeUpdate();
1064 catch (SQLException sqe) {
1065 throwSQLException(sqe, "update");
1069 con.setAutoCommit(true);
1071 catch (Exception e) {
1075 freeConnection(con, pstmt);
1081 * @param id des zu loeschenden Datensatzes
1082 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
1084 public boolean delete(String id) throws StorageObjectFailure {
1085 invalidatePopupCache();
1087 // ostore send notification
1088 if (StoreUtil.implementsStorableObject(theEntityClass)) {
1089 String uniqueId = id;
1091 if (theEntityClass.equals(StorableObjectEntity.class)) {
1092 uniqueId += ("@" + theTable);
1095 logger.debug("CACHE: (del) " + id);
1097 StoreIdentifier search_sid =
1098 new StoreIdentifier(theEntityClass,
1099 StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
1100 o_store.invalidate(search_sid);
1103 /** @todo could be prepared Statement */
1104 Statement stmt = null;
1105 Connection con = null;
1108 "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
1110 //theLog.printInfo("DELETE " + sql);
1112 con = getPooledCon();
1113 stmt = con.createStatement();
1114 res = stmt.executeUpdate(sql);
1115 } catch (SQLException sqe) {
1116 throwSQLException(sqe, "delete");
1118 freeConnection(con, stmt);
1121 return (res > 0) ? true : false;
1125 * Deletes entities based on a where clause
1127 * @param aWhereClause
1129 * @throws StorageObjectFailure
1131 public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
1132 invalidatePopupCache();
1133 if (StoreUtil.implementsStorableObject(theEntityClass)) {
1134 StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
1135 o_store.invalidate(stoc_type);
1138 Statement stmt = null;
1139 Connection con = null;
1142 "delete from " + theTable + " where " + aWhereClause;
1144 //theLog.printInfo("DELETE " + sql);
1146 con = getPooledCon();
1147 stmt = con.createStatement();
1148 res = stmt.executeUpdate(sql);
1150 catch (SQLException sqe) {
1151 throwSQLException(sqe, "delete");
1154 freeConnection(con, stmt);
1160 /* noch nicht implementiert.
1161 * @return immer false
1163 public boolean delete(EntityList theEntityList) {
1164 invalidatePopupCache();
1169 /* invalidates the popupCache
1171 protected void invalidatePopupCache() {
1172 /** @todo invalidates toooo much */
1178 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1179 * @param stmt Statemnt
1180 * @param sql Sql-String
1182 * @exception StorageObjectException
1184 public ResultSet executeSql(Statement stmt, String sql)
1185 throws StorageObjectFailure, SQLException {
1187 long startTime = System.currentTimeMillis();
1190 rs = stmt.executeQuery(sql);
1192 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1194 catch (SQLException e) {
1195 logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1202 public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
1203 long startTime = System.currentTimeMillis();
1204 Connection connection = null;
1205 Statement statement = null;
1208 connection = getPooledCon();
1209 statement = connection.createStatement();
1212 result = statement.executeQuery(sql);
1214 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1217 catch (Throwable e) {
1218 logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1219 throw new StorageObjectFailure(e);
1222 if (connection!=null) {
1223 freeConnection(connection, statement);
1228 private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
1230 Map result = new HashMap();
1231 ResultSetMetaData metaData = aResultSet.getMetaData();
1232 int nrColumns = metaData.getColumnCount();
1233 for (int i=0; i<nrColumns; i++) {
1234 result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
1239 catch (Throwable e) {
1240 throw new StorageObjectFailure(e);
1244 public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
1245 Connection connection = null;
1246 Statement statement = null;
1248 List result = new Vector();
1249 connection = getPooledCon();
1250 statement = connection.createStatement();
1251 ResultSet resultset = executeSql(statement, sql);
1253 while (resultset.next() && result.size() < aLimit) {
1254 result.add(processRow(resultset));
1263 catch (Throwable e) {
1264 throw new StorageObjectFailure(e);
1267 if (connection!=null) {
1268 freeConnection(connection, statement);
1273 public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
1275 List resultList = executeFreeSql(anSqlStatement, 1);
1277 if (resultList.size()>0)
1278 return (Map) resultList.get(0);
1285 catch (Throwable t) {
1286 throw new StorageObjectFailure(t);
1290 public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
1291 Map row = executeFreeSingleRowSql(sql);
1296 Iterator i = row.values().iterator();
1298 return (String) i.next();
1303 public int getSize(String where) throws SQLException, StorageObjectFailure {
1304 return getSize("", null, where);
1307 * returns the number of rows in the table
1309 public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, StorageObjectFailure {
1311 long startTime = System.currentTimeMillis();
1313 String useTable = theTable;
1314 if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
1315 useTable+=" "+mainTablePrefix;
1317 StringBuffer countSql =
1318 new StringBuffer("select count(*) from ").append(useTable);
1319 // append extratables, if necessary
1320 if (extraTables!=null) {
1321 for (int i=0;i < extraTables.size();i++) {
1322 if (!extraTables.get(i).equals("")) {
1323 countSql.append( ", " + extraTables.get(i));
1328 if ((where != null) && (where.length() != 0)) {
1329 countSql.append( " where " + where);
1332 Connection con = null;
1333 Statement stmt = null;
1337 con = getPooledCon();
1338 stmt = con.createStatement();
1340 ResultSet rs = executeSql(stmt, countSql.toString());
1343 result = rs.getInt(1);
1346 catch (SQLException e) {
1347 logger.error("Database.getSize: " + e.getMessage());
1350 freeConnection(con, stmt);
1352 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + countSql);
1357 public int executeUpdate(Statement stmt, String sql)
1358 throws StorageObjectFailure, SQLException {
1360 long startTime = System.currentTimeMillis();
1363 rs = stmt.executeUpdate(sql);
1365 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1367 catch (SQLException e) {
1368 logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1375 public int executeUpdate(String sql)
1376 throws StorageObjectFailure, SQLException {
1378 long startTime = System.currentTimeMillis();
1379 Connection con = null;
1380 PreparedStatement pstmt = null;
1383 con = getPooledCon();
1384 pstmt = con.prepareStatement(sql);
1385 result = pstmt.executeUpdate();
1387 catch (Throwable e) {
1388 logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
1389 throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
1392 freeConnection(con, pstmt);
1395 logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
1400 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1401 * @param md ResultSetMetaData
1402 * @exception StorageObjectException
1404 private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
1405 this.evaluatedMetaData = true;
1406 this.metadataFields = new ArrayList();
1407 this.metadataLabels = new ArrayList();
1408 this.metadataNotNullFields = new ArrayList();
1411 int numFields = md.getColumnCount();
1412 this.metadataTypes = new int[numFields];
1417 for (int i = 1; i <= numFields; i++) {
1418 aField = md.getColumnName(i);
1419 metadataFields.add(aField);
1420 metadataLabels.add(md.getColumnLabel(i));
1421 aType = md.getColumnType(i);
1422 metadataTypes[i - 1] = aType;
1424 if (aField.equals(thePKeyName)) {
1425 thePKeyType = aType;
1429 if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
1430 metadataNotNullFields.add(aField);
1434 catch (SQLException e) {
1435 throwSQLException(e, "evalMetaData");
1440 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1441 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1443 private void get_meta_data() throws StorageObjectFailure {
1444 Connection con = null;
1445 PreparedStatement pstmt = null;
1446 String sql = "select * from " + theTable + " where 0=1";
1449 con = getPooledCon();
1450 pstmt = con.prepareStatement(sql);
1452 logger.debug("METADATA: " + sql);
1453 ResultSet rs = pstmt.executeQuery();
1454 evalMetaData(rs.getMetaData());
1457 catch (SQLException e) {
1458 throwSQLException(e, "get_meta_data");
1461 freeConnection(con, pstmt);
1465 public Connection getPooledCon() throws StorageObjectFailure {
1466 Connection con = null;
1469 con = SQLManager.getInstance().requestConnection();
1471 catch (SQLException e) {
1472 logger.error("could not connect to the database " + e.getMessage());
1474 throw new StorageObjectFailure("Could not connect to the database", e);
1480 public void freeConnection(Connection con, Statement stmt)
1481 throws StorageObjectFailure {
1482 SQLManager.closeStatement(stmt);
1483 SQLManager.getInstance().returnConnection(con);
1487 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1488 * @param sqe SQLException
1489 * @param wo Funktonsname, in der die SQLException geworfen wurde
1490 * @exception StorageObjectException
1492 protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {
1494 String message = "";
1498 state = sqe.getSQLState();
1499 message = sqe.getMessage();
1500 vendor = sqe.getErrorCode();
1503 String information =
1506 ", vendor= " + vendor +
1507 ", message=" + message +
1508 ", function= " + aFunction;
1510 logger.error(information);
1512 throw new StorageObjectFailure(information, sqe);
1515 protected void _throwStorageObjectException(Exception e, String aFunction)
1516 throws StorageObjectFailure {
1519 logger.error(e.getMessage() + aFunction);
1520 throw new StorageObjectFailure(aFunction, e);
1525 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1526 * eine StorageObjectException
1527 * @param message Nachricht mit dem Fehler
1528 * @exception StorageObjectException
1530 void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
1531 logger.error(aMessage);
1532 throw new StorageObjectFailure(aMessage, null);