Skip to main content
summaryrefslogtreecommitdiffstats
blob: 509309e1987e7785100cdd23e099c5b76697b2f0 (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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/*
 * Copyright (c) 2009-2013, 2015 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:
 *    Eike Stepper - initial API and implementation
 *    Stefan Winkler - 271444: [DB] Multiple refactorings bug 271444
 */
package org.eclipse.emf.cdo.server.internal.db.mapping.horizontal;

import org.eclipse.emf.cdo.common.CDOCommonRepository.IDGenerationLocation;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.model.CDOClassifierRef;
import org.eclipse.emf.cdo.common.protocol.CDODataInput;
import org.eclipse.emf.cdo.common.protocol.CDODataOutput;
import org.eclipse.emf.cdo.common.revision.CDORevision;
import org.eclipse.emf.cdo.eresource.CDOResourceNode;
import org.eclipse.emf.cdo.eresource.EresourcePackage;
import org.eclipse.emf.cdo.server.IRepository;
import org.eclipse.emf.cdo.server.IStoreAccessor.QueryResourcesContext;
import org.eclipse.emf.cdo.server.IStoreAccessor.QueryXRefsContext;
import org.eclipse.emf.cdo.server.db.IDBStore;
import org.eclipse.emf.cdo.server.db.IDBStoreAccessor;
import org.eclipse.emf.cdo.server.db.IIDHandler;
import org.eclipse.emf.cdo.server.db.mapping.IClassMapping;
import org.eclipse.emf.cdo.server.db.mapping.IClassMappingBulkSupport;
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.IObjectTypeMapper;
import org.eclipse.emf.cdo.server.internal.db.IObjectTypeMapperBulkSupport;
import org.eclipse.emf.cdo.server.internal.db.bundle.OM;
import org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy;
import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;

import org.eclipse.net4j.db.DBException;
import org.eclipse.net4j.db.DBUtil;
import org.eclipse.net4j.db.DBUtil.DeserializeRowHandler;
import org.eclipse.net4j.db.IDBAdapter;
import org.eclipse.net4j.db.IDBConnection;
import org.eclipse.net4j.db.ddl.IDBTable;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.monitor.OMMonitor;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import org.eclipse.emf.ecore.EClass;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * * This abstract base class refines {@link AbstractMappingStrategy} by implementing aspects common to horizontal
 * mapping strategies -- namely:
 * <ul>
 * <li>object type cache (table cdo_objects)
 * <li>resource query handling
 * </ul>
 *
 * @author Eike Stepper
 * @since 2.0
 */
public abstract class AbstractHorizontalMappingStrategy extends AbstractMappingStrategy implements IMappingConstants
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, AbstractHorizontalMappingStrategy.class);

  /**
   * The associated object type mapper.
   */
  private IObjectTypeMapper objectTypeMapper;

  public AbstractHorizontalMappingStrategy()
  {
  }

  public CDOClassifierRef readObjectType(IDBStoreAccessor accessor, CDOID id)
  {
    return objectTypeMapper.getObjectType(accessor, id);
  }

  public boolean putObjectType(IDBStoreAccessor accessor, long timeStamp, CDOID id, EClass type)
  {
    return objectTypeMapper.putObjectType(accessor, timeStamp, id, type);
  }

  public boolean removeObjectType(IDBStoreAccessor accessor, CDOID id)
  {
    return objectTypeMapper.removeObjectType(accessor, id);
  }

  public void repairAfterCrash(IDBAdapter dbAdapter, Connection connection)
  {
    IDBStore store = getStore();
    IRepository repository = store.getRepository();
    if (repository.getIDGenerationLocation() == IDGenerationLocation.STORE)
    {
      IIDHandler idHandler = store.getIDHandler();

      if (repository.isSupportingBranches())
      {
        CDOID minLocalID = getMinLocalID(connection);
        idHandler.setNextLocalObjectID(minLocalID);
      }

      CDOID maxID = objectTypeMapper.getMaxID(connection, idHandler);
      idHandler.setLastObjectID(maxID);
    }
  }

  public void queryResources(IDBStoreAccessor accessor, QueryResourcesContext context)
  {
    // only support timestamp in audit mode
    if (context.getTimeStamp() != CDORevision.UNSPECIFIED_DATE && !hasAuditSupport())
    {
      throw new IllegalArgumentException("Mapping Strategy does not support audits"); //$NON-NLS-1$
    }

    EresourcePackage resourcesPackage = EresourcePackage.eINSTANCE;

    // first query folders
    IClassMapping resourceFolder = getClassMapping(resourcesPackage.getCDOResourceFolder());
    boolean shallContinue = queryResources(accessor, resourceFolder, context);

    // not enough results? -> query resources
    if (shallContinue)
    {
      IClassMapping resource = getClassMapping(resourcesPackage.getCDOResource());
      queryResources(accessor, resource, context);
    }
  }

  public void queryXRefs(IDBStoreAccessor accessor, QueryXRefsContext context)
  {
    IIDHandler idHandler = getStore().getIDHandler();
    StringBuilder builder = null;

    // create a string containing "(id1,id2,...)"
    // NOTE: this might not scale infinitely, because of dbms-dependent
    // max size for SQL strings. But for now, it's the easiest way...
    for (CDOID targetID : context.getTargetObjects().keySet())
    {
      // NOTE: currently no support for external references!
      if (builder == null)
      {
        builder = new StringBuilder("(");
      }
      else
      {
        builder.append(",");
      }

      idHandler.appendCDOID(builder, targetID);
    }

    builder.append(")");
    String idString = builder.toString();

    for (EClass eClass : context.getSourceCandidates().keySet())
    {
      IClassMapping classMapping = getClassMapping(eClass);
      boolean more = classMapping.queryXRefs(accessor, context, idString);
      if (!more)
      {
        // cancel query (max results reached or user canceled)
        return;
      }
    }
  }

  public void rawExport(IDBStoreAccessor accessor, CDODataOutput out, int fromBranchID, int toBranchID,
      long fromCommitTime, long toCommitTime) throws IOException
  {
    StringBuilder builder = new StringBuilder();
    builder.append(" WHERE a_t."); //$NON-NLS-1$
    builder.append(ATTRIBUTES_CREATED);
    builder.append(" BETWEEN "); //$NON-NLS-1$
    builder.append(fromCommitTime);
    builder.append(" AND "); //$NON-NLS-1$
    builder.append(toCommitTime);

    String attrSuffix = builder.toString();
    IDBConnection connection = accessor.getDBConnection();

    Collection<IClassMapping> classMappings = getClassMappings(true).values();
    out.writeInt(classMappings.size());

    for (IClassMapping classMapping : classMappings)
    {
      EClass eClass = classMapping.getEClass();
      out.writeCDOClassifierRef(eClass);

      IDBTable table = classMapping.getDBTables().get(0);
      DBUtil.serializeTable(out, connection, table, "a_t", attrSuffix);

      for (IListMapping listMapping : classMapping.getListMappings())
      {
        rawExportList(out, connection, listMapping, table, attrSuffix);
      }
    }

    objectTypeMapper.rawExport(connection, out, fromCommitTime, toCommitTime);
  }

  protected void rawExportList(CDODataOutput out, IDBConnection connection, IListMapping listMapping,
      IDBTable attrTable, String attrSuffix) throws IOException
  {
    for (IDBTable table : listMapping.getDBTables())
    {
      String listSuffix = ", " + attrTable + " a_t" + attrSuffix;
      String listJoin = getListJoinForRawExport("a_t", "l_t");
      if (listJoin != null)
      {
        listSuffix += listJoin;
      }

      DBUtil.serializeTable(out, connection, table, "l_t", listSuffix);
    }
  }

  protected String getListJoinForRawExport(String attrTable, String listTable)
  {
    return getListJoin(attrTable, listTable);
  }

  public void rawImport(IDBStoreAccessor accessor, CDODataInput in, long fromCommitTime, long toCommitTime,
      OMMonitor monitor) throws IOException
  {
    int size = in.readInt();
    if (size == 0)
    {
      return;
    }

    int objectTypeMapperWork = 10;
    monitor.begin(3 * size + objectTypeMapperWork);

    try
    {
      IDBConnection connection = accessor.getDBConnection();

      for (int i = 0; i < size; i++)
      {
        EClass eClass = (EClass)in.readCDOClassifierRefAndResolve();
        IClassMapping classMapping = getClassMapping(eClass);

        // IClassMapping classMapping;
        // IDBSchemaTransaction schemaTransaction = null;
        //
        // try
        // {
        // schemaTransaction = accessor.getStore().getDatabase().openSchemaTransaction();
        // classMapping = getClassMapping(eClass);
        // schemaTransaction.commit();
        // }
        // catch (RuntimeException ex)
        // {
        // throw ex;
        // }
        // catch (Error ex)
        // {
        // throw ex;
        // }
        // finally
        // {
        // if (schemaTransaction != null)
        // {
        // schemaTransaction.close();
        // }
        // }

        IDBTable table = classMapping.getDBTables().get(0);
        DBUtil.deserializeTable(in, connection, table, monitor.fork());
        rawImportReviseOldRevisions(connection, table, monitor.fork());
        rawImportUnreviseNewRevisions(connection, table, fromCommitTime, toCommitTime, monitor.fork());

        List<IListMapping> listMappings = classMapping.getListMappings();
        int listSize = listMappings.size();
        if (listSize == 0)
        {
          monitor.worked();
        }
        else
        {
          OMMonitor listMonitor = monitor.fork();
          listMonitor.begin(listSize);

          try
          {
            for (IListMapping listMapping : listMappings)
            {
              rawImportList(in, connection, listMapping, listMonitor.fork());
            }
          }
          finally
          {
            listMonitor.done();
          }
        }
      }

      objectTypeMapper.rawImport(connection, in, monitor.fork(objectTypeMapperWork));
    }
    finally
    {
      monitor.done();
    }
  }

  protected void rawImportUnreviseNewRevisions(IDBConnection connection, IDBTable table, long fromCommitTime,
      long toCommitTime, OMMonitor monitor)
  {
    throw new UnsupportedOperationException("Must be overridden");
  }

  protected void rawImportReviseOldRevisions(IDBConnection connection, IDBTable table, OMMonitor monitor)
  {
    throw new UnsupportedOperationException("Must be overridden");
  }

  protected void rawImportList(CDODataInput in, IDBConnection connection, IListMapping listMapping, OMMonitor monitor)
      throws IOException
  {
    Collection<IDBTable> tables = listMapping.getDBTables();
    int size = tables.size();
    if (size == 0)
    {
      return;
    }

    monitor.begin(size);

    try
    {
      for (IDBTable table : tables)
      {
        DBUtil.deserializeTable(in, connection, table, monitor.fork(), getImportListHandler());
      }
    }
    finally
    {
      monitor.done();
    }
  }

  protected DeserializeRowHandler getImportListHandler()
  {
    // Only needed with ranges
    return null;
  }

  public String getListJoin(String attrTable, String listTable)
  {
    return " AND " + attrTable + "." + ATTRIBUTES_ID + "=" + listTable + "." + LIST_REVISION_ID;
  }

  @Override
  protected boolean isMapped(EClass eClass)
  {
    return !eClass.isAbstract() && !eClass.isInterface();
  }

  @Override
  protected Collection<EClass> getClassesWithObjectInfo()
  {
    return getClassMappings().keySet();
  }

  @Override
  public void writeBulkRevisions(IDBStoreAccessor accessor, Map<EClass, List<InternalCDORevision>> revisionsPerClass,
      Map<CDOID, EClass> newObjectTypes, CDOBranch branch, long timeStamp, OMMonitor monitor)
  {
    monitor.begin(revisionsPerClass.size() + (newObjectTypes.isEmpty() ? 0 : 1));

    try
    {
      for (Entry<EClass, List<InternalCDORevision>> entry : revisionsPerClass.entrySet())
      {
        EClass eClass = entry.getKey();
        List<InternalCDORevision> revisions = entry.getValue();

        IClassMappingBulkSupport classMapping = (IClassMappingBulkSupport)getClassMapping(eClass);
        classMapping.writeBulkRevisions(accessor, revisions, branch, timeStamp, monitor.fork());
      }

      if (!newObjectTypes.isEmpty())
      {
        if (objectTypeMapper instanceof IObjectTypeMapperBulkSupport)
        {
          IObjectTypeMapperBulkSupport bulkSupport = (IObjectTypeMapperBulkSupport)objectTypeMapper;
          bulkSupport.putObjectTypes(accessor, newObjectTypes, timeStamp, monitor.fork());
        }
        else
        {
          putObjectTypes(accessor, newObjectTypes, timeStamp, monitor.fork());
        }
      }
    }
    catch (SQLException ex)
    {
      throw new DBException(ex);
    }
    finally
    {
      monitor.done();
    }
  }

  @Override
  protected void doActivate() throws Exception
  {
    super.doActivate();
    if (objectTypeMapper == null)
    {
      objectTypeMapper = createObjectTypeMapper();
    }

    LifecycleUtil.activate(objectTypeMapper);
  }

  @Override
  protected void doDeactivate() throws Exception
  {
    LifecycleUtil.deactivate(objectTypeMapper);
    super.doDeactivate();
  }

  private IObjectTypeMapper createObjectTypeMapper()
  {
    ObjectTypeTable table = new ObjectTypeTable();
    table.setMappingStrategy(this);

    int cacheSize = getObjectTypeCacheSize();
    if (cacheSize == 0)
    {
      return table;
    }

    ObjectTypeCache cache = new ObjectTypeCache(cacheSize);
    cache.setMappingStrategy(this);
    cache.setDelegate(table);
    return cache;
  }

  private int getObjectTypeCacheSize()
  {
    int objectTypeCacheSize = ObjectTypeCache.DEFAULT_CACHE_CAPACITY;

    Object value = getProperties().get(Props.OBJECT_TYPE_CACHE_SIZE);
    if (value != null)
    {
      try
      {
        int intValue = Integer.parseInt((String)value);
        objectTypeCacheSize = intValue;
      }
      catch (NumberFormatException e)
      {
        OM.LOG.warn("Malformed configuration option for object type cache size. Using default.");
      }
    }

    return objectTypeCacheSize;
  }

  private void putObjectTypes(IDBStoreAccessor accessor, Map<CDOID, EClass> newObjectTypes, long timeStamp,
      OMMonitor monitor)
  {
    monitor.begin(newObjectTypes.size());

    try
    {
      for (Entry<CDOID, EClass> entry : newObjectTypes.entrySet())
      {
        putObjectType(accessor, timeStamp, entry.getKey(), entry.getValue());
        monitor.worked();
      }
    }
    finally
    {
      monitor.done();
    }
  }

  /**
   * This is an intermediate implementation. It should be changed after classmappings support a general way to implement
   * queries ...
   *
   * @param accessor
   *          the accessor to use.
   * @param classMapping
   *          the class mapping of a class instanceof {@link CDOResourceNode} which should be queried.
   * @param context
   *          the query context containing the parameters and the result.
   * @return <code>true</code> if result context is not yet full and query should continue false, if result context is
   *         full and query should stop.
   */
  private boolean queryResources(IDBStoreAccessor accessor, IClassMapping classMapping, QueryResourcesContext context)
  {
    CDOID folderID = context.getFolderID();
    String name = context.getName();
    boolean exactMatch = context.exactMatch();

    IIDHandler idHandler = getStore().getIDHandler();
    PreparedStatement stmt = classMapping.createResourceQueryStatement(accessor, folderID, name, exactMatch, context);
    ResultSet resultSet = null;

    try
    {
      resultSet = stmt.executeQuery();
      while (resultSet.next())
      {
        CDOID id = idHandler.getCDOID(resultSet, 1);
        if (TRACER.isEnabled())
        {
          TRACER.trace("Resource query returned ID " + id); //$NON-NLS-1$
        }

        if (!context.addResource(id))
        {
          // No more results allowed
          return false; // don't continue
        }
      }

      return true; // continue with other results
    }
    catch (SQLException ex)
    {
      throw new DBException(ex);
    }
    finally
    {
      DBUtil.close(resultSet);
      DBUtil.close(stmt);
    }
  }

  private CDOID getMinLocalID(Connection connection)
  {
    final IIDHandler idHandler = getStore().getIDHandler();
    final CDOID[] min = { idHandler.getMaxCDOID() };

    final String prefix = "SELECT MIN(t." + ATTRIBUTES_ID + ") FROM " + CDODBSchema.CDO_OBJECTS + " o, ";

    final String suffix = " t WHERE t." + ATTRIBUTES_BRANCH + "<0 AND t." + ATTRIBUTES_ID + "=o." + ATTRIBUTES_ID
        + " AND t." + ATTRIBUTES_CREATED + "=o." + ATTRIBUTES_CREATED;

    getStore().visitAllTables(connection, new IDBStore.TableVisitor()
    {
      public void visitTable(Connection connection, String name) throws SQLException
      {
        Statement stmt = null;
        ResultSet resultSet = null;

        try
        {
          stmt = connection.createStatement();
          resultSet = stmt.executeQuery(prefix + name + suffix);

          if (resultSet.next())
          {
            CDOID id = idHandler.getCDOID(resultSet, 1);
            if (id != null && idHandler.compare(id, min[0]) < 0)
            {
              min[0] = id;
            }
          }
        }
        finally
        {
          DBUtil.close(resultSet);
          DBUtil.close(stmt);
        }
      }
    });

    return min[0];
  }
}

Back to the top