Search in sources :

Example 16 with KernelException

use of org.neo4j.exceptions.KernelException in project neo4j by neo4j.

the class SchemaStatementProcedure method createStatement.

public static String createStatement(Function<String, IndexDescriptor> indexLookup, TokenRead tokenRead, ConstraintDescriptor constraint) throws ProcedureException {
    try {
        String name = constraint.getName();
        if (constraint.isIndexBackedConstraint()) {
            final String labelsOrRelTypes = labelsOrRelTypesAsStringArray(tokenRead, constraint.schema());
            final String properties = propertiesAsStringArray(tokenRead, constraint.schema());
            IndexDescriptor backingIndex = indexLookup.apply(name);
            String providerName = backingIndex.getIndexProvider().name();
            String config = btreeConfigAsString(backingIndex);
            if (constraint.isUniquenessConstraint()) {
                return format(CREATE_UNIQUE_PROPERTY_CONSTRAINT, name, labelsOrRelTypes, properties, providerName, config);
            }
            if (constraint.isNodeKeyConstraint()) {
                return format(CREATE_NODE_KEY_CONSTRAINT, name, labelsOrRelTypes, properties, providerName, config);
            }
        }
        if (constraint.isNodePropertyExistenceConstraint()) {
            // "create CONSTRAINT ON (a:A) ASSERT (a.p) IS NOT NULL"
            int labelId = constraint.schema().getLabelId();
            String label = tokenRead.nodeLabelName(labelId);
            int propertyId = constraint.schema().getPropertyId();
            String property = tokenRead.propertyKeyName(propertyId);
            return format(CREATE_NODE_EXISTENCE_CONSTRAINT, escapeBackticks(name), escapeBackticks(label), escapeBackticks(property));
        }
        if (constraint.isRelationshipPropertyExistenceConstraint()) {
            // "create CONSTRAINT ON ()-[r:R]-() ASSERT (r.p) IS NOT NULL"
            int relationshipTypeId = constraint.schema().getRelTypeId();
            String relationshipType = tokenRead.relationshipTypeName(relationshipTypeId);
            int propertyId = constraint.schema().getPropertyId();
            String property = tokenRead.propertyKeyName(propertyId);
            return format(CREATE_RELATIONSHIP_EXISTENCE_CONSTRAINT, escapeBackticks(name), escapeBackticks(relationshipType), escapeBackticks(property));
        }
        throw new IllegalArgumentException("Did not recognize constraint type " + constraint);
    } catch (KernelException e) {
        throw new ProcedureException(Status.General.UnknownError, e, "Failed to re-create create statement.");
    }
}
Also used : ProcedureException(org.neo4j.internal.kernel.api.exceptions.ProcedureException) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) PropertyKeyIdNotFoundKernelException(org.neo4j.internal.kernel.api.exceptions.PropertyKeyIdNotFoundKernelException) IndexNotFoundKernelException(org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException) KernelException(org.neo4j.exceptions.KernelException)

Example 17 with KernelException

use of org.neo4j.exceptions.KernelException in project neo4j by neo4j.

the class IndexProcedures method createIndex.

private Stream<BuiltInProcedures.SchemaIndexInfo> createIndex(String name, List<String> labels, List<String> properties, IndexProviderDescriptor indexProviderDescriptor, Map<String, Object> configMap, String statusMessage, IndexCreator indexCreator) throws ProcedureException {
    IndexConfig indexConfig = IndexSettingUtil.toIndexConfigFromStringObjectMap(configMap);
    assertSingleLabel(labels);
    assertValidIndexProvider(indexProviderDescriptor);
    int labelId = getOrCreateLabelId(labels.get(0));
    int[] propertyKeyIds = getOrCreatePropertyIds(properties);
    try {
        SchemaWrite schemaWrite = ktx.schemaWrite();
        LabelSchemaDescriptor labelSchemaDescriptor = SchemaDescriptor.forLabel(labelId, propertyKeyIds);
        indexCreator.create(schemaWrite, name, labelSchemaDescriptor, indexProviderDescriptor, indexConfig);
        return Stream.of(new BuiltInProcedures.SchemaIndexInfo(name, labels, properties, indexProviderDescriptor.name(), statusMessage));
    } catch (KernelException e) {
        throw new ProcedureException(e.status(), e, e.getMessage());
    }
}
Also used : IndexConfig(org.neo4j.internal.schema.IndexConfig) SchemaWrite(org.neo4j.internal.kernel.api.SchemaWrite) LabelSchemaDescriptor(org.neo4j.internal.schema.LabelSchemaDescriptor) ProcedureException(org.neo4j.internal.kernel.api.exceptions.ProcedureException) IndexNotFoundKernelException(org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException) KernelException(org.neo4j.exceptions.KernelException)

Example 18 with KernelException

use of org.neo4j.exceptions.KernelException in project neo4j by neo4j.

the class DelegatingTokenHolder method createUnresolvedTokens.

