2 * Copyright (C) 2001-2006 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 * and distribute linked combinations including the two. You must obey the
23 * GNU General Public License in all respects for all of the code used other than
24 * the above mentioned libraries. If you modify this file, you may extend this
25 * exception to your version of the file, but you are not obligated to do so.
26 * If you do not wish to do so, delete this exception statement from your version.
30 import mir.config.MirPropertiesConfiguration;
31 import mir.entity.AbstractEntity;
32 import mir.entity.Entity;
33 import mir.entity.EntityList;
34 import mir.entity.StorableObjectEntity;
35 import mir.log.LoggerWrapper;
36 import mir.storage.store.*;
37 import mir.util.JDBCStringRoutines;
38 import mir.util.StreamCopier;
39 import mircoders.global.MirGlobal;
40 import org.apache.commons.dbcp.DelegatingConnection;
41 import org.postgresql.PGConnection;
42 import org.postgresql.largeobject.LargeObject;
43 import org.postgresql.largeobject.LargeObjectManager;
45 import java.io.ByteArrayOutputStream;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
49 import java.text.ParseException;
50 import java.text.SimpleDateFormat;
54 * Implements database access.
56 * @version $Id: Database.java,v 1.44.2.36 2006/08/10 19:29:36 zapata Exp $
61 public class Database {
62 private static final int DEFAULT_LIMIT = 20;
63 private static final Class GENERIC_ENTITY_CLASS = StorableObjectEntity.class;
64 protected static final ObjectStore o_store = ObjectStore.getInstance();
66 protected LoggerWrapper logger;
68 protected String mainTable;
69 protected String primaryKeyField = "id";
71 private List fieldNames;
72 private int[] fieldTypes;
73 private Map fieldNameToType;
75 protected Class entityClass;
78 private Set binaryFields;
80 private TimeZone timezone;
81 private SimpleDateFormat userInputDateFormat;
83 public Database() throws DatabaseFailure {
84 MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
85 logger = new LoggerWrapper("Database");
86 timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
88 userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
89 userInputDateFormat.setTimeZone(timezone);
91 binaryFields = new HashSet();
93 String adapterName = configuration.getString("Database.Adaptor");
96 entityClass = GENERIC_ENTITY_CLASS;
99 logger.error("Error in Database() constructor with " + adapterName + " -- " + e.getMessage());
100 throw new DatabaseFailure("Error in Database() constructor.", e);
104 public Class getEntityClass() {
108 public Entity createNewEntity() throws DatabaseFailure {
110 AbstractEntity result = (AbstractEntity) entityClass.newInstance();
111 result.setStorage(this);
115 catch (Throwable t) {
116 throw new DatabaseFailure(t);
120 public String getIdFieldName() {
121 return primaryKeyField;
124 public String getTableName() {
129 * Returns a list of field names for this <code>Database</code>
131 public List getFieldNames() throws DatabaseFailure {
132 if (fieldNames == null) {
139 public boolean hasField(String aFieldName) {
140 return getFieldNames().contains(aFieldName);
144 * Gets value out of ResultSet according to type and converts to String
146 * @param aResultSet ResultSet.
147 * @param aType a type from java.sql.Types.*
148 * @param aFieldIndex index in ResultSet
149 * @return returns the value as String. If no conversion is possible
150 * /unsupported value/ is returned
152 private String getValueAsString(ResultSet aResultSet, int aFieldIndex, int aType)
153 throws DatabaseFailure {
154 String outValue = null;
156 if (aResultSet != null) {
159 case java.sql.Types.BIT:
160 outValue = (aResultSet.getBoolean(aFieldIndex) == true) ? "1" : "0";
164 case java.sql.Types.INTEGER:
165 case java.sql.Types.SMALLINT:
166 case java.sql.Types.TINYINT:
167 case java.sql.Types.BIGINT:
169 int out = aResultSet.getInt(aFieldIndex);
171 if (!aResultSet.wasNull()) {
172 outValue = new Integer(out).toString();
177 case java.sql.Types.NUMERIC:
178 long outl = aResultSet.getLong(aFieldIndex);
180 if (!aResultSet.wasNull()) {
181 outValue = new Long(outl).toString();
186 case java.sql.Types.REAL:
188 float tempf = aResultSet.getFloat(aFieldIndex);
190 if (!aResultSet.wasNull()) {
194 int tempf_int = (int) tempf;
195 tempf = (float) tempf_int;
197 outValue = "" + tempf;
198 outValue = outValue.replace('.', ',');
203 case java.sql.Types.DOUBLE:
205 double tempd = aResultSet.getDouble(aFieldIndex);
207 if (!aResultSet.wasNull()) {
211 int tempd_int = (int) tempd;
212 tempd = (double) tempd_int;
214 outValue = "" + tempd;
215 outValue = outValue.replace('.', ',');
220 case java.sql.Types.CHAR:
221 case java.sql.Types.VARCHAR:
222 case java.sql.Types.LONGVARCHAR:
223 outValue = aResultSet.getString(aFieldIndex);
227 case java.sql.Types.LONGVARBINARY:
228 outValue = aResultSet.getString(aFieldIndex);
232 case java.sql.Types.TIMESTAMP:
234 // it's important to use Timestamp here as getting it
235 // as a string is undefined and is only there for debugging
236 // according to the API. we can make it a string through formatting.
238 Timestamp timestamp = (aResultSet.getTimestamp(aFieldIndex));
240 if (!aResultSet.wasNull()) {
241 java.util.Date date = new java.util.Date(timestamp.getTime());
242 outValue = DatabaseHelper.convertDateToInternalRepresenation(date);
248 outValue = "<unsupported value>";
249 logger.warn("Unsupported Datatype: at " + aFieldIndex + " (" + aType + ")");
252 catch (SQLException e) {
253 throw new DatabaseFailure("Could not get Value out of Resultset -- ",
262 * Return an entity specified by id
264 public Entity selectById(String anId) throws DatabaseExc {
265 if ((anId == null) || anId.equals("")) {
266 throw new DatabaseExc("Database.selectById: Missing id");
269 // ask object store for object
270 if (StoreUtil.extendsStorableEntity(entityClass)) {
271 String uniqueId = anId;
273 if (entityClass.equals(StorableObjectEntity.class)) {
274 uniqueId += ("@" + mainTable);
277 StoreIdentifier search_sid = new StoreIdentifier(entityClass, uniqueId);
278 logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
280 Entity hit = (Entity) o_store.use(search_sid);
287 Connection con = obtainConnection();
288 Entity returnEntity = null;
289 PreparedStatement statement = null;
293 String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?";
295 statement = con.prepareStatement(query);
296 statement.setString(1, anId);
298 logQueryBefore(query);
300 long startTime = System.currentTimeMillis();
302 rs = statement.executeQuery();
304 logQueryAfter(query, (System.currentTimeMillis() - startTime));
306 catch (SQLException e) {
307 logQueryError(query, (System.currentTimeMillis() - startTime), e);
313 returnEntity = makeEntityFromResultSet(rs);
316 logger.warn("No data for id: " + anId + " in table " + mainTable);
322 logger.warn("No Data for Id " + anId + " in Table " + mainTable);
325 catch (Throwable e) {
326 throw new DatabaseFailure(e);
329 freeConnection(con, statement);
335 public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, List extraTables, String aWhereClause) throws DatabaseExc, DatabaseFailure {
336 return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, DEFAULT_LIMIT);
339 public EntityList selectByFieldValue(String aField, String aValue) throws DatabaseExc, DatabaseFailure {
340 return selectByFieldValue(aField, aValue, 0);
343 public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure {
344 return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset);
347 public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure {
348 return selectByWhereClause(where, 0);
351 public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure {
352 return selectByWhereClause(whereClause, null, offset);
355 public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws DatabaseExc, DatabaseFailure {
356 return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, DEFAULT_LIMIT);
359 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure {
360 return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT);
363 public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
364 int offset, int limit) throws DatabaseExc, DatabaseFailure {
365 return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
368 public EntityList selectByWhereClause(
369 String aMainTablePrefix, List anExtraTables,
370 String aWhereClause, String anOrderByClause,
371 int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure {
373 if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){
377 // check o_store for entitylist
378 // only if no relational select
379 if (anExtraTables==null) {
380 if (StoreUtil.extendsStorableEntity(entityClass)) {
381 StoreIdentifier searchSid = new StoreIdentifier(entityClass,
382 StoreContainerType.STOC_TYPE_ENTITYLIST,
383 StoreUtil.getEntityListUniqueIdentifierFor(mainTable,
384 aWhereClause, anOrderByClause, anOffset, aLimit));
385 EntityList hit = (EntityList) o_store.use(searchSid);
393 RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
395 EntityList result = null;
396 Connection connection = null;
398 if (anExtraTables!=null) {
399 Iterator i = anExtraTables.iterator();
400 while (i.hasNext()) {
401 String table = (String) i.next();
402 if (!"".equals(table)) {
403 retriever.addExtraTable(table);
408 if (aWhereClause != null) {
409 retriever.appendWhereClause(aWhereClause);
412 if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
413 retriever.appendOrderByClause(anOrderByClause);
416 if (anOffset>-1 && aLimit>-1) {
417 retriever.setLimit(aLimit+1);
418 retriever.setOffset(anOffset);
421 Iterator i = getFieldNames().iterator();
422 while (i.hasNext()) {
423 retriever.addField((String) i.next());
428 connection = obtainConnection();
429 ResultSet resultSet = retriever.execute(connection);
431 boolean hasMore = false;
433 if (resultSet != null) {
434 result = new EntityList();
438 while (((aLimit == -1) || (position<aLimit)) && resultSet.next()) {
439 entity = makeEntityFromResultSet(resultSet);
444 hasMore = resultSet.next();
448 if (result != null) {
449 result.setOffset(anOffset);
450 result.setWhere(aWhereClause);
451 result.setOrder(anOrderByClause);
452 result.setStorage(this);
453 result.setLimit(aLimit);
456 result.setNextBatch(anOffset + aLimit);
459 if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
460 StoreIdentifier sid = result.getStoreIdentifier();
461 logger.debug("CACHE (add): " + sid.toString());
466 catch (Throwable e) {
467 throw new DatabaseFailure(e);
471 if (connection != null) {
472 freeConnection(connection);
474 } catch (Throwable t) {
481 private Entity makeEntityFromResultSet(ResultSet rs) {
482 Map fields = new HashMap();
483 String theResult = null;
485 Entity returnEntity = null;
488 if (StoreUtil.extendsStorableEntity(entityClass)) {
489 StoreIdentifier searchSid = StorableObjectEntity.getStoreIdentifier(this,
491 Entity hit = (Entity) o_store.use(searchSid);
492 if (hit != null) return hit;
495 for (int i = 0; i < getFieldNames().size(); i++) {
496 type = fieldTypes[i];
498 if (type == java.sql.Types.LONGVARBINARY) {
499 InputStreamReader is =
500 (InputStreamReader) rs.getCharacterStream(i + 1);
503 char[] data = new char[32768];
504 StringBuffer theResultString = new StringBuffer();
507 while ((len = is.read(data)) > 0) {
508 theResultString.append(data, 0, len);
512 theResult = theResultString.toString();
519 theResult = getValueAsString(rs, (i + 1), type);
522 if (theResult != null) {
523 fields.put(getFieldNames().get(i), theResult);
527 if (entityClass != null) {
528 returnEntity = createNewEntity();
529 returnEntity.setFieldValues(fields);
531 if (returnEntity instanceof StorableObject) {
532 logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + mainTable);
533 o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
537 throw new DatabaseExc("Internal Error: entityClass not set!");
540 catch (Throwable e) {
541 throw new DatabaseFailure(e);
548 * Inserts an entity into the database.
551 * @return the value of the primary key of the inserted record
553 public String insert(Entity anEntity) throws DatabaseFailure {
556 RecordInserter inserter =
557 new RecordInserter(mainTable, getPrimaryKeySequence());
559 String returnId = null;
560 Connection con = null;
566 for (int i = 0; i < getFieldNames().size(); i++) {
567 fieldName = (String) getFieldNames().get(i);
569 if (!fieldName.equals(primaryKeyField)) {
571 if (!anEntity.hasFieldValue(fieldName) && (
572 fieldName.equals("webdb_create") ||
573 fieldName.equals("webdb_lastchange"))) {
574 inserter.assignVerbatim(fieldName, "now()");
577 if (anEntity.hasFieldValue(fieldName)) {
578 inserter.assignString(fieldName, anEntity.getFieldValue(fieldName));
584 con = obtainConnection();
585 returnId = inserter.execute(con);
587 anEntity.setId(returnId);
597 * Updates an entity in the database
601 public void update(Entity theEntity) throws DatabaseFailure {
604 RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
606 // build sql statement
607 for (int i = 0; i < getFieldNames().size(); i++) {
608 String field = (String) getFieldNames().get(i);
610 if (!(field.equals(primaryKeyField) ||
611 "webdb_create".equals(field) ||
612 "webdb_lastchange".equals(field) ||
613 binaryFields.contains(field))) {
615 if (theEntity.hasFieldValue(field)) {
616 generator.assignString(field, theEntity.getFieldValue(field));
622 if (hasField("webdb_lastchange")) {
623 generator.assignVerbatim("webdb_lastchange", "now()");
626 // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
627 // format so anything extra will be ignored. -mh
628 if (hasField("webdb_create") &&
629 theEntity.hasFieldValue("webdb_create")) {
630 // minimum of 10 (yyyy-mm-dd)...
631 if (theEntity.getFieldValue("webdb_create").length() >= 10) {
632 String dateString = theEntity.getFieldValue("webdb_create");
634 // if only 10, then add 00:00 so it doesn't throw a ParseException
635 if (dateString.length() == 10) {
636 dateString = dateString + " 00:00";
641 java.util.Date d = userInputDateFormat.parse(dateString);
642 generator.assignDateTime("webdb_create", d);
644 catch (ParseException e) {
645 throw new DatabaseFailure(e);
649 Connection connection = null;
652 connection = obtainConnection();
653 generator.execute(connection);
656 freeConnection(connection);
660 private void invalidateObject(String anId) {
661 // ostore send notification
662 if (StoreUtil.extendsStorableEntity(entityClass)) {
663 String uniqueId = anId;
665 if (entityClass.equals(StorableObjectEntity.class)) {
666 uniqueId += ("@" + mainTable);
669 logger.debug("CACHE: (del) " + anId);
671 StoreIdentifier search_sid =
672 new StoreIdentifier(entityClass,
673 StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
674 o_store.invalidate(search_sid);
680 * @param id des zu loeschenden Datensatzes
681 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
683 public boolean delete(String id) throws DatabaseFailure {
684 invalidateObject(id);
687 Connection connection = obtainConnection();
688 PreparedStatement statement = null;
691 statement = connection.prepareStatement("delete from " + mainTable + " where " + primaryKeyField + "=?");
692 statement.setInt(1, Integer.parseInt(id));
693 logQueryBefore("delete from " + mainTable + " where " + primaryKeyField + "=" + id + "");
694 resultCode = statement.executeUpdate();
696 catch (SQLException e) {
697 logger.warn("Can't delete record", e);
700 freeConnection(connection, statement);
705 return (resultCode > 0) ? true : false;
709 * Deletes entities based on a where clause
711 public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure {
714 Statement stmt = null;
715 Connection con = null;
718 "delete from " + mainTable + " where " + aWhereClause;
720 //theLog.printInfo("DELETE " + sql);
722 con = obtainConnection();
723 stmt = con.createStatement();
724 res = stmt.executeUpdate(sql);
726 catch (Throwable e) {
727 throw new DatabaseFailure(e);
730 freeConnection(con, stmt);
736 /* noch nicht implementiert.
737 * @return immer false
739 public boolean delete(EntityList theEntityList) {
743 public ResultSet executeSql(Statement stmt, String sql)
744 throws DatabaseFailure, SQLException {
747 long startTime = System.currentTimeMillis();
749 rs = stmt.executeQuery(sql);
751 logQueryAfter(sql, (System.currentTimeMillis() - startTime));
753 catch (SQLException e) {
754 logQueryError(sql, (System.currentTimeMillis() - startTime), e);
761 private Map processRow(ResultSet aResultSet) throws DatabaseFailure {
763 Map result = new HashMap();
764 ResultSetMetaData metaData = aResultSet.getMetaData();
765 int nrColumns = metaData.getColumnCount();
766 for (int i=0; i<nrColumns; i++) {
767 result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
772 catch (Throwable e) {
773 throw new DatabaseFailure(e);
778 * Executes 1 sql statement and returns the results as a <code>List</code> of
781 public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc {
782 Connection connection = null;
783 Statement statement = null;
785 List result = new ArrayList();
786 connection = obtainConnection();
787 statement = connection.createStatement();
788 ResultSet resultset = executeSql(statement, sql);
790 while (resultset.next() && result.size() < aLimit) {
791 result.add(processRow(resultset));
800 catch (Throwable e) {
801 throw new DatabaseFailure(e);
804 if (connection!=null) {
805 freeConnection(connection, statement);
811 * Executes 1 sql statement and returns the first result row as a <code>Map</code>s
812 * (<code>null</code> if there wasn't any row)
814 public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc {
816 List resultList = executeFreeSql(anSqlStatement, 1);
818 if (resultList.size()>0)
819 return (Map) resultList.get(0);
825 catch (Throwable t) {
826 throw new DatabaseFailure(t);
831 * Executes 1 sql statement and returns the first column of the first result row as a <code>String</code>s
832 * (<code>null</code> if there wasn't any row)
834 public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc {
835 Map row = executeFreeSingleRowSql(sql);
840 Iterator i = row.values().iterator();
842 return (String) i.next();
846 public int getSize(String where) throws SQLException, DatabaseFailure {
847 return getSize("", null, where);
850 * returns the number of rows in the table
852 public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure {
854 String useTable = mainTable;
855 if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
856 useTable+=" "+mainTablePrefix;
858 StringBuffer countSql =
859 new StringBuffer("select count(*) from ").append(useTable);
860 // append extratables, if necessary
861 if (extraTables!=null) {
862 for (int i=0;i < extraTables.size();i++) {
863 if (!extraTables.get(i).equals("")) {
864 countSql.append( ", " + extraTables.get(i));
869 if ((where != null) && (where.length() != 0)) {
870 countSql.append( " where " + where);
873 Connection con = null;
874 Statement stmt = null;
876 logQueryBefore(countSql.toString());
877 long startTime = System.currentTimeMillis();
880 con = obtainConnection();
881 stmt = con.createStatement();
883 ResultSet rs = executeSql(stmt, countSql.toString());
886 result = rs.getInt(1);
889 catch (SQLException e) {
890 logger.error("Database.getSize: " + e.getMessage());
893 freeConnection(con, stmt);
895 logQueryAfter(countSql.toString(), (System.currentTimeMillis() - startTime));
900 public int executeUpdate(Statement stmt, String sql)
901 throws DatabaseFailure, SQLException {
905 long startTime = System.currentTimeMillis();
908 rs = stmt.executeUpdate(sql);
910 logQueryAfter(sql, (System.currentTimeMillis() - startTime));
912 catch (SQLException e) {
913 logQueryError(sql, (System.currentTimeMillis() - startTime), e);
920 public int executeUpdate(String sql)
921 throws DatabaseFailure, SQLException {
923 Connection con = null;
924 PreparedStatement pstmt = null;
927 long startTime = System.currentTimeMillis();
929 con = obtainConnection();
930 pstmt = con.prepareStatement(sql);
931 result = pstmt.executeUpdate();
932 logQueryAfter(sql, System.currentTimeMillis() - startTime);
934 catch (Throwable e) {
935 logQueryError(sql, System.currentTimeMillis() - startTime, e);
936 throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
939 freeConnection(con, pstmt);
945 * Processes the metadata for the table this Database object is responsible for.
947 private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure {
948 fieldNames = new ArrayList();
949 fieldNameToType = new HashMap();
952 int numFields = aMetaData.getColumnCount();
953 fieldTypes = new int[numFields];
955 for (int i = 1; i <= numFields; i++) {
956 fieldNames.add(aMetaData.getColumnName(i));
957 fieldTypes[i - 1] = aMetaData.getColumnType(i);
958 fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i)));
961 catch (Throwable e) {
962 throw new DatabaseFailure(e);
967 * Retrieves metadata from the table this Database object represents
969 private void acquireMetaData() throws DatabaseFailure {
970 Connection connection = null;
971 PreparedStatement statement = null;
972 String sql = "select * from " + mainTable + " where 0=1";
975 connection = obtainConnection();
976 statement = connection.prepareStatement(sql);
978 logger.debug("METADATA: " + sql);
979 ResultSet resultSet = statement.executeQuery();
981 processMetaData(resultSet.getMetaData());
987 catch (Throwable e) {
988 throw new DatabaseFailure(e);
991 freeConnection(connection, statement);
995 public Connection obtainConnection() throws DatabaseFailure {
997 return MirGlobal.getDatabaseEngine().obtainConnection();
999 catch (Exception e) {
1000 throw new DatabaseFailure(e);
1004 public void freeConnection(Connection aConnection) throws DatabaseFailure {
1006 MirGlobal.getDatabaseEngine().releaseConnection(aConnection);
1008 catch (Throwable t) {
1009 logger.warn("Can't release connection: " + t.toString());
1013 public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure {
1017 catch (Throwable t) {
1018 logger.warn("Can't close statement", t);
1021 freeConnection(aConnection);
1024 protected void _throwStorageObjectException(Exception e, String aFunction)
1025 throws DatabaseFailure {
1028 logger.error(e.getMessage() + aFunction);
1029 throw new DatabaseFailure(aFunction, e);
1035 * Invalidates any cached entity list
1037 private void invalidateStore() {
1038 // invalidating all EntityLists corresponding with entityClass
1039 if (StoreUtil.extendsStorableEntity(entityClass)) {
1040 StoreContainerType stoc_type =
1041 StoreContainerType.valueOf(entityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
1042 o_store.invalidate(stoc_type);
1047 * Retrieves a binary value
1049 public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException {
1050 Connection connection=null;
1051 Statement statement=null;
1052 InputStream inputStream;
1055 connection = obtainConnection();
1057 connection.setAutoCommit(false);
1058 statement = connection.createStatement();
1059 ResultSet resultSet = executeSql(statement, aQuery);
1061 if(resultSet!=null) {
1062 if (resultSet.next()) {
1063 if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
1064 return resultSet.getBytes(1);
1067 inputStream = resultSet.getBlob(1).getBinaryStream();
1068 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1069 StreamCopier.copy(inputStream, outputStream);
1070 return outputStream.toByteArray();
1078 connection.setAutoCommit(true);
1080 catch (Throwable e) {
1081 logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
1082 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1086 freeConnection(connection, statement);
1088 catch (Throwable e) {
1089 logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
1094 catch (Throwable t) {
1095 logger.error("EntityImages.getImage failed: " + t.toString());
1096 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1098 throw new DatabaseFailure(t);
1105 * Sets a binary value for a particular field in a record specified by its identifier
1107 public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException {
1108 PreparedStatement statement = null;
1109 Connection connection = obtainConnection();
1112 connection.setAutoCommit(false);
1114 // are we using bytea ?
1115 if (getFieldType(aFieldName) == java.sql.Types.BINARY) {
1116 statement = connection.prepareStatement(
1117 "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
1118 statement.setBytes(1, aData);
1119 statement.execute();
1120 connection.commit();
1124 PGConnection postgresqlConnection = (org.postgresql.PGConnection) ((DelegatingConnection) connection).getDelegate();
1125 LargeObjectManager lobManager = postgresqlConnection.getLargeObjectAPI();
1126 int oid = lobManager.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
1127 LargeObject obj = lobManager.open(oid, LargeObjectManager.WRITE); // Now open the file File file =
1130 statement = connection.prepareStatement(
1131 "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
1132 statement.setInt(1, oid);
1133 statement.execute();
1134 connection.commit();
1138 connection.setAutoCommit(true);
1142 freeConnection(connection, statement);
1147 * Can be overridden to specify a primary key sequence name not named according to
1148 * the convention (tablename _id_seq)
1150 protected String getPrimaryKeySequence() {
1151 return mainTable+"_id_seq";
1155 * Can be called by subclasses to specify fields that are binary, and that shouldn't
1156 * be updated outside of {@link #setBinaryField}
1158 * @param aBinaryField The field name of the binary field
1160 protected void markBinaryField(String aBinaryField) {
1161 binaryFields.add(aBinaryField);
1164 private void logQueryBefore(String aQuery) {
1165 logger.debug("about to perform QUERY " + aQuery);
1166 // (new Throwable()).printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1169 private void logQueryAfter(String aQuery, long aTime) {
1170 logger.info("QUERY " + aQuery + " took " + aTime + "ms.");
1173 private void logQueryError(String aQuery, long aTime, Throwable anException) {
1174 logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());
1177 private int getFieldType(String aFieldName) {
1178 if (fieldNameToType == null) {
1182 return ((Integer) fieldNameToType.get(aFieldName)).intValue();