KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > dataobjs > DBTable


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oña, 107 1º2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.dataobjs;
34
35 import java.io.IOException JavaDoc;
36 import java.io.File JavaDoc;
37 import java.io.InputStream JavaDoc;
38 import java.io.ByteArrayInputStream JavaDoc;
39 import java.io.StringBufferInputStream JavaDoc;
40 import java.io.FileInputStream JavaDoc;
41
42 import java.math.BigDecimal JavaDoc;
43
44 import java.sql.SQLException JavaDoc;
45 import java.sql.DatabaseMetaData JavaDoc;
46 import java.sql.Connection JavaDoc;
47 import java.sql.PreparedStatement JavaDoc;
48 import java.sql.ResultSet JavaDoc;
49 import java.sql.ResultSetMetaData JavaDoc;
50 import java.sql.Statement JavaDoc;
51 import java.sql.Timestamp JavaDoc;
52 import java.sql.Types JavaDoc;
53 import java.sql.ParameterMetaData JavaDoc;
54
55 import java.util.HashMap JavaDoc;
56 import java.util.LinkedList JavaDoc;
57 import java.util.ListIterator JavaDoc;
58
59 import com.knowgate.debug.*;
60 import com.knowgate.jdc.*;
61
62 /**
63  * <p>A database table as a Java Object</p>
64  * @author Sergio Montoro Ten
65  * @version 3.0
66  */

