import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
-import java.util.*;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
-
-import com.codestudio.util.SQLManager;
-
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
+import java.util.TimeZone;
+import java.util.Vector;
import mir.config.MirPropertiesConfiguration;
import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
import mir.entity.EntityList;
import mir.entity.StorableObjectEntity;
import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
import mir.misc.StringUtil;
import mir.storage.store.ObjectStore;
import mir.storage.store.StorableObject;
import mir.storage.store.StoreUtil;
import mir.util.JDBCStringRoutines;
+import com.codestudio.util.SQLManager;
+
/**
* Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
* Treiber, Host, User und Passwort, ueber den der Zugriff auf die
* Datenbank erfolgt.
*
- * @version $Id: Database.java,v 1.42 2003/05/03 00:21:22 zapata Exp $
+ * @version $Id: Database.java,v 1.44.2.12 2003/11/24 23:54:06 rk Exp $
* @author rk
*
*/
private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
- private static SimpleHash POPUP_EMPTYLINE = new SimpleHash();
+ private static Map POPUP_EMPTYLINE = new HashMap();
protected static final ObjectStore o_store = ObjectStore.getInstance();
private static final int _millisPerHour = 60 * 60 * 1000;
private static final int _millisPerMinute = 60 * 1000;
protected ArrayList metadataNotNullFields;
protected int[] metadataTypes;
protected Class theEntityClass;
- protected SimpleList popupCache = null;
+ protected List popupCache = null;
protected boolean hasPopupCache = false;
- protected SimpleHash hashCache = null;
+ protected Map hashCache = null;
protected boolean hasTimestamp = true;
private String database_driver;
private String database_url;
private int defaultLimit;
- protected DatabaseAdaptor theAdaptor;
- private SimpleDateFormat _dateFormatterOut =
- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- private SimpleDateFormat _dateFormatterIn =
- new SimpleDateFormat("yyyy-MM-dd HH:mm");
- private Calendar _cal = new GregorianCalendar();
+
+ TimeZone timezone;
+ SimpleDateFormat internalDateFormat;
+ SimpleDateFormat userInputDateFormat;
+/*
+ private SimpleDateFormat _dateFormatterOut;
+ private SimpleDateFormat _dateFormatterIn;
+ _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+*/
/**
* Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
throw new StorageObjectFailure(e);
}
logger = new LoggerWrapper("Database");
+ timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
+ internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ internalDateFormat.setTimeZone(timezone);
+
+ userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+ userInputDateFormat.setTimeZone(timezone);
+
String theAdaptorName = configuration.getString("Database.Adaptor");
defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
try {
theEntityClass = GENERIC_ENTITY_CLASS;
- theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance();
}
catch (Throwable e) {
logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
return metadataFields;
}
- /*
- * Gets value out of ResultSet according to type and converts to String
- * @param inValue Wert aus ResultSet.
- * @param aType Datenbanktyp.
- * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
- * dann /unsupported value/
+ /**
+ * Gets value out of ResultSet according to type and converts to String
+ * @param rs ResultSet.
+ * @param aType a type from java.sql.Types.*
+ * @param index index in ResultSet
+ * @return returns the value as String. If no conversion is possible
+ * /unsupported value/ is returned
*/
private String getValueAsString(ResultSet rs, int valueIndex, int aType)
throws StorageObjectFailure {
if (!rs.wasNull()) {
java.util.Date date = new java.util.Date(timestamp.getTime());
- outValue = _dateFormatterOut.format(date);
- _cal.setTime(date);
-
- int offset =
- _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET);
- String tzOffset =
- StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2);
- outValue = outValue + "+" + tzOffset;
+
+ Calendar calendar = new GregorianCalendar();
+ calendar.setTime(date);
+ calendar.setTimeZone(timezone);
+ outValue = internalDateFormat.format(date);
+
+ int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
+ String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
+
+ if (offset<0)
+ outValue = outValue + "-";
+ else
+ outValue = outValue + "+";
+ outValue = outValue + tzOffset;
}
break;
return outValue;
}
- /*
- * select-Operator um einen Datensatz zu bekommen.
- * @param id Primaerschluessel des Datensatzes.
- * @return liefert EntityObject des gefundenen Datensatzes oder null.
+ /**
+ * select-Operator um einen Datensatz zu bekommen.
+ * @param id Primaerschluessel des Datensatzes.
+ * @return liefert EntityObject des gefundenen Datensatzes oder null.
*/
public Entity selectById(String id) throws StorageObjectExc {
if ((id == null) || id.equals("")) {
}
/**
+ * This method makes it possible to make selects across multiple tables
+ *
+ * @param mainTablePrefix prefix for the mainTable
+ * @param extraTables a vector of tables for relational select
+ * @param aWhereClause whereClause
+ * @return EntityList of selected Objects
+ * @throws StorageObjectFailure
+ */
+
+ public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix,
+ List extraTables, String aWhereClause )
+ throws StorageObjectFailure {
+ return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, -1);
+ }
+
+ /**
* select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
* @param key Datenbankfeld der Bedingung.
* @param value Wert die der key anehmen muss.
}
/**
- * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
+ * select-Operator returns EntityList with matching rows in Database.
* @param aWhereClause where-Clause
* @param anOrderByClause orderBy-Clause
* @param offset ab welchem Datensatz
*/
public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
int offset, int limit) throws StorageObjectFailure {
+ return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
+ }
+ /**
+ * select-Operator returns EntityList with matching rows in Database.
+ * @param aWhereClause where-Clause
+ * @param anOrderByClause orderBy-Clause
+ * @param offset ab welchem Datensatz
+ * @param limit wieviele Datens?tze
+ * @return EntityList mit den gematchten Entities
+ * @exception StorageObjectException
+ */
+ public EntityList selectByWhereClause(String mainTablePrefix, List extraTables,
+ String aWhereClause, String anOrderByClause,
+ int offset, int limit) throws StorageObjectFailure {
+
+
+ String useTable = theTable;
+ String selectStar = "*";
+ if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
+ useTable+=" "+mainTablePrefix;
+ selectStar=mainTablePrefix.trim() + ".*";
+ }
+
// check o_store for entitylist
- if (StoreUtil.implementsStorableObject(theEntityClass)) {
- StoreIdentifier search_sid =
- new StoreIdentifier(
- theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
- StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));
- EntityList hit = (EntityList) o_store.use(search_sid);
-
- if (hit != null) {
- logger.debug("CACHE (hit): " + search_sid.toString());
-
- return hit;
+ // only if no relational select
+ if (extraTables==null) {
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {
+ StoreIdentifier search_sid =
+ new StoreIdentifier(
+ theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
+ StoreUtil.getEntityListUniqueIdentifierFor(useTable, aWhereClause, anOrderByClause, offset, limit));
+ EntityList hit = (EntityList) o_store.use(search_sid);
+
+ if (hit != null) {
+ logger.debug("CACHE (hit): " + search_sid.toString());
+
+ return hit;
+ }
}
}
// build sql-statement
- /** @todo count sql string should only be assembled if we really count
- * see below at the end of method //rk */
if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
aWhereClause = null;
}
StringBuffer countSql =
- new StringBuffer("select count(*) from ").append(theTable);
+ new StringBuffer("select count(*) from ").append(useTable);
StringBuffer selectSql =
- new StringBuffer("select * from ").append(theTable);
-
+ new StringBuffer("select "+selectStar+" from ").append(useTable);
+
+ // append extratables, if necessary
+ if (extraTables!=null) {
+ for (int i=0;i < extraTables.size();i++) {
+ if (!extraTables.get(i).equals("")) {
+ countSql.append( ", " + extraTables.get(i));
+ selectSql.append( ", " + extraTables.get(i));
+ }
+ }
+ }
+
if (aWhereClause != null) {
selectSql.append(" where ").append(aWhereClause);
countSql.append(" where ").append(aWhereClause);
selectSql.append(" order by ").append(anOrderByClause);
}
- if (theAdaptor.hasLimit()) {
- if ((limit > -1) && (offset > -1)) {
- selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
- }
+ if ((limit > -1) && (offset > -1)) {
+ selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
}
// execute sql
}
theReturnList = new EntityList();
-
Entity theResultEntity;
-
while (rs.next()) {
theResultEntity = makeEntityFromResultSet(rs);
theReturnList.add(theResultEntity);
offsetCount++;
}
-
rs.close();
}
// making entitylist infos
- if (!(theAdaptor.hasLimit())) {
- count = offsetCount;
- }
+ count = offsetCount;
if (theReturnList != null) {
// now we decide if we have to know an overall count...
if ((limit > -1) && (offset > -1)) {
if (offsetCount == limit) {
- /** @todo counting should be deffered to entitylist
- * getSize() should be used */
rs = executeSql(stmt, countSql.toString());
if (rs != null) {
theReturnList.setNextBatch(offset + limit);
}
- if (StoreUtil.implementsStorableObject(theEntityClass)) {
+ if (extraTables==null && StoreUtil.implementsStorableObject(theEntityClass)) {
StoreIdentifier sid = theReturnList.getStoreIdentifier();
logger.debug("CACHE (add): " + sid.toString());
o_store.add(sid);
}
}
- } catch (SQLException sqe) {
+ }
+ catch (SQLException sqe) {
throwSQLException(sqe, "selectByWhereClause");
- } finally {
+ }
+ finally {
try {
if (con != null) {
freeConnection(con, stmt);
if (theEntityClass != null) {
returnEntity = (Entity) theEntityClass.newInstance();
- returnEntity.setValues(theResultHash);
returnEntity.setStorage(this);
+ returnEntity.setValues(theResultHash);
if (returnEntity instanceof StorableObject) {
logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
aValue = null;
// exceptions
- if (aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange")) {
+ if (!theEntity.hasValueForField(aField) && (
+ aField.equals("webdb_create") ||
+ aField.equals("webdb_lastchange"))) {
aValue = "NOW()";
}
else {
if ((streamedInput != null) && streamedInput.contains(aField)) {
aValue = "?";
- } else {
+ }
+ else {
if (theEntity.hasValueForField(aField)) {
aValue =
"'" +
- JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(
- aField)) + "'";
+ JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";
}
}
}
return null;
}
- pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL(this));
+ pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");
ResultSet rs = pstmt.executeQuery();
rs.next();
// TimeStamp stuff
try {
- java.util.Date d = _dateFormatterIn.parse(dateString);
- Timestamp tStamp = new Timestamp(d.getTime());
- sql.append(",webdb_create='" + tStamp.toString() + "'");
- } catch (ParseException e) {
+ java.util.Date d = userInputDateFormat.parse(dateString);
+// Timestamp tStamp = new Timestamp(d.getTime());
+ sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
+ }
+ catch (ParseException e) {
throw new StorageObjectFailure(e);
}
}
return (res > 0) ? true : false;
}
- /* noch nicht implementiert.
- * @return immer false
- */
- public boolean delete(EntityList theEntityList) {
- invalidatePopupCache();
-
- return false;
- }
-
/**
- * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
- * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
- * @return null
- */
- public SimpleList getPopupData() throws StorageObjectFailure {
- return null;
- }
-
- /**
- * Holt Daten fuer Popups.
- * @param name Name des Feldes.
- * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
- * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
- */
- public SimpleList getPopupData(String name, boolean hasNullValue)
- throws StorageObjectFailure {
- return getPopupData(name, hasNullValue, null);
- }
-
- /**
- * Holt Daten fuer Popups.
- * @param name Name des Feldes.
- * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
- * @param where Schraenkt die Selektion der Datensaetze ein.
- * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
- */
- public SimpleList getPopupData(String name, boolean hasNullValue, String where)
- throws StorageObjectFailure {
- return getPopupData(name, hasNullValue, where, null);
- }
-
- /**
- * Holt Daten fuer Popups.
- * @param name Name des Feldes.
- * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
- * @param where Schraenkt die Selektion der Datensaetze ein.
- * @param order Gibt ein Feld als Sortierkriterium an.
- * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
+ * Deletes entities based on a where clause
+ *
+ * @param aWhereClause
+ * @return
+ * @throws StorageObjectFailure
*/
- public SimpleList getPopupData(String name, boolean hasNullValue,
- String where, String order) throws StorageObjectFailure {
- // caching
- if (hasPopupCache && (popupCache != null)) {
- return popupCache;
+ public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
+ invalidatePopupCache();
+ if (StoreUtil.implementsStorableObject(theEntityClass)) {
+ StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
+ o_store.invalidate(stoc_type);
}
- SimpleList simpleList = null;
- Connection con = null;
Statement stmt = null;
+ Connection con = null;
+ int res = 0;
+ String sql =
+ "delete from " + theTable + " where " + aWhereClause;
- // build sql
- StringBuffer sql =
- new StringBuffer("select ").append(thePKeyName).append(",").append(name)
- .append(" from ").append(theTable);
-
- if ((where != null) && !(where.length() == 0)) {
- sql.append(" where ").append(where);
- }
-
- sql.append(" order by ");
-
- if ((order != null) && !(order.length() == 0)) {
- sql.append(order);
- } else {
- sql.append(name);
- }
-
- // execute sql
+ //theLog.printInfo("DELETE " + sql);
try {
con = getPooledCon();
- } catch (Exception e) {
- throw new StorageObjectFailure(e);
- }
-
- try {
stmt = con.createStatement();
-
- ResultSet rs = executeSql(stmt, sql.toString());
-
- if (rs != null) {
- if (!evaluatedMetaData) {
- get_meta_data();
- }
-
- simpleList = new SimpleList();
-
- // if popup has null-selector
- if (hasNullValue) {
- simpleList.add(POPUP_EMPTYLINE);
- }
-
- SimpleHash popupDict;
-
- while (rs.next()) {
- popupDict = new SimpleHash();
- popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
- popupDict.put("value", rs.getString(2));
- simpleList.add(popupDict);
- }
-
- rs.close();
- }
+ res = stmt.executeUpdate(sql);
}
- catch (Exception e) {
- logger.error("getPopupData: " + e.getMessage());
- throw new StorageObjectFailure(e);
- } finally {
- freeConnection(con, stmt);
+ catch (SQLException sqe) {
+ throwSQLException(sqe, "delete");
}
-
- if (hasPopupCache) {
- popupCache = simpleList;
+ finally {
+ freeConnection(con, stmt);
}
- return simpleList;
+ return res;
}
- /**
- * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
- * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
- * Tabellen Verwendung finden.
- * @return SimpleHash mit den Tabellezeilen.
+ /* noch nicht implementiert.
+ * @return immer false
*/
- public SimpleHash getHashData() {
- /** @todo dangerous! this should have a flag to be enabled, otherwise
- * very big Hashes could be returned */
- if (hashCache == null) {
- try {
- hashCache =
- HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1));
- }
- catch (StorageObjectFailure e) {
- logger.debug(e.getMessage());
- }
- }
+ public boolean delete(EntityList theEntityList) {
+ invalidatePopupCache();
- return hashCache;
+ return false;
}
/* invalidates the popupCache
return rs;
}
-
+/*
public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
long startTime = System.currentTimeMillis();
+ Connection connection = null;
+ Statement statement = null;
try {
- Connection connection = getPooledCon();
- Statement statement = connection.createStatement();
+ connection = getPooledCon();
+ statement = connection.createStatement();
ResultSet result;
result = statement.executeQuery(sql);
logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
throw new StorageObjectFailure(e);
}
+ finally {
+ if (connection!=null) {
+ freeConnection(connection, statement);
+ }
+ }
}
-
+*/
private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
try {
Map result = new HashMap();
}
public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
+ Connection connection = null;
+ Statement statement = null;
try {
- ResultSet resultset = executeSql(sql);
List result = new Vector();
-
- while (resultset.next() && result.size() < aLimit) {
- result.add(processRow(resultset));
+ connection = getPooledCon();
+ statement = connection.createStatement();
+ ResultSet resultset = executeSql(statement, sql);
+ try {
+ while (resultset.next() && result.size() < aLimit) {
+ result.add(processRow(resultset));
+ }
+ }
+ finally {
+ resultset.close();
}
return result;
catch (Throwable e) {
throw new StorageObjectFailure(e);
}
+ finally {
+ if (connection!=null) {
+ freeConnection(connection, statement);
+ }
+ }
};
- public Map executeFreeSingleRowSql(String sql) throws StorageObjectFailure, StorageObjectExc {
+ public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
try {
- ResultSet resultset = executeSql(sql);
-
- if (resultset.next())
- return processRow(resultset);
- else
- return null;
+ List resultList = executeFreeSql(anSqlStatement, 1);
+ try {
+ if (resultList.size()>0)
+ return (Map) resultList.get(0);
+ else
+ return null;
+ }
+ finally {
+ }
}
catch (Throwable t) {
throw new StorageObjectFailure(t);