private ObjectIntHashMap<String> createUnresolvedTokens(IntSet unresolvedIndexes, String[] names, int[] ids, boolean internal) throws KernelException {
    // First, we need to filter out all of the tokens that are already resolved, so we only create tokens for
    // indexes that are in the unresolvedIndexes set.
    // However, we also need to deal with duplicate token names. For any token index we decide needs to have a
    // token created, we will add a mapping from the token name, to the ids-index into which the token id will
    // be written. This is the 'createdTokens' map. It maps token names to indexes into the 'ids' array.
    // If we find that the 'created'Tokens' map already has an entry for a given name, then that name is a
    // duplicate, and we will need to "remap" it later, by reading the token id from the correct index in the
    // 'ids' array, and storing it at the indexes of the duplicates. This is what the 'remappingIndexes' map is
    // for. This is a map from 'a' to 'b', where both 'a' and 'b' are indexes into the 'ids' array, and where
    // the corresponding name for 'a' is a duplicate of the name for 'b', and where we have already decided
    // that we will create a token id for index 'b'. After the token ids have been created, we go through the
    // 'remappingIndexes' map, and for every '(a,b)' entry, we store the token id created for 'b' and 'ids'
    // index 'a'.
    ObjectIntHashMap<String> createdTokens = new ObjectIntHashMap<>();
    IntIntHashMap remappingIndexes = new IntIntHashMap();
    IntPredicate tokenCreateFilter = index -> {
        boolean needsCreate = unresolvedIndexes.contains(index);
        if (needsCreate) {
            // The name at this index is unresolved.
            String name = names[index];
            int creatingIndex = createdTokens.getIfAbsentPut(name, index);
            if (creatingIndex != index) {
                // This entry has a duplicate name, so we need to remap this entry instead of creating a token
                // for it.
                remappingIndexes.put(index, creatingIndex);
                needsCreate = false;
            }
        }
        return needsCreate;
    };
    // Create tokens for all the indexes that we don't filter out.
    tokenCreator.createTokens(names, ids, internal, tokenCreateFilter);
    // Remap duplicate tokens to the token id we created for the first instance of any duplicate token name.
    if (remappingIndexes.notEmpty()) {
        remappingIndexes.forEachKeyValue((index, creatingIndex) -> ids[index] = ids[creatingIndex]);
    }
    return createdTokens;
}
Also used : Status(org.neo4j.kernel.api.exceptions.Status) ALWAYS_TRUE_INT(org.neo4j.function.Predicates.ALWAYS_TRUE_INT) NonUniqueTokenException(org.neo4j.token.api.NonUniqueTokenException) IntIntHashMap(org.eclipse.collections.impl.map.mutable.primitive.IntIntHashMap) IntPredicate(java.util.function.IntPredicate) ArrayList(java.util.ArrayList) IntSet(org.eclipse.collections.api.set.primitive.IntSet) IntHashSet(org.eclipse.collections.impl.set.mutable.primitive.IntHashSet) List(java.util.List) MutableIntSet(org.eclipse.collections.api.set.primitive.MutableIntSet) KernelException(org.neo4j.exceptions.KernelException) ObjectIntHashMap(org.eclipse.collections.impl.map.mutable.primitive.ObjectIntHashMap) NamedToken(org.neo4j.token.api.NamedToken) UnspecifiedKernelException(org.neo4j.exceptions.UnspecifiedKernelException) IntIntHashMap(org.eclipse.collections.impl.map.mutable.primitive.IntIntHashMap) ObjectIntHashMap(org.eclipse.collections.impl.map.mutable.primitive.ObjectIntHashMap) IntPredicate(java.util.function.IntPredicate)

Example 19 with KernelException

use of org.neo4j.exceptions.KernelException in project neo4j by neo4j.

the class IndexStatisticsTest method repeatCreateNamedPeopleFor.

private long[] repeatCreateNamedPeopleFor(int totalNumberOfPeople) throws Exception {
    // Parallelize the creation of persons
    final long[] nodes = new long[totalNumberOfPeople];
    final int threads = 100;
    final int peoplePerThread = totalNumberOfPeople / threads;
    final ExecutorService service = Executors.newFixedThreadPool(threads);
    final AtomicReference<KernelException> exception = new AtomicReference<>();
    final List<Callable<Void>> jobs = new ArrayList<>(threads);
    // Start threads that creates these people, relying on batched writes to speed things up
    for (int i = 0; i < threads; i++) {
        final int finalI = i;
        jobs.add(() -> {
            int offset = finalI * peoplePerThread;
            while (offset < (finalI + 1) * peoplePerThread) {
                try {
                    offset += createNamedPeople(nodes, offset);
                } catch (KernelException e) {
                    exception.compareAndSet(null, e);
                    throw new RuntimeException(e);
                }
            }
            return null;
        });
    }
    Futures.getAllResults(service.invokeAll(jobs));
    service.awaitTermination(1, TimeUnit.SECONDS);
    service.shutdown();
    // Make any KernelException thrown from a creation thread visible in the main thread
    Exception ex = exception.get();
    if (ex != null) {
        throw ex;
    }
    return nodes;
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) IndexNotFoundKernelException(org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException) KernelException(org.neo4j.exceptions.KernelException) Callable(java.util.concurrent.Callable) IndexNotFoundKernelException(org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException) NotFoundException(org.neo4j.graphdb.NotFoundException) IOException(java.io.IOException) KernelException(org.neo4j.exceptions.KernelException)