67
68 public class DBTable {
69
70   /**
71    * <p>Constructor</p>
72    * Catalog and schema names are set to <b>null</b>.<br>
73    * Table index is set to 1.
74    * @param sSchemaName Database schema name
75   */

76
77   public DBTable(String JavaDoc sTableName) {
78     sCatalog = null;
79     sSchema = null;
80     sName = sTableName;
81     iHashCode = 1;
82   }
83
84   /**
85    * Constructor
86    * @param sCatalogName Database catalog name
87    * @param sSchemaName Database schema name
88    * @param sTableName Database table name (not qualified)
89    * @param iIndex Ordinal number identifier for table
90    */

91
92   public DBTable(String JavaDoc sCatalogName, String JavaDoc sSchemaName, String JavaDoc sTableName, int iIndex) {
93     sName = sTableName;
94     sCatalog = sCatalogName;
95     sSchema = sSchemaName;
96     iHashCode = iIndex;
97   }
98
99   // ---------------------------------------------------------------------------
100

101   /**
102    * @return Column Count for this table
103    * @throws IllegalStateException if columns list has not been initialized
104    */

105
106   public int columnCount() throws IllegalStateException JavaDoc {
107     if (null==oColumns)
108       throw new IllegalStateException JavaDoc("Table columns list not initialized");
109     return oColumns.size();
110   }
111
112   // ---------------------------------------------------------------------------
113

114   /**
115    * <p>Load a single table register into a Java HashMap</p>
116    * @param oConn Database Connection
117    * @param PKValues Primary key values of register to be readed, in the same order as they appear in table source.
118    * @param AllValues Output parameter. Readed values.
119    * @return <b>true</b> if register was found <b>false</b> otherwise.
120    * @throws NullPointerException If all objects in PKValues array are null (only debug version)
121    * @throws IllegalStateException if columns list has not been initialized
122    * @throws SQLException
123    */

124   public boolean loadRegister(JDCConnection oConn, Object JavaDoc[] PKValues, HashMap JavaDoc AllValues)
125     throws SQLException JavaDoc, NullPointerException JavaDoc, IllegalStateException JavaDoc {
126     int c;
127     boolean bFound;
128     Object JavaDoc oVal;
129     DBColumn oDBCol;
130     ListIterator JavaDoc oColIterator;
131     PreparedStatement JavaDoc oStmt = null;
132     ResultSet JavaDoc oRSet = null;
133
134     if (null==oColumns)
135       throw new IllegalStateException JavaDoc("Table columns list not initialized");
136
137     if (DebugFile.trace) {
138       DebugFile.writeln("Begin DBTable.loadRegister([Connection], Object[], [HashMap])" );
139       DebugFile.incIdent();
140
141       boolean bAllNull = true;
142       for (int n=0; n<PKValues.length; n++)
143         bAllNull &= (PKValues[n]==null);
144
145       if (bAllNull)
146         throw new NullPointerException JavaDoc(sName + " cannot retrieve register, value supplied for primary key is NULL.");
147     }
148
149     if (sSelect==null) {
150       throw new SQLException JavaDoc("Primary key not found", "42S12");
151     }
152
153     AllValues.clear();
154
155     bFound = false;
156
157     try {
158
159       if (DebugFile.trace) DebugFile.writeln(" Connection.prepareStatement(" + sSelect + ")");
160
161       // Prepare SELECT sentence for reading
162
oStmt = oConn.prepareStatement(sSelect);
163
164       try {
165         oStmt.setQueryTimeout(10);
166       }
167       catch (SQLException JavaDoc sqle) {
168         if (DebugFile.trace) DebugFile.writeln("Error at PreparedStatement.setQueryTimeout(10)" + sqle.getMessage());
169       }
170
171
172       // Bind primary key values
173
for (int p=0; p<oPrimaryKeys.size(); p++) {
174         if (DebugFile.trace) DebugFile.writeln(" binding primary key " + PKValues[p] + ".");
175
176         bindParameter(oConn, oStmt, p+1, PKValues[p]);
177         //oStmt.setObject(p+1, PKValues[p]);
178
} // next
179

180       if (DebugFile.trace) DebugFile.writeln(" Connection.executeQuery()");
181
182       oRSet = oStmt.executeQuery();
183
184       if (oRSet.next()) {
185         if (DebugFile.trace) DebugFile.writeln(" ResultSet.next()");
186
187         bFound = true;
188
189         // Iterate throught readed columns
190
// and store readed values at AllValues
191
oColIterator = oColumns.listIterator();
192
193         c = 1;
194         while (oColIterator.hasNext()) {
195           oVal = oRSet.getObject(c++);
196           oDBCol = (DBColumn) oColIterator.next();
197           if (null!=oVal)
198             AllValues.put(oDBCol.getName(), oVal);
199         }
200       }
201
202       if (DebugFile.trace) DebugFile.writeln(" ResultSet.close()");
203
204       oRSet.close();
205       oRSet = null;
206
207       oStmt.close();
208       oStmt = null;
209     }
210     catch (SQLException JavaDoc sqle) {
211       try {
212         if (null!=oRSet) oRSet.close();
213         if (null!=oStmt) oStmt.close();
214       }
215       catch (Exception JavaDoc ignore) { }
216
217       throw new SQLException JavaDoc(sqle.getMessage(), sqle.getSQLState(), sqle.getErrorCode());
218     }
219
220     if (DebugFile.trace) {
221       DebugFile.decIdent();
222       DebugFile.writeln("End DBTable.loadRegister() : " + (bFound ? "true" : "false"));
223     }
224
225     return bFound;
226
227   } // loadRegister
228

229   // ---------------------------------------------------------------------------
230

231   private static void bindParameter (JDCConnection oConn, PreparedStatement JavaDoc oStmt,
232                               int iParamIndex, Object JavaDoc oParamValue, int iSQLType)
233     throws SQLException JavaDoc {
234
235     Class JavaDoc oParamClass;
236
237     switch (oConn.getDataBaseProduct()) {
238
239       case JDCConnection.DBMS_ORACLE:
240         if (oParamValue!=null) {
241
242           oParamClass = oParamValue.getClass();
243
244           if (DebugFile.trace) DebugFile.writeln("binding " + oParamClass.getName() + " as SQL " + DBColumn.typeName(iSQLType));
245
246           if (oParamClass.equals(Short JavaDoc.class) || oParamClass.equals(Integer JavaDoc.class) || oParamClass.equals(Float JavaDoc.class) || oParamClass.equals(Double JavaDoc.class))
247             oStmt.setBigDecimal (iParamIndex, new java.math.BigDecimal JavaDoc(oParamValue.toString()));
248
249           // New for hipergate v2.1 support for Oracle 9.2 change of behaviour with regard of DATE and TIMESTAMP columns
250
// see http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.htm#08_01 for more details
251
// If the binded parameter if a java.sql.Timestamp and the underlying database column is a DATE
252
// Then create a new java.util.Date object from the Timestamp miliseconds and pass it to the
253
// JDBC driver instead of the original Timestamp
254
else if ((oParamClass.getName().equals("java.sql.Timestamp") ||
255                     oParamClass.getName().equals("java.util.Date")) &&
256                    iSQLType==Types.DATE) {
257             try {
258               Class JavaDoc[] aTimestamp = new Class JavaDoc[1];
259               aTimestamp[0] = Class.forName("java.sql.Timestamp");
260               Class JavaDoc cDATE = Class.forName("oracle.sql.DATE");
261               java.lang.reflect.Constructor JavaDoc cNewDATE = cDATE.getConstructor(aTimestamp);
262               Object JavaDoc oDATE;
263               if (oParamClass.getName().equals("java.sql.Timestamp")) {
264                 oDATE = cNewDATE.newInstance(new Object JavaDoc[]{oParamValue});
265               } else {
266                 oDATE = cNewDATE.newInstance(new Object JavaDoc[]{new Timestamp JavaDoc(((java.util.Date JavaDoc)oParamValue).getTime())});
267               }
268               oStmt.setObject (iParamIndex, oDATE, iSQLType);
269             } catch (ClassNotFoundException JavaDoc cnf) {
270               throw new SQLException JavaDoc("ClassNotFoundException oracle.sql.DATE " + cnf.getMessage());
271             } catch (NoSuchMethodException JavaDoc nsm) {
272               throw new SQLException JavaDoc("NoSuchMethodException " + nsm.getMessage());
273             } catch (IllegalAccessException JavaDoc iae) {
274               throw new SQLException JavaDoc("IllegalAccessException " + iae.getMessage());
275             } catch (InstantiationException JavaDoc ine) {
276               throw new SQLException JavaDoc("InstantiationException " + ine.getMessage());
277             } catch (java.lang.reflect.InvocationTargetException JavaDoc ite) {
278               throw new SQLException JavaDoc("InvocationTargetException " + ite.getMessage());
279             }
280           }
281           else if (oParamClass.getName().equals("java.util.Date") && iSQLType==Types.TIMESTAMP) {
282             oStmt.setTimestamp(iParamIndex, new Timestamp JavaDoc(((java.util.Date JavaDoc)oParamValue).getTime()));
283           }
284           else {
285             oStmt.setObject (iParamIndex, oParamValue, iSQLType);
286           }
287         }
288         else
289           oStmt.setObject (iParamIndex, null, iSQLType);
290         break;
291
292       default:
293         String JavaDoc sParamClassName;
294         if (null!=oParamValue)
295           sParamClassName = oParamValue.getClass().getName();
296         else
297           sParamClassName = "null";
298
299         if ((Types.TIMESTAMP==iSQLType) && (oParamValue!=null)) {
300           if (sParamClassName.equals("java.util.Date")) {
301             if (DebugFile.trace) DebugFile.writeln("binding java.sql.Timestamp as SQL " + DBColumn.typeName(Types.TIMESTAMP));
302             oStmt.setTimestamp(iParamIndex, new Timestamp JavaDoc(((java.util.Date JavaDoc)oParamValue).getTime()));
303           }
304           else {
305             if (DebugFile.trace) DebugFile.writeln("binding " + sParamClassName + " as SQL " + DBColumn.typeName(iSQLType));
306             oStmt.setObject(iParamIndex, oParamValue, iSQLType);
307           }
308         }
309         else if ((Types.DATE==iSQLType) && (oParamValue!=null)) {
310           if (sParamClassName.equals("java.util.Date")) {
311             if (DebugFile.trace) DebugFile.writeln("binding java.sql.Date as SQL " + DBColumn.typeName(Types.DATE));
312             oStmt.setDate(iParamIndex, new java.sql.Date JavaDoc(((java.util.Date JavaDoc)oParamValue).getTime()));
313           }
314           else {
315             if (DebugFile.trace) DebugFile.writeln("binding " + sParamClassName + " as SQL " + DBColumn.typeName(iSQLType));
316             oStmt.setObject(iParamIndex, oParamValue, iSQLType);
317           }
318         }
319         else {
320           if ((oParamValue!=null) && DebugFile.trace) {
321              if (DebugFile.trace) DebugFile.writeln("binding " + sParamClassName + " as SQL " + DBColumn.typeName(iSQLType));
322           }
323           oStmt.setObject(iParamIndex, oParamValue, iSQLType);
324         }
325     }
326   } // bindParameter
327

328   // ---------------------------------------------------------------------------
329

330   private static void bindParameter (JDCConnection oConn, PreparedStatement JavaDoc oStmt,
331                                      int iParamIndex, Object JavaDoc oParamValue)
332     throws SQLException JavaDoc {
333
334     if (oConn.getDataBaseProduct()==JDCConnection.DBMS_ORACLE) {
335       if (oParamValue.getClass().equals(Integer JavaDoc.class) ||
336           oParamValue.getClass().equals(Short JavaDoc.class) ||
337           oParamValue.getClass().equals(Float JavaDoc.class) ||
338           oParamValue.getClass().equals(Double JavaDoc.class)) {
339         bindParameter(oConn, oStmt, iParamIndex, oParamValue, Types.NUMERIC);
340       }
341       else if (oParamValue.getClass().getName().equals("java.util.Date") ||
342                oParamValue.getClass().getName().equals("java.sql.Timestamp") ) {
343         bindParameter(oConn, oStmt, iParamIndex, oParamValue, Types.DATE);
344       }
345       else {
346         oStmt.setObject(iParamIndex, oParamValue);
347       }
348     } else {
349       oStmt.setObject(iParamIndex, oParamValue);
350     }
351   } // bindParameter
352

353   // ---------------------------------------------------------------------------
354

355   /**
356    * <p>Store a single register at the database representing a Java Object</p>
357    * for register containing LONGVARBINARY, IMAGE, BYTEA or BLOB fields use
358    * storeRegisterLong() method.
359    * Columns named "dt_created" are invisible for storeRegister() method so that
360    * register creation timestamp is not altered by afterwards updates.
361    * @param oConn Database Connection
362    * @param AllValues Values to assign to fields.
363    * @return <b>true</b> if register was inserted for first time, <false> if it was updated.
364    * @throws SQLException
365    */

366
367   public boolean storeRegister(JDCConnection oConn, HashMap JavaDoc AllValues) throws SQLException JavaDoc {
368     int c;
369     boolean bNewRow = false;
370     DBColumn oCol;
371     String JavaDoc sCol;
372     String JavaDoc sSQL = "";
373     ListIterator JavaDoc oColIterator;
374     int iAffected = 0;
375     PreparedStatement JavaDoc oStmt = null;
376
377     if (DebugFile.trace)
378       {
379       DebugFile.writeln("Begin DBTable.storeRegister([Connection], {" + AllValues.toString() + "})" );
380       DebugFile.incIdent();
381       }
382
383     try {
384       if (null!=sUpdate) {
385         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sUpdate + ")");
386
387         sSQL = sUpdate;
388
389         oStmt = oConn.prepareStatement(sSQL);
390
391         try { oStmt.setQueryTimeout(10); } catch (SQLException JavaDoc sqle) { if (DebugFile.trace) DebugFile.writeln("Error at PreparedStatement.setQueryTimeout(10)" + sqle.getMessage()); }
392
393         c = 1;
394         oColIterator = oColumns.listIterator();
395
396         while (oColIterator.hasNext()) {
397           oCol = (DBColumn) oColIterator.next();
398           sCol = oCol.getName().toLowerCase();
399
400           if (!oPrimaryKeys.contains(sCol) &&
401               (sCol.compareTo(DB.dt_created)!=0)) {
402
403             if (DebugFile.trace) {
404               if (oCol.getSqlType()==java.sql.Types.CHAR || oCol.getSqlType()==java.sql.Types.VARCHAR) {
405
406                 if (AllValues.get(sCol)!=null) {
407                   DebugFile.writeln("Binding " + sCol + "=" + AllValues.get(sCol).toString());
408
409                   if (AllValues.get(sCol).toString().length() > oCol.getPrecision())
410                     DebugFile.writeln("ERROR: value for " + oCol.getName() + " exceeds columns precision of " + String.valueOf(oCol.getPrecision()));
411                 } // fi (AllValues.get(sCol)!=null)
412
else
413                   DebugFile.writeln("Binding " + sCol + "=NULL");
414               }
415             } // fi (DebugFile.trace)
416

417             try {
418               bindParameter (oConn, oStmt, c, AllValues.get(sCol), oCol.getSqlType());
419               c++;
420             } catch (ClassCastException JavaDoc e) {
421                 if (AllValues.get(sCol)!=null)
422                   throw new SQLException JavaDoc("ClassCastException at column " + sCol + " Cannot cast Java " + AllValues.get(sCol).getClass().getName() + " to SQL type " + oCol.getSqlTypeName(), "07006");
423                 else
424                   throw new SQLException JavaDoc("ClassCastException at column " + sCol + " Cannot cast NULL to SQL type " + oCol.getSqlTypeName(), "07006");
425             }
426
427             } // endif (!oPrimaryKeys.contains(sCol))
428
} // wend
429

430         oColIterator = oPrimaryKeys.listIterator();
431         while (oColIterator.hasNext()) {
432           sCol = (String JavaDoc) oColIterator.next();
433           oCol = getColumnByName(sCol);
434
435           if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setObject (" + String.valueOf(c) + "," + AllValues.get(sCol) + "," + oCol.getSqlTypeName() + ")");
436
437           bindParameter (oConn, oStmt, c, AllValues.get(sCol), oCol.getSqlType());
438           c++;
439         } // wend
440

441         if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeUpdate()");
442
443         iAffected = oStmt.executeUpdate();
444
445         if (DebugFile.trace) DebugFile.writeln(String.valueOf(iAffected) + " affected rows");
446
447         oStmt.close();
448         oStmt = null;
449       } // fi (sUpdate!=null)
450
else
451         iAffected = 0;
452
453       if (0==iAffected)
454           {
455           bNewRow = true;
456
457           if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sInsert + ")");
458
459           sSQL = sInsert;
460
461           oStmt = oConn.prepareStatement(sInsert);
462
463           try { oStmt.setQueryTimeout(10); } catch (SQLException JavaDoc sqle) { if (DebugFile.trace) DebugFile.writeln("Error at PreparedStatement.setQueryTimeout(10)" + sqle.getMessage()); }
464
465           c = 1;
466           oColIterator = oColumns.listIterator();
467
468           while (oColIterator.hasNext()) {
469
470             oCol = (DBColumn)oColIterator.next();
471             sCol = oCol.getName();
472
473             if (DebugFile.trace) {
474               if (null!=AllValues.get(sCol))
475                 DebugFile.writeln("Binding " + sCol + "=" + AllValues.get(sCol).toString());
476               else
477                 DebugFile.writeln("Binding " + sCol + "=NULL");
478             } // fi
479

480             bindParameter (oConn, oStmt, c, AllValues.get(sCol), oCol.getSqlType());
481             c++;
482           } // wend
483

484           if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeUpdate()");
485
486           iAffected = oStmt.executeUpdate();
487
488           if (DebugFile.trace) DebugFile.writeln(String.valueOf(iAffected) + " affected rows");
489
490           oStmt.close();
491           oStmt =null;
492           }
493         else
494           bNewRow = false;
495     }
496     catch (SQLException JavaDoc sqle) {
497       try { if (null!=oStmt) oStmt.close(); } catch (Exception JavaDoc ignore) { }
498
499       throw new SQLException JavaDoc (sqle.getMessage() + " " + sSQL, sqle.getSQLState(), sqle.getErrorCode());
500     }
501
502     if (DebugFile.trace) {
503       DebugFile.decIdent();
504       DebugFile.writeln("End DBTable.storeRegister() : " + String.valueOf(bNewRow && (iAffected>0)));
505     }
506
507     return bNewRow && (iAffected>0);
508   } // storeRegister
509

