KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > server > sessionsystem > SessionWithCommit


1 package com.daffodilwoods.daffodildb.server.sessionsystem;
2
3 import com.daffodilwoods.daffodildb.server.sql99.dql.iterator._Iterator;
4
5
6
7 import java.util.*;
8 import com.daffodilwoods.database.resource.*;
9 import com.daffodilwoods.database.sqlinitiator.*;
10 import com.daffodilwoods.daffodildb.server.datasystem.utility.*;
11 import com.daffodilwoods.daffodildb.server.sql99.expression.booleanvalueexpression.*;
12 import com.daffodilwoods.daffodildb.server.sql99.utils.*;
13 import com.daffodilwoods.daffodildb.server.serversystem.dmlvalidation.constraintsystem.*;
14 import com.daffodilwoods.database.general.*;
15 import com.daffodilwoods.daffodildb.server.serversystem.*;
16
17 import com.daffodilwoods.daffodildb.server.datasystem.mergesystem.*;
18 import com.daffodilwoods.daffodildb.server.datasystem.interfaces.*;
19 import com.daffodilwoods.daffodildb.server.datadictionarysystem.*;
20 import com.daffodilwoods.daffodildb.utils.*;
21 import com.daffodilwoods.daffodildb.server.datasystem.interfaces._IndexIteratorInfo;
22 import com.daffodilwoods.daffodildb.server.datadictionarysystem.SystemTables;
23 import java.io.File JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.PrintStream JavaDoc;
27 import com.daffodilwoods.daffodildb.server.datasystem.indexsystem.IndexDatabase;
28 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.PersistentDatabase;
29 import com.daffodilwoods.daffodildb.server.datasystem.interfaces.Utility;
30
31 /**
32  *
33  * <p>Title: </p>
34  * <p>Description: </p>
35  * <p>Copyright: Copyright (c) 2002</p>
36  * <p>Company: </p>
37  * @author unascribed
38  * @version 1.0
39  *
40  * This class is responsible for transfering record from memory to file system
41  * through commit method and also checking of deferred Constraints. It completes
42  * its work with the help of Session.
43  *
44  */

