Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 95e34ef7e9fcfd625c2d11974529561885ff2efb (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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*
 * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
 * 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:
 *    Stefan Winkler - initial API and implementation
 */
package org.eclipse.emf.cdo.tests.db.verifier;

import static junit.framework.Assert.assertEquals;

import org.eclipse.emf.cdo.common.model.EMFUtil;
import org.eclipse.emf.cdo.server.IRepository;
import org.eclipse.emf.cdo.server.IStore;
import org.eclipse.emf.cdo.server.db.IDBStore;
import org.eclipse.emf.cdo.server.db.IDBStoreAccessor;
import org.eclipse.emf.cdo.server.db.mapping.IClassMapping;
import org.eclipse.emf.cdo.server.db.mapping.IListMapping;
import org.eclipse.emf.cdo.server.internal.db.CDODBSchema;
import org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalAuditClassMapping;
import org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalAuditMappingStrategy;
import org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalNonAuditClassMapping;
import org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalNonAuditMappingStrategy;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry;
import org.eclipse.emf.cdo.tests.db.bundle.OM;

import org.eclipse.net4j.util.collection.Pair;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import org.eclipse.emf.ecore.EClass;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import junit.framework.AssertionFailedError;

/**
 * @author Stefan Winkler
 */
public abstract class DBStoreVerifier
{
  protected static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, DBStoreVerifier.class);

  private IRepository repository;

  private IDBStoreAccessor accessor;

  public DBStoreVerifier(IRepository repository)
  {
    this.repository = repository;
    if (repository != null)
    {
      assertEquals(true, repository.getStore() instanceof IDBStore);
    }
  }

  protected IRepository getRepository()
  {
    return repository;
  }

  protected IDBStore getStore()
  {
    return (IDBStore)repository.getStore();
  }

  protected Statement getStatement()
  {
    if (accessor == null)
    {
      accessor = (IDBStoreAccessor)repository.getStore().getReader(null);
    }

    try
    {
      return accessor.getConnection().createStatement();
    }
    catch (SQLException ex)
    {
      ex.printStackTrace();
      return null;
    }
  }

  protected Connection getConnection() throws SQLException
  {
    return getStatement().getConnection();
  }

  protected DatabaseMetaData getMetaData() throws SQLException
  {
    return getConnection().getMetaData();
  }

  protected List<IClassMapping> getClassMappings()
  {
    ArrayList<IClassMapping> result = new ArrayList<IClassMapping>();
    InternalCDOPackageRegistry packageRegistry = (InternalCDOPackageRegistry)repository.getPackageRegistry();
    for (InternalCDOPackageInfo packageInfo : packageRegistry.getPackageInfos())
    {
      // CDO core package is not mapped in horizontal mapping
      if (!packageInfo.isCorePackage())
      {
        for (EClass cls : EMFUtil.getPersistentClasses(packageInfo.getEPackage()))
        {
          result.add(getStore().getMappingStrategy().getClassMapping(cls));
        }
      }
    }

    return result;
  }

  protected void cleanUp()
  {
    if (accessor != null)
    {
      accessor.release();
    }
  }

  public void verify() throws VerificationException
  {
    try
    {
      if (TRACER.isEnabled())
      {
        TRACER.format("Starting {0}...", getClass().getSimpleName());
      }

      doVerify();

      if (TRACER.isEnabled())
      {
        TRACER.format("{0} completed without complaints...", getClass().getSimpleName());
      }
    }
    catch (Exception e)
    {
      throw new VerificationException(e);
    }
    finally
    {
      cleanUp();
    }
  }

  protected void sqlDump(String sql)
  {
    ResultSet rs = null;

    try
    {
      TRACER.format("Dumping output of {0}", sql);
      rs = getStatement().executeQuery(sql);
      int numCol = rs.getMetaData().getColumnCount();

      StringBuilder row = new StringBuilder();
      for (int c = 1; c <= numCol; c++)
      {
        row.append(String.format("%10s | ", rs.getMetaData().getColumnLabel(c)));
      }

      TRACER.trace(row.toString());

      row = new StringBuilder();
      for (int c = 1; c <= numCol; c++)
      {
        row.append("-----------+--");
      }

      TRACER.trace(row.toString());

      while (rs.next())
      {
        row = new StringBuilder();
        for (int c = 1; c <= numCol; c++)
        {
          row.append(String.format("%10s | ", rs.getString(c)));
        }

        TRACER.trace(row.toString());
      }

      row = new StringBuilder();
      for (int c = 1; c <= numCol; c++)
      {
        row.append("-----------+-");
      }

      TRACER.trace(row.toString());
    }
    catch (SQLException ex)
    {
      // NOP
    }
    finally
    {
      if (rs != null)
      {
        try
        {
          rs.close();
        }
        catch (SQLException ex)
        {
          // NOP
        }
      }
    }
  }

  protected abstract void doVerify() throws Exception;

  /**
   * @author Stefan Winkler
   */
  public static class VerificationException extends RuntimeException
  {
    private static final long serialVersionUID = 1L;

    public VerificationException(String message)
    {
      super(message);
    }

    public VerificationException(String message, Throwable t)
    {
      super(message, t);
    }

    public VerificationException(Throwable t)
    {
      super(t);
    }
  }

  /**
   * @author Stefan Winkler
   */
  public static class Audit extends DBStoreVerifier
  {
    public Audit(IRepository repo)
    {
      super(repo);

      // this is a verifier for auditing mode
      assertEquals(true, getStore().getMappingStrategy() instanceof HorizontalAuditMappingStrategy);
    }

    @Override
    protected void doVerify() throws Exception
    {
      for (IClassMapping mapping : getClassMappings())
      {
        if (mapping != null && mapping.getDBTables() != null)
        {
          verifyClassMapping(mapping);
        }
      }
    }

    private void verifyClassMapping(IClassMapping mapping) throws Exception
    {
      verifyAtMostOneUnrevised(mapping);
      verifyUniqueIdVersion(mapping);
      verifyReferences(mapping);
    }

    private void verifyAtMostOneUnrevised(IClassMapping mapping) throws Exception
    {
      String tableName = mapping.getDBTables().iterator().next().getName();
      TRACER.format("verifyAtMostOneUnrevised: {0} ...", tableName);

      String sql = "SELECT " + CDODBSchema.ATTRIBUTES_ID + ", count(1) FROM " + tableName + " WHERE "
          + CDODBSchema.ATTRIBUTES_REVISED + "= 0 GROUP BY " + CDODBSchema.ATTRIBUTES_ID;
      TRACER.format("  Executing SQL: {0} ", sql);

      ResultSet resultSet = getStatement().executeQuery(sql);
      try
      {
        while (resultSet.next())
        {
          assertEquals("Multiple unrevised rows for ID " + resultSet.getLong(1), true, resultSet.getInt(2) <= 1);
        }
      }
      finally
      {
        resultSet.close();
      }
    }

    /**
     * Verify that the pair (id,version) is unique.
     */
    private void verifyUniqueIdVersion(IClassMapping mapping) throws Exception
    {
      String tableName = mapping.getDBTables().iterator().next().getName();
      TRACER.format("verifyUniqueIdVersion: {0} ...", tableName);

      String sql = "SELECT " + CDODBSchema.ATTRIBUTES_ID + "," + CDODBSchema.ATTRIBUTES_VERSION + ", count(1) FROM "
          + tableName + " GROUP BY " + CDODBSchema.ATTRIBUTES_ID + "," + CDODBSchema.ATTRIBUTES_VERSION;

      TRACER.format("  Executing SQL: {0} ", sql);

      ResultSet resultSet = getStatement().executeQuery(sql);
      try
      {
        while (resultSet.next())
        {
          assertEquals("Multiple rows for ID " + resultSet.getLong(1) + "v" + resultSet.getInt(2), true,
              resultSet.getInt(3) <= 1);
        }
      }
      catch (AssertionFailedError e)
      {
        TRACER.trace(e.getMessage());
        sqlDump("SELECT * FROM " + tableName + " WHERE " + CDODBSchema.ATTRIBUTES_REVISED + "=0");
        throw e;
      }
      finally
      {
        resultSet.close();
      }
    }

    private void verifyReferences(IClassMapping mapping) throws Exception
    {
      List<IListMapping> listMappings = ((HorizontalAuditClassMapping)mapping).getListMappings();
      if (listMappings == null)
      {
        return;
      }

      String tableName = mapping.getDBTables().iterator().next().getName();
      String sql = "SELECT " + CDODBSchema.ATTRIBUTES_ID + ", " + CDODBSchema.ATTRIBUTES_VERSION + " FROM " + tableName;

      ArrayList<Pair<Long, Integer>> idVersions = new ArrayList<Pair<Long, Integer>>();

      ResultSet resultSet = getStatement().executeQuery(sql);
      try
      {
        while (resultSet.next())
        {
          idVersions.add(Pair.create(resultSet.getLong(1), resultSet.getInt(2)));
        }
      }
      finally
      {
        resultSet.close();
      }

      for (IListMapping listMapping : listMappings)
      {
        for (Pair<Long, Integer> idVersion : idVersions)
        {
          verifyCorrectIndices(listMapping, idVersion.getElement1(), idVersion.getElement2());
        }
      }
    }

    private void verifyCorrectIndices(IListMapping refMapping, long id, int version) throws Exception
    {
      String tableName = refMapping.getDBTables().iterator().next().getName();

      TRACER.format("verifyUniqueIdVersion: {0} for ID{1}v{2} ...", tableName, id, version);

      String sql = "SELECT " + CDODBSchema.LIST_IDX + " FROM " + tableName + " WHERE " + CDODBSchema.LIST_REVISION_ID
          + "=" + id + " AND " + CDODBSchema.LIST_REVISION_VERSION + "=" + version + " ORDER BY "
          + CDODBSchema.LIST_IDX;

      TRACER.format("  Executing SQL: {0} ", sql);

      ResultSet resultSet = getStatement().executeQuery(sql);
      int indexShouldBe = 0;

      try
      {
        while (resultSet.next())
        {
          assertEquals("Index " + indexShouldBe + " missing for ID" + id + "v" + version, indexShouldBe++,
              resultSet.getInt(1));
        }
      }
      catch (AssertionFailedError e)
      {
        sqlDump("SELECT * FROM " + tableName + " WHERE " + CDODBSchema.LIST_REVISION_ID + "=" + id + " AND "
            + CDODBSchema.LIST_REVISION_VERSION + "=" + version + " ORDER BY " + CDODBSchema.LIST_IDX);
        throw e;
      }
      finally
      {
        resultSet.close();
      }
    }
  }

  /**
   * @author Stefan Winkler
   */
  public static class NonAudit extends DBStoreVerifier
  {
    public NonAudit(IRepository repo)
    {
      super(repo);

      // this is a verifier for non-auditing mode
      assertEquals(true, getStore().getRevisionTemporality() == IStore.RevisionTemporality.NONE);
      // ... and for horizontal class mapping
      assertEquals(true, getStore().getMappingStrategy() instanceof HorizontalNonAuditMappingStrategy);
    }

    @Override
    protected void doVerify() throws Exception
    {
      for (IClassMapping mapping : getClassMappings())
      {
        if (mapping != null && mapping.getDBTables().size() > 0)
        {
          verifyClassMapping(mapping);
        }
      }
    }

    private void verifyClassMapping(IClassMapping mapping) throws Exception
    {
      verifyNoUnrevisedRevisions(mapping);
      verifyUniqueId(mapping);
      verifyReferences(mapping);
    }

    /**
     * Verify that there is no row with cdo_revised == 0.
     */
    private void verifyNoUnrevisedRevisions(IClassMapping mapping) throws Exception
    {
      String tableName = mapping.getDBTables().iterator().next().getName();
      String sql = "SELECT count(1) FROM " + tableName + " WHERE " + CDODBSchema.ATTRIBUTES_REVISED + " <> 0";
      ResultSet resultSet = getStatement().executeQuery(sql);
      try
      {
        assertEquals(true, resultSet.next());
        assertEquals("Revised revision in table " + tableName, 0, resultSet.getInt(1));
      }
      finally
      {
        resultSet.close();
      }
    }

    /**
     * Verify that the id is unique.
     */
    private void verifyUniqueId(IClassMapping mapping) throws Exception
    {
      String tableName = mapping.getDBTables().iterator().next().getName();
      String sql = "SELECT " + CDODBSchema.ATTRIBUTES_ID + ", count(1) FROM " + tableName + " GROUP BY "
          + CDODBSchema.ATTRIBUTES_ID;

      ResultSet resultSet = getStatement().executeQuery(sql);

      try
      {
        while (resultSet.next())
        {
          assertEquals("Multiple rows for ID " + resultSet.getLong(1), 1, resultSet.getInt(2));
        }
      }
      finally
      {
        resultSet.close();
      }
    }

    private void verifyReferences(IClassMapping mapping) throws Exception
    {
      List<IListMapping> referenceMappings = ((HorizontalNonAuditClassMapping)mapping).getListMappings();
      if (referenceMappings == null)
      {
        return;
      }

      String tableName = mapping.getDBTables().iterator().next().getName();
      String sql = "SELECT " + CDODBSchema.ATTRIBUTES_ID + ", " + CDODBSchema.ATTRIBUTES_VERSION + " FROM " + tableName;

      ArrayList<Pair<Long, Integer>> idVersions = new ArrayList<Pair<Long, Integer>>();

      ResultSet resultSet = getStatement().executeQuery(sql);
      try
      {
        while (resultSet.next())
        {
          idVersions.add(Pair.create(resultSet.getLong(1), resultSet.getInt(2)));
        }
      }
      finally
      {
        resultSet.close();
      }

      for (IListMapping refMapping : referenceMappings)
      {
        for (Pair<Long, Integer> idVersion : idVersions)
        {
          verifyCorrectIndices(refMapping, idVersion.getElement1());
        }
      }
    }

    private void verifyCorrectIndices(IListMapping refMapping, long id) throws Exception
    {
      String tableName = refMapping.getDBTables().iterator().next().getName();
      String sql = "SELECT " + CDODBSchema.LIST_IDX + " FROM " + tableName + " WHERE " + CDODBSchema.LIST_REVISION_ID
          + "=" + id + " ORDER BY " + CDODBSchema.LIST_IDX;

      ResultSet resultSet = getStatement().executeQuery(sql);
      int indexShouldBe = 0;
      try
      {
        while (resultSet.next())
        {
          assertEquals("Index " + indexShouldBe + " missing for ID" + id, indexShouldBe++, resultSet.getInt(1));
        }
      }
      finally
      {
        resultSet.close();
      }
    }
  }
}

Back to the top