e18d3a5ee52c04d02156cd00bbca1ee975df25a3
[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.36 2006/08/10 19:29:36 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
263    */
264   public Entity selectById(String anId) throws DatabaseExc {
265     if ((anId == null) || anId.equals("")) {
266       throw new DatabaseExc("Database.selectById: Missing id");
267     }
268
269     // ask object store for object
270     if (StoreUtil.extendsStorableEntity(entityClass)) {
271       String uniqueId = anId;
272
273       if (entityClass.equals(StorableObjectEntity.class)) {
274         uniqueId += ("@" + mainTable);
275       }
276
277       StoreIdentifier search_sid = new StoreIdentifier(entityClass, uniqueId);
278       logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
279
280       Entity hit = (Entity) o_store.use(search_sid);
281
282       if (hit != null) {
283         return hit;
284       }
285     }
286
287     Connection con = obtainConnection();
288     Entity returnEntity = null;
289     PreparedStatement statement = null;
290
291     try {
292       ResultSet rs;
293       String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?";
294
295       statement = con.prepareStatement(query);
296       statement.setString(1, anId);
297
298       logQueryBefore(query);
299
300       long startTime = System.currentTimeMillis();
301       try {
302         rs = statement.executeQuery();
303
304         logQueryAfter(query, (System.currentTimeMillis() - startTime));
305       }
306       catch (SQLException e) {
307         logQueryError(query, (System.currentTimeMillis() - startTime), e);
308         throw e;
309       }
310
311       if (rs != null) {
312         if (rs.next()) {
313           returnEntity = makeEntityFromResultSet(rs);
314         }
315         else {
316           logger.warn("No data for id: " + anId + " in table " + mainTable);
317         }
318
319         rs.close();
320       }
321       else {
322         logger.warn("No Data for Id " + anId + " in Table " + mainTable);
323       }
324     }
325     catch (Throwable e) {
326       throw new DatabaseFailure(e);
327     }
328     finally {
329       freeConnection(con, statement);
330     }
331
332     return returnEntity;
333   }
334
335   public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, List extraTables, String aWhereClause) throws DatabaseExc, DatabaseFailure {
336         return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, DEFAULT_LIMIT);
337   }
338
339   public EntityList selectByFieldValue(String aField, String aValue) throws DatabaseExc, DatabaseFailure {
340     return selectByFieldValue(aField, aValue, 0);
341   }
342
343   public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure {
344     return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset);
345   }
346
347   public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure {
348     return selectByWhereClause(where, 0);
349   }
350
351   public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure {
352     return selectByWhereClause(whereClause, null, offset);
353   }
354
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);
357   }
358
359   public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure {
360     return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT);
361   }
362
363   public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
364             int offset, int limit) throws DatabaseExc, DatabaseFailure {
365     return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
366   }
367
368   public EntityList selectByWhereClause(
369       String aMainTablePrefix, List anExtraTables,
370       String aWhereClause, String anOrderByClause,
371                         int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure {
372
373     if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){
374       anExtraTables=null;
375     }
376
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);
386
387          if (hit != null) {
388             return hit;
389          }
390       }
391     }
392
393     RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
394
395     EntityList result = null;
396     Connection connection = null;
397
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);
404         }
405       }
406     }
407
408     if (aWhereClause != null) {
409       retriever.appendWhereClause(aWhereClause);
410     }
411
412     if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
413       retriever.appendOrderByClause(anOrderByClause);
414     }
415
416     if (anOffset>-1 && aLimit>-1) {
417       retriever.setLimit(aLimit+1);
418       retriever.setOffset(anOffset);
419     }
420
421     Iterator i = getFieldNames().iterator();
422     while (i.hasNext()) {
423       retriever.addField((String) i.next());
424     }
425
426     // execute sql
427     try {
428       connection = obtainConnection();
429       ResultSet resultSet = retriever.execute(connection);
430
431       boolean hasMore = false;
432
433       if (resultSet != null) {
434         result = new EntityList();
435         Entity entity;
436         int position = 0;
437
438         while (((aLimit == -1) || (position<aLimit)) && resultSet.next()) {
439           entity = makeEntityFromResultSet(resultSet);
440           result.add(entity);
441           position++;
442         }
443
444         hasMore = resultSet.next();
445         resultSet.close();
446       }
447
448       if (result != null) {
449         result.setOffset(anOffset);
450         result.setWhere(aWhereClause);
451         result.setOrder(anOrderByClause);
452         result.setStorage(this);
453         result.setLimit(aLimit);
454
455         if (hasMore) {
456           result.setNextBatch(anOffset + aLimit);
457         }
458
459         if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
460           StoreIdentifier sid = result.getStoreIdentifier();
461           logger.debug("CACHE (add): " + sid.toString());
462           o_store.add(sid);
463         }
464       }
465     }
466     catch (Throwable e) {
467       throw new DatabaseFailure(e);
468     }
469     finally {
470       try {
471         if (connection != null) {
472           freeConnection(connection);
473         }
474       } catch (Throwable t) {
475       }
476     }
477
478     return result;
479   }
480
481   private Entity makeEntityFromResultSet(ResultSet rs) {
482     Map fields = new HashMap();
483     String theResult = null;
484     int type;
485     Entity returnEntity = null;
486
487     try {
488       if (StoreUtil.extendsStorableEntity(entityClass)) {
489          StoreIdentifier searchSid = StorableObjectEntity.getStoreIdentifier(this,
490                entityClass, rs);
491          Entity hit = (Entity) o_store.use(searchSid);
492          if (hit != null) return hit;
493       }
494
495       for (int i = 0; i < getFieldNames().size(); i++) {
496         type = fieldTypes[i];
497
498         if (type == java.sql.Types.LONGVARBINARY) {
499           InputStreamReader is =
500             (InputStreamReader) rs.getCharacterStream(i + 1);
501
502           if (is != null) {
503             char[] data = new char[32768];
504             StringBuffer theResultString = new StringBuffer();
505             int len;
506
507             while ((len = is.read(data)) > 0) {
508               theResultString.append(data, 0, len);
509             }
510
511             is.close();
512             theResult = theResultString.toString();
513           }
514           else {
515             theResult = null;
516           }
517         }
518         else {
519           theResult = getValueAsString(rs, (i + 1), type);
520         }
521
522         if (theResult != null) {
523           fields.put(getFieldNames().get(i), theResult);
524         }
525       }
526
527       if (entityClass != null) {
528         returnEntity = createNewEntity();
529         returnEntity.setFieldValues(fields);
530
531         if (returnEntity instanceof StorableObject) {
532           logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + mainTable);
533           o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
534         }
535       }
536       else {
537         throw new DatabaseExc("Internal Error: entityClass not set!");
538       }
539     }
540     catch (Throwable e) {
541       throw new DatabaseFailure(e);
542     }
543
544     return returnEntity;
545   }
546
547   /**
548    * Inserts an entity into the database.
549    *
550    * @param anEntity
551    * @return the value of the primary key of the inserted record
552    */
553   public String insert(Entity anEntity) throws DatabaseFailure {
554     invalidateStore();
555
556     RecordInserter inserter =
557         new RecordInserter(mainTable, getPrimaryKeySequence());
558
559     String returnId = null;
560     Connection con = null;
561
562     try {
563       String fieldName;
564
565       // make sql-string
566       for (int i = 0; i < getFieldNames().size(); i++) {
567         fieldName = (String) getFieldNames().get(i);
568
569         if (!fieldName.equals(primaryKeyField)) {
570           // exceptions
571           if (!anEntity.hasFieldValue(fieldName) && (
572               fieldName.equals("webdb_create") ||
573               fieldName.equals("webdb_lastchange"))) {
574             inserter.assignVerbatim(fieldName, "now()");
575           }
576           else {
577             if (anEntity.hasFieldValue(fieldName)) {
578               inserter.assignString(fieldName, anEntity.getFieldValue(fieldName));
579             }
580           }
581         }
582       }
583
584       con = obtainConnection();
585       returnId = inserter.execute(con);
586
587       anEntity.setId(returnId);
588     }
589     finally {
590       freeConnection(con);
591     }
592
593     return returnId;
594   }
595
596   /**
597    * Updates an entity in the database
598    *
599    * @param theEntity
600    */
601   public void update(Entity theEntity) throws DatabaseFailure {
602     invalidateStore();
603
604     RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
605
606     // build sql statement
607     for (int i = 0; i < getFieldNames().size(); i++) {
608       String field = (String) getFieldNames().get(i);
609
610       if (!(field.equals(primaryKeyField) ||
611             "webdb_create".equals(field) ||
612             "webdb_lastchange".equals(field) ||
613             binaryFields.contains(field))) {
614
615         if (theEntity.hasFieldValue(field)) {
616           generator.assignString(field, theEntity.getFieldValue(field));
617         }
618       }
619     }
620
621     // exceptions
622     if (hasField("webdb_lastchange")) {
623       generator.assignVerbatim("webdb_lastchange", "now()");
624     }
625
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");
633
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";
637         }
638
639         // TimeStamp stuff
640         try {
641           java.util.Date d = userInputDateFormat.parse(dateString);
642           generator.assignDateTime("webdb_create", d);
643         }
644         catch (ParseException e) {
645           throw new DatabaseFailure(e);
646         }
647       }
648     }
649     Connection connection = null;
650
651     try {
652       connection = obtainConnection();
653       generator.execute(connection);
654     }
655     finally {
656       freeConnection(connection);
657     }
658   }
659   
660   private void invalidateObject(String anId) {
661     // ostore send notification
662     if (StoreUtil.extendsStorableEntity(entityClass)) {
663       String uniqueId = anId;
664
665       if (entityClass.equals(StorableObjectEntity.class)) {
666         uniqueId += ("@" + mainTable);
667       }
668
669       logger.debug("CACHE: (del) " + anId);
670
671       StoreIdentifier search_sid =
672         new StoreIdentifier(entityClass,
673           StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
674       o_store.invalidate(search_sid);
675     }
676   }
677
678   /*
679   *   delete-Operator
680   *   @param id des zu loeschenden Datensatzes
681   *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
682    */
683   public boolean delete(String id) throws DatabaseFailure {
684         invalidateObject(id);
685         
686     int resultCode = 0;
687     Connection connection = obtainConnection();
688     PreparedStatement statement = null;
689
690     try {
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();
695     }
696     catch (SQLException e) {
697         logger.warn("Can't delete record", e);
698     }
699     finally {
700       freeConnection(connection, statement);
701     }
702
703     invalidateStore();
704
705     return (resultCode > 0) ? true : false;
706   }
707
708   /**
709    * Deletes entities based on a where clause
710    */
711   public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure {
712     invalidateStore();
713
714     Statement stmt = null;
715     Connection con = null;
716     int res = 0;
717     String sql =
718       "delete from " + mainTable + " where " + aWhereClause;
719
720     //theLog.printInfo("DELETE " + sql);
721     try {
722       con = obtainConnection();
723       stmt = con.createStatement();
724       res = stmt.executeUpdate(sql);
725     }
726     catch (Throwable e) {
727       throw new DatabaseFailure(e);
728     }
729     finally {
730       freeConnection(con, stmt);
731     }
732
733     return res;
734   }
735
736   /* noch nicht implementiert.
737   * @return immer false
738    */
739   public boolean delete(EntityList theEntityList) {
740     return false;
741   }
742
743   public ResultSet executeSql(Statement stmt, String sql)
744                             throws DatabaseFailure, SQLException {
745     ResultSet rs;
746     logQueryBefore(sql);
747     long startTime = System.currentTimeMillis();
748     try {
749       rs = stmt.executeQuery(sql);
750
751       logQueryAfter(sql, (System.currentTimeMillis() - startTime));
752     }
753     catch (SQLException e) {
754       logQueryError(sql, (System.currentTimeMillis() - startTime), e);
755       throw e;
756     }
757
758     return rs;
759   }
760
761   private Map processRow(ResultSet aResultSet) throws DatabaseFailure {
762     try {
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)));
768       }
769
770       return result;
771     }
772     catch (Throwable e) {
773       throw new DatabaseFailure(e);
774     }
775   }
776
777   /**
778    * Executes 1 sql statement and returns the results as a <code>List</code> of
779    * <code>Map</code>s
780    */
781   public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc {
782     Connection connection = null;
783     Statement statement = null;
784     try {
785       List result = new ArrayList();
786       connection = obtainConnection();
787       statement = connection.createStatement();
788       ResultSet resultset = executeSql(statement, sql);
789       try {
790         while (resultset.next() && result.size() < aLimit) {
791           result.add(processRow(resultset));
792         }
793       }
794       finally {
795         resultset.close();
796       }
797
798       return result;
799     }
800     catch (Throwable e) {
801       throw new DatabaseFailure(e);
802     }
803     finally {
804       if (connection!=null) {
805         freeConnection(connection, statement);
806       }
807     }
808   }
809
810   /**
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)
813    */
814   public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc {
815     try {
816       List resultList = executeFreeSql(anSqlStatement, 1);
817       try {
818         if (resultList.size()>0)
819           return (Map) resultList.get(0);
820                                 return null;
821       }
822       finally {
823       }
824     }
825     catch (Throwable t) {
826       throw new DatabaseFailure(t);
827     }
828   }
829
830   /**
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)
833    */
834   public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc {
835     Map row = executeFreeSingleRowSql(sql);
836
837     if (row==null)
838       return null;
839
840     Iterator i = row.values().iterator();
841     if (i.hasNext())
842       return (String) i.next();
843                 return null;
844   }
845
846   public int getSize(String where) throws SQLException, DatabaseFailure {
847     return getSize("", null, where);
848   }
849   /**
850    * returns the number of rows in the table
851    */
852   public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure {
853
854     String useTable = mainTable;
855     if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
856       useTable+=" "+mainTablePrefix;
857     }
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));
865           }
866         }
867       }
868
869     if ((where != null) && (where.length() != 0)) {
870       countSql.append( " where " + where);
871     }
872
873     Connection con = null;
874     Statement stmt = null;
875     int result = 0;
876     logQueryBefore(countSql.toString());
877     long startTime = System.currentTimeMillis();
878
879     try {
880       con = obtainConnection();
881       stmt = con.createStatement();
882
883       ResultSet rs = executeSql(stmt, countSql.toString());
884
885       while (rs.next()) {
886         result = rs.getInt(1);
887       }
888     }
889     catch (SQLException e) {
890       logger.error("Database.getSize: " + e.getMessage());
891     }
892     finally {
893       freeConnection(con, stmt);
894     }
895     logQueryAfter(countSql.toString(), (System.currentTimeMillis() - startTime));
896
897     return result;
898   }
899
900   public int executeUpdate(Statement stmt, String sql)
901     throws DatabaseFailure, SQLException {
902     int rs;
903
904     logQueryBefore(sql);
905     long startTime = System.currentTimeMillis();
906
907     try {
908       rs = stmt.executeUpdate(sql);
909
910       logQueryAfter(sql, (System.currentTimeMillis() - startTime));
911     }
912     catch (SQLException e) {
913       logQueryError(sql, (System.currentTimeMillis() - startTime), e);
914       throw e;
915     }
916
917     return rs;
918   }
919
920   public int executeUpdate(String sql)
921     throws DatabaseFailure, SQLException {
922     int result = -1;
923     Connection con = null;
924     PreparedStatement pstmt = null;
925
926     logQueryBefore(sql);
927     long startTime = System.currentTimeMillis();
928     try {
929       con = obtainConnection();
930       pstmt = con.prepareStatement(sql);
931       result = pstmt.executeUpdate();
932       logQueryAfter(sql, System.currentTimeMillis() - startTime);
933     }
934     catch (Throwable e) {
935       logQueryError(sql, System.currentTimeMillis() - startTime, e);
936       throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
937     }
938     finally {
939       freeConnection(con, pstmt);
940     }
941     return result;
942   }
943
944   /**
945    * Processes the metadata for the table this Database object is responsible for.
946    */
947   private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure {
948     fieldNames = new ArrayList();
949     fieldNameToType = new HashMap();
950
951     try {
952       int numFields = aMetaData.getColumnCount();
953       fieldTypes = new int[numFields];
954
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)));
959       }
960     }
961     catch (Throwable e) {
962       throw new DatabaseFailure(e);
963     }
964   }
965
966   /**
967    * Retrieves metadata from the table this Database object represents
968    */
969   private void acquireMetaData() throws DatabaseFailure {
970     Connection connection = null;
971     PreparedStatement statement = null;
972     String sql = "select * from " + mainTable + " where 0=1";
973
974     try {
975       connection = obtainConnection();
976       statement = connection.prepareStatement(sql);
977
978       logger.debug("METADATA: " + sql);
979       ResultSet resultSet = statement.executeQuery();
980       try {
981         processMetaData(resultSet.getMetaData());
982       }
983       finally {
984         resultSet.close();
985       }
986     }
987     catch (Throwable e) {
988       throw new DatabaseFailure(e);
989     }
990     finally {
991       freeConnection(connection, statement);
992     }
993   }
994
995   public Connection obtainConnection() throws DatabaseFailure {
996     try {
997       return MirGlobal.getDatabaseEngine().obtainConnection();
998     }
999     catch (Exception e) {
1000       throw new DatabaseFailure(e);
1001     }
1002   }
1003
1004   public void freeConnection(Connection aConnection) throws DatabaseFailure {
1005     try {
1006       MirGlobal.getDatabaseEngine().releaseConnection(aConnection);
1007     }
1008     catch (Throwable t) {
1009       logger.warn("Can't release connection: " + t.toString());
1010     }
1011   }
1012
1013   public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure {
1014     try {
1015       aStatement.close();
1016     }
1017     catch (Throwable t) {
1018       logger.warn("Can't close statement", t);
1019     }
1020
1021     freeConnection(aConnection);
1022   }
1023
1024   protected void _throwStorageObjectException(Exception e, String aFunction)
1025     throws DatabaseFailure {
1026
1027     if (e != null) {
1028       logger.error(e.getMessage() + aFunction);
1029       throw new DatabaseFailure(aFunction, e);
1030     }
1031   }
1032
1033
1034   /**
1035    * Invalidates any cached entity list
1036    */
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);
1043     }
1044   }
1045
1046   /**
1047    * Retrieves a binary value
1048    */
1049   public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException {
1050     Connection connection=null;
1051     Statement statement=null;
1052     InputStream inputStream;
1053
1054     try {
1055       connection = obtainConnection();
1056       try {
1057         connection.setAutoCommit(false);
1058         statement = connection.createStatement();
1059         ResultSet resultSet = executeSql(statement, aQuery);
1060
1061         if(resultSet!=null) {
1062           if (resultSet.next()) {
1063             if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
1064               return resultSet.getBytes(1);
1065             }
1066             else {
1067               inputStream = resultSet.getBlob(1).getBinaryStream();
1068               ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1069               StreamCopier.copy(inputStream, outputStream);
1070               return outputStream.toByteArray();
1071             }
1072           }
1073           resultSet.close();
1074         }
1075       }
1076       finally {
1077         try {
1078           connection.setAutoCommit(true);
1079         }
1080         catch (Throwable e) {
1081           logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
1082           e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1083         }
1084
1085         try {
1086           freeConnection(connection, statement);
1087         }
1088         catch (Throwable e) {
1089           logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
1090         }
1091
1092       }
1093     }
1094     catch (Throwable t) {
1095       logger.error("EntityImages.getImage failed: " + t.toString());
1096       t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1097
1098       throw new DatabaseFailure(t);
1099     }
1100
1101     return new byte[0];
1102   }
1103
1104   /**
1105    * Sets a binary value for a particular field in a record specified by its identifier
1106    */
1107   public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException {
1108     PreparedStatement statement = null;
1109     Connection connection = obtainConnection();
1110
1111     try {
1112       connection.setAutoCommit(false);
1113       try {
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();
1121         }
1122         // or the old oid's
1123         else {
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 =
1128           obj.write(aData);
1129           obj.close();
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();
1135         }
1136       }
1137       finally {
1138         connection.setAutoCommit(true);
1139       }
1140     }
1141     finally {
1142       freeConnection(connection, statement);
1143     }
1144   }
1145
1146   /**
1147    * Can be overridden to specify a primary key sequence name not named according to
1148    * the convention (tablename _id_seq)
1149    */
1150   protected String getPrimaryKeySequence() {
1151     return mainTable+"_id_seq";
1152   }
1153
1154   /**
1155    * Can be called by subclasses to specify fields that are binary, and that shouldn't
1156    * be updated outside of {@link #setBinaryField}
1157    *
1158    * @param aBinaryField The field name of the binary field
1159    */
1160   protected void markBinaryField(String aBinaryField) {
1161     binaryFields.add(aBinaryField);
1162   }
1163
1164   private void logQueryBefore(String aQuery) {
1165     logger.debug("about to perform QUERY " + aQuery);
1166 //    (new Throwable()).printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
1167   }
1168
1169   private void logQueryAfter(String aQuery, long aTime) {
1170     logger.info("QUERY " + aQuery + " took " + aTime + "ms.");
1171   }
1172
1173   private void logQueryError(String aQuery, long aTime, Throwable anException) {
1174     logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());
1175   }
1176
1177   private int getFieldType(String aFieldName) {
1178     if (fieldNameToType == null) {
1179       acquireMetaData();
1180     }
1181
1182     return ((Integer) fieldNameToType.get(aFieldName)).intValue();
1183   }
1184 }