45 public class SessionWithCommit extends Session {
46
47    private ArrayList listOfTablesAffected;
48
49    /**
50     * Constructs the SessionWithCommit and passes parameters to its super class
51     *
52     * @param sessionConstant
53     * @param SessionId
54     * @param transactionId
55     * @param sessionDatabase
56     * @throws DException
57     */

58    public SessionWithCommit(Object JavaDoc sessionConstant, Object JavaDoc SessionId, Object JavaDoc transactionId, SessionDatabase sessionDatabase) throws DException {
59       super(sessionConstant, SessionId, transactionId, sessionDatabase);
60       listOfTablesAffected = new ArrayList();
61    }
62
63    /**
64     * Identifies the tables on which checking has to be performed and transfers call
65     * to FireSet Constraint method to check the constraints. It Checks the constraits
66     * for the initially deferred as well as for the constraint which were initially
67     * deferred but has been changed to deferred.
68     * @param statementExecutionContext
69     * @throws DException
70     */

71
72    public void checkConstraints(_StatementExecutionContext statementExecutionContext) throws DException {
73
74       for (int i = 0; i < listOfTablesAffected.size(); i++) {
75          _SessionTable sessionTable = (_SessionTable) getSessionTableList().get(listOfTablesAffected.get(i).toString());
76          QualifiedIdentifier tableName = sessionTable.getTableName();
77
78          _ConstraintTable constTable = ( (SessionDatabase) getSessionDatabase()).getConstraintTable(tableName);
79          if (constTable.hasDefferred()) {
80             statementExecutionContext.setOperationTypePerformSameOperation(false);
81             fireSetConstraints( (SessionTable) sessionTable, constTable, statementExecutionContext);
82          }
83
84       }
85
86       for (int i = listOfTablesAffected.size(); i-- > 0; ) {
87          _SessionTable sessionTable = (_SessionTable) getSessionTableList().get(listOfTablesAffected.get(i).toString());
88          QualifiedIdentifier tableName = sessionTable.getTableName();
89          _ConstraintTable constTable = ( (SessionDatabase) getSessionDatabase()).getDeferrableConstraintTable(tableName);
90          if (constTable.hasDefferred()) {
91             statementExecutionContext.setOperationTypePerformSameOperation(true);
92             fireSetConstraints( (SessionTable) sessionTable, constTable, statementExecutionContext);
93          }
94       }
95
96    }
97
98    /**
99     * calls rollback in Session i.e to undo the changes made after last commit in the Session.
100     * @param statementExecutionContext
101     * @throws DException
102     */

103
104    public void rollback(_StatementExecutionContext statementExecutionContext) throws DException {
105       getLock().lock(2);
106       try {
107          super.rollback(statementExecutionContext);
108          listOfTablesAffected.clear();
109          TransactionIsolationLevelHandler tih = ( (SessionDatabase) getSessionDatabase()).getTransactionIsolationLevelHandler();
110          tih.transactionRollbacked(sessionId);
111       } finally {
112          getLock().unLock();
113          synchronized (getSessionDatabase()) {
114             getSessionDatabase().notifyAll();
115          }
116          resetTransaction( ( (SessionDatabase) getSessionDatabase()).getSystemFieldsValue().getLastTransactionId());
117          resetTransactionDate();
118       }
119    }
120
121
122
123
124    /**
125     * It is responsible for transfering the records from memory to file.
126     * i.e makes the changes permanenet performed during session. It works in
127     * three steps , in first step it checks the deferred constraints ,in second
128     * step it prepare the records to trasfer in file by providing the new
129     * transactionId to each record in memory and in third step it transfers all
130     * the record in file.
131     * @param statementExecutionContext
132     * @throws DException
133     */

134
135    public void commit(_StatementExecutionContext statementExecutionContext) throws DException {
136       try {
137         checkConstraints(statementExecutionContext);
138         transferRecords(statementExecutionContext);
139         listOfTablesAffected.clear();
140         removeSession();
141       }
142       finally {
143         getLock().unLock();
144         synchronized (getSessionDatabase()) {
145           getSessionDatabase().notifyAll();
146         }
147         resetTransaction( ( (SessionDatabase) getSessionDatabase()).
148                          getSystemFieldsValue().getLastTransactionId());
149         resetTransactionDate();
150       }
151
152
153    }
154
155    public void transferRecords(_StatementExecutionContext statementExecutionContext) throws DException {
156       if (getIsolationLevel() == ReadUncommitted)
157          throw new SessionException("DSE276", null);
158       _DatabaseUser databaseUser = null;
159       try {
160          Object JavaDoc transactionIdForCommit = null;
161          SystemFieldsValue systemFieldsValue = null;
162          Iterator sessionTablesIterator = getSessionTableList().values().iterator();
163          systemFieldsValue = ( (SessionDatabase) getSessionDatabase()).getSystemFieldsValue();
164
165          SessionDatabase sessionDatabase = ( (SessionDatabase) getSessionDatabase());
166
167          ArrayList list = getTablesForLock(listOfTablesAffected, statementExecutionContext);
168          if (list.size() == 0) {
169             sessionDatabase.getTransactionIsolationLevelHandler().transactionEnded(sessionId);
170             return;
171          }
172          databaseUser = getSessionDatabase().getMergeDatabase().getDatabaseUser(list);
173          transactionIdForCommit = systemFieldsValue.getNextTransactionId();
174          /*
175                            while(sessionTablesIterator.hasNext()){
176                               _SessionTable sessionTable = ( _SessionTable )sessionTablesIterator.next();
177                               if( sessionTable.isDataModified()){
178                                  entryInTransactionTable = true;
179                                  Lock sessionTableLock = sessionTable.getSessionLock();
180                                  sessionTableLock.lock(1);
181                                  if(SessionTable.tableType == SessionTable.sessionTable)
182                                      sessionTablesToBeCommitted.add( sessionTable );
183                               }
184                            }
185           */

186          if (listOfTablesAffected.size() > 0) {
187             int[] cols = new int[] {2, 4};
188             Object JavaDoc[] vals = new Object JavaDoc[] {transactionIdForCommit, getSessionId()};
189             try {
190                ArrayList sessionTableList = new ArrayList();
191                boolean isAnyDependentTransaction = sessionDatabase.getTransactionIsolationLevelHandler().hasAnyDependentTransaction(sessionId);
192                for (int i = 0, count = listOfTablesAffected.size(); i < count; i++) {
193                   transferRecordsInFile( (SessionTable) getSessionTableList().get( ( (QualifiedIdentifier) listOfTablesAffected.get(i)).getIdentifier()), cols, vals, transactionIdForCommit, databaseUser, sessionTableList, isAnyDependentTransaction);
194                }
195
196
197
198
199
200                ArrayList indexesList = statementExecutionContext.getCreateIndexList();
201                if (indexesList.size() > 0) {
202                   for (int i = 0; i < indexesList.size(); i++) {
203                      IndexInfo indexInfo = (IndexInfo) indexesList.get(i);
204                      if (indexInfo.getType() == indexInfo.CREATEINDEX)
205                         ( (_IndexDatabase) sessionDatabase.getMergeDatabase()).createPermanantIndex(indexInfo.getTableName(), indexInfo.getIndexName(), indexInfo.getIndexInformation(), databaseUser);
206                      else if (indexInfo.getType() == indexInfo.DROPINDEX)
207                         ( (_IndexDatabase) sessionDatabase.getMergeDatabase()).dropPeramanantIndex(indexInfo.getTableName(), indexInfo.getIndexName(), databaseUser);
208                      else
209                         ( (_IndexDatabase) sessionDatabase.getMergeDatabase()).alterTable(indexInfo.getTableName(), indexInfo.getColumnInformation(), indexInfo.getAlterRecord(), indexInfo.getDefaultValue(), databaseUser);
210                   }
211                }
212                databaseUser.writeToFile();
213
214
215
216                if (!isAnyDependentTransaction)
217                   sessionDatabase.getTransactionIsolationLevelHandler().transactionEnded(sessionId);
218                else
219                   sessionDatabase.getTransactionIsolationLevelHandler().transactionCommitted(sessionId, transactionIdForCommit, sessionTableList);
220             } catch (Exception JavaDoc exdonotRemove) {
221                MergeDatabase md = ( (MergeDatabase) sessionDatabase.getMergeDatabase());
222                md.getStatus();
223                String JavaDoc daffodilHome = ( (PersistentDatabase) ( (IndexDatabase) md.getFileDatabase()).getUnderLyingDatabase()).getDaffodilHome();
224                File JavaDoc file = new File JavaDoc(daffodilHome + File.separator + "ProblemInCommit.err");
225                try {
226                   FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(file);
227                   PrintStream JavaDoc ps = new PrintStream JavaDoc(fos);
228                   exdonotRemove.printStackTrace(ps);
229                   ps.flush();
230                   ps.close();
231                   fos.close();
232                } catch (IOException JavaDoc ex1) {
233                }
234
235                databaseUser.rollback();
236             } catch (Throwable JavaDoc exdonotRemove) {
237                MergeDatabase md = ( (MergeDatabase) sessionDatabase.getMergeDatabase());
238                md.getStatus();
239                String JavaDoc daffodilHome = ( (PersistentDatabase) ( (IndexDatabase) md.getFileDatabase()).getUnderLyingDatabase()).getDaffodilHome();
240                File JavaDoc file = new File JavaDoc(daffodilHome + File.separator + "ProblemInCommit.err");
241                try {
242                   FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(file);
243                   PrintStream JavaDoc ps = new PrintStream JavaDoc(fos);
244                   exdonotRemove.printStackTrace(ps);
245                   ps.flush();
246                   ps.close();
247                   fos.close();
248                } catch (IOException JavaDoc ex1) {
249                }
250                databaseUser.rollback();
251
252             }
253          }
254
255       } catch (RuntimeException JavaDoc ex) {
256          throw ex;
257       } finally {
258
259          setDataModifiedStatusFalse();
260          resetTransaction( ( (SessionDatabase) getSessionDatabase()).getSystemFieldsValue().getLastTransactionId());
261          if (databaseUser != null)
262             databaseUser.releaseCluster();
263             /* if( entryInTransactionTable ){
264                                   SessionDatabase sessionDatabase = ((SessionDatabase)getSessionDatabase());
265                                   for (int i = 0; i < sessionTablesToBeCommitted.size(); i++) {
266                                       _SessionTable sessionTable =((_SessionTable)sessionTablesToBeCommitted.get(i));
267                                       Lock sessionTableLock = sessionTable.getSessionLock();
268                                       sessionTableLock.unLock();
269                                   }
270                                   synchronized(sessionDatabase){
271                                       sessionDatabase.notifyAll();
272                                   }
273
274                               }*/

275          synchronized (sessionDatabase) {
276             sessionDatabase.notifyAll();
277          }
278          resetTransactionDate();
279       }
280    }
281
282    private void resetTransaction(Object JavaDoc transactionIdForCommit) throws DException {
283       if (getIsolationLevel() == ReadTransactionSerializable) {
284          setTransactionId(transactionIdForCommit, ReadTransactionSerializable);
285          isTransactionStarted = false;
286       }
287
288    }
289
290    private void transferRecordsInFile(SessionTable sessionTable, int[] columnIndexes, Object JavaDoc[] values, Object JavaDoc transactionId, _DatabaseUser databaseUser, ArrayList sessionTableList, boolean isAnyDependentTransaction) throws DException {
291       _MergeTable mergeTable = (_MergeTable) sessionTable.getMergeTable();
292       sessionTableList.add(sessionTable);
293       sessionTableList.add(Utility.getBooleanValue(sessionTable.delete));
294       sessionTable.transferRecords(databaseUser, transactionId, isAnyDependentTransaction);
295
296       sessionTable.setPerformCommit(false);
297       sessionTable.resetAll();
298    }
299
300    protected void finalize() {
301       try {
302          rollback(null);
303
304       } catch (DException d) {
305       } finally {
306          try {
307             ( (SessionDatabase) getSessionDatabase()).getTransactionIsolationLevelHandler().transactionRollbacked(sessionId);
308          } catch (DException ex) {
309          }
310       }
311    }
312
313    /** @todo Methos needs to be checked */
314    /**
315     * Insert address of record from referenced table to referencing table.
316     * @throws DException
317     */

318
319    private void includeCreateIndexTable(ArrayList list, _StatementExecutionContext sec) throws DException {
320       ArrayList indexesList = sec.getCreateIndexList();
321       if (indexesList.size() > 0) {
322          list.add( ( (IndexInfo) indexesList.get(0)).getTableName());
323          list.add(SystemTables.DATABASEINDEXINFO);
324          list.add(SystemTables.DATABASEINDEXCOLUMNS);
325          list.add(SystemTables.CLUSTERINFO);
326       }
327    }
328
329    /**
330     * Prepare is used for Distributed transactions, it writes the data in memory to a file on disk.
331     * <br><br>
332     * fetches the next transaction id for commit.
333     * with the help of session table list iterator, passes the SEC to every session table in session table list
334     * to prepare it self for ccommit.
335     * @param statementExecutionContext
336     * @return boolean
337     * @throws DException
338     */

339
340    public boolean prepare(_StatementExecutionContext statementExecutionContext) {
341
342       try {
343          checkConstraints(statementExecutionContext);
344
345       } catch (DException ex) {
346          return false;
347       }
348       return true;
349    }
350
351    /**
352     * makes the changes made during prepare statement permanent, (used for distributed transactions)
353     * <br><br>
354     * Fetches the next transaction id for commit.
355     * passes this transaction id and SEC to each session table to make persistent.
356     * @param statementExecutionContext
357     * @return boolean
358     * @throws DException
359     */

360
361    public boolean makePersistent(_StatementExecutionContext statementExecutionContext) throws DException {
362       try {
363          transferRecords(statementExecutionContext);
364          listOfTablesAffected.clear();
365       } catch (DException ex) {
366          return false;
367       }
368       return true;
369    }
370
371    private ArrayList getTablesForLock(ArrayList list, _StatementExecutionContext sec) throws DException {
372       ArrayList tables = new ArrayList(list.size());
373       for (int i = 0; i < list.size(); i++) {
374          tables.add(list.get(i));
375       }
376       includeCreateIndexTable(tables, sec);
377       return tables;
378    }
379
380    public void addTableInChangedTableList(QualifiedIdentifier tableName) {
381       listOfTablesAffected.add(tableName);
382    }
383
384    public void removeTable(QualifiedIdentifier tableName) throws DException {
385       listOfTablesAffected.remove(tableName);
386       super.removeTable(tableName);
387    }
388
389    private void removeSession() throws DException {
390       Iterator sessionTablesIterator = getSessionTableList().values().iterator();
391       while (sessionTablesIterator.hasNext()) {
392          _SessionTable sessionTable = (_SessionTable) sessionTablesIterator.next();
393          ( (SessionTable) sessionTable).removeSession();
394       }
395    }
396 }
397
Popular Tags