summaryrefslogtreecommitdiffstats
blob: 8a50c9f59acfcae4abba63bfa87d93ad761b5fb2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.ui.skynet.dbHealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.osee.framework.core.enums.ModificationType;
import org.eclipse.osee.framework.core.enums.TxChange;
import org.eclipse.osee.framework.core.exception.OseeCoreException;
import org.eclipse.osee.framework.database.core.ConnectionHandler;
import org.eclipse.osee.framework.database.core.IOseeStatement;
import org.eclipse.osee.framework.jdk.core.type.DoubleKeyHashMap;
import org.eclipse.osee.framework.jdk.core.util.AHTML;
import org.eclipse.osee.framework.ui.skynet.results.XResultData;
import org.eclipse.osee.framework.ui.skynet.results.html.XResultPage.Manipulations;

/**
 * {@link RelationIntegrityCheckTest }
 *
 * @author Theron Virgin
 */
public class RelationIntegrityCheck extends DatabaseHealthOperation {
   public static class LocalRelationLink {
      public int relLinkId, gammaId, relTransId, branchId, aArtId, bArtId, transIdForArtifactDeletion, commitTrans,
         modType;

      public LocalRelationLink(int relLinkId, int gammaId, int transactionId, int branchId, int aArtId, int bArtId, int transIdForArtifactDeletion, int commitTrans, int modType) {
         this.aArtId = aArtId;
         this.bArtId = bArtId;
         this.branchId = branchId;
         this.gammaId = gammaId;
         this.relLinkId = relLinkId;
         this.relTransId = transactionId;
         this.transIdForArtifactDeletion = transIdForArtifactDeletion;
         this.commitTrans = commitTrans;
         this.modType = modType;
      }

