-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
SchemaImpl.java
882 lines (824 loc) · 39 KB
/
SchemaImpl.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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
/*
* Copyright (c) 2002-2019 "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 org.neo4j.kernel.impl.coreapi.schema;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import org.neo4j.graphdb.ConstraintViolationException;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.TransactionTerminatedException;
import org.neo4j.graphdb.index.IndexPopulationProgress;
import org.neo4j.graphdb.schema.ConstraintCreator;
import org.neo4j.graphdb.schema.ConstraintDefinition;
import org.neo4j.graphdb.schema.IndexCreator;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.internal.kernel.api.IndexReference;
import org.neo4j.internal.kernel.api.InternalIndexState;
import org.neo4j.internal.kernel.api.SchemaRead;
import org.neo4j.internal.kernel.api.TokenRead;
import org.neo4j.internal.kernel.api.TokenWrite;
import org.neo4j.internal.kernel.api.exceptions.InvalidTransactionTypeKernelException;
import org.neo4j.internal.kernel.api.exceptions.KernelException;
import org.neo4j.internal.kernel.api.exceptions.schema.CreateConstraintFailureException;
import org.neo4j.internal.kernel.api.exceptions.schema.IllegalTokenNameException;
import org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException;
import org.neo4j.internal.kernel.api.exceptions.schema.SchemaKernelException;
import org.neo4j.internal.kernel.api.exceptions.schema.TooManyLabelsException;
import org.neo4j.internal.kernel.api.schema.LabelSchemaDescriptor;
import org.neo4j.internal.kernel.api.schema.RelationTypeSchemaDescriptor;
import org.neo4j.internal.kernel.api.schema.SchemaDescriptor;
import org.neo4j.internal.kernel.api.schema.constraints.ConstraintDescriptor;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.SilentTokenNameLookup;
import org.neo4j.kernel.api.Statement;
import org.neo4j.kernel.api.exceptions.Status;
import org.neo4j.kernel.api.exceptions.schema.AlreadyConstrainedException;
import org.neo4j.kernel.api.exceptions.schema.AlreadyIndexedException;
import org.neo4j.kernel.api.exceptions.schema.DropConstraintFailureException;
import org.neo4j.kernel.api.exceptions.schema.DropIndexFailureException;
import org.neo4j.kernel.api.exceptions.schema.RepeatedPropertyInCompositeSchemaException;
import org.neo4j.kernel.api.exceptions.schema.SchemaRuleNotFoundException;
import org.neo4j.kernel.api.schema.SchemaDescriptorFactory;
import org.neo4j.kernel.api.schema.constraints.ConstraintDescriptorFactory;
import org.neo4j.kernel.api.schema.constraints.NodeExistenceConstraintDescriptor;
import org.neo4j.kernel.api.schema.constraints.NodeKeyConstraintDescriptor;
import org.neo4j.kernel.api.schema.constraints.RelExistenceConstraintDescriptor;
import org.neo4j.kernel.api.schema.constraints.UniquenessConstraintDescriptor;
import org.neo4j.kernel.impl.api.index.IndexPopulationFailure;
import org.neo4j.storageengine.api.EntityType;
import org.neo4j.storageengine.api.schema.PopulationProgress;
import org.neo4j.storageengine.api.schema.SchemaRule;
import static java.util.Collections.emptyList;
import static org.neo4j.graphdb.Label.label;
import static org.neo4j.graphdb.RelationshipType.withName;
import static org.neo4j.graphdb.schema.Schema.IndexState.FAILED;
import static org.neo4j.graphdb.schema.Schema.IndexState.ONLINE;
import static org.neo4j.graphdb.schema.Schema.IndexState.POPULATING;
import static org.neo4j.helpers.collection.Iterables.single;
import static org.neo4j.helpers.collection.Iterators.addToCollection;
import static org.neo4j.helpers.collection.Iterators.asCollection;
import static org.neo4j.helpers.collection.Iterators.map;
import static org.neo4j.kernel.api.schema.SchemaDescriptorFactory.forLabel;
import static org.neo4j.kernel.api.schema.SchemaDescriptorFactory.forRelType;
import static org.neo4j.kernel.api.schema.SchemaDescriptorFactory.multiToken;
import static org.neo4j.kernel.impl.coreapi.schema.IndexDefinitionImpl.labelNameList;
import static org.neo4j.kernel.impl.coreapi.schema.PropertyNameUtils.getOrCreatePropertyKeyIds;
public class SchemaImpl implements Schema
{
private final Supplier<KernelTransaction> transactionSupplier;
private final InternalSchemaActions actions;
public SchemaImpl( Supplier<KernelTransaction> transactionSupplier )
{
this.transactionSupplier = transactionSupplier;
this.actions = new GDBSchemaActions( transactionSupplier );
}
@Override
public IndexCreator indexFor( Label label )
{
return new IndexCreatorImpl( actions, label );
}
@Override
public Iterable<IndexDefinition> getIndexes( final Label label )
{
KernelTransaction transaction = transactionSupplier.get();
try ( Statement ignore = transaction.acquireStatement() )
{
TokenRead tokenRead = transaction.tokenRead();
SchemaRead schemaRead = transaction.schemaRead();
List<IndexDefinition> definitions = new ArrayList<>();
int labelId = tokenRead.nodeLabel( label.name() );
if ( labelId == TokenRead.NO_TOKEN )
{
return emptyList();
}
Iterator<IndexReference> indexes = schemaRead.indexesGetForLabel( labelId );
addDefinitions( definitions, tokenRead, IndexReference.sortByType( indexes ) );
return definitions;
}
}
@Override
public Iterable<IndexDefinition> getIndexes()
{
KernelTransaction transaction = transactionSupplier.get();
SchemaRead schemaRead = transaction.schemaRead();
try ( Statement ignore = transaction.acquireStatement() )
{
List<IndexDefinition> definitions = new ArrayList<>();
Iterator<IndexReference> indexes = schemaRead.indexesGetAll();
addDefinitions( definitions, transaction.tokenRead(), IndexReference.sortByType( indexes ) );
return definitions;
}
}
private IndexDefinition descriptorToDefinition( final TokenRead tokenRead, IndexReference index )
{
try
{
SchemaDescriptor schema = index.schema();
int[] entityTokenIds = schema.getEntityTokenIds();
boolean constraintIndex = index.isUnique();
String[] propertyNames = PropertyNameUtils.getPropertyKeys( tokenRead, index.properties() );
switch ( schema.entityType() )
{
case NODE:
Label[] labels = new Label[entityTokenIds.length];
for ( int i = 0; i < labels.length; i++ )
{
labels[i] = label( tokenRead.nodeLabelName( entityTokenIds[i] ) );
}
return new IndexDefinitionImpl( actions, index, labels, propertyNames, constraintIndex );
case RELATIONSHIP:
RelationshipType[] relTypes = new RelationshipType[entityTokenIds.length];
for ( int i = 0; i < relTypes.length; i++ )
{
relTypes[i] = withName( tokenRead.relationshipTypeName( entityTokenIds[i] ) );
}
return new IndexDefinitionImpl( actions, index, relTypes, propertyNames, constraintIndex );
default:
throw new IllegalArgumentException( "Cannot create IndexDefinition for " + schema.entityType() + " entity-typed schema." );
}
}
catch ( KernelException e )
{
throw new RuntimeException( e );
}
}
private void addDefinitions( List<IndexDefinition> definitions, final TokenRead tokenRead,
Iterator<IndexReference> indexes )
{
addToCollection(
map( index -> descriptorToDefinition( tokenRead, index ), indexes ),
definitions );
}
@Override
public void awaitIndexOnline( IndexDefinition index, long duration, TimeUnit unit )
{
actions.assertInOpenTransaction();
long timeout = System.currentTimeMillis() + unit.toMillis( duration );
do
{
IndexState state = getIndexState( index );
switch ( state )
{
case ONLINE:
return;
case FAILED:
String cause = getIndexFailure( index );
String message = IndexPopulationFailure
.appendCauseOfFailure( String.format( "Index entered a %s state. Please see database logs. Index: %s", state, index ), cause );
throw new IllegalStateException( message );
default:
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
// Ignore interrupted exceptions here.
}
break;
}
} while ( System.currentTimeMillis() < timeout );
throw new IllegalStateException( "Expected index to come online within a reasonable time." );
}
@Override
public void awaitIndexesOnline( long duration, TimeUnit unit )
{
actions.assertInOpenTransaction();
long millisLeft = TimeUnit.MILLISECONDS.convert( duration, unit );
Collection<IndexDefinition> onlineIndexes = new ArrayList<>();
for ( Iterator<IndexDefinition> iter = getIndexes().iterator(); iter.hasNext(); )
{
if ( millisLeft < 0 )
{
throw new IllegalStateException( "Expected all indexes to come online within a reasonable time."
+ "Indexes brought online: " + onlineIndexes
+ ". Indexes not guaranteed to be online: " + asCollection( iter ) );
}
IndexDefinition index = iter.next();
long millisBefore = System.currentTimeMillis();
awaitIndexOnline( index, millisLeft, TimeUnit.MILLISECONDS );
millisLeft -= System.currentTimeMillis() - millisBefore;
onlineIndexes.add( index );
}
}
@Override
public IndexDefinition getIndexByName( String indexName )
{
Objects.requireNonNull( indexName );
Iterator<IndexDefinition> indexes = getIndexes().iterator();
IndexDefinition index = null;
while ( indexes.hasNext() )
{
IndexDefinition candidate = indexes.next();
if ( candidate.getName().equals( indexName ) )
{
if ( index != null )
{
throw new IllegalStateException( "Multiple indexes found by the name '" + indexName + "'. " +
"Try iterating Schema#getIndexes() and filter by name instead." );
}
index = candidate;
}
}
if ( index == null )
{
throw new IllegalArgumentException( "No index found with the name '" + indexName + "'." );
}
return index;
}
@Override
public IndexState getIndexState( final IndexDefinition index )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
SchemaRead schemaRead = transaction.schemaRead();
IndexReference reference = getIndexReference( schemaRead, transaction.tokenRead(), (IndexDefinitionImpl) index );
InternalIndexState indexState = schemaRead.indexGetState( reference );
switch ( indexState )
{
case POPULATING:
return POPULATING;
case ONLINE:
return ONLINE;
case FAILED:
return FAILED;
default:
throw new IllegalArgumentException( String.format( "Illegal index state %s", indexState ) );
}
}
catch ( SchemaRuleNotFoundException | IndexNotFoundKernelException e )
{
throw newIndexNotFoundException( index, e );
}
}
private NotFoundException newIndexNotFoundException( IndexDefinition index, KernelException e )
{
return new NotFoundException( "No index was found corresponding to " + index + ".", e );
}
@Override
public IndexPopulationProgress getIndexPopulationProgress( IndexDefinition index )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
SchemaRead schemaRead = transaction.schemaRead();
IndexReference descriptor = getIndexReference( schemaRead, transaction.tokenRead(), (IndexDefinitionImpl) index );
PopulationProgress progress = schemaRead.indexGetPopulationProgress( descriptor );
return progress.toIndexPopulationProgress();
}
catch ( SchemaRuleNotFoundException | IndexNotFoundKernelException e )
{
throw newIndexNotFoundException( index, e );
}
}
@Override
public String getIndexFailure( IndexDefinition index )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
SchemaRead schemaRead = transaction.schemaRead();
IndexReference descriptor = getIndexReference( schemaRead, transaction.tokenRead(), (IndexDefinitionImpl) index );
return schemaRead.indexGetFailure( descriptor );
}
catch ( SchemaRuleNotFoundException | IndexNotFoundKernelException e )
{
throw newIndexNotFoundException( index, e );
}
}
@Override
public ConstraintCreator constraintFor( Label label )
{
actions.assertInOpenTransaction();
return new BaseNodeConstraintCreator( actions, label );
}
@Override
public Iterable<ConstraintDefinition> getConstraints()
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
return asConstraintDefinitions( transaction.schemaRead().constraintsGetAll(), transaction.tokenRead() );
}
}
@Override
public Iterable<ConstraintDefinition> getConstraints( final Label label )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
TokenRead tokenRead = transaction.tokenRead();
SchemaRead schemaRead = transaction.schemaRead();
int labelId = tokenRead.nodeLabel( label.name() );
if ( labelId == TokenRead.NO_TOKEN )
{
return emptyList();
}
return asConstraintDefinitions( schemaRead.constraintsGetForLabel( labelId ), tokenRead );
}
}
@Override
public Iterable<ConstraintDefinition> getConstraints( RelationshipType type )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
TokenRead tokenRead = transaction.tokenRead();
SchemaRead schemaRead = transaction.schemaRead();
int typeId = tokenRead.relationshipType( type.name() );
if ( typeId == TokenRead.NO_TOKEN )
{
return emptyList();
}
return asConstraintDefinitions( schemaRead.constraintsGetForRelationshipType( typeId ), tokenRead );
}
}
private static IndexReference getIndexReference( SchemaRead schemaRead, TokenRead tokenRead, IndexDefinitionImpl index ) throws SchemaRuleNotFoundException
{
// Use the precise embedded index reference when available.
IndexReference reference = index.getIndexReference();
if ( reference != null )
{
return reference;
}
// Otherwise attempt to reverse engineer the schema that will let us look up the real IndexReference.
int[] propertyKeyIds = resolveAndValidatePropertyKeys( tokenRead, index.getPropertyKeysArrayShared() );
SchemaDescriptor schema;
if ( index.isNodeIndex() )
{
int[] labelIds = resolveAndValidateTokens( "Label", index.getLabelArrayShared(), Label::name, tokenRead::nodeLabel );
if ( index.isMultiTokenIndex() )
{
schema = multiToken( labelIds, EntityType.NODE, propertyKeyIds );
}
else
{
schema = forLabel( labelIds[0], propertyKeyIds );
}
}
else if ( index.isRelationshipIndex() )
{
int[] relTypes = resolveAndValidateTokens(
"Relationship type", index.getRelationshipTypesArrayShared(), RelationshipType::name, tokenRead::relationshipType );
if ( index.isMultiTokenIndex() )
{
schema = multiToken( relTypes, EntityType.RELATIONSHIP, propertyKeyIds );
}
else
{
schema = forRelType( relTypes[0], propertyKeyIds );
}
}
else
{
throw new IllegalArgumentException( "The given index is neither a node index, nor a relationship index: " + index + "." );
}
reference = schemaRead.index( schema );
if ( reference == IndexReference.NO_INDEX )
{
throw new SchemaRuleNotFoundException( SchemaRule.Kind.INDEX_RULE, schema );
}
return reference;
}
private static int[] resolveAndValidatePropertyKeys( TokenRead tokenRead, String[] propertyKeys )
{
return resolveAndValidateTokens( "Property key", propertyKeys, s -> s, tokenRead::propertyKey );
}
private static <T> int[] resolveAndValidateTokens( String tokenTypeName, T[] tokens, Function<T,String> getTokenName, ToIntFunction<String> getTokenId )
{
int[] tokenIds = new int[tokens.length];
for ( int i = 0; i < tokenIds.length; i++ )
{
String tokenName = getTokenName.apply( tokens[i] );
int tokenId = getTokenId.applyAsInt( tokenName );
if ( tokenId == TokenRead.NO_TOKEN )
{
throw new NotFoundException( tokenTypeName + " " + tokenName + " not found." );
}
tokenIds[i] = tokenId;
}
return tokenIds;
}
private Iterable<ConstraintDefinition> asConstraintDefinitions(
Iterator<? extends ConstraintDescriptor> constraints,
TokenRead tokenRead )
{
// Intentionally create an eager list so that used statement can be closed
List<ConstraintDefinition> definitions = new ArrayList<>();
while ( constraints.hasNext() )
{
ConstraintDescriptor constraint = constraints.next();
definitions.add( asConstraintDefinition( constraint, tokenRead ) );
}
return definitions;
}
private ConstraintDefinition asConstraintDefinition( ConstraintDescriptor constraint,
TokenRead tokenRead )
{
// This was turned inside out. Previously a low-level constraint object would reference a public enum type
// which made it impossible to break out the low-level component from kernel. There could be a lower level
// constraint type introduced to mimic the public ConstraintType, but that would be a duplicate of it
// essentially. Checking instanceof here is OKish since the objects it checks here are part of the
// internal storage engine API.
SilentTokenNameLookup lookup = new SilentTokenNameLookup( tokenRead );
if ( constraint instanceof NodeExistenceConstraintDescriptor ||
constraint instanceof NodeKeyConstraintDescriptor ||
constraint instanceof UniquenessConstraintDescriptor )
{
SchemaDescriptor schemaDescriptor = constraint.schema();
int[] entityTokenIds = schemaDescriptor.getEntityTokenIds();
Label[] labels = new Label[entityTokenIds.length];
for ( int i = 0; i < entityTokenIds.length; i++ )
{
labels[i] = label( lookup.labelGetName( entityTokenIds[i] ) );
}
String[] propertyKeys = Arrays.stream( schemaDescriptor.getPropertyIds() ).mapToObj( lookup::propertyKeyGetName ).toArray( String[]::new );
if ( constraint instanceof NodeExistenceConstraintDescriptor )
{
return new NodePropertyExistenceConstraintDefinition( actions, labels[0], propertyKeys );
}
else if ( constraint instanceof UniquenessConstraintDescriptor )
{
return new UniquenessConstraintDefinition( actions, new IndexDefinitionImpl( actions, null, labels, propertyKeys, true ) );
}
else
{
return new NodeKeyConstraintDefinition( actions, new IndexDefinitionImpl( actions, null, labels, propertyKeys, true ) );
}
}
else if ( constraint instanceof RelExistenceConstraintDescriptor )
{
RelationTypeSchemaDescriptor descriptor = (RelationTypeSchemaDescriptor) constraint.schema();
return new RelationshipPropertyExistenceConstraintDefinition( actions,
withName( lookup.relationshipTypeGetName( descriptor.getRelTypeId() ) ),
lookup.propertyKeyGetName( descriptor.getPropertyId() ) );
}
throw new IllegalArgumentException( "Unknown constraint " + constraint );
}
private static KernelTransaction safeAcquireTransaction( Supplier<KernelTransaction> transactionSupplier )
{
KernelTransaction transaction = transactionSupplier.get();
if ( transaction.isTerminated() )
{
Status terminationReason = transaction.getReasonIfTerminated().orElse( Status.Transaction.Terminated );
throw new TransactionTerminatedException( terminationReason );
}
return transaction;
}
private static class GDBSchemaActions implements InternalSchemaActions
{
private final Supplier<KernelTransaction> transactionSupplier;
GDBSchemaActions( Supplier<KernelTransaction> transactionSupplier )
{
this.transactionSupplier = transactionSupplier;
}
@Override
public IndexDefinition createIndexDefinition( Label label, Optional<String> indexName, String... propertyKeys )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenWrite tokenWrite = transaction.tokenWrite();
int labelId = tokenWrite.labelGetOrCreateForName( label.name() );
int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, propertyKeys );
LabelSchemaDescriptor descriptor = forLabel( labelId, propertyKeyIds );
IndexReference indexReference = transaction.schemaWrite().indexCreate( descriptor, indexName );
return new IndexDefinitionImpl( this, indexReference, new Label[]{label}, propertyKeys, false );
}
catch ( IllegalTokenNameException e )
{
throw new IllegalArgumentException( e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
}
}
@Override
public void dropIndexDefinitions( IndexDefinition indexDefinition )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
IndexReference reference = getIndexReference( transaction.schemaRead(), transaction.tokenRead(), (IndexDefinitionImpl) indexDefinition );
transaction.schemaWrite().indexDrop( reference );
}
catch ( NotFoundException e )
{
// Silently ignore invalid label and property names
}
catch ( SchemaRuleNotFoundException | DropIndexFailureException e )
{
throw new ConstraintViolationException( e.getUserMessage(
new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public ConstraintDefinition createPropertyUniquenessConstraint( IndexDefinition indexDefinition )
{
if ( indexDefinition.isMultiTokenIndex() )
{
throw new ConstraintViolationException( "A property uniqueness constraint does not support multi-token index definitions. " +
"That is, only a single label is supported, but the following labels were provided: " +
labelNameList( indexDefinition.getLabels(), "", "." ) );
}
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenWrite tokenWrite = transaction.tokenWrite();
int labelId = tokenWrite.labelGetOrCreateForName( single( indexDefinition.getLabels() ).name() );
int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, indexDefinition );
transaction.schemaWrite().uniquePropertyConstraintCreate(
forLabel( labelId, propertyKeyIds ) );
return new UniquenessConstraintDefinition( this, indexDefinition );
}
catch ( AlreadyConstrainedException | CreateConstraintFailureException | AlreadyIndexedException |
RepeatedPropertyInCompositeSchemaException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( IllegalTokenNameException e )
{
throw new IllegalArgumentException( e );
}
catch ( TooManyLabelsException e )
{
throw new IllegalStateException( e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public ConstraintDefinition createNodeKeyConstraint( IndexDefinition indexDefinition )
{
if ( indexDefinition.isMultiTokenIndex() )
{
throw new ConstraintViolationException( "A node key constraint does not support multi-token index definitions. " +
"That is, only a single label is supported, but the following labels were provided: " +
labelNameList( indexDefinition.getLabels(), "", "." ) );
}
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenWrite tokenWrite = transaction.tokenWrite();
int labelId = tokenWrite.labelGetOrCreateForName( single( indexDefinition.getLabels() ).name() );
int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, indexDefinition );
transaction.schemaWrite().nodeKeyConstraintCreate(
forLabel( labelId, propertyKeyIds ) );
return new NodeKeyConstraintDefinition( this, indexDefinition );
}
catch ( AlreadyConstrainedException | CreateConstraintFailureException | AlreadyIndexedException |
RepeatedPropertyInCompositeSchemaException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( IllegalTokenNameException e )
{
throw new IllegalArgumentException( e );
}
catch ( TooManyLabelsException e )
{
throw new IllegalStateException( e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public ConstraintDefinition createPropertyExistenceConstraint( Label label, String... propertyKeys )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenWrite tokenWrite = transaction.tokenWrite();
int labelId = tokenWrite.labelGetOrCreateForName( label.name() );
int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, propertyKeys );
transaction.schemaWrite().nodePropertyExistenceConstraintCreate(
forLabel( labelId, propertyKeyIds ) );
return new NodePropertyExistenceConstraintDefinition( this, label, propertyKeys );
}
catch ( AlreadyConstrainedException | CreateConstraintFailureException |
RepeatedPropertyInCompositeSchemaException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( IllegalTokenNameException e )
{
throw new IllegalArgumentException( e );
}
catch ( TooManyLabelsException e )
{
throw new IllegalStateException( e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public ConstraintDefinition createPropertyExistenceConstraint( RelationshipType type, String propertyKey )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenWrite tokenWrite = transaction.tokenWrite();
int typeId = tokenWrite.relationshipTypeGetOrCreateForName( type.name() );
int[] propertyKeyId = getOrCreatePropertyKeyIds( tokenWrite, propertyKey );
transaction.schemaWrite().relationshipPropertyExistenceConstraintCreate(
SchemaDescriptorFactory.forRelType( typeId, propertyKeyId ) );
return new RelationshipPropertyExistenceConstraintDefinition( this, type, propertyKey );
}
catch ( AlreadyConstrainedException | CreateConstraintFailureException |
RepeatedPropertyInCompositeSchemaException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( IllegalTokenNameException e )
{
throw new IllegalArgumentException( e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public void dropPropertyUniquenessConstraint( Label label, String[] properties )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenRead tokenRead = transaction.tokenRead();
int labelId = tokenRead.nodeLabel( label.name() );
int[] propertyKeyIds = resolveAndValidatePropertyKeys( tokenRead, properties );
transaction.schemaWrite().constraintDrop(
ConstraintDescriptorFactory.uniqueForLabel( labelId, propertyKeyIds ) );
}
catch ( DropConstraintFailureException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public void dropNodeKeyConstraint( Label label, String[] properties )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenRead tokenRead = transaction.tokenRead();
int labelId = tokenRead.nodeLabel( label.name() );
int[] propertyKeyIds = resolveAndValidatePropertyKeys( tokenRead, properties );
transaction.schemaWrite().constraintDrop(
ConstraintDescriptorFactory.nodeKeyForLabel( labelId, propertyKeyIds ) );
}
catch ( DropConstraintFailureException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public void dropNodePropertyExistenceConstraint( Label label, String[] properties )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenRead tokenRead = transaction.tokenRead();
int labelId = tokenRead.nodeLabel( label.name() );
int[] propertyKeyIds = resolveAndValidatePropertyKeys( tokenRead, properties );
transaction.schemaWrite().constraintDrop(
ConstraintDescriptorFactory.existsForLabel( labelId, propertyKeyIds ) );
}
catch ( DropConstraintFailureException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public void dropRelationshipPropertyExistenceConstraint( RelationshipType type, String propertyKey )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
try
{
TokenRead tokenRead = transaction.tokenRead();
int typeId = tokenRead.relationshipType( type.name() );
int propertyKeyId = tokenRead.propertyKey( propertyKey );
transaction.schemaWrite().constraintDrop(
ConstraintDescriptorFactory.existsForRelType( typeId, propertyKeyId ) );
}
catch ( DropConstraintFailureException e )
{
throw new ConstraintViolationException(
e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
}
catch ( InvalidTransactionTypeKernelException | SchemaKernelException e )
{
throw new ConstraintViolationException( e.getMessage(), e );
}
}
}
@Override
public String getUserMessage( KernelException e )
{
KernelTransaction transaction = safeAcquireTransaction( transactionSupplier );
try ( Statement ignore = transaction.acquireStatement() )
{
return e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) );
}
}
@Override
public void assertInOpenTransaction()
{
KernelTransaction transaction = transactionSupplier.get();
if ( transaction.isTerminated() )
{
Status terminationReason = transaction.getReasonIfTerminated().orElse( Status.Transaction.Terminated );
throw new TransactionTerminatedException( terminationReason );
}
}
}
}