510   // ---------------------------------------------------------------------------
511

512   /**
513    * <p>Store a single register at the database representing a Java Object</p>
514    * for register NOT containing LONGVARBINARY, IMAGE, BYTEA or BLOB fields use
515    * storeRegister() method witch is faster than storeRegisterLong().
516    * Columns named "dt_created" are invisible for storeRegisterLong() method so that
517    * register creation timestamp is not altered by afterwards updates.
518    * @param oConn Database Connection
519    * @param AllValues Values to assign to fields.
520    * @param BinaryLengths map of lengths for long fields.
521    * @return <b>true</b> if register was inserted for first time, <false> if it was updated.
522    * @throws SQLException
523    */

524
525   public boolean storeRegisterLong(JDCConnection oConn, HashMap JavaDoc AllValues, HashMap JavaDoc BinaryLengths) throws IOException JavaDoc, SQLException JavaDoc {
526     int c;
527     boolean bNewRow = false;
528     DBColumn oCol;
529     String JavaDoc sCol;
530     ListIterator JavaDoc oColIterator;
531     PreparedStatement JavaDoc oStmt;
532     int iAffected;
533
534     LinkedList JavaDoc oStreams;
535     InputStream JavaDoc oStream;
536     String JavaDoc sClassName;
537
538     if (DebugFile.trace)
539       {
540       DebugFile.writeln("Begin DBTable.storeRegisterLong([Connection], {" + AllValues.toString() + "})" );
541       DebugFile.incIdent();
542       }
543
544     oStreams = new LinkedList JavaDoc();
545
546     if (null!=sUpdate) {
547
548       if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sUpdate + ")");
549
550       oStmt = oConn.prepareStatement(sUpdate);
551
552       try { oStmt.setQueryTimeout(10); } catch (SQLException JavaDoc sqle) { if (DebugFile.trace) DebugFile.writeln("Error at PreparedStatement.setQueryTimeout(10)" + sqle.getMessage()); }
553
554       c = 1;
555       oColIterator = oColumns.listIterator();
556       while (oColIterator.hasNext()) {
557         oCol = (DBColumn) oColIterator.next();
558         sCol = oCol.getName().toLowerCase();
559
560         if (!oPrimaryKeys.contains(sCol) &&
561             (!sCol.equalsIgnoreCase(DB.dt_created))) {
562
563           if (DebugFile.trace) {
564             if (oCol.getSqlType()==java.sql.Types.CHAR || oCol.getSqlType()==java.sql.Types.VARCHAR) {
565               if (AllValues.get(sCol) != null) {
566                 DebugFile.writeln("Binding " + sCol + "=" +
567                                   AllValues.get(sCol).toString());
568                 if (AllValues.get(sCol).toString().length() > oCol.getPrecision())
569                   DebugFile.writeln("ERROR: value for " + oCol.getName() +
570                                     " exceeds columns precision of " +
571                                     String.valueOf(oCol.getPrecision()));
572               } // fi (AllValues.get(sCol)!=null)
573
else
574                 DebugFile.writeln("Binding " + sCol + "=NULL");
575             }
576           } // fi (DebugFile.trace)
577

578           if (oCol.getSqlType()==java.sql.Types.LONGVARCHAR || oCol.getSqlType()==java.sql.Types.CLOB || oCol.getSqlType()==java.sql.Types.LONGVARBINARY || oCol.getSqlType()==java.sql.Types.BLOB) {
579             if (BinaryLengths.containsKey(sCol)) {
580               if (((Long JavaDoc)BinaryLengths.get(sCol)).intValue()>0) {
581                 sClassName = AllValues.get(sCol).getClass().getName();
582                 if (sClassName.equals("java.io.File"))
583                   oStream = new FileInputStream JavaDoc((File JavaDoc) AllValues.get(sCol));
584                 else if (sClassName.equals("[B"))
585                   oStream = new ByteArrayInputStream JavaDoc((byte[]) AllValues.get(sCol));
586                 else if (sClassName.equals("[C"))
587                   oStream = new StringBufferInputStream JavaDoc(new String JavaDoc((char[]) AllValues.get(sCol)));
588                 else
589                   throw new SQLException JavaDoc ("Invalid object binding for column " + sCol);
590                 oStreams.addLast(oStream);
591                 oStmt.setBinaryStream(c++, oStream, ((Long JavaDoc)BinaryLengths.get(sCol)).intValue());
592               }
593               else
594                 oStmt.setObject (c++, null, oCol.getSqlType());
595             }
596             else
597              oStmt.setObject (c++, null, oCol.getSqlType());
598           }
599           else
600             bindParameter (oConn, oStmt, c++, AllValues.get(sCol), oCol.getSqlType());
601           } // fi (!oPrimaryKeys.contains(sCol))
602
} // wend
603

604       oColIterator = oPrimaryKeys.listIterator();
605       while (oColIterator.hasNext()) {
606         sCol = (String JavaDoc) oColIterator.next();
607         oCol = getColumnByName(sCol);
608
609         if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setObject (" + String.valueOf(c) + "," + AllValues.get(sCol) + "," + oCol.getSqlTypeName() + ")");
610
611         bindParameter (oConn, oStmt, c, AllValues.get(sCol), oCol.getSqlType());
612         c++;
613       } // wend
614

615       if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeUpdate()");
616
617       iAffected = oStmt.executeUpdate();
618
619       if (DebugFile.trace) DebugFile.writeln(String.valueOf(iAffected) + " affected rows");
620
621       oStmt.close();
622
623       oColIterator = oStreams.listIterator();
624
625       while (oColIterator.hasNext())
626         ((InputStream JavaDoc) oColIterator.next()).close();
627
628       oStreams.clear();
629
630     }
631     else
632       iAffected = 0;
633
634     if (0==iAffected)
635         {
636         bNewRow = true;
637
638         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sInsert + ")");
639
640         oStmt = oConn.prepareStatement(sInsert);
641
642         c = 1;
643         oColIterator = oColumns.listIterator();
644
645         while (oColIterator.hasNext()) {
646
647           oCol = (DBColumn)oColIterator.next();
648           sCol = oCol.getName();
649
650           if (DebugFile.trace) {
651             if (null!=AllValues.get(sCol))
652               DebugFile.writeln("Binding " + sCol + "=" + AllValues.get(sCol).toString());
653             else
654               DebugFile.writeln("Binding " + sCol + "=NULL");
655           }
656
657           if (oCol.getSqlType()==java.sql.Types.LONGVARCHAR || oCol.getSqlType()==java.sql.Types.CLOB || oCol.getSqlType()==java.sql.Types.LONGVARBINARY || oCol.getSqlType()==java.sql.Types.BLOB) {
658             if (BinaryLengths.containsKey(sCol)) {
659               if ( ( (Long JavaDoc) BinaryLengths.get(sCol)).intValue() > 0) {
660                 sClassName = AllValues.get(sCol).getClass().getName();
661                 if (sClassName.equals("java.io.File"))
662                   oStream = new FileInputStream JavaDoc((File JavaDoc) AllValues.get(sCol));
663                 else if (sClassName.equals("[B"))
664                   oStream = new ByteArrayInputStream JavaDoc((byte[]) AllValues.get(sCol));
665                 else if (sClassName.equals("[C"))
666                   oStream = new StringBufferInputStream JavaDoc(new String JavaDoc((char[]) AllValues.get(sCol)));
667                 else
668                   throw new SQLException JavaDoc ("Invalid object binding for column " + sCol);
669                 oStreams.addLast(oStream);
670                 oStmt.setBinaryStream(c++, oStream, ((Long JavaDoc) BinaryLengths.get(sCol)).intValue());
671               }
672               else
673                 oStmt.setObject(c++, null, oCol.getSqlType());
674             }
675             else
676               oStmt.setObject(c++, null, oCol.getSqlType());
677           }
678           else
679             bindParameter (oConn, oStmt, c++, AllValues.get(sCol), oCol.getSqlType());
680         } // wend
681