      @Override
      public String toString() {
         //System.out.println("gamma_id \t transaction_id \t rel_link_id \t branch_d \t a_art_id \t b_art_id \t deleted_tran \t commit trans \t commit trans mod type");
         return String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s", gammaId, relTransId, relLinkId, branchId, aArtId,
            bArtId, transIdForArtifactDeletion, commitTrans, modType);
      }
   }
   //@formatter:off
   private static final String DELETED_ARTIFACTS_QUERY =
      " SELECT    " +
      "     tx1.gamma_id, " +
      "     tx1.transaction_id, " +
      "     tx1.branch_id, " +
      "     rel1.rel_link_id, " +
      "     rel1.a_art_id, " +
      "     rel1.b_art_id, " +
      "     tx2.transaction_id AS deleted_tran, " +
      "     txd.commit_art_id AS commit_trans_art_id, " +
      "     tx1.mod_type AS creating_trans_mod_type " +
      " FROM " +
      "     osee_txs tx1, " +
      "     osee_txs tx2, " +
      "     osee_relation_link rel1, " +
      "     osee_artifact av1, " +
      "     osee_tx_details txd " +
      " WHERE " +
      "     tx1.branch_id = tx2.branch_id AND " +
      "     tx1.tx_current = " + TxChange.CURRENT.getValue() + " AND " +
      "     tx2.tx_current = " + TxChange.DELETED.getValue() + " AND " +
      "     tx1.gamma_id = rel1.gamma_id AND " +
      "     tx2.gamma_id = av1.gamma_id AND " +
      "     av1.art_id = rel1.%s AND " +
      "     tx1.transaction_id = txd.transaction_id ";
    //@formatter:on

   // relations that reference deleted artifacts on side A
   public static final String DELETED_A_ARTIFACTS = String.format(DELETED_ARTIFACTS_QUERY, "a_art_id");
   public static final String DELETED_B_ARTIFACTS = String.format(DELETED_ARTIFACTS_QUERY, "b_art_id");

   public static final String DELETE_FROM_TXS = "DELETE FROM osee_txs where gamma_id = ? AND transaction_id = ?";

   public static final String DEL_FROM_TXS_W_SPEC_BRANCH_ID =
      "DELETE FROM osee_txs where gamma_id = ? AND transaction_id = ? AND branch_id = ?";

   // relations that no artifact (on side A of relation) references
   private static final String NO_ADDRESSING_ARTIFACTS_A =
      "SELECT tx1.gamma_id, tx1.transaction_id, rel1.rel_link_id, tx1.branch_id, rel1.a_art_id, rel1.b_art_id, 0 AS deleted_tran FROM osee_txs tx1, osee_relation_link rel1 WHERE tx1.gamma_id = rel1.gamma_id AND NOT EXISTS (SELECT 'x' FROM osee_txs tx2, osee_artifact av1 WHERE tx1.branch_id = tx2.branch_id AND tx2.gamma_id = av1.gamma_id AND av1.art_id = rel1.a_art_id)";
   // relations that no artifact (on side B of relation) references
   private static final String NO_ADDRESSING_ARTIFACTS_B =
      "SELECT tx1.gamma_id, tx1.transaction_id, rel1.rel_link_id, tx1.branch_id, rel1.a_art_id, rel1.b_art_id, 0 AS deleted_tran FROM osee_txs tx1, osee_relation_link rel1 WHERE tx1.gamma_id = rel1.gamma_id AND NOT EXISTS (SELECT 'x' FROM osee_txs tx2, osee_artifact av1 WHERE tx1.branch_id = tx2.branch_id AND tx2.gamma_id = av1.gamma_id AND av1.art_id = rel1.b_art_id)";

   private static final String UPDATE_TXS_PREVIOUS =
      "UPDATE osee_txs SET tx_current = 0 WHERE gamma_id = ? AND transaction_id = ?";
   private static final String UPDATE_TXS_CURRENT =
      "UPDATE osee_txs SET tx_current = " + TxChange.ARTIFACT_DELETED.getValue() + ", mod_type = " + ModificationType.ARTIFACT_DELETED.getValue() + " WHERE gamma_id = ? AND transaction_id = ?";

   private static final String INSERT_TXS =
      "INSERT INTO osee_txs (gamma_id, transaction_id, tx_current, mod_type, branch_id) VALUES (?, ?, " + TxChange.ARTIFACT_DELETED.getValue() + ", " + ModificationType.ARTIFACT_DELETED.getValue() + ", ?)";

   private static final String[] columnHeaders = new String[] {
      "Rel Link ID",
      "Gamma Id",
      "Transaction Id",
      "Branch_id",
      "A Art Id",
      "B Art Id",
      "Transaction ID of Deleted Artifact"};

   private static final String[] DESCRIPTION = {
      "Relation Links with non existent Artifacts on the Branch\n",
      "Relation Links with deleted Artifacts on the Branch\n"};

   private static final String[] HEADER = {
      "%S Relation Links that have artifacts that don't exist on the branch",
      "%s Relation Links that have artifacts that are deleted on the branch"};

   private DoubleKeyHashMap<Integer, Integer, LocalRelationLink> deleteMap = null;
   private DoubleKeyHashMap<Integer, Integer, LocalRelationLink> updateMap = null;
   private IProgressMonitor monitor;
   private StringBuffer sbFull = null;
   private boolean fix;
   private boolean verify;

   @Override
   protected void doHealthCheck(IProgressMonitor monitor) throws Exception {
      init(monitor);
      loadBrokenRelations();
      createReport();
      setItemsToFix(updateMap.size() + deleteMap.size());

      if (fix) {
         fix();
      } else {
         monitor.worked(calculateWork(0.40));
      }

      endReport();
   }

   private void init(IProgressMonitor monitor) {
      this.monitor = monitor;
      sbFull = new StringBuffer(AHTML.beginMultiColumnTable(100, 1));
      fix = isFixOperationEnabled();
      verify = !fix;
   }

   public RelationIntegrityCheck() {
      super("Relation Integrity Errors");
   }

   private void loadBrokenRelations() throws OseeCoreException {
      if (isLoadingBrokenRelationsNecessary()) {
         deleteMap = new DoubleKeyHashMap<Integer, Integer, LocalRelationLink>();
         updateMap = new DoubleKeyHashMap<Integer, Integer, LocalRelationLink>();

         loadData("Loading Relations with nonexistent artifacts on the A side", NO_ADDRESSING_ARTIFACTS_A, true);
         loadData("Loading Relations with nonexistent artifacts on the B side", NO_ADDRESSING_ARTIFACTS_B, true);
         loadData("Loading Relations with Deleted artifacts on the A side", DELETED_A_ARTIFACTS, false);
         loadData("Loading Relations with Deleted artifacts on the B side", DELETED_B_ARTIFACTS, false);
      } else {
         checkForCancelledStatus(monitor);
         monitor.worked(calculateWork(0.40));
      }
   }

   private boolean isLoadingBrokenRelationsNecessary() {
      return verify || isFirstRun();
   }

   private boolean isFirstRun() {
      return updateMap == null || deleteMap == null;
   }

   private void createReport() throws IOException {
      sbFull.append(AHTML.beginMultiColumnTable(100, 1));
      sbFull.append(AHTML.addHeaderRowMultiColumnTable(columnHeaders));
      displayData(0, sbFull, getSummary(), verify, deleteMap);
      displayData(1, sbFull, getSummary(), verify, updateMap);
      monitor.worked(calculateWork(0.10));
      checkForCancelledStatus(monitor);
   }

   private void deleteInvalidRelationAddressing() throws OseeCoreException {
      List<Object[]> rowsToDelete = new LinkedList<Object[]>();
      for (LocalRelationLink relLink : deleteMap.allValues()) {
         rowsToDelete.add(new Object[] {relLink.gammaId, relLink.relTransId});
      }

      monitor.subTask("Deleting Relation Addressing with " + TxChange.DELETED + " Artifact");
      if (rowsToDelete.size() != 0) {
         ConnectionHandler.runBatchUpdate(DELETE_FROM_TXS, rowsToDelete);
      }
      deleteMap = null;

      monitor.worked(calculateWork(0.10));
   }

   private void fix() throws OseeCoreException {

      //fix for NO_ADDRESSING_ARTIFACTS_A or NO_ADDRESSING_ARTIFACTS_B
      deleteInvalidRelationAddressing();

      List<Object[]> insertArtifactDeleted = new LinkedList<Object[]>();
      List<Object[]> updatePreviousAddressing = new LinkedList<Object[]>();
      List<Object[]> updateCurrentAddressing = new LinkedList<Object[]>();
      List<LocalRelationLink> unExpectedCases = new ArrayList<LocalRelationLink>();
      List<Object[]> commitOfNewRelationOnDeletedArtifactCases = new ArrayList<Object[]>();

      for (LocalRelationLink relLink : updateMap.allValues()) {
         if (relLink.relTransId > relLink.transIdForArtifactDeletion) {

            if (relLink.commitTrans > 0 && relLink.modType == 1) {
               commitOfNewRelationOnDeletedArtifactCases.add(new Object[] {
                  relLink.gammaId,
                  relLink.relTransId,
                  relLink.branchId}); //typically during a merge of a branch
               //displayUnexpectedRelLinks(unExpectedCases);
            } else {
               //NO POST PROCESSING HERE, subset of relLink(s) that are not understood to be classified.
               //At minimum they should be displayed.
               unExpectedCases.add(relLink);
            }

         } else if (relLink.relTransId == relLink.transIdForArtifactDeletion) {
            updateCurrentAddressing.add(new Object[] {relLink.gammaId, relLink.relTransId});
         } else {
            updatePreviousAddressing.add(new Object[] {relLink.gammaId, relLink.relTransId});
            insertArtifactDeleted.add(new Object[] {
               relLink.gammaId,
               relLink.transIdForArtifactDeletion,
               relLink.branchId});
         }
      }

      runInsert(commitOfNewRelationOnDeletedArtifactCases, DEL_FROM_TXS_W_SPEC_BRANCH_ID,
         "Deleting TXs with relation links made with deleted artifacts.");
      runInsert(insertArtifactDeleted, INSERT_TXS, "Inserting Addressing for Deleted Artifacts");
      runInsert(updatePreviousAddressing, UPDATE_TXS_PREVIOUS, "Updating Addressing for Deleted Artifacts");
      runInsert(updateCurrentAddressing, UPDATE_TXS_CURRENT, "Updating Addressing for Deleted Artifacts");
      updateMap = null;
   }

   @SuppressWarnings("unused")
   private void displayUnexpectedRelLinks(LocalRelationLink relationLink) {
      System.out.println("gam_id \t transaction_id \t rel_link_id \t branch_d \t a_art_id \t b_art_id \t deleted_tran \t commit trans \t commit trans mod type");
      System.out.println(relationLink.toString());
   }

   private void runInsert(List<Object[]> insertParameters, String sql, String taskName) throws OseeCoreException {
      monitor.subTask(taskName);
      if (insertParameters.size() != 0) {
         ConnectionHandler.runBatchUpdate(sql, insertParameters);
      }
      monitor.worked(calculateWork(0.10));
   }

   private void endReport() {
      sbFull.append(AHTML.endMultiColumnTable());
      XResultData rd = new XResultData();
      rd.addRaw(sbFull.toString());
      rd.report(getVerifyTaskName(), Manipulations.RAW_HTML);
      monitor.worked(calculateWork(0.10));
   }

   private void displayData(int x, StringBuffer sbFull, Appendable builder, boolean verify, DoubleKeyHashMap<Integer, Integer, LocalRelationLink> map) throws IOException {
      int count = 0;
      String header = String.format(HEADER[x], map.allValues().size());
      sbFull.append(AHTML.addRowSpanMultiColumnTable(header, columnHeaders.length));
      for (LocalRelationLink relLink : map.allValues()) {
         count++;
         sbFull.append(AHTML.addRowMultiColumnTable(new String[] {
            Integer.toString(relLink.relLinkId),
            Integer.toString(relLink.gammaId),
            Integer.toString(relLink.relTransId),
            Integer.toString(relLink.branchId),
            Integer.toString(relLink.aArtId),
            Integer.toString(relLink.bArtId),
            Integer.toString(relLink.transIdForArtifactDeletion)}));
      }

      builder.append(verify ? "Found " : "Fixed ");
      builder.append(String.valueOf(count));
      builder.append(" ");
      builder.append(DESCRIPTION[x]);
   }

   private void loadData(String description, String sql, boolean forDelete) throws OseeCoreException {
      monitor.subTask(description);
      IOseeStatement chStmt = ConnectionHandler.getStatement();
      DoubleKeyHashMap<Integer, Integer, LocalRelationLink> map = forDelete ? deleteMap : updateMap;
      try {
         chStmt.runPreparedQuery(sql);
         while (chStmt.next()) {
            //@formatter:off
            int version =              chStmt.getInt("gamma_id");
            int transactionId =        chStmt.getInt("transaction_id");
            int relationId =           chStmt.getInt("rel_link_id");
            int branchId =             chStmt.getInt("branch_id");
            int a_sideArtifactId =     chStmt.getInt("a_art_id");
            int b_sideArtifactId =     chStmt.getInt("b_art_id");
            int deletedTransaction =   chStmt.getInt("deleted_tran");

            int commitTransId =        chStmt.getInt("commit_trans_art_id");
            int modType =              chStmt.getInt("creating_trans_mod_type");
            //@formatter:on

            if (!map.containsKey(version, transactionId) && (forDelete || !deleteMap.containsKey(version, transactionId))) {
               map.put(version, transactionId, new LocalRelationLink(relationId, version, transactionId, branchId,
                  a_sideArtifactId, b_sideArtifactId, deletedTransaction, commitTransId, modType));
            } else {
               System.out.print("");
            }
         }
      } finally {
         chStmt.close();
      }
      checkForCancelledStatus(monitor);
      monitor.worked(calculateWork(0.10));
   }

   @Override
   public String getCheckDescription() {
      return "Enter Check Description Here";
   }

   @Override
   public String getFixDescription() {
      return "Enter Fix Description Here";
   }
}