KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > server > sql99 > dql > iterator > table > UpdatableSelectIterator


1 package com.daffodilwoods.daffodildb.server.sql99.dql.iterator.table;
2
3 import java.util.*;
4
5 import com.daffodilwoods.daffodildb.server.datasystem.utility.*;
6 import com.daffodilwoods.daffodildb.server.serversystem.*;
7 import com.daffodilwoods.daffodildb.server.sql99.common.*;
8 import com.daffodilwoods.daffodildb.server.sql99.dql.execution.*;
9 import com.daffodilwoods.daffodildb.server.sql99.dql.iterator.*;
10 import com.daffodilwoods.daffodildb.server.sql99.dql.listenerevents.*;
11 import com.daffodilwoods.daffodildb.server.sql99.dql.queryexpression.queryspecification.*;
12 import com.daffodilwoods.daffodildb.server.sql99.dql.resultsetmetadata.*;
13 import com.daffodilwoods.daffodildb.server.sql99.dql.tableexpression.*;
14 import com.daffodilwoods.daffodildb.server.sql99.expression.booleanvalueexpression.*;
15 import com.daffodilwoods.daffodildb.server.sql99.utils.*;
16 import com.daffodilwoods.daffodildb.utils.*;
17 import com.daffodilwoods.daffodildb.utils.field.*;
18 import com.daffodilwoods.database.resource.*;
19 import com.daffodilwoods.database.utility.*;
20
21 /**
22  * <p>Title: UpdatableSelectIterator </p>
23  * <p>Description: This Class is responsible to support DML operations
24  * in the JDBC resultset. </p>
25  * <p>Copyright: Copyright (c) 2003</p>
26  * <p>Company: </p>
27  * @author unascribed
28  * @version 1.0
29  */