682         if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeUpdate()");
683
684         iAffected = oStmt.executeUpdate();
685
686         if (DebugFile.trace) DebugFile.writeln(String.valueOf(iAffected) + " affected rows");
687
688         oStmt.close();
689
690         oColIterator = oStreams.listIterator();
691
692         while (oColIterator.hasNext())
693           ((InputStream JavaDoc) oColIterator.next()).close();
694
695         oStreams.clear();
696     }
697
698     else
699         bNewRow = false;
700
701     // End SQLException
702

703     if (DebugFile.trace)
704       {
705       DebugFile.decIdent();
706       DebugFile.writeln("End DBTable.storeRegisterLong() : " + String.valueOf(bNewRow));
707       }
708
709     return bNewRow;
710   } // storeRegisterLong
711

712   // ---------------------------------------------------------------------------
713

714   /**
715    * <p>Delete a single register from this table at the database</p>
716    * @param oConn Database connection
717    * @param AllValues A Map with, at least, the primary key values for the register. Other Map values are ignored.
718    * @return <b>true</b> if register was delete, <b>false</b> if register to be deleted was not found.
719    * @throws SQLException
720    */

721
722   public boolean deleteRegister(JDCConnection oConn, HashMap JavaDoc AllValues) throws SQLException JavaDoc {
723     int c;
724     boolean bDeleted;
725     ListIterator JavaDoc oColIterator;
726     PreparedStatement JavaDoc oStmt;
727     Object JavaDoc oPK;
728     DBColumn oCol;
729
730     if (DebugFile.trace)
731       {
732       DebugFile.writeln("Begin DBTable.deleteRegister([Connection], {" + AllValues.toString() + "})" );
733       DebugFile.incIdent();
734       }
735
736       if (sDelete==null) {
737         throw new SQLException JavaDoc("Primary key not found", "42S12");
738       }
739
740     // Begin SQLException
741

742       if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sDelete + ")");
743
744       oStmt = oConn.prepareStatement(sDelete);
745
746       c = 1;
747       oColIterator = oPrimaryKeys.listIterator();
748
749       while (oColIterator.hasNext()) {
750         oPK = oColIterator.next();
751         oCol = getColumnByName((String JavaDoc) oPK);
752
753         if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setObject(" + String.valueOf(c) + "," + AllValues.get(oPK) + "," + oCol.getSqlTypeName() + ")");
754
755         oStmt.setObject (c++, AllValues.get(oPK), oCol.getSqlType());
756       } // wend
757