Example 20 with KernelException

use of org.neo4j.exceptions.KernelException in project neo4j by neo4j.

the class FullCheckIntegrationTest method shouldReportDuplicateConstraintReferences.

@Test
void shouldReportDuplicateConstraintReferences() throws Exception {
    // given
    AtomicReference<IndexDescriptor> descriptor1 = new AtomicReference<>();
    AtomicReference<IndexDescriptor> descriptor2 = new AtomicReference<>();
    fixture.apply(new GraphStoreFixture.Transaction() {

        @Override
        protected void transactionData(GraphStoreFixture.TransactionDataBuilder tx, GraphStoreFixture.IdGenerator next) throws KernelException {
            int ruleId1 = (int) next.schema();
            int ruleId2 = (int) next.schema();
            int labelId = next.label();
            int propertyKeyId = next.propertyKey();
            SchemaRecord before1 = new SchemaRecord(ruleId1);
            SchemaRecord before2 = new SchemaRecord(ruleId2);
            SchemaRecord after1 = cloneRecord(before1).initialize(true, 0);
            SchemaRecord after2 = cloneRecord(before2).initialize(true, 0);
            IndexDescriptor rule1 = constraintIndexRule(ruleId1, labelId, propertyKeyId, DESCRIPTOR, ruleId1);
            rule1 = tx.completeConfiguration(rule1);
            IndexDescriptor rule2 = constraintIndexRule(ruleId2, labelId, propertyKeyId, DESCRIPTOR, ruleId1);
            rule2 = tx.completeConfiguration(rule2);
            serializeRule(rule1, after1, tx, next);
            serializeRule(rule2, after2, tx, next);
            tx.nodeLabel(labelId, "label", false);
            tx.propertyKey(propertyKeyId, "property", false);
            tx.createSchema(before1, after1, rule1);
            tx.createSchema(before2, after2, rule2);
            descriptor1.set(rule1);
            descriptor2.set(rule2);
        }
    });
    fixture.indexingService().activateIndex(descriptor1.get());
    fixture.indexingService().activateIndex(descriptor2.get());
    // when
    ConsistencySummaryStatistics stats = check();
    // then
    on(stats).verify(RecordType.SCHEMA, 4).andThatsAllFolks();
    String logContents = logStream.toString();
    assertThat(logContents).contains(descriptor1.get().userDescription(fixture.directStoreAccess().tokenHolders()));
    assertThat(logContents).contains(descriptor2.get().userDescription(fixture.directStoreAccess().tokenHolders()));
}
Also used : TransactionDataBuilder(org.neo4j.consistency.checking.GraphStoreFixture.TransactionDataBuilder) SchemaRecord(org.neo4j.kernel.impl.store.record.SchemaRecord) IdGenerator(org.neo4j.consistency.checking.GraphStoreFixture.IdGenerator) AtomicReference(java.util.concurrent.atomic.AtomicReference) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) KernelException(org.neo4j.exceptions.KernelException) GraphStoreFixture(org.neo4j.consistency.checking.GraphStoreFixture) ConsistencySummaryStatistics(org.neo4j.consistency.report.ConsistencySummaryStatistics) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Aggregations

KernelException (org.neo4j.exceptions.KernelException)58 IndexNotFoundKernelException (org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException)22 InvalidTransactionTypeKernelException (org.neo4j.internal.kernel.api.exceptions.InvalidTransactionTypeKernelException)21 SchemaKernelException (org.neo4j.internal.kernel.api.exceptions.schema.SchemaKernelException)16 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)15 IndexDescriptor (org.neo4j.internal.schema.IndexDescriptor)13 TokenCapacityExceededKernelException (org.neo4j.internal.kernel.api.exceptions.schema.TokenCapacityExceededKernelException)12 Test (org.junit.jupiter.api.Test)11 ProcedureException (org.neo4j.internal.kernel.api.exceptions.ProcedureException)10 PropertyKeyIdNotFoundKernelException (org.neo4j.internal.kernel.api.exceptions.PropertyKeyIdNotFoundKernelException)10 QueryExecutionKernelException (org.neo4j.kernel.impl.query.QueryExecutionKernelException)10 List (java.util.List)8 NotFoundException (org.neo4j.graphdb.NotFoundException)8 SchemaRead (org.neo4j.internal.kernel.api.SchemaRead)8 Arrays (java.util.Arrays)7 Collectors (java.util.stream.Collectors)7 ConstraintViolationException (org.neo4j.graphdb.ConstraintViolationException)7 EntityNotFoundException (org.neo4j.internal.kernel.api.exceptions.EntityNotFoundException)7 IllegalTokenNameException (org.neo4j.internal.kernel.api.exceptions.schema.IllegalTokenNameException)7 ArrayList (java.util.ArrayList)6