30 public class UpdatableSelectIterator extends SelectedColumnIterator {
31
32   /**
33    * Variable representing the tables involved in the from clause of given query.
34    */

35   private tableexpression tableExpression;
36   /**
37    * Variable representing the connection instance i.e used to perform
38    * persistant updation.
39    */

40   private _ServerSession serverSession;
41   /**
42    * A mapping of tables involved in the given query w.r.t. data and key columns
43    * of corresponding table.
44    */

45   private HashMap tableKeyMapping;
46   /**
47    * A mapping of tables involved in the given query and key columns of the
48    * corresponding table.
49    */

50   private HashMap tableIteratorAndKey;
51   /**
52    * Variable representing the row on which updations to be performed.
53    */

54   private Object JavaDoc insertedRow;
55   /**
56    * A list of tables requiring the corrosponding updation as per the updation
57    * on the resultset to maintain the conditions/join relations given in the query.
58    */

59   private TableDetails[] minimalTableDetails;
60
61    public UpdatableSelectIterator(ColumnDetails[] selectListColumnDetails, _Iterator iterator0, _Reference[] selectReferences, TableDetails[] allTableDetails, TableDetails[] viewTables0, String JavaDoc[] groupByPrimaryColumns, boolean isView, tableexpression tableExpression0, _ServerSession serverSession0, _Reference[] underlyingReferencesSolvableByCurrentIterator, queryspecification qs ,_Reference[] ref ,_Iterator[] iter) throws DException {
62       super(selectListColumnDetails, iterator0, selectReferences, allTableDetails, viewTables0, groupByPrimaryColumns, isView, underlyingReferencesSolvableByCurrentIterator, serverSession0, qs ,ref , iter);
63       tableExpression = tableExpression0;
64       serverSession = serverSession0;
65       tableIteratorAndKey = new HashMap();
66    }
67
68    /**
69     * This method is used to insert a new row into the result set.
70     * 1. Starts a new session to perform updation in actual database to maintain
71     * consistency. If the insert is succesfull, updation performed in this new
72     * session is commited, else, work done in this session is rolled back.
73     * 2. Inserts a blank row in the iterator and determines the tables in which
74     * updation is required so as to maintain given join relation/condtions.
75     * 3. Sets the default values defined at table definition. Checks the where
76     * clause and join conditions for the passed values given by user.
77     * 4. Updates the blank row for the passed column indexes. Some other Columns
78     * are also updated so as to satisfy given conditions.
79     * @param columns column indexes in which passed values to insert
80     * @param values to insert
81     * @return row with inserted values
82     * @throws DException
83     */

84    public Object JavaDoc insert(int[] columns, Object JavaDoc[] values) throws DException {
85       serverSession.startSavePoint();
86       ColumnMapping[] columnsMapping = columns == null ? null :
87           getColumnMappingInvolved(columns, values);
88       ColumnMappingHandler mappingHandler = new ColumnMappingHandler();
89       if (columnsMapping != null) {
90          mappingHandler.setTableColumnMapping(columnsMapping);
91       }
92       _VariableValueOperations vv = new VariableValueOperations(serverSession);
93       ( (VariableValueOperations) vv).setColumnMappingHandler(mappingHandler);
94       ( (VariableValueOperations) vv).setTableKeyMappings(tableKeyMapping);
95       ( (VariableValueOperations) vv).setVariableValue(variableValues);
96       tableExpression.setTablesForInsertion(mappingHandler, vv);
97       TableDetails[] tableNames = mappingHandler.getTablesForInsertProcess(tableKeyMapping); // why have u done this ???
98
if (tableNames != null) {
99          int len = tableNames.length;
100          _Iterator iter = null;
101          for (int i = 0; i < len; i++) {
102             _ServerTable serverTable = serverSession.getServerTable(tableNames[i].getQualifiedIdentifier());
103             _Record rec = null;
104             iter = getSessionIterator(tableNames[i]);
105             if (tableNames[i].isDated()) {
106                rec = serverTable.insertVersion(null, null, tableNames[i].getDate(vv));
107             } else {
108                rec = serverTable.insert();
109             }
110             TableKeyMapping tkm = new TableKeyMapping(tableNames[i]);
111             tkm.setRecord(rec);
112             tkm.setKey(getTableKeyFromRecord(tableNames[i], rec));
113             tkm.setIterator(iter);
114             tableKeyMapping.put(tableNames[i], tkm);
115          }
116       }
117       try {
118          tableExpression.setDefaultValues(vv);
119          tableExpression.verifyValues(vv);
120
121          /*Reason Same as mentioned in Docmentation of updateRecordsForInsert method */
122          updateRecordsForInsert(mappingHandler);
123
124       } catch (DException e) {
125          e.printStackTrace();
126          serverSession.rollbackSavePoint();
127          throw e;
128       }
129       try {
130          serverSession.commitSavePoint();
131          serverSession.commitSavePoint();
132       } catch (DException de) {
133       }
134
135       return getRowWithChangedValues(insertedRow, mappingHandler);
136    }
137
138    /**
139     * Updation of record having the passed key with the values supplied by user.
140     * 1. Starts a new session to perform updation in actual database to maintain
141     * consistency. If the update is succesfull, updation performed in this new
142     * session is commited, else, work done in this session is rolled back.
143     * This method is used to insert a new row into the result set.
144     * 2. Determines the tables in which updation is required so as to maintain
145     * given join relation/condtions.
146     * 3. Checks the where clause and join conditions for the passed values given by user.
147     * 4. Updates the row for the passed column indexes. Some other Columns are
148     * also updated so as to satisfy given conditions.
149     * @param key Key of the which is to be updated
150     * @param columns column indexes of the row to be updated
151     * @param values new values required for updation
152     * @param row row with values before updation
153     * @return updated row
154     * @throws DException
155     */

156    public Object JavaDoc update(Object JavaDoc key, int[] columns, Object JavaDoc[] values, Object JavaDoc row) throws DException {
157       insertedRow = row;
158       ColumnMapping[] columnMapp = columns == null ? null : getColumnMappingInvolved(columns, values);
159       ColumnMappingHandler columnMappHandler = new ColumnMappingHandler();
160       if (columnMapp != null) {
161          columnMappHandler.setTableColumnMapping(columnMapp);
162       }
163       int origState = state;
164       Object JavaDoc origKey = state != 0 ? null : getKey();
165
166       move(key);
167       insertedRow = getColumnValues();
168
169       serverSession.startSavePoint();
170       tableKeyMapping = new HashMap();
171       try {
172          int length = tableDetailsCC.length;
173          for (int i = 0; i < length; i++) {
174             TableDetails td = (TableDetails) tableDetailsCC[i][0];
175             Object JavaDoc tableKey = getTableKey(td, insertedRow);
176             if (tableKey != null) {
177                TableKeyMapping tkm = new TableKeyMapping(td);
178                tkm.setKey(tableKey);
179                tkm.setIterator(getSessionIterator(td));
180                tableKeyMapping.put(td, tkm);
181             }
182          }
183          VariableValueOperations vv = new VariableValueOperations(serverSession);
184          vv.setColumnMappingHandler(columnMappHandler);
185          vv.setTableKeyMappings(tableKeyMapping);
186          vv.setVariableValue(variableValues);
187          AllColumnRowReader reader = (AllColumnRowReader) rowReader;
188          vv.setRow(insertedRow, reader);
189          tableExpression.setTablesForInsertion(columnMappHandler, vv);
190          TableDetails[] tableNames = columnMappHandler.getTablesForInsertProcess(tableKeyMapping);
191          if (tableNames != null) {
192             int len = tableNames.length;
193             for (int i = 0; i < len; i++) {
194                _ServerTable serverTable = serverSession.getServerTable(tableNames[i].getQualifiedIdentifier());
195                _Record rec = tableNames[i].isDated() ?
196                    serverTable.insertVersionWithoutConstraints(tableNames[i].getDate(variableValues)) :
197                    serverTable.insert();
198                TableKeyMapping tkm = new TableKeyMapping(tableNames[i]);
199                tkm.setRecord(rec);
200                tkm.setKey(getTableKeyFromRecord(tableNames[i], rec));
201                tkm.setIterator(getSessionIterator(tableNames[i]));
202                tableKeyMapping.put(tableNames[i], tkm);
203             }
204          }
205          callForDeletingHasRecordType(insertedRow, columnMappHandler.getTablesForDelete());
206          if (tableNames != null) {
207             tableExpression.setDefaultValues(vv);
208          }
209          tableExpression.verifyValues(vv);
210          updateRecords(columnMappHandler);
211       } catch (DException ex) {
212          serverSession.rollbackSavePoint();
213          throw ex;
214       } finally {
215          if (origKey != null) {
216             int cmp = Arrays.equals( (Object JavaDoc[]) origKey, (Object JavaDoc[]) key) ? 0 : 1; // ((_AllColumnRowReader)rowReader).getComparator().compare(origKey,key);
217
try {
218                if (cmp != 0) {
219                   move(origKey);
220                } else {
221                   state = origState;
222                }
223             } catch (DException ex) {
224             }
225          } else {
226             state = origState;
227          }
228       }
229       try {
230          serverSession.commitSavePoint();
231       } catch (DException de) {
232       }
233       return getRowWithChangedValues(insertedRow, columnMappHandler);
234    }
235
236    /**
237     * This method is used to update the blank inserted row.
238     * 1. Starts a new session to maintain consistency.
239     * 2. Determines the tables in which insertion is required so as to maintain
240     * the given conditons in the query.
241     * 3. Make appropriate provision for dated table.
242     * 4. A dml instance is retrived from the connection for table to be updated
243     * and required updations are performed.
244     * @return inserted row
245     * @throws DException
246     */

247    public Object JavaDoc moveToInsertRow() throws DException {
248       if (minimalTableDetails == null) {
249          minimalTableDetails = tableExpression._fromclause3.getTablesForBlankInsert();
250       }
251       if (minimalTableDetails == null) {
252          throw new DException("DSE1258", null);
253       }
254       int len = minimalTableDetails.length;
255       tableKeyMapping = new HashMap();
256       AllColumnRowReader reader = (AllColumnRowReader) rowReader;
257       serverSession.startSavePoint();
258       try {
259          insertedRow = reader.getBlankRow();
260          for (int i = 0; i < len; i++) {
261             _ServerTable serverTable = serverSession.getServerTable(minimalTableDetails[i].getQualifiedIdentifier());
262             _Record rec = null;
263             if (minimalTableDetails[i].isDated()) {
264                variableValues.setIterator(this);
265                rec = serverTable.insertVersionWithoutConstraints(minimalTableDetails[i].getDate(variableValues));
266             } else {
267                rec = serverTable.insert();
268             }
269             TableKeyMapping tkm = new TableKeyMapping(minimalTableDetails[i]);
270             tkm.setRecord(rec);
271             tkm.setKey(getTableKeyFromRecord(minimalTableDetails[i], rec));
272             tkm.setIterator(getSessionIterator(minimalTableDetails[i]));
273             tableKeyMapping.put(minimalTableDetails[i], tkm);
274             _TableInfo tableInfo = minimalTableDetails[i].getTableInfo();
275             Object JavaDoc[] tableColumnValues = rec.getObject();
276             for (int k = 0; k < tableColumnValues.length; k++) {
277                reader.setObject(tableInfo, k, tableColumnValues[k], insertedRow);
278             }
279          }
280          return insertedRow; // changeToObjectValues(insertedRow);
281
} catch (DException e) {
282          e.printStackTrace();
283          serverSession.rollbackSavePoint();
284          throw e;
285       }
286    }
287
288    /**
289     * This method is used to delete a particular record from the result set.
290     * Moves to the particular passed key and deletes teh current row.
291     * @param key key of row to delete
292     * @throws DException
293     */

294    public void delete(Object JavaDoc key) throws DException {
295       if (minimalTableDetails == null) {
296          minimalTableDetails = tableExpression._fromclause3.getTablesForBlankInsert();
297       }
298       AllColumnRowReader reader = (AllColumnRowReader) rowReader;
299       int origState = state;
300       Object JavaDoc origKey = state != 0 ? null : getKey();
301       move(key);
302       Object JavaDoc RowValue = getColumnValues();
303
304       int lengthOfTables = minimalTableDetails.length;
305       _Iterator tableIterator = null;
306       _ServerTable serverTable = null;
307       Object JavaDoc tableKey = null;
308       serverSession.startSavePoint();
309       boolean datedTable = false;
310       try {
311          for (int i = 0; i < lengthOfTables; i++) {
312             datedTable = minimalTableDetails[i].isDated();
313             tableIterator = getSessionIterator(minimalTableDetails[i]);
314             tableKey = getTableKey(minimalTableDetails[i], RowValue);
315             tableIterator.move(tableKey);
316             serverTable = serverSession.getServerTable(minimalTableDetails[i].getQualifiedIdentifier());
317             if (datedTable) {
318                serverTable.deleteVersion(tableIterator, minimalTableDetails[i].getDate(variableValues));
319             } else {
320                _Record rd = serverTable.delete(tableIterator);
321             }
322          }
323       } catch (DException de) {
324          serverSession.rollbackSavePoint();
325          throw de;
326       } finally {
327          if (origKey != null) {
328             int cmp = Arrays.equals( (Object JavaDoc[]) origKey, (Object JavaDoc[]) key) ? 0 : 1; // ((_AllColumnRowReader)rowReader).getComparator().compare(origKey,key);
329
try {
330                if (cmp != 0) {
331                   move(origKey);
332                } else {
333                   state = origState;
334                   if (move(1) != 1) {
335                      move( -1);
336                   }
337                }
338             } catch (DException ex) {
339             }
340          } else {
341             state = origState;
342          }
343       }
344       try {
345          serverSession.commitSavePoint();
346       } catch (DException de) {
347       }
348    }
349
350    /**
351     * This method is used to referesh the data updated in case of constraints
352     * violation or any known error.
353     * @throws DException
354     */

355    public void flushInsertedRecord() throws DException {
356       serverSession.rollbackSavePoint();
357       insertedRow = null;
358    }
359
360    /**
361     * NOT USED
362     * @param td
363     * @param columnMapp
364     * @return
365     * @throws DException
366     */

367    private boolean isTableMappingToBeMade(TableDetails td, ColumnMappingHandler columnMapp) throws DException {
368       ColumnMapping cmp = columnMapp.getColumnMappingForTableDetails(td);
369       if (cmp == null || cmp.isHasRecord_False() != 1 && cmp.isHasRecord_False() != 0) {
370          return true;
371       }
372       return false;
373    }
374
375    /**
376     * Deletes the particular row for the query having HASRECORD column.
377     * @param insertedRow row to be deleted
378     * @param tddd list of tables in which deletion are required as per the result
379     * of updating HAS record column
380     * @throws DException
381     */

382    private void callForDeletingHasRecordType(Object JavaDoc insertedRow, TableDetails[] tddd) throws DException {
383       if (tddd != null) {
384          int len = tddd.length;
385          _Iterator tableIterator = null;
386          for (int i = 0; i < len; i++) {
387             _ServerTable serverTable = serverSession.getServerTable(tddd[i].getQualifiedIdentifier());
388             tableIterator = getSessionIterator(tddd[i]);
389             Object JavaDoc tableKey = getTableKey(tddd[i], insertedRow);
390             if (tableKey != null) {
391                tableIterator.move(tableKey);
392                serverTable.delete(tableIterator);
393             }
394          }
395       }
396    }
397
398    /**
399     * This method is used to perform the actual updation. It updates the columns
400     * of for each of the table involved in updation with corresponding values.
401     * @param mappingHandler column indexes verses values
402     * @throws DException
403     */

404    private void updateRecords(ColumnMappingHandler mappingHandler) throws DException {
405       int lenColumnMapping = mappingHandler.getLengthOfTableColumnValues();
406       if (lenColumnMapping > 0) {
407          TableDetails tName = null;
408          ColumnMapping columnMap;
409          Iterator iterator = mappingHandler.getIteratorOnTableKeys();
410          while (iterator.hasNext()) {
411             tName = (TableDetails) iterator.next();
412             columnMap = (ColumnMapping) mappingHandler.getColumnMappingForTableDetail(tName);
413             checkInTableMapAndUpdate(tName, columnMap);
414          }
415       }
416    }
417
418    /**
419     * This method updates the passed table with the values got from passed column
420     * mapping for the column indexes maintained in the mapping.
421     * @param td table to be updated
422     * @param columnMapping mapping of column indexes and corresponding values
423     * @throws DException
424     */

425    private void checkInTableMapAndUpdate(TableDetails td, ColumnMapping columnMapping) throws DException {
426       if (columnMapping.isHasRecord_False() == 0 /*|| columnMapping.isHasRecord_False() == 1*/) {
427          return;
428       }
429       int[] columns = null;
430       Object JavaDoc[] values = null;
431       columns = columnMapping.getIndexes();
432       values = columnMapping.getValues();
433       if (!tableKeyMapping.containsKey(td)) {
434          throw new DException("DSE3516", new Object JavaDoc[] {td.getNameOfTable()});
435       }
436
437       TableKeyMapping tKMap = (TableKeyMapping) tableKeyMapping.get(td);
438       _Iterator iter = tKMap.getIterator();
439       _Record rec = tKMap.getRecord();
440       Object JavaDoc seekKey = tKMap.getSeekKey();
441       _ServerTable serverTable = serverSession.getServerTable(td.getQualifiedIdentifier());
442       boolean seeked = iter.seek(tKMap.getSeekKey());
443       if (td.isDated()) {
444          _Record updatedRecord = serverTable.updateVersion(iter, columns, FieldUtility.getFields(values), td.getDate(variableValues));
445          tKMap.setRecord(updatedRecord);
446       } else {
447         _Record updatedRecord = serverTable.update(iter, columns, values);
448          tKMap.setRecord(updatedRecord);
449       }
450    }
451
452    /**
453     * This method is required to get the index key of the table to be updated.
454     * It also maintains a mapping of all the tables involved with their index
455     * keys.
456     * @param td table for which key is required
457     * @param record current record of resultset
458     * @return index key for the passed table
459     * @throws DException
460     */

461    private Object JavaDoc getTableKeyFromRecord(TableDetails td, _Record record) throws DException {
462       _Iterator it = null;
463       int[] columnIndexes = null;
464       if (tableIteratorAndKey.containsKey(td)) {
465          columnIndexes = (int[]) ( (Object JavaDoc[]) tableIteratorAndKey.get(td))[1];
466          it = (_Iterator) ( (Object JavaDoc[]) tableIteratorAndKey.get(td))[0];
467       } else {
468          columnIndexes = getKeyIndexes(td);
469          it = getIteratorNow(td);
470          tableIteratorAndKey.put(td, new Object JavaDoc[] {it, columnIndexes});
471       }
472       int len = columnIndexes.length;
473       Object JavaDoc[] tableKey = new Object JavaDoc[len];
474       for (int i = 0; i < len; i++) {
475          int index = columnIndexes[i];
476          tableKey[i] = record.getObject(index);
477       }
478       return tableKey;
479    }
480
481    /**
482     * Gets the key column index for passed columns.
483     * @param td table for which key column indexes are to found
484     * @return column indexes of primary key for passed table
485     * @throws DException
486     */

487    private int[] getKeyIndexes(TableDetails td) throws DException {
488       int[] columnIndexes = null;
489       AllColumnRowReader reader = (AllColumnRowReader) rowReader;
490       _Iterator it = getIteratorNow(td);
491       _KeyColumnInformation[] keys = it.getKeyColumnInformations();
492       columnIndexes = new int[keys.length];
493       for (int i = 0; i < keys.length; i++) {
494          ColumnDetails cd = keys[i].getColumnDetails();
495          int index = td.getColumnCharacteristics().getColumnIndex(cd.getAppropriateColumn());
496          columnIndexes[i] = index;
497       }
498       return columnIndexes;
499    }
500
501    /**
502     * Updates the passed row with passed column mapping of columns to be updated
503     * with their corresponding values.
504     * @param oldRow row to be updated
505     * @param clmMapping mapping of columns to be updated with their values
506     * @return updated row
507     * @throws DException
508     */

509    private Object JavaDoc getRowWithChangedValues(Object JavaDoc oldRow, ColumnMappingHandler clmMapping) throws DException {
510       AllColumnRowReader reader = (AllColumnRowReader) rowReader;
511       Object JavaDoc newRow = reader.getRowClone(oldRow);
512       Iterator tables = clmMapping.getIteratorOnTableKeys();
513       while (tables.hasNext()) {
514          TableDetails td = (TableDetails) tables.next();
515          String JavaDoc tableName = td.getQualifiedTableName();
516          TableKeyMapping tkm = (TableKeyMapping) tableKeyMapping.get(td);
517
518          if (tkm != null) {
519             _Record rec = tkm.getRecord();
520             if (rec != null) {
521                Object JavaDoc[] tableColumnValues = rec.getObject();
522                for (int k = 0; k < tableColumnValues.length; k++) {
523                   reader.setObject(td.getTableInfo(), k, tableColumnValues[k], newRow);
524                }
525             }
526          }
527
528          ColumnMapping cmp = clmMapping.getColumnMappingForTableDetails(td);
529          if (cmp.isHasRecord_False() != -1) {
530             ColumnDetails[] cdetails = cmp.getHasRecordColumnDetails();
531             if (cdetails != null) {
532                Object JavaDoc[] val = cmp.getHasRecordColumnValues();
533                for (int i = 0; i < val.length; i++) {
534                   int index = P.indexOf(selectColumnDetails, cdetails[i]);
535                   reader.setObject(index + 1, val[i], newRow);
536                }
537             }
538          }
539       }
540
541       TableDetails[] td = clmMapping.getTablesForDelete();
542       if (td != null) {
543          for (int i = 0; i < td.length; i++) {
544             String JavaDoc tableName = td[i].getQualifiedTableName();
545             int columnCount = td[i].cc.getColumnCount();
546             for (int j = 0; j < columnCount; j++) {
547                reader.setObject(td[i].getTableInfo(), j, null, newRow);
548             }
549          }
550       }
551       return newRow; //changeToObjectValues(newRow);
552
}
553
554    /**
555     * This method is required to create a mapping of column indexes and the
556     * values to be updated.
557     * @param col columns in which updation is required
558     * @param values new values
559     * @return required mapping of columns with their corresponding values
560     * @throws DException
561     */

562    private ColumnMapping[] getColumnMappingInvolved(int[] col, Object JavaDoc[] values) throws DException {
563       int len = col.length;
564       ColumnDetails[] cd = new ColumnDetails[len];
565       ArrayList arr = new ArrayList(len);
566       for (int i = 0; i < len; i++) {
567          cd[i] = selectColumnDetails[col[i] - 1];
568          arr.add(new ColumnMapping(cd[i], values[i]));
569       }
570
571       for (int k = 0; k < arr.size(); k++) {
572          ColumnMapping cm = (ColumnMapping) arr.get(k);
573          for (int j = k + 1; j < arr.size(); j++) {
574             if ( ( (ColumnMapping) arr.get(j)).getTableDetails() == cm.getTableDetails()) {
575                ColumnMapping cmtemp = (ColumnMapping) arr.remove(j);
576                cm.addColumnsAndValues(cmtemp.getOrignalColumnDetail(), cmtemp.getValue());
577                j--;
578             }
579          }
580       }
581       makeProvisionForHasRecord(arr);
582       return (ColumnMapping[]) arr.toArray(new ColumnMapping[0]);
583    }
584
585    /**
586     * This method is required to perform corresponding updations when a
587     * particular HASRECORD Column is updated. Updating HasRecord Column from true
588     * to false requires corresponding insertion into the right table and deletion
589     * is required for vice-versa fucntioning.
590     * @param arr given mapping of column indexes and values to be updated/inserted
591     * @throws DException
592     */

593    private void makeProvisionForHasRecord(ArrayList arr) throws DException {
594       int size = arr.size();
595       for (int k = 0; k < size; k++) {
596          ColumnMapping cm = (ColumnMapping) arr.get(k);
597          cm.applyColumnHasRecordCHANGES();
598       }
599    }
600
601    /**
602     * REquired to show the passed column indexes and their corresponding values
603     * to be inserted or updated.
604     * @param cmp mapping of columns and values
605     * @throws DException
606     */

607    private void showForColumnMappings(ColumnMapping[] cmp) throws DException {
608       if (cmp != null) {
609          int len = cmp.length;
610          for (int i = 0; i < len; i++) {
611             cmp[i].show();
612          }
613       }
614    }
615
616    private void showForTableKeyRecords() throws DException {
617       int len = tableKeyMapping.size();
618       if (len > 0) {
619          Iterator iter = tableKeyMapping.keySet().iterator();
620          while (iter.hasNext()) {
621          }
622       } else {
623          ;//// Removed By Program ** System.out.println(" There is no table in the HashMap ");
624
}
625    }
626
627    /**
628     * This method is required to get the iterator to perform required updation
629     * for the passed table.
630     * @param td table for which iterator is required
631     * @return iterator
632     * @throws DException
633     */

634    private _Iterator getSessionIterator(TableDetails td) throws DException {
635       _Iterator iter = null;
636       if (tableIteratorAndKey.containsKey(td)) {
637          iter = (_Iterator) ( (Object JavaDoc[]) tableIteratorAndKey.get(td))[0];
638       } else {
639          int[] columnIndexes = getKeyIndexes(td);
640          iter = getIteratorNow(td);
641          tableIteratorAndKey.put(td, new Object JavaDoc[] {iter, columnIndexes});
642       }
643       return iter;
644    }
645
646    /**
647     * This method is required to get the iterator to perform required updation
648     * for the passed table.
649     * @param td table for which iterator is required
650     * @return iterator
651     * @throws DException
652     */

653    private _Iterator getIteratorNow(TableDetails td) throws DException {
654       _Iterator itera = null;
655       if (td.isDated()) {
656          booleanvalueexpression bve = td.getDatedBooleanValueExpression();
657          _SingleTableExecuter ste = new ConditionSingleTableExecuter(null, td, serverSession, bve, null);
658          itera = serverSession.getInternalIterator(td.getQualifiedIdentifier(), ste);
659          itera.setConditionVariableValue(referencesPassed, valuesPassed, 1);
660       } else {
661          _SingleTableExecuter ste = new ConditionSingleTableExecuter(null, td, serverSession, null, null);
662          itera = serverSession.getInternalIterator(td.getQualifiedIdentifier(), ste);
663       }
664       return itera;
665    }
666
667    /**
668     * This method is required to get the key column values from the passed row
669     * for the passed table.
670     * @param td table for which values are to be retrieved
671     * @param row row from which values re to be extracted
672     * @return key column values for the passed table
673     * @throws DException
674     */

675    private Object JavaDoc getTableKey(TableDetails td, Object JavaDoc row) throws DException {
676       int[] columnIndexes = null;
677       if (tableIteratorAndKey.containsKey(td)) {
678          columnIndexes = (int[]) ( (Object JavaDoc[]) tableIteratorAndKey.get(td))[1];
679       } else {
680          columnIndexes = getKeyIndexes(td);
681          _Iterator iter = getIteratorNow(td);
682          tableIteratorAndKey.put(td, new Object JavaDoc[] {iter, columnIndexes});
683       }
684       AllColumnRowReader reader = (AllColumnRowReader) rowReader;
685       boolean nullKey = true;
686       int len = columnIndexes.length;
687       Object JavaDoc[] tableKey = new Object JavaDoc[len];
688       for (int i = 0; i < len; i++) {
689          int index = columnIndexes[i];
690          tableKey[i] = reader.getObject(td.getTableInfo(), index, row);
691          nullKey = nullKey && tableKey[i] == null;
692       }
693       return nullKey ? null : tableKey;
694    }
695
696    /**
697     * This method is required to get the data types of the columns to be updated.
698     * @return an int array having data types for all the columns of current row
699     * @throws DException
700     */

701    public int[] getDataTypes() throws DException {
702       int columnCount = 0;
703       for (int i = 0; i < tableAndIteratorMapping.length; columnCount += ( (ColumnDetails[]) tableAndIteratorMapping[i][1]).length, i++) {
704          ;
705       }
706
707       int[] dataTypes = new int[columnCount];
708       for (int i = 0, k = 0; i < tableAndIteratorMapping.length; i++) {
709          ColumnDetails[] columns = (ColumnDetails[]) tableAndIteratorMapping[i][1];
710          for (int j = 0; j < columns.length; j++) {
711             dataTypes[k++] = columns[j].getDatatype();
712          }
713       }
714       return dataTypes;
715    }
716
717    /**
718     * This method is required to get rowCount records starting from the current
719     * record and navigating in forward direction from the result set. Records
720     * are returned after being cloned to distinguise the actual record and
721     * temporary updated record.
722     * @param rowCount number of records to be returned
723     * @return an array of rowCount records
724     * @throws com.daffodilwoods.database.resource.DException
725     */

726    public Object JavaDoc[] fetchForward(int rowCount) throws com.daffodilwoods.database.resource.DException {
727       Object JavaDoc[] rows = super.fetchForward(rowCount);
728       return rows == null ? null : getRowsClone(rows);
729    }
730
731    /**
732     * This method is required to get rowCount records starting from the current
733     * record and navigating in backward direction from the result set. Records
734     * are returned after being cloned to distinguise the actual record and
735     * temporary updated record.
736     * @param rowCount number of records to be returned
737     * @return an array of rowCount records
738     * @throws com.daffodilwoods.database.resource.DException
739     */

740    public Object JavaDoc[] fetchBackward(int rowCount) throws com.daffodilwoods.database.resource.DException {
741       Object JavaDoc[] rows = super.fetchBackward(rowCount);
742       return rows == null ? null : getRowsClone(rows);
743    }
744
745    /**
746     * This method is used to get a cloned set of passed records.
747     * @param rows set of records to be clonned
748     * @return clonned set of records
749     * @throws DException
750     */

751    private Object JavaDoc[] getRowsClone(Object JavaDoc[] rows) throws DException {
752       for (int i = 0; i < rows.length; i++) {
753          Object JavaDoc[] row = (Object JavaDoc[]) rows[i];
754          for (int j = 0; j < row.length; j++) {
755             FieldBase fb = (FieldBase) row[j];
756             fb.setBufferRange(fb.getNull() ? FieldUtility.NULLBUFFERRANGE :
757                               new BufferRange(fb.getBufferRange().getBytes()));
758          }
759       }
760       return rows;
761    }
762
763    public String JavaDoc toString() {
764       return " UpdatableSelectIterator[" + iterator + "]";
765    }
766
767
768 /* These 2 Methods Pasted From OlD Source i.e 8 April 2003 on 7/08/2004 by Kaushik as said by Mr. Parveen Agarwal, undone previously by someone during Merging */
769  private void updateRecordsForInsert( ColumnMappingHandler mappingHandler ) throws DException {
770   int lenColumnMapping = mappingHandler.getLengthOfTableColumnValues();
771   if( lenColumnMapping > 0 ){
772     TableDetails tName = null ;
773     ColumnMapping columnMap ;
774     Iterator iterator = mappingHandler.getIteratorOnTableKeys();
775     while( iterator.hasNext() ){
776       tName = (TableDetails)iterator.next();
777       columnMap = (ColumnMapping)mappingHandler.getColumnMappingForTableDetail( tName );
778       checkInTableMapAndUpdateForInsert( tName , columnMap );
779     }
780   }
781 }
782
783    private void checkInTableMapAndUpdateForInsert( TableDetails td , ColumnMapping columnMapping ) throws DException {
784      if( columnMapping.isHasRecord_False() == 0 /*|| columnMapping.isHasRecord_False() == 1*/ )
785         return;
786      int[] columns = null;
787      Object JavaDoc[] values = null;
788      columns = columnMapping.getIndexes();
789      values = columnMapping.getValues();
790      if( !tableKeyMapping.containsKey(td) )
791        throw new DException("DSE Table Not Found",(Object JavaDoc[])null);
792
793      TableKeyMapping tKMap = (TableKeyMapping)tableKeyMapping.get(td);
794      _Iterator iter = tKMap.getIterator();
795      _Record rec = tKMap.getRecord();
796      Object JavaDoc seekKey = tKMap.getSeekKey();
797      _ServerTable serverTable = serverSession.getServerTable( td.getQualifiedIdentifier() );
798      boolean seeked = iter.seek( tKMap.getSeekKey());
799      if( td.isDated() ){
800          _Record updatedRecord = serverTable.updateVersion( iter , columns , values , td.getDate(variableValues));
801          tKMap.setRecord(updatedRecord);
802      }
803      else{
804          _Record updatedRecord = serverTable.insertForAlreadyInsertedRecord( iter , columns , values ,true);
805          tKMap.setRecord(updatedRecord);
806      }
807    }
808    /* Done by vibha on 13-102004 .True is returned in case of query is in parantheseis.
809       Check bug no 11614*/

810      public boolean isUpdatable() {
811        return true;
812      }
813
814
815
816 }
817
Popular Tags