758       if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeUpdate()");
759
760       bDeleted = (oStmt.executeUpdate()>0);
761
762     // End SQLException
763

764     if (DebugFile.trace)
765       {
766       DebugFile.decIdent();
767       DebugFile.writeln("End DBTable.deleteRegister() : " + (bDeleted ? "true" : "false"));
768       }
769
770     return bDeleted;
771   } // deleteRegister
772

773   // ---------------------------------------------------------------------------
774

775   /**
776    * <p>Checks if register exists at this table</p>
777    * @param oConn Database Connection
778    * @param sQueryString Register Query String, as a SQL WHERE clause syntax
779    * @return <b>true</b> if register exists, <b>false</b> otherwise.
780    * @throws SQLException
781    */

782
783   public boolean existsRegister(JDCConnection oConn, String JavaDoc sQueryString) throws SQLException JavaDoc {
784     Statement JavaDoc oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
785
786     ResultSet JavaDoc oRSet = oStmt.executeQuery("SELECT NULL FROM " + getName() + " WHERE " + sQueryString);
787     boolean bExists = oRSet.next();
788     oRSet.close();
789     oStmt.close();
790
791     return bExists;
792   }
793
794   // ---------------------------------------------------------------------------
795

796   /**
797    * <p>Checks if register exists at this table</p>
798    * @param oConn Database Connection
799    * @param sQueryString Register Query String, as a SQL WHERE clause syntax
800    * @return <b>true</b> if register exists, <b>false</b> otherwise.
801    * @throws SQLException
802    */

