-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
MultiIndexPopulationConcurrentUpdatesIT.java
677 lines (600 loc) · 27.3 KB
/
MultiIndexPopulationConcurrentUpdatesIT.java
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/*
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package schema;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;
import org.neo4j.collection.PrimitiveLongResourceIterator;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.helpers.collection.Iterators;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.internal.kernel.api.InternalIndexState;
import org.neo4j.internal.kernel.api.TokenNameLookup;
import org.neo4j.internal.kernel.api.TokenRead;
import org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException;
import org.neo4j.internal.kernel.api.schema.IndexProviderDescriptor;
import org.neo4j.internal.kernel.api.schema.LabelSchemaDescriptor;
import org.neo4j.internal.kernel.api.schema.SchemaDescriptor;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.SilentTokenNameLookup;
import org.neo4j.kernel.api.Statement;
import org.neo4j.kernel.api.exceptions.index.IndexActivationFailedKernelException;
import org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException;
import org.neo4j.kernel.api.exceptions.index.IndexPopulationFailedKernelException;
import org.neo4j.kernel.api.impl.schema.LuceneIndexProviderFactory;
import org.neo4j.kernel.api.impl.schema.NativeLuceneFusionIndexProviderFactory10;
import org.neo4j.kernel.api.impl.schema.NativeLuceneFusionIndexProviderFactory20;
import org.neo4j.kernel.api.index.IndexEntryUpdate;
import org.neo4j.kernel.api.labelscan.LabelScanStore;
import org.neo4j.kernel.api.labelscan.NodeLabelUpdate;
import org.neo4j.kernel.api.schema.SchemaDescriptorFactory;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.api.SchemaState;
import org.neo4j.kernel.impl.api.index.EntityUpdates;
import org.neo4j.kernel.impl.api.index.IndexProviderMap;
import org.neo4j.kernel.impl.api.index.IndexProxy;
import org.neo4j.kernel.impl.api.index.IndexingService;
import org.neo4j.kernel.impl.api.index.IndexingServiceFactory;
import org.neo4j.kernel.impl.api.index.MultipleIndexPopulator;
import org.neo4j.kernel.impl.api.index.StoreScan;
import org.neo4j.kernel.impl.core.ThreadToStatementContextBridge;
import org.neo4j.kernel.impl.locking.LockService;
import org.neo4j.kernel.impl.storageengine.impl.recordstorage.RecordStorageEngine;
import org.neo4j.kernel.impl.store.NeoStores;
import org.neo4j.kernel.impl.store.NodeStore;
import org.neo4j.kernel.impl.store.PropertyStore;
import org.neo4j.kernel.impl.store.SchemaStorage;
import org.neo4j.kernel.impl.transaction.state.DirectIndexUpdates;
import org.neo4j.kernel.impl.transaction.state.storeview.DynamicIndexStoreView;
import org.neo4j.kernel.impl.transaction.state.storeview.LabelScanViewNodeStoreScan;
import org.neo4j.kernel.impl.transaction.state.storeview.NeoStoreIndexStoreView;
import org.neo4j.logging.NullLogProvider;
import org.neo4j.scheduler.JobScheduler;
import org.neo4j.storageengine.api.EntityType;
import org.neo4j.storageengine.api.schema.IndexDescriptorFactory;
import org.neo4j.storageengine.api.schema.IndexReader;
import org.neo4j.storageengine.api.schema.StoreIndexDescriptor;
import org.neo4j.test.rule.EmbeddedDatabaseRule;
import org.neo4j.values.storable.Values;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
//[NodePropertyUpdate[0, prop:0 add:Sweden, labelsBefore:[], labelsAfter:[0]]]
//[NodePropertyUpdate[1, prop:0 add:USA, labelsBefore:[], labelsAfter:[0]]]
//[NodePropertyUpdate[2, prop:0 add:red, labelsBefore:[], labelsAfter:[1]]]
//[NodePropertyUpdate[3, prop:0 add:green, labelsBefore:[], labelsAfter:[0]]]
//[NodePropertyUpdate[4, prop:0 add:Volvo, labelsBefore:[], labelsAfter:[2]]]
//[NodePropertyUpdate[5, prop:0 add:Ford, labelsBefore:[], labelsAfter:[2]]]
//TODO: check count store counts
@RunWith( Parameterized.class )
public class MultiIndexPopulationConcurrentUpdatesIT
{
private static final String NAME_PROPERTY = "name";
private static final String COUNTRY_LABEL = "country";
private static final String COLOR_LABEL = "color";
private static final String CAR_LABEL = "car";
@Rule
public EmbeddedDatabaseRule embeddedDatabase = new EmbeddedDatabaseRule();
private StoreIndexDescriptor[] rules;
@Parameterized.Parameters( name = "{0}" )
public static Collection<IndexProviderDescriptor> parameters()
{
return asList( LuceneIndexProviderFactory.PROVIDER_DESCRIPTOR,
NativeLuceneFusionIndexProviderFactory10.DESCRIPTOR,
NativeLuceneFusionIndexProviderFactory20.DESCRIPTOR );
}
@Parameterized.Parameter
public IndexProviderDescriptor indexDescriptor;
private IndexingService indexService;
private int propertyId;
private Map<String,Integer> labelsNameIdMap;
private Map<Integer,String> labelsIdNameMap;
private Node country1;
private Node country2;
private Node color1;
private Node color2;
private Node car1;
private Node car2;
private Node[] otherNodes;
@After
public void tearDown() throws Throwable
{
if ( indexService != null )
{
indexService.shutdown();
}
}
@Before
public void setUp()
{
prepareDb();
labelsNameIdMap = getLabelsNameIdMap();
labelsIdNameMap = labelsNameIdMap.entrySet()
.stream()
.collect( Collectors.toMap( Map.Entry::getValue, Map.Entry::getKey ) );
propertyId = getPropertyId();
}
@Test
public void applyConcurrentDeletesToPopulatedIndex() throws Throwable
{
List<EntityUpdates> updates = new ArrayList<>( 2 );
updates.add( EntityUpdates.forEntity( country1.getId() ).withTokens( id( COUNTRY_LABEL ) )
.removed( propertyId, Values.of( "Sweden" ) ).build() );
updates.add( EntityUpdates.forEntity( color2.getId() ).withTokens( id( COLOR_LABEL ) )
.removed( propertyId, Values.of( "green" ) ).build() );
launchCustomIndexPopulation( labelsNameIdMap, propertyId, new UpdateGenerator( updates ) );
waitAndActivateIndexes( labelsNameIdMap, propertyId );
try ( Transaction ignored = embeddedDatabase.beginTx() )
{
Integer countryLabelId = labelsNameIdMap.get( COUNTRY_LABEL );
Integer colorLabelId = labelsNameIdMap.get( COLOR_LABEL );
try ( IndexReader indexReader = getIndexReader( propertyId, countryLabelId ) )
{
assertEquals("Should be removed by concurrent remove.",
0, indexReader.countIndexedNodes( 0, Values.of( "Sweden" )) );
}
try ( IndexReader indexReader = getIndexReader( propertyId, colorLabelId ) )
{
assertEquals("Should be removed by concurrent remove.",
0, indexReader.countIndexedNodes( 3, Values.of( "green" )) );
}
}
}
@Test
public void applyConcurrentAddsToPopulatedIndex() throws Throwable
{
List<EntityUpdates> updates = new ArrayList<>( 2 );
updates.add( EntityUpdates.forEntity( otherNodes[0].getId() ).withTokens( id( COUNTRY_LABEL ) )
.added( propertyId, Values.of( "Denmark" ) ).build() );
updates.add( EntityUpdates.forEntity( otherNodes[1].getId() ).withTokens( id( CAR_LABEL ) )
.added( propertyId, Values.of( "BMW" ) ).build() );
launchCustomIndexPopulation( labelsNameIdMap, propertyId, new UpdateGenerator( updates ) );
waitAndActivateIndexes( labelsNameIdMap, propertyId );
try ( Transaction ignored = embeddedDatabase.beginTx() )
{
Integer countryLabelId = labelsNameIdMap.get( COUNTRY_LABEL );
Integer carLabelId = labelsNameIdMap.get( CAR_LABEL );
try ( IndexReader indexReader = getIndexReader( propertyId, countryLabelId ) )
{
assertEquals("Should be added by concurrent add.", 1,
indexReader.countIndexedNodes( otherNodes[0].getId(), Values.of( "Denmark" ) ) );
}
try ( IndexReader indexReader = getIndexReader( propertyId, carLabelId ) )
{
assertEquals("Should be added by concurrent add.", 1,
indexReader.countIndexedNodes( otherNodes[1].getId(), Values.of( "BMW" ) ) );
}
}
}
@Test
public void applyConcurrentChangesToPopulatedIndex() throws Exception
{
List<EntityUpdates> updates = new ArrayList<>( 2 );
updates.add( EntityUpdates.forEntity( color2.getId() ).withTokens( id( COLOR_LABEL ) )
.changed( propertyId, Values.of( "green" ), Values.of( "pink" ) ).build() );
updates.add( EntityUpdates.forEntity( car2.getId() ).withTokens( id( CAR_LABEL ) )
.changed( propertyId, Values.of( "Ford" ), Values.of( "SAAB" ) ).build() );
launchCustomIndexPopulation( labelsNameIdMap, propertyId, new UpdateGenerator( updates ) );
waitAndActivateIndexes( labelsNameIdMap, propertyId );
try ( Transaction ignored = embeddedDatabase.beginTx() )
{
Integer colorLabelId = labelsNameIdMap.get( COLOR_LABEL );
Integer carLabelId = labelsNameIdMap.get( CAR_LABEL );
try ( IndexReader indexReader = getIndexReader( propertyId, colorLabelId ) )
{
assertEquals( format( "Should be deleted by concurrent change. Reader is: %s, ", indexReader ), 0,
indexReader.countIndexedNodes( color2.getId(), Values.of( "green" ) ) );
}
try ( IndexReader indexReader = getIndexReader( propertyId, colorLabelId ) )
{
assertEquals("Should be updated by concurrent change.", 1,
indexReader.countIndexedNodes( color2.getId(), Values.of( "pink" ) ) );
}
try ( IndexReader indexReader = getIndexReader( propertyId, carLabelId ) )
{
assertEquals("Should be added by concurrent change.", 1,
indexReader.countIndexedNodes( car2.getId(), Values.of( "SAAB" ) ) );
}
}
}
@Test
public void dropOneOfTheIndexesWhilePopulationIsOngoingDoesInfluenceOtherPopulators() throws Exception
{
launchCustomIndexPopulation( labelsNameIdMap, propertyId,
new IndexDropAction( labelsNameIdMap.get( COLOR_LABEL ) ) );
labelsNameIdMap.remove( COLOR_LABEL );
waitAndActivateIndexes( labelsNameIdMap, propertyId );
checkIndexIsOnline( labelsNameIdMap.get( CAR_LABEL ) );
checkIndexIsOnline( labelsNameIdMap.get( COUNTRY_LABEL ));
}
@Test
public void indexDroppedDuringPopulationDoesNotExist() throws Exception
{
Integer labelToDropId = labelsNameIdMap.get( COLOR_LABEL );
launchCustomIndexPopulation( labelsNameIdMap, propertyId,
new IndexDropAction( labelToDropId ) );
labelsNameIdMap.remove( COLOR_LABEL );
waitAndActivateIndexes( labelsNameIdMap, propertyId );
try
{
indexService.getIndexProxy( SchemaDescriptorFactory.forLabel( labelToDropId, propertyId ) );
fail( "Index does not exist, we should fail to find it." );
}
catch ( IndexNotFoundKernelException infe )
{
// expected
}
}
private void checkIndexIsOnline( int labelId ) throws IndexNotFoundKernelException
{
IndexProxy indexProxy = indexService.getIndexProxy( SchemaDescriptorFactory.forLabel( labelId, propertyId ) );
assertSame( indexProxy.getState(), InternalIndexState.ONLINE );
}
private long[] id( String label )
{
return new long[]{labelsNameIdMap.get( label )};
}
private IndexReader getIndexReader( int propertyId, Integer countryLabelId ) throws IndexNotFoundKernelException
{
return indexService.getIndexProxy( SchemaDescriptorFactory.forLabel( countryLabelId, propertyId ) )
.newReader();
}
private void launchCustomIndexPopulation( Map<String,Integer> labelNameIdMap, int propertyId,
Runnable customAction ) throws Exception
{
NeoStores neoStores = getNeoStores();
LabelScanStore labelScanStore = getLabelScanStore();
ThreadToStatementContextBridge transactionStatementContextBridge = getTransactionStatementContextBridge();
try ( Transaction transaction = embeddedDatabase.beginTx();
KernelTransaction ktx = transactionStatementContextBridge.getKernelTransactionBoundToThisThread( true ) )
{
DynamicIndexStoreView storeView = dynamicIndexStoreViewWrapper( customAction, neoStores, labelScanStore );
IndexProviderMap providerMap = getIndexProviderMap();
JobScheduler scheduler = getJobScheduler();
TokenNameLookup tokenNameLookup = new SilentTokenNameLookup( ktx.tokenRead() );
indexService = IndexingServiceFactory.createIndexingService( Config.defaults(), scheduler,
providerMap, storeView, tokenNameLookup, getIndexRules( neoStores ),
NullLogProvider.getInstance(), IndexingService.NO_MONITOR, getSchemaState() );
indexService.start();
rules = createIndexRules( labelNameIdMap, propertyId );
indexService.createIndexes( rules );
transaction.success();
}
}
private DynamicIndexStoreView dynamicIndexStoreViewWrapper( Runnable customAction, NeoStores neoStores,
LabelScanStore labelScanStore )
{
LockService locks = LockService.NO_LOCK_SERVICE;
NeoStoreIndexStoreView neoStoreIndexStoreView = new NeoStoreIndexStoreView( locks, neoStores );
return new DynamicIndexStoreViewWrapper( neoStoreIndexStoreView, labelScanStore, locks, neoStores, customAction );
}
private void waitAndActivateIndexes( Map<String,Integer> labelsIds, int propertyId )
throws IndexNotFoundKernelException, IndexPopulationFailedKernelException, InterruptedException,
IndexActivationFailedKernelException
{
try ( Transaction ignored = embeddedDatabase.beginTx() )
{
for ( int labelId : labelsIds.values() )
{
waitIndexOnline( indexService, propertyId, labelId );
}
}
}
private int getPropertyId()
{
try ( Transaction ignored = embeddedDatabase.beginTx() )
{
return getPropertyIdByName( NAME_PROPERTY );
}
}
private Map<String,Integer> getLabelsNameIdMap()
{
try ( Transaction ignored = embeddedDatabase.beginTx() )
{
return getLabelIdsByName( COUNTRY_LABEL, COLOR_LABEL, CAR_LABEL );
}
}
private void waitIndexOnline( IndexingService indexService, int propertyId, int labelId )
throws IndexNotFoundKernelException, IndexPopulationFailedKernelException, InterruptedException,
IndexActivationFailedKernelException
{
IndexProxy indexProxy = indexService.getIndexProxy( SchemaDescriptorFactory.forLabel( labelId, propertyId ) );
indexProxy.awaitStoreScanCompleted();
while ( indexProxy.getState() != InternalIndexState.ONLINE )
{
Thread.sleep( 10 );
}
indexProxy.activate();
}
private StoreIndexDescriptor[] createIndexRules( Map<String,Integer> labelNameIdMap, int propertyId )
{
return labelNameIdMap.values().stream()
.map( index -> IndexDescriptorFactory.forSchema( SchemaDescriptorFactory.forLabel( index, propertyId ), indexDescriptor ).withId( index ) )
.toArray( StoreIndexDescriptor[]::new );
}
private List<StoreIndexDescriptor> getIndexRules( NeoStores neoStores )
{
return Iterators.asList( new SchemaStorage( neoStores.getSchemaStore() ).indexesGetAll() );
}
private Map<String, Integer> getLabelIdsByName( String... names )
{
ThreadToStatementContextBridge transactionStatementContextBridge = getTransactionStatementContextBridge();
Map<String,Integer> labelNameIdMap = new HashMap<>();
KernelTransaction ktx =
transactionStatementContextBridge.getKernelTransactionBoundToThisThread( true );
try ( Statement ignore = ktx.acquireStatement() )
{
TokenRead tokenRead = ktx.tokenRead();
for ( String name : names )
{
labelNameIdMap.put( name, tokenRead.nodeLabel( name ) );
}
}
return labelNameIdMap;
}
private int getPropertyIdByName( String name )
{
ThreadToStatementContextBridge transactionStatementContextBridge = getTransactionStatementContextBridge();
KernelTransaction ktx =
transactionStatementContextBridge.getKernelTransactionBoundToThisThread( true );
try ( Statement ignore = ktx.acquireStatement() )
{
return ktx.tokenRead().propertyKey( name );
}
}
private void prepareDb()
{
Label countryLabel = Label.label( COUNTRY_LABEL );
Label color = Label.label( COLOR_LABEL );
Label car = Label.label( CAR_LABEL );
try ( Transaction transaction = embeddedDatabase.beginTx() )
{
country1 = createNamedLabeledNode( countryLabel, "Sweden" );
country2 = createNamedLabeledNode( countryLabel, "USA" );
color1 = createNamedLabeledNode( color, "red" );
color2 = createNamedLabeledNode( color, "green" );
car1 = createNamedLabeledNode( car, "Volvo" );
car2 = createNamedLabeledNode( car, "Ford" );
otherNodes = new Node[250];
for ( int i = 0; i < 250; i++ )
{
otherNodes[i] = embeddedDatabase.createNode();
}
transaction.success();
}
}
private Node createNamedLabeledNode( Label label, String name )
{
Node node = embeddedDatabase.createNode( label );
node.setProperty( NAME_PROPERTY, name );
return node;
}
private LabelScanStore getLabelScanStore()
{
return embeddedDatabase.resolveDependency( LabelScanStore.class );
}
private NeoStores getNeoStores()
{
RecordStorageEngine recordStorageEngine = embeddedDatabase.resolveDependency( RecordStorageEngine.class );
return recordStorageEngine.testAccessNeoStores();
}
private SchemaState getSchemaState()
{
return embeddedDatabase.resolveDependency( SchemaState.class );
}
private ThreadToStatementContextBridge getTransactionStatementContextBridge()
{
return embeddedDatabase.resolveDependency( ThreadToStatementContextBridge.class );
}
private IndexProviderMap getIndexProviderMap()
{
return embeddedDatabase.resolveDependency( IndexProviderMap.class );
}
private JobScheduler getJobScheduler()
{
return embeddedDatabase.resolveDependency( JobScheduler.class );
}
private class DynamicIndexStoreViewWrapper extends DynamicIndexStoreView
{
private final Runnable customAction;
DynamicIndexStoreViewWrapper( NeoStoreIndexStoreView neoStoreIndexStoreView, LabelScanStore labelScanStore, LockService locks,
NeoStores neoStores, Runnable customAction )
{
super( neoStoreIndexStoreView, labelScanStore, locks, neoStores, NullLogProvider.getInstance() );
this.customAction = customAction;
}
@Override
public <FAILURE extends Exception> StoreScan<FAILURE> visitNodes( int[] labelIds,
IntPredicate propertyKeyIdFilter,
Visitor<EntityUpdates,FAILURE> propertyUpdatesVisitor,
Visitor<NodeLabelUpdate,FAILURE> labelUpdateVisitor,
boolean forceStoreScan )
{
StoreScan<FAILURE> storeScan = super.visitNodes( labelIds, propertyKeyIdFilter, propertyUpdatesVisitor,
labelUpdateVisitor, forceStoreScan );
return new LabelScanViewNodeStoreWrapper<>( nodeStore, locks, propertyStore, getLabelScanStore(),
element -> false, propertyUpdatesVisitor, labelIds, propertyKeyIdFilter,
(LabelScanViewNodeStoreScan<FAILURE>) storeScan, customAction );
}
}
private class LabelScanViewNodeStoreWrapper<FAILURE extends Exception> extends LabelScanViewNodeStoreScan<FAILURE>
{
private final LabelScanViewNodeStoreScan<FAILURE> delegate;
private final Runnable customAction;
LabelScanViewNodeStoreWrapper( NodeStore nodeStore, LockService locks,
PropertyStore propertyStore,
LabelScanStore labelScanStore, Visitor<NodeLabelUpdate,FAILURE> labelUpdateVisitor,
Visitor<EntityUpdates,FAILURE> propertyUpdatesVisitor, int[] labelIds, IntPredicate propertyKeyIdFilter,
LabelScanViewNodeStoreScan<FAILURE> delegate,
Runnable customAction )
{
super( nodeStore, locks, propertyStore, labelScanStore, labelUpdateVisitor,
propertyUpdatesVisitor, labelIds, propertyKeyIdFilter );
this.delegate = delegate;
this.customAction = customAction;
}
@Override
public void acceptUpdate( MultipleIndexPopulator.MultipleIndexUpdater updater, IndexEntryUpdate<?> update,
long currentlyIndexedNodeId )
{
delegate.acceptUpdate( updater, update, currentlyIndexedNodeId );
}
@Override
public PrimitiveLongResourceIterator getEntityIdIterator()
{
PrimitiveLongResourceIterator originalIterator = delegate.getEntityIdIterator();
return new DelegatingPrimitiveLongResourceIterator( originalIterator, customAction );
}
}
private class DelegatingPrimitiveLongResourceIterator implements PrimitiveLongResourceIterator
{
private final Runnable customAction;
private final PrimitiveLongResourceIterator delegate;
DelegatingPrimitiveLongResourceIterator(
PrimitiveLongResourceIterator delegate,
Runnable customAction )
{
this.delegate = delegate;
this.customAction = customAction;
}
@Override
public boolean hasNext()
{
return delegate.hasNext();
}
@Override
public long next()
{
long value = delegate.next();
if ( !hasNext() )
{
customAction.run();
}
return value;
}
@Override
public void close()
{
delegate.close();
}
}
private class UpdateGenerator implements Runnable
{
private Iterable<EntityUpdates> updates;
UpdateGenerator( Iterable<EntityUpdates> updates )
{
this.updates = updates;
}
@Override
public void run()
{
for ( EntityUpdates update : updates )
{
try ( Transaction transaction = embeddedDatabase.beginTx() )
{
Node node = embeddedDatabase.getNodeById( update.getEntityId() );
for ( int labelId : labelsNameIdMap.values() )
{
LabelSchemaDescriptor schema = SchemaDescriptorFactory.forLabel( labelId, propertyId );
for ( IndexEntryUpdate<?> indexUpdate :
update.forIndexKeys( Collections.singleton( schema ) ) )
{
switch ( indexUpdate.updateMode() )
{
case CHANGED:
case ADDED:
node.addLabel(
Label.label( labelsIdNameMap.get( schema.getLabelId() ) ) );
node.setProperty( NAME_PROPERTY, indexUpdate.values()[0].asObject() );
break;
case REMOVED:
node.addLabel(
Label.label( labelsIdNameMap.get( schema.getLabelId() ) ) );
node.delete();
break;
default:
throw new IllegalArgumentException( indexUpdate.updateMode().name() );
}
}
}
transaction.success();
}
}
try
{
for ( EntityUpdates update : updates )
{
Iterable<IndexEntryUpdate<SchemaDescriptor>> entryUpdates =
indexService.convertToIndexUpdates( update, EntityType.NODE );
DirectIndexUpdates directIndexUpdates = new DirectIndexUpdates( entryUpdates );
indexService.apply( directIndexUpdates );
}
}
catch ( UncheckedIOException | IndexEntryConflictException e )
{
throw new RuntimeException( e );
}
}
}
private class IndexDropAction implements Runnable
{
private int labelIdToDropIndexFor;
private IndexDropAction( int labelIdToDropIndexFor )
{
this.labelIdToDropIndexFor = labelIdToDropIndexFor;
}
@Override
public void run()
{
org.neo4j.kernel.api.schema.LabelSchemaDescriptor descriptor =
SchemaDescriptorFactory.forLabel( labelIdToDropIndexFor, propertyId );
StoreIndexDescriptor rule = findRuleForLabel( descriptor );
indexService.dropIndex( rule );
}
private StoreIndexDescriptor findRuleForLabel( LabelSchemaDescriptor schemaDescriptor )
{
for ( StoreIndexDescriptor rule : rules )
{
if ( rule.schema().equals( schemaDescriptor ) )
{
return rule;
}
}
return null;
}
}
}