added:
[mir.git] / source / mir / storage / Database.java
1 /*
2  * Copyright (C) 2001-2006 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
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.
10  *
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.
15  *
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
19  *
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.
27  */
28 package mir.storage;
29
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;
44
45 import java.io.ByteArrayOutputStream;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
48 import java.sql.*;
49 import java.text.ParseException;
50 import java.text.SimpleDateFormat;
51 import java.util.*;
52
53 /**
54  * Implements database access.
55  *
56  * @version $Id: Database.java,v 1.44.2.37 2006/12/25 20:10:22 zapata Exp $
57  * @author rk
58  * @author Zapata
59  *
60  */
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();
65
66   protected LoggerWrapper logger;
67
68   protected String mainTable;
69   protected String primaryKeyField = "id";
70
71   private List fieldNames;
72   private int[] fieldTypes;
73   private Map fieldNameToType;
74
75   protected Class entityClass;
76
77   //
78   private Set binaryFields;
79
80   private TimeZone timezone;
81   private SimpleDateFormat userInputDateFormat;
82
83   public Database() throws DatabaseFailure {
84     MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
85     logger = new LoggerWrapper("Database");
86     timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
87
88     userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
89     userInputDateFormat.setTimeZone(timezone);
90
91     binaryFields = new HashSet();
92
93     String adapterName = configuration.getString("Database.Adaptor");
94
95     try {
96       entityClass = GENERIC_ENTITY_CLASS;
97     }
98     catch (Throwable e) {
99       logger.error("Error in Database() constructor with " + adapterName + " -- " + e.getMessage());
100       throw new DatabaseFailure("Error in Database() constructor.", e);
101     }
102   }
103
104   public Class getEntityClass() {
105     return entityClass;
106   }
107
108   public Entity createNewEntity() throws DatabaseFailure {
109     try {
110       AbstractEntity result = (AbstractEntity) entityClass.newInstance();
111       result.setStorage(this);
112
113       return result;
114     }
115     catch (Throwable t) {
116       throw new DatabaseFailure(t);
117     }
118   }
119
120   public String getIdFieldName() {
121     return primaryKeyField;
122   }
123
124   public String getTableName() {
125     return mainTable;
126   }
127
128   /**
129    * Returns a list of field names for this <code>Database</code>
130    */
131   public List getFieldNames() throws DatabaseFailure {
132     if (fieldNames == null) {
133       acquireMetaData();
134     }
135
136     return fieldNames;
137   }
138
139   public boolean hasField(String aFieldName) {
140     return getFieldNames().contains(aFieldName);
141   }
142
143   /**
144    *   Gets value out of ResultSet according to type and converts to String
145    *
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
151    */
152   private String getValueAsString(ResultSet aResultSet, int aFieldIndex, int aType)
153     throws DatabaseFailure {
154     String outValue = null;
155
156     if (aResultSet != null) {
157       try {
158         switch (aType) {
159           case java.sql.Types.BIT:
160             outValue = (aResultSet.getBoolean(aFieldIndex) == true) ? "1" : "0";
161
162             break;
163
164           case java.sql.Types.INTEGER:
165           case java.sql.Types.SMALLINT:
166           case java.sql.Types.TINYINT:
167           case java.sql.Types.BIGINT:
168
169             int out = aResultSet.getInt(aFieldIndex);
170
171             if (!aResultSet.wasNull()) {
172               outValue = new Integer(out).toString();
173             }
174
175             break;
176
177           case java.sql.Types.NUMERIC:
178             long outl = aResultSet.getLong(aFieldIndex);
179
180             if (!aResultSet.wasNull()) {
181               outValue = new Long(outl).toString();
182             }
183
184             break;
185
186           case java.sql.Types.REAL:
187
188             float tempf = aResultSet.getFloat(aFieldIndex);
189
190             if (!aResultSet.wasNull()) {
191               tempf *= 10;
192               tempf += 0.5;
193
194               int tempf_int = (int) tempf;
195               tempf = (float) tempf_int;
196               tempf /= 10;
197               outValue = "" + tempf;
198               outValue = outValue.replace('.', ',');
199             }
200
201             break;
202
203           case java.sql.Types.DOUBLE:
204
205             double tempd = aResultSet.getDouble(aFieldIndex);
206
207             if (!aResultSet.wasNull()) {
208               tempd *= 10;
209               tempd += 0.5;
210
211               int tempd_int = (int) tempd;
212               tempd = (double) tempd_int;
213               tempd /= 10;
214               outValue = "" + tempd;
215               outValue = outValue.replace('.', ',');
216             }
217
218             break;
219
220           case java.sql.Types.CHAR:
221           case java.sql.Types.VARCHAR:
222           case java.sql.Types.LONGVARCHAR:
223             outValue = aResultSet.getString(aFieldIndex);
224
225             break;
226
227           case java.sql.Types.LONGVARBINARY:
228             outValue = aResultSet.getString(aFieldIndex);
229
230             break;
231
232           case java.sql.Types.TIMESTAMP:
233
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.
237             // -mh
238             Timestamp timestamp = (aResultSet.getTimestamp(aFieldIndex));
239
240             if (!aResultSet.wasNull()) {
241               java.util.Date date = new java.util.Date(timestamp.getTime());
242               outValue = DatabaseHelper.convertDateToInternalRepresenation(date);
243             }
244
245             break;
246
247           default:
248             outValue = "<unsupported value>";
249             logger.warn("Unsupported Datatype: at " + aFieldIndex + " (" + aType + ")");
250         }
251       }
252       catch (SQLException e) {
253         throw new DatabaseFailure("Could not get Value out of Resultset -- ",
254           e);
255       }
256     }
257
258     return outValue;
259   }
260
261   /**
262    * Return an entity specified by id, or <code>null</code> if no such
263    * entity exists.
264    */
265   public Entity selectById(String anId) throws DatabaseExc {
266     if ((anId == null) || anId.equals("")) {
267       throw new DatabaseExc("Database.selectById: Missing id");
268     }
269
270     // ask object store for object
271     if (StoreUtil.extendsStorableEntity(entityClass)) {
272       String uniqueId = anId;
273
274       if (entityClass.equals(StorableObjectEntity.class)) {
275         uniqueId += ("@" + mainTable);
276       }
277
278       StoreIdentifier search_sid = new StoreIdentifier(entityClass, uniqueId);
279       logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
280
281       Entity hit = (Entity) o_store.use(search_sid);
282
283       if (hit != null) {
284         return hit;
285       }
286     }
287
288     Connection con = obtainConnection();
289     Entity returnEntity = null;
290     PreparedStatement statement = null;
291
292     try {
293       ResultSet rs;
294       String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?";
295
296       statement = con.prepareStatement(query);
297       statement.setString(1, anId);
298
299       logQueryBefore(query);
300
301       long startTime = System.currentTimeMillis();
302       try {
303         rs = statement.executeQuery();
304
305         logQueryAfter(query, (System.currentTimeMillis() - startTime));
306       }
307       catch (SQLException e) {
308         logQueryError(query, (System.currentTimeMillis() - startTime), e);
309         throw e;
310       }
311
312       if (rs != null) {
313         if (rs.next()) {
314           returnEntity = makeEntityFromResultSet(rs);
315         }
316         else {
317           logger.warn("No data for id: " + anId + " in table " + mainTable);
318         }
319
320         rs.close();
321       }
322       else {
323         logger.warn("No Data for Id " + anId + " in Table " + mainTable);
324       }
325     }
326     catch (Throwable e) {
327       throw new DatabaseFailure(e);
328     }
329     finally {
330       freeConnection(con, statement);
331     }
332
333     return returnEntity;
334   }
335
336   public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, List extraTables, String aWhereClause) throws DatabaseExc, DatabaseFailure {
337         return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, DEFAULT_LIMIT);
338   }
339
340   public EntityList selectByFieldValue(String aField, String aValue) throws DatabaseExc, DatabaseFailure {
341     return selectByFieldValue(aField, aValue, 0);
342   }
343
344   public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure {
345     return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset);
346   }
347
348   public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure {
349     return selectByWhereClause(where, 0);
350   }
351
352   public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure {
353     return selectByWhereClause(whereClause, null, offset);
354   }
355
356   public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws DatabaseExc, DatabaseFailure {
357     return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, DEFAULT_LIMIT);
358   }
359
360   public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure {
361     return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT);
362   }
363
364   public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
365             int offset, int limit) throws DatabaseExc, DatabaseFailure {
366     return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
367   }
368
369   public EntityList selectByWhereClause(
370       String aMainTablePrefix, List anExtraTables,
371       String aWhereClause, String anOrderByClause,
372                         int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure {
373
374     if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){
375       anExtraTables=null;
376     }
377
378     // check o_store for entitylist
379     // only if no relational select
380     if (anExtraTables==null) {
381       if (StoreUtil.extendsStorableEntity(entityClass)) {
382          StoreIdentifier searchSid = new StoreIdentifier(entityClass,
383                StoreContainerType.STOC_TYPE_ENTITYLIST,
384                StoreUtil.getEntityListUniqueIdentifierFor(mainTable,
385                 aWhereClause, anOrderByClause, anOffset, aLimit));
386          EntityList hit = (EntityList) o_store.use(searchSid);
387
388          if (hit != null) {
389             return hit;
390          }
391       }
392     }
393
394     RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
395
396     EntityList result = null;
397     Connection connection = null;
398
399     if (anExtraTables!=null) {
400       Iterator i = anExtraTables.iterator();
401       while (i.hasNext()) {
402         String table = (String) i.next();
403         if (!"".equals(table)) {
404           retriever.addExtraTable(table);
405         }
406       }
407     }
408
409     if (aWhereClause != null) {
410       retriever.appendWhereClause(aWhereClause);
411     }
412
413     if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
414       retriever.appendOrderByClause(anOrderByClause);
415     }
416
417     if (anOffset>-1 && aLimit>-1) {
418       retriever.setLimit(aLimit+1);
419       retriever.setOffset(anOffset);
420     }
421
422     Iterator i = getFieldNames().iterator();
423     while (i.hasNext()) {
424       retriever.addField((String) i.next());
425     }
426
427     // execute sql
428     try {
429       connection = obtainConnection();
430       ResultSet resultSet = retriever.execute(connection);
431
432       boolean hasMore = false;
433
434       if (resultSet != null) {
435         result = new EntityList();
436         Entity entity;
437         int position = 0;
438
439         while (((aLimit == -1) || (position<aLimit)) && resultSet.next()) {
440           entity = makeEntityFromResultSet(resultSet);
441           result.add(entity);
442           position++;
443         }
444
445         hasMore = resultSet.next();
446         resultSet.close();
447       }
448
449       if (result != null) {
450         result.setOffset(anOffset);
451         result.setWhere(aWhereClause);
452         result.setOrder(anOrderByClause);
453         result.setStorage(this);
454         result.setLimit(aLimit);
455
456         if (hasMore) {
457           result.setNextBatch(anOffset + aLimit);
458         }
459
460         if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
461           StoreIdentifier sid = result.getStoreIdentifier();
462           logger.debug("CACHE (add): " + sid.toString());
463           o_store.add(sid);
464         }
465       }
466     }
467     catch (Throwable e) {
468       throw new DatabaseFailure(e);
469     }
470     finally {
471       try {
472         if (connection != null) {
473           freeConnection(connection);
474         }
475       } catch (Throwable t) {
476       }
477     }
478
479     return result;
480   }
481
482   private Entity makeEntityFromResultSet(ResultSet rs) {
483     Map fields = new HashMap();
484     String theResult = null;
485     int type;
486     Entity returnEntity = null;
487
488     try {
489       if (StoreUtil.extendsStorableEntity(entityClass)) {
490          StoreIdentifier searchSid = StorableObjectEntity.getStoreIdentifier(this,
491                entityClass, rs);
492          Entity hit = (Entity) o_store.use(searchSid);
493          if (hit != null) return hit;
494       }
495
496       for (int i = 0; i < getFieldNames().size(); i++) {
497         type = fieldTypes[i];
498
499         if (type == java.sql.Types.LONGVARBINARY) {
500           InputStreamReader is =
501             (InputStreamReader) rs.getCharacterStream(i + 1);
502
503           if (is != null) {
504             char[] data = new char[32768];
505             StringBuffer theResultString = new StringBuffer();
506             int len;
507
508             while ((len = is.read(data)) > 0) {
509               theResultString.append(data, 0, len);
510             }
511
512             is.close();
513             theResult = theResultString.toString();
514           }
515           else {
516             theResult = null;
517           }
518         }
519         else {
520           theResult = getValueAsString(rs, (i + 1), type);
521         }
522
523         if (theResult != null) {
524           fields.put(getFieldNames().get(i), theResult);
525         }
526       }
527
528       if (entityClass != null) {
529         returnEntity = createNewEntity();
530         returnEntity.setFieldValues(fields);
531
532         if (returnEntity instanceof StorableObject) {
533           logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + mainTable);
534           o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
535         }
536       }
537       else {
538         throw new DatabaseExc("Internal Error: entityClass not set!");
539       }
540     }
541     catch (Throwable e) {
542       throw new DatabaseFailure(e);
543     }
544
545     return returnEntity;
546   }
547
548   /**
549    * Inserts an entity into the database.
550    *
551    * @param anEntity
552    * @return the value of the primary key of the inserted record
553    */
554   public String insert(Entity anEntity) throws DatabaseFailure {
555     invalidateStore();
556
557     RecordInserter inserter =
558         new RecordInserter(mainTable, getPrimaryKeySequence());
559
560     String returnId = null;
561     Connection con = null;
562
563     try {
564       String fieldName;
565
566       // make sql-string
567       for (int i = 0; i < getFieldNames().size(); i++) {
568         fieldName = (String) getFieldNames().get(i);
569
570         if (!fieldName.equals(primaryKeyField)) {
571           // exceptions
572           if (!anEntity.hasFieldValue(fieldName) && (
573               fieldName.equals("webdb_create") ||
574               fieldName.equals("webdb_lastchange"))) {
575             inserter.assignVerbatim(fieldName, "now()");
576           }
577           else {
578             if (anEntity.hasFieldValue(fieldName)) {
579               inserter.assignString(fieldName, anEntity.getFieldValue(fieldName));
580             }
581           }
582         }
583       }
584
585       con = obtainConnection();
586       returnId = inserter.execute(con);
587
588       anEntity.setId(returnId);
589     }
590     finally {
591       freeConnection(con);
592     }
593
594     return returnId;
595   }
596
597   /**
598    * Updates an entity in the database
599    *
600    * @param theEntity
601    */
602   public void update(Entity theEntity) throws DatabaseFailure {
603     invalidateStore();
604
605     RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
606
607     // build sql statement
608     for (int i = 0; i < getFieldNames().size(); i++) {
609       String field = (String) getFieldNames().get(i);
610
611       if (!(field.equals(primaryKeyField) ||
612             "webdb_create".equals(field) ||
613             "webdb_lastchange".equals(field) ||
614             binaryFields.contains(field))) {
615
616         if (theEntity.hasFieldValue(field)) {
617           generator.assignString(field, theEntity.getFieldValue(field));
618         }
619       }
620     }
621
622     // exceptions
623     if (hasField("webdb_lastchange")) {
624       generator.assignVerbatim("webdb_lastchange", "now()");
625     }
626
627     // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
628     // format so anything extra will be ignored. -mh
629     if (hasField("webdb_create") &&
630         theEntity.hasFieldValue("webdb_create")) {
631       // minimum of 10 (yyyy-mm-dd)...
632       if (theEntity.getFieldValue("webdb_create").length() >= 10) {
633         String dateString = theEntity.getFieldValue("webdb_create");
634
635         // if only 10, then add 00:00 so it doesn't throw a ParseException
636         if (dateString.length() == 10) {
637           dateString = dateString + " 00:00";
638         }
639
640         // TimeStamp stuff
641         try {
642           java.util.Date d = userInputDateFormat.parse(dateString);
643           generator.assignDateTime("webdb_create", d);
644         }
645         catch (ParseException e) {
646           throw new DatabaseFailure(e);
647         }
648       }
649     }
650     Connection connection = null;
651
652     try {
653       connection = obtainConnection();
654       generator.execute(connection);
655     }
656     finally {
657       freeConnection(connection);
658     }
659   }
660   
661   private void invalidateObject(String anId) {
662     // ostore send notification
663     if (StoreUtil.extendsStorableEntity(entityClass)) {
664       String uniqueId = anId;
665
666       if (entityClass.equals(StorableObjectEntity.class)) {
667         uniqueId += ("@" + mainTable);
668       }
669
670       logger.debug("CACHE: (del) " + anId);
671
672       StoreIdentifier search_sid =
673         new StoreIdentifier(entityClass,
674           StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
675       o_store.invalidate(search_sid);
676     }
677   }
678
679   /*
680   *   delete-Operator
681   *   @param id des zu loeschenden Datensatzes
682   *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
683    */
684   public boolean delete(String id) throws DatabaseFailure {
685         invalidateObject(id);
686         
687     int resultCode = 0;
688     Connection connection = obtainConnection();
689     PreparedStatement statement = null;
690
691     try {
692         statement = connection.prepareStatement("delete from " + mainTable + " where " + primaryKeyField + "=?");
693             statement.setInt(1, Integer.parseInt(id));
694             logQueryBefore("delete from " + mainTable + " where " + primaryKeyField + "=" + id + "");
695             resultCode = statement.executeUpdate();
696     }
697     catch (SQLException e) {
698         logger.warn("Can't delete record", e);
699     }
700     finally {
701       freeConnection(connection, statement);
702     }
703
704     invalidateStore();
705
706     return (resultCode > 0) ? true : false;
707   }
708
709   /**
710    * Deletes entities based on a where clause
711    */
712   public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure {
713     invalidateStore();
714
715     Statement stmt = null;
716     Connection con = null;
717     int res = 0;
718     String sql =
719       "delete from " + mainTable + " where " + aWhereClause;
720
721     //theLog.printInfo("DELETE " + sql);
722     try {
723       con = obtainConnection();
724       stmt = con.createStatement();
725       res = stmt.executeUpdate(sql);
726     }
727     catch (Throwable e) {
728       throw new DatabaseFailure(e);
729     }
730     finally {
731       freeConnection(con, stmt);
732     }
733
734     return res;
735   }
736
737   /* noch nicht implementiert.
738   * @return immer false
739    */
740   public boolean delete(EntityList theEntityList) {
741     return false;
742   }
743
744   public ResultSet executeSql(Statement stmt, String sql)
745                             throws DatabaseFailure, SQLException {
746     ResultSet rs;
747     logQueryBefore(sql);
748     long startTime = System.currentTimeMillis();
749     try {
750       rs = stmt.executeQuery(sql);
751
752       logQueryAfter(sql, (System.currentTimeMillis() - startTime));
753     }
754     catch (SQLException e) {
755       logQueryError(sql, (System.currentTimeMillis() - startTime), e);
756       throw e;
757     }
758
759     return rs;
760   }
761
762   private Map processRow(ResultSet aResultSet) throws DatabaseFailure {
763     try {
764       Map result = new HashMap();
765       ResultSetMetaData metaData = aResultSet.getMetaData();
766       int nrColumns = metaData.getColumnCount();
767       for (int i=0; i<nrColumns; i++) {
768         result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
769       }
770
771       return result;
772     }
773     catch (Throwable e) {
774       throw new DatabaseFailure(e);
775     }
776   }
777
778   /**
779    * Executes 1 sql statement and returns the results as a <code>List</code> of
780    * <code>Map</code>s
781    */
782   public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc {
783     Connection connection = null;
784     Statement statement = null;
785     try {
786       List result = new ArrayList();
787       connection = obtainConnection();
788       statement = connection.createStatement();
789       ResultSet resultset = executeSql(statement, sql);
790       try {
791         while (resultset.next() && result.size() < aLimit) {
792           result.add(processRow(resultset));
793         }
794       }
795       finally {
796         resultset.close();
797       }
798
799       return result;
800     }
801     catch (Throwable e) {
802       throw new DatabaseFailure(e);
803     }
804     finally {
805       if (connection!=null) {
806         freeConnection(connection, statement);
807       }
808     }
809   }
810
811   /**
812    * Executes 1 sql statement and returns the first result row as a <code>Map</code>s
813    * (<code>null</code> if there wasn't any row)
814    */
815   public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc {
816     try {
817       List resultList = executeFreeSql(anSqlStatement, 1);
818       try {
819         if (resultList.size()>0)
820           return (Map) resultList.get(0);
821                                 return null;
822       }
823       finally {
824       }
825     }
826     catch (Throwable t) {
827       throw new DatabaseFailure(t);
828     }
829   }
830
831   /**
832    * Executes 1 sql statement and returns the first column of the first result row as a <code>String</code>s
833    * (<code>null</code> if there wasn't any row)
834    */
835   public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc {
836     Map row = executeFreeSingleRowSql(sql);
837
838     if (row==null)
839       return null;
840
841     Iterator i = row.values().iterator();
842     if (i.hasNext())
843       return (String) i.next();
844                 return null;
845   }
846
847   public int getSize(String where) throws SQLException, DatabaseFailure {
848     return getSize("", null, where);
849   }
850   /**
851    * returns the number of rows in the table
852    */
853   public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure {
854
855     String useTable = mainTable;
856     if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
857       useTable+=" "+mainTablePrefix;
858     }
859     StringBuffer countSql =
860       new StringBuffer("select count(*) from ").append(useTable);
861         // append extratables, if necessary
862       if (extraTables!=null) {
863         for (int i=0;i < extraTables.size();i++) {
864           if (!extraTables.get(i).equals("")) {
865             countSql.append( ", " + extraTables.get(i));
866           }
867         }
868       }
869
870     if ((where != null) && (where.length() != 0)) {
871       countSql.append( " where " + where);
872     }
873
874     Connection con = null;
875     Statement stmt = null;
876     int result = 0;
877     logQueryBefore(countSql.toString());
878     long startTime = System.currentTimeMillis();
879
880     try {
881       con = obtainConnection();
882       stmt = con.createStatement();
883
884       ResultSet rs = executeSql(stmt, countSql.toString());
885
886       while (rs.next()) {
887         result = rs.getInt(1);
888       }
889     }
890     catch (SQLException e) {
891       logger.error("Database.getSize: " + e.getMessage());
892     }
893     finally {
894       freeConnection(con, stmt);
895     }
896     logQueryAfter(countSql.toString(), (System.currentTimeMillis() - startTime));
897
898     return result;
899   }
900
901   public int executeUpdate(Statement stmt, String sql)
902     throws DatabaseFailure, SQLException {
903     int rs;
904
905     logQueryBefore(sql);
906     long startTime = System.currentTimeMillis();
907
908     try {
909       rs = stmt.executeUpdate(sql);
910
911       logQueryAfter(sql, (System.currentTimeMillis() - startTime));
912     }
913     catch (SQLException e) {
914       logQueryError(sql, (System.currentTimeMillis() - startTime), e);
915       throw e;
916     }
917
918     return rs;
919   }
920
921   public int executeUpdate(String sql)
922     throws DatabaseFailure, SQLException {
923     int result = -1;
924     Connection con = null;
925     PreparedStatement pstmt = null;
926
927     logQueryBefore(sql);
928     long startTime = System.currentTimeMillis();
929     try {
930       con = obtainConnection();
931       pstmt = con.prepareStatement(sql);
932       result = pstmt.executeUpdate();
933       logQueryAfter(sql, System.currentTimeMillis() - startTime);
934     }
935     catch (Throwable e) {
936       logQueryError(sql, System.currentTimeMillis() - startTime, e);
937       throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
938     }
939     finally {
940       freeConnection(con, pstmt);
941     }
942     return result;
943   }
944
945   /**
946    * Processes the metadata for the table this Database object is responsible for.
947    */
948   private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure {
949     fieldNames = new ArrayList();
950     fieldNameToType = new HashMap();
951
952     try {
953       int numFields = aMetaData.getColumnCount();
954       fieldTypes = new int[numFields];
955
956       for (int i = 1; i <= numFields; i++) {
957         fieldNames.add(aMetaData.getColumnName(i));
958         fieldTypes[i - 1] = aMetaData.getColumnType(i);
959         fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i)));
960       }
961     }
962     catch (Throwable e) {
963       throw new DatabaseFailure(e);
964     }
965   }
966
967   /**
968    * Retrieves metadata from the table this Database object represents
969    */
970   private void acquireMetaData() throws DatabaseFailure {
971     Connection connection = null;
972     PreparedStatement statement = null;
973     String sql = "select * from " + mainTable + " where 0=1";
974
975     try {
976       connection = obtainConnection();
977       statement = connection.prepareStatement(sql);
978
979       logger.debug("METADATA: " + sql);
980       ResultSet resultSet = statement.executeQuery();
981       try {
982         processMetaData(resultSet.getMetaData());
983       }
984       finally {
985         resultSet.close();
986       }
987     }
988     catch (Throwable e) {
989       throw new DatabaseFailure(e);
990     }
991     finally {
992       freeConnection(connection, statement);
993     }
994   }
995
996   public Connection obtainConnection() throws DatabaseFailure {
997     try {
998       return MirGlobal.getDatabaseEngine().obtainConnection();
999     }
1000     catch (Exception e) {
1001       throw new DatabaseFailure(e);
1002     }
1003   }
1004
1005   public void freeConnection(Connection aConnection) throws DatabaseFailure {
1006     try {
1007       MirGlobal.getDatabaseEngine().releaseConnection(aConnection);
1008     }
1009     catch (Throwable t) {
1010       logger.warn("Can't release connection: " + t.toString());
1011     }
1012   }
1013
1014   public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure {
1015     try {
1016       aStatement.close();
1017     }
1018     catch (Throwable t) {
1019       logger.warn("Can't close statement", t);
1020     }
1021
1022     freeConnection(aConnection);
1023   }
1024
1025   protected void _throwStorageObjectException(Exception e, String aFunction)
1026     throws DatabaseFailure {
1027
1028     if (e != null) {
1029       logger.error(e.getMessage() + aFunction);
1030       throw new DatabaseFailure(aFunction, e);
1031     }
1032   }
1033
1034
1035   /**
1036    * Invalidates any cached entity list
1037    */
1038   private void invalidateStore() {
1039     // invalidating all EntityLists corresponding with entityClass
1040     if (StoreUtil.extendsStorableEntity(entityClass)) {
1041       StoreContainerType stoc_type =
1042         StoreContainerType.valueOf(entityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
1043       o_store.invalidate(stoc_type);
1044     }
1045   }
1046
1047   /**
1048    * Retrieves a binary value
1049    */
1050   public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException {
1051     Connection connection=null;
1052     Statement statement=null;
1053     InputStream inputStream;
1054
1055     try {
1056       connection = obtainConnection();
1057       try {
1058         connection.setAutoCommit(false);
1059         statement = connection.createStatement();
1060         ResultSet resultSet = executeSql(statement, aQuery);
1061
1062         if(resultSet!=null) {
1063           if (resultSet.next()) {
1064             if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
1065               return resultSet.getBytes(1);
1066             }
1067             else {
1068               inputStream = resultSet.getBlob(1).getBinaryStream();
1069               ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1070               StreamCopier.copy(inputStream, outputStream);
1071               return outputStream.toByteArray();
1072             }
1073           }
1074           resultSet.close();
1075         }
1076       }
1077       finally {
1078         try {
1079           connection.setAutoCommit(true);
1080         }
1081         catch (Throwable e) {
1082           logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
1083           e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1084         }
1085
1086         try {
1087           freeConnection(connection, statement);
1088         }
1089         catch (Throwable e) {
1090           logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
1091         }
1092
1093       }
1094     }
1095     catch (Throwable t) {
1096       logger.error("EntityImages.getImage failed: " + t.toString());
1097       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1098
1099       throw new DatabaseFailure(t);
1100     }
1101
1102     return new byte[0];
1103   }
1104
1105   /**
1106    * Sets a binary value for a particular field in a record specified by its identifier
1107    */
1108   public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException {
1109     PreparedStatement statement = null;
1110     Connection connection = obtainConnection();
1111
1112     try {
1113       connection.setAutoCommit(false);
1114       try {
1115         // are we using bytea ?
1116         if (getFieldType(aFieldName) == java.sql.Types.BINARY) {
1117           statement = connection.prepareStatement(
1118                 "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
1119           statement.setBytes(1, aData);
1120           statement.execute();
1121           connection.commit();
1122         }
1123         // or the old oid's
1124         else {
1125           PGConnection postgresqlConnection = (org.postgresql.PGConnection) ((DelegatingConnection) connection).getDelegate();
1126           LargeObjectManager lobManager = postgresqlConnection.getLargeObjectAPI();
1127           int oid = lobManager.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
1128           LargeObject obj = lobManager.open(oid, LargeObjectManager.WRITE);  // Now open the file File file =
1129           obj.write(aData);
1130           obj.close();
1131           statement = connection.prepareStatement(
1132                 "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
1133           statement.setInt(1, oid);
1134           statement.execute();
1135           connection.commit();
1136         }
1137       }
1138       finally {
1139         connection.setAutoCommit(true);
1140       }
1141     }
1142     finally {
1143       freeConnection(connection, statement);
1144     }
1145   }
1146
1147   /**
1148    * Can be overridden to specify a primary key sequence name not named according to
1149    * the convention (tablename _id_seq)
1150    */
1151   protected String getPrimaryKeySequence() {
1152     return mainTable+"_id_seq";
1153   }
1154
1155   /**
1156    * Can be called by subclasses to specify fields that are binary, and that shouldn't
1157    * be updated outside of {@link #setBinaryField}
1158    *
1159    * @param aBinaryField The field name of the binary field
1160    */
1161   protected void markBinaryField(String aBinaryField) {
1162     binaryFields.add(aBinaryField);
1163   }
1164
1165   private void logQueryBefore(String aQuery) {
1166     logger.debug("about to perform QUERY " + aQuery);
1167 //    (new Throwable()).printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1168   }
1169
1170   private void logQueryAfter(String aQuery, long aTime) {
1171     logger.info("QUERY " + aQuery + " took " + aTime + "ms.");
1172   }
1173
1174   private void logQueryError(String aQuery, long aTime, Throwable anException) {
1175     logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());
1176   }
1177
1178   private int getFieldType(String aFieldName) {
1179     if (fieldNameToType == null) {
1180       acquireMetaData();
1181     }
1182
1183     return ((Integer) fieldNameToType.get(aFieldName)).intValue();
1184   }
1185 }