803
804   public boolean existsRegister(JDCConnection oConn, String JavaDoc sQueryString, Object JavaDoc[] oQueryParams) throws SQLException JavaDoc {
805     PreparedStatement JavaDoc oStmt = oConn.prepareStatement("SELECT NULL FROM " + getName() + " WHERE " + sQueryString, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
806
807     if (oQueryParams!=null) {
808       for (int p=0; p<oQueryParams.length; p++)
809         oStmt.setObject(p+1, oQueryParams[p]);
810     }
811
812     ResultSet JavaDoc oRSet = oStmt.executeQuery();
813     boolean bExists = oRSet.next();
814     oRSet.close();
815     oStmt.close();
816
817     return bExists;
818   }
819
820   // ---------------------------------------------------------------------------
821

822   /**
823    * <p>Checks if register exists at this table</p>
824    * @param oConn Database Connection
825    * @return <b>true</b> if register exists, <b>false</b> otherwise.
826    * @throws SQLException
827    */

828
829   public boolean existsRegister(JDCConnection oConn, HashMap JavaDoc AllValues) throws SQLException JavaDoc {
830     int c;
831     boolean bExists;
832     PreparedStatement JavaDoc oStmt;
833     ResultSet JavaDoc oRSet;
834     ListIterator JavaDoc oColIterator;
835     Object JavaDoc oPK;
836     DBColumn oCol;
837
838     if (DebugFile.trace)
839       {
840       DebugFile.writeln("Begin DBTable.existsRegister([Connection], {" + AllValues.toString() + "})" );
841       DebugFile.incIdent();
842       }
843
844     oStmt = oConn.prepareStatement(sExists, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
845
846     c = 1;
847     oColIterator = oPrimaryKeys.listIterator();
848
849     while (oColIterator.hasNext()) {
850       oPK = oColIterator.next();
851       oCol = getColumnByName((String JavaDoc) oPK);
852
853       oStmt.setObject (c++, AllValues.get(oPK), oCol.getSqlType());
854     } // wend
855

856     oRSet = oStmt.executeQuery();
857     bExists = oRSet.next();
858
859     oRSet.close();
860     oStmt.close();
861
862     if (DebugFile.trace)
863       {
864       DebugFile.decIdent();
865       DebugFile.writeln("End DBTable.existsRegister() : " + String.valueOf(bExists));
866       }
867
868     return bExists;
869   } // existsRegister
870

871   // ---------------------------------------------------------------------------
872

873   /**
874    * @return List of {@link DBColumn} objects composing this table.
875    */

876
877   public LinkedList JavaDoc getColumns() {
878     return oColumns;
879   }
880
881   // ---------------------------------------------------------------------------
882

883   /**
884    * @return Columns names separated by commas
885    * @throws IllegalStateException
886    */

887
888   public String JavaDoc getColumnsStr() throws IllegalStateException JavaDoc {
889
890     if (null==oColumns)
891       throw new IllegalStateException JavaDoc("Table columns list has not been initialized");
892
893     ListIterator JavaDoc oColIterator = oColumns.listIterator();
894     String JavaDoc sGetAllCols = new String JavaDoc("");
895
896     while (oColIterator.hasNext())
897       sGetAllCols += ((DBColumn) oColIterator.next()).getName() + ",";
898
899     return sGetAllCols.substring(0, sGetAllCols.length()-1);
900
901   } // getColumnsStr
902

903   // ---------------------------------------------------------------------------
904

905   /**
906    * <p>Get DBColumn by name</p>
907    * @param sColumnName Column Name
908    * @return Reference to DBColumn ot <b>null</b> if no column with such name was found.
909    * @throws IllegalStateException If column list for table has not been initialized
910    */

911
912   public DBColumn getColumnByName (String JavaDoc sColumnName) throws IllegalStateException JavaDoc {
913
914     if (null==oColumns)
915       throw new IllegalStateException JavaDoc("Table columns list not initialized");
916
917     ListIterator JavaDoc oColIterator = oColumns.listIterator();
918     DBColumn oCol = null;
919
920     while (oColIterator.hasNext()) {
921       oCol = (DBColumn) oColIterator.next();
922       if (oCol.getName().equalsIgnoreCase(sColumnName)) {
923         break;
924       }
925       oCol = null;
926     } // wend
927

928     return oCol;
929
930   } // getColumnByName
931

932   // ---------------------------------------------------------------------------
933

934   /**
935    * <p>Get DBColumn index given its by name</p>
936    * @param sColumnName Column Name
937    * @return Column Index[1..columnsCount()] or -1 if no column with such name was found.
938    */

939
940   public int getColumnIndex (String JavaDoc sColumnName) {
941     ListIterator JavaDoc oColIterator = oColumns.listIterator();
942     DBColumn oCol = null;
943
944     while (oColIterator.hasNext()) {
945       oCol = (DBColumn) oColIterator.next();
946       if (oCol.getName().equalsIgnoreCase(sColumnName)) {
947         return oCol.getPosition();
948       }
949       oCol = null;
950     } // wend
951

952     return -1;
953
954   } // getColumnIndex
955

956   // ---------------------------------------------------------------------------
957

958   /**
959    * @return List of primary key column names
960    */

961
962   public LinkedList JavaDoc getPrimaryKey() {
963     return oPrimaryKeys;
964
965   }
966
967   // ---------------------------------------------------------------------------
968

969   /**
970    * @return Unqualified table name
971    */

972
973   public String JavaDoc getName() { return sName; }
974
975   // ---------------------------------------------------------------------------
976

977   /**
978    * @return Catalog name
979    */

980
981   public String JavaDoc getCatalog() { return sCatalog; }
982
983   // ---------------------------------------------------------------------------
984

985   public void setCatalog(String JavaDoc sCatalogName) { sCatalog=sCatalogName; }
986
987   // ---------------------------------------------------------------------------
988

989   /**
990    * @return Schema name
991    */

992
993   public String JavaDoc getSchema() { return sSchema; }
994
995   // ---------------------------------------------------------------------------
996

997   /**
998    * Set schema name
999    * @param sSchemaName String
1000   */

1001  public void setSchema(String JavaDoc sSchemaName) { sSchema=sSchemaName; }
1002
1003  // ---------------------------------------------------------------------------
1004

1005  public int hashCode() { return iHashCode; }
1006
1007  // ---------------------------------------------------------------------------
1008

1009  /**
1010   * <p>Read DBColumn List from DatabaseMetaData</p>
1011   * This is primarily an internal initialization method for DBTable object.
1012   * Usually there is no need to call it from any other class.
1013   * @param oConn Database Connection
1014   * @param oMData DatabaseMetaData
1015   * @throws SQLException
1016   */

1017  public void readColumns(Connection JavaDoc oConn, DatabaseMetaData JavaDoc oMData) throws SQLException JavaDoc {
1018      int iErrCode;
1019      Statement JavaDoc oStmt;
1020      ResultSet JavaDoc oRSet;
1021      ResultSetMetaData JavaDoc oRData;
1022      DBColumn oCol;
1023      String JavaDoc sCol;
1024      int iCols;
1025      ListIterator JavaDoc oColIterator;
1026
1027      String JavaDoc sColName;
1028      short iSQLType;
1029      String JavaDoc sTypeName;
1030      int iPrecision;
1031      int iDigits;
1032      int iNullable;
1033      int iColPos;
1034
1035      int iDBMS;
1036
1037      String JavaDoc sGetAllCols = "";
1038      String JavaDoc sSetPKCols = "";
1039      String JavaDoc sSetAllCols = "";
1040      String JavaDoc sSetNoPKCols = "";
1041
1042      oColumns = new LinkedList JavaDoc();
1043      oPrimaryKeys = new LinkedList JavaDoc();
1044
1045      if (DebugFile.trace)
1046        {
1047        DebugFile.writeln("Begin DBTable.readColumns([DatabaseMetaData])" );
1048        DebugFile.incIdent();
1049
1050        DebugFile.writeln("DatabaseMetaData.getColumns(" + sCatalog + "," + sSchema + "," + sName + ",%)");
1051        }
1052
1053      if (oConn.getMetaData().getDatabaseProductName().equals("PostgreSQL"))
1054        iDBMS = JDCConnection.DBMS_POSTGRESQL;
1055      else if (oConn.getMetaData().getDatabaseProductName().equals("Oracle"))
1056        iDBMS = JDCConnection.DBMS_ORACLE;
1057      else
1058        iDBMS = 0;
1059
1060      oStmt = oConn.createStatement();
1061
1062      try {
1063        if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(SELECT * FROM " + sName + " WHERE 1=0)");
1064
1065        oRSet = oStmt.executeQuery("SELECT * FROM " + sName + " WHERE 1=0");
1066        iErrCode = 0;
1067      }
1068      catch (SQLException JavaDoc sqle) {
1069        // Path for Oracle. DatabaseMetadata.getTables() returns table names
1070
// that later cannot be SELECTed, so this catch ignore these system tables
1071

1072        oStmt.close();
1073        oRSet = null;
1074
1075        if (DebugFile.trace) DebugFile.writeln("SQLException " + sName + " " + sqle.getMessage());
1076
1077        iErrCode = sqle.getErrorCode();
1078        if (iErrCode==0) iErrCode=-1;
1079        if (!sqle.getSQLState().equals("42000"))
1080          throw new SQLException JavaDoc(sqle.getMessage(), sqle.getSQLState(), sqle.getErrorCode());
1081      }
1082
1083      if (0==iErrCode) {
1084        if (DebugFile.trace) DebugFile.writeln("ResultSet.getMetaData()");
1085
1086        oRData= oRSet.getMetaData();
1087
1088        iCols = oRData.getColumnCount();
1089
1090        if (DebugFile.trace) DebugFile.writeln("table has " + String.valueOf(iCols) + " columns");
1091
1092        for (int c=1; c<=iCols; c++) {
1093          sColName = oRData.getColumnName(c).toLowerCase();
1094          sTypeName = oRData.getColumnTypeName(c);
1095          iSQLType = (short) oRData.getColumnType(c);
1096
1097          if (iDBMS==JDCConnection.DBMS_POSTGRESQL)
1098            switch (iSQLType) {
1099              case Types.CHAR:
1100              case Types.VARCHAR:
1101                iPrecision = oRData.getColumnDisplaySize(c);
1102                break;
1103              default:
1104                iPrecision = oRData.getPrecision(c);
1105            }
1106          else {
1107            // New for v2.0, solves bug SF887614
1108
if (iSQLType==Types.BLOB || iSQLType==Types.CLOB)
1109              iPrecision = 2147483647;
1110            // end v2.0
1111
else
1112              iPrecision = oRData.getPrecision(c);
1113          }
1114
1115          iDigits = oRData.getScale(c);
1116          iNullable = oRData.isNullable(c);
1117          iColPos = c;
1118
1119          if (5==iDBMS && iSQLType==Types.NUMERIC && iPrecision<=6 && iDigits==0) {
1120            // Workaround for an Oracle 9i bug witch is unable to convert from Short to NUMERIC but does understand SMALLINT
1121
oCol = new DBColumn (sName,sColName,(short) Types.SMALLINT, sTypeName, iPrecision, iDigits, iNullable,iColPos);
1122          }
1123          else {
1124            oCol = new DBColumn (sName,sColName,iSQLType,sTypeName,iPrecision,iDigits,iNullable,iColPos);
1125          }
1126
1127          // Establecer el comportamiento de no tocar en ningún caso los campos dt_created
1128
// quitar este if si se desea asignarlos manualmente al insertar cada registro
1129
if (!sColName.equals(DB.dt_created))
1130            oColumns.add(oCol);
1131        } // next
1132

1133        if (DebugFile.trace) DebugFile.writeln("ResultSet.close()");
1134
1135        oRSet.close();
1136        oRSet = null;
1137        oStmt.close();
1138        oStmt = null;
1139
1140        if (5==iDBMS) /* Oracle */ {
1141
1142          /* getPrimaryKeys() not working properly on some Oracle versions,
1143             use non portable implementation instead. Sergio 12-01-2004.
1144
1145          Code until v1.1.4:
1146
1147          if (DebugFile.trace)
1148            DebugFile.writeln("DatabaseMetaData.getPrimaryKeys(null, " + sSchema.toUpperCase() + ", " + sName.toUpperCase() + ")");
1149
1150          oRSet = oMData.getPrimaryKeys(sCatalog, sSchema.toUpperCase(), sName.toUpperCase());
1151          */

1152
1153          oStmt = oConn.createStatement();
1154
1155          if (DebugFile.trace) {
1156            if (null==sSchema)
1157              DebugFile.writeln("Statement.executeQuery(SELECT NULL AS TABLE_CAT, COLS.OWNER AS TABLE_SCHEM, COLS.TABLE_NAME, COLS.COLUMN_NAME, COLS.POSITION AS KEY_SEQ, COLS.CONSTRAINT_NAME AS PK_NAME FROM USER_CONS_COLUMNS COLS, USER_CONSTRAINTS CONS WHERE CONS.OWNER=COLS.OWNER AND CONS.CONSTRAINT_NAME=COLS.CONSTRAINT_NAME AND CONS.CONSTRAINT_TYPE='P' AND CONS.TABLE_NAME='" + sName.toUpperCase()+ "')");
1158            else
1159              DebugFile.writeln("Statement.executeQuery(SELECT NULL AS TABLE_CAT, COLS.OWNER AS TABLE_SCHEM, COLS.TABLE_NAME, COLS.COLUMN_NAME, COLS.POSITION AS KEY_SEQ, COLS.CONSTRAINT_NAME AS PK_NAME FROM USER_CONS_COLUMNS COLS, USER_CONSTRAINTS CONS WHERE CONS.OWNER=COLS.OWNER AND CONS.CONSTRAINT_NAME=COLS.CONSTRAINT_NAME AND CONS.CONSTRAINT_TYPE='P' AND CONS.OWNER='" + sSchema.toUpperCase() + "' AND CONS.TABLE_NAME='" + sName.toUpperCase()+ "')");
1160          }
1161
1162          if (null==sSchema)
1163            oRSet = oStmt.executeQuery("SELECT NULL AS TABLE_CAT, COLS.OWNER AS TABLE_SCHEM, COLS.TABLE_NAME, COLS.COLUMN_NAME, COLS.POSITION AS KEY_SEQ, COLS.CONSTRAINT_NAME AS PK_NAME FROM USER_CONS_COLUMNS COLS, USER_CONSTRAINTS CONS WHERE CONS.OWNER=COLS.OWNER AND CONS.CONSTRAINT_NAME=COLS.CONSTRAINT_NAME AND CONS.CONSTRAINT_TYPE='P' AND CONS.TABLE_NAME='" + sName.toUpperCase()+ "'");
1164          else
1165            oRSet = oStmt.executeQuery("SELECT NULL AS TABLE_CAT, COLS.OWNER AS TABLE_SCHEM, COLS.TABLE_NAME, COLS.COLUMN_NAME, COLS.POSITION AS KEY_SEQ, COLS.CONSTRAINT_NAME AS PK_NAME FROM USER_CONS_COLUMNS COLS, USER_CONSTRAINTS CONS WHERE CONS.OWNER=COLS.OWNER AND CONS.CONSTRAINT_NAME=COLS.CONSTRAINT_NAME AND CONS.CONSTRAINT_TYPE='P' AND CONS.OWNER='" + sSchema.toUpperCase() + "' AND CONS.TABLE_NAME='" + sName.toUpperCase()+ "'");
1166
1167          // End new code v1.2.0
1168
}
1169          else {
1170            if (DebugFile.trace)
1171              DebugFile.writeln("DatabaseMetaData.getPrimaryKeys(" + sCatalog + "," + sSchema + "," + sName + ")");
1172
1173            oRSet = oMData.getPrimaryKeys(sCatalog, sSchema, sName);
1174          }
1175
1176        if (oRSet!=null) {
1177          while (oRSet.next()) {
1178            oPrimaryKeys.add(oRSet.getString(4).toLowerCase());
1179            sSetPKCols += oRSet.getString(4) + "=? AND ";
1180          } // wend
1181

1182          if (DebugFile.trace) DebugFile.writeln("pk cols " + sSetPKCols);
1183
1184          if (sSetPKCols.length()>7)
1185            sSetPKCols = sSetPKCols.substring(0, sSetPKCols.length()-5);
1186
1187          if (DebugFile.trace) DebugFile.writeln("ResultSet.close()");
1188
1189          oRSet.close();
1190          oRSet = null;
1191        } // fi (oRSet)
1192

1193      if (null!=oStmt) { oStmt.close(); oStmt = null; }
1194
1195      oColIterator = oColumns.listIterator();
1196
1197      while (oColIterator.hasNext()) {
1198        sCol = ((DBColumn) oColIterator.next()).getName();
1199
1200        sGetAllCols += sCol + ",";
1201        sSetAllCols += "?,";
1202
1203        if (!oPrimaryKeys.contains(sCol) && !sCol.equalsIgnoreCase(DB.dt_created))
1204          sSetNoPKCols += sCol + "=?,";
1205      } // wend
1206

1207      if (DebugFile.trace) DebugFile.writeln("get all cols " + sGetAllCols );
1208
1209      if (sGetAllCols.length()>0)
1210        sGetAllCols = sGetAllCols.substring(0, sGetAllCols.length()-1);
1211      else
1212        sGetAllCols = "*";
1213
1214      if (DebugFile.trace) DebugFile.writeln("set all cols " + sSetAllCols );
1215
1216      if (sSetAllCols.length()>0)
1217        sSetAllCols = sSetAllCols.substring(0, sSetAllCols.length()-1);
1218
1219      if (DebugFile.trace) DebugFile.writeln("set no pk cols " + sSetNoPKCols );
1220
1221      if (sSetNoPKCols.length()>0)
1222        sSetNoPKCols = sSetNoPKCols.substring(0, sSetNoPKCols.length()-1);
1223
1224      if (DebugFile.trace) DebugFile.writeln("set pk cols " + sSetPKCols );
1225
1226      if (sSetPKCols.length()>0) {
1227        sSelect = "SELECT " + sGetAllCols + " FROM " + sName + " WHERE " + sSetPKCols;
1228        sInsert = "INSERT INTO " + sName + "(" + sGetAllCols + ") VALUES (" + sSetAllCols + ")";
1229        if (sSetNoPKCols.length()>0)
1230          sUpdate = "UPDATE " + sName + " SET " + sSetNoPKCols + " WHERE " + sSetPKCols;
1231        else
1232          sUpdate = null;
1233        sDelete = "DELETE FROM " + sName + " WHERE " + sSetPKCols;
1234        sExists = "SELECT NULL FROM " + sName + " WHERE " + sSetPKCols;
1235      }
1236      else {
1237        sSelect = null;
1238        sInsert = "INSERT INTO " + sName + "(" + sGetAllCols + ") VALUES (" + sSetAllCols + ")";
1239        sUpdate = null;
1240        sDelete = null;
1241        sExists = null;
1242      }
1243    } // fi (o==iErrCode)
1244

1245    if (DebugFile.trace)
1246      {
1247      DebugFile.writeln(sSelect!=null ? sSelect : "NO SELECT STATEMENT");
1248      DebugFile.writeln(sInsert!=null ? sInsert : "NO INSERT STATEMENT");
1249      DebugFile.writeln(sUpdate!=null ? sUpdate : "NO UPDATE STATEMENT");
1250      DebugFile.writeln(sDelete!=null ? sDelete : "NO DELETE STATEMENT");
1251      DebugFile.writeln(sExists!=null ? sExists : "NO EXISTS STATEMENT");
1252
1253      DebugFile.decIdent();
1254      DebugFile.writeln("End DBTable.readColumns()");
1255      }
1256
1257  } // readColumns
1258
// ----------------------------------------------------------
1259

1260  private String JavaDoc sCatalog;
1261  private String JavaDoc sSchema;
1262  private String JavaDoc sName;
1263  private int iHashCode;
1264  private LinkedList JavaDoc oColumns;
1265  private LinkedList JavaDoc oPrimaryKeys;
1266
1267  private String JavaDoc sSelect;
1268  private String JavaDoc sInsert;
1269  private String JavaDoc sUpdate;
1270  private String JavaDoc sDelete;
1271  private String JavaDoc sExists;
1272
1273} // DBTable
1274
Popular Tags