Example #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBeAbleToStoreAndRetrieveConstraintAfterRestart() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBeAbleToStoreAndRetrieveConstraintAfterRestart()
        {
            // given
            Transaction transaction = newTransaction(AUTH_DISABLED);

            // when
            ConstraintDescriptor constraint = CreateConstraint(transaction.SchemaWrite(), Descriptor);

            // then
            assertEquals(constraint, single(transaction.SchemaRead().constraintsGetAll()));

            // given
            commit();
            restartDb();
            transaction = newTransaction();

            // when
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Iterator<?> constraints = transaction.schemaRead().constraintsGetAll();
            IEnumerator <object> constraints = transaction.SchemaRead().constraintsGetAll();

            // then
            assertEquals(constraint, single(constraints));

            commit();
        }
Example #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void should_list_constraints()
        public virtual void ShouldListConstraints()
        {
            // GIVEN
            SchemaCache cache = NewSchemaCache();

            // WHEN
            cache.AddSchemaRule(UniquenessConstraintRule(0L, 1, 2, 133L));
            cache.AddSchemaRule(UniquenessConstraintRule(1L, 3, 4, 133L));
            cache.AddSchemaRule(RelPropertyExistenceConstraintRule(2L, 5, 6));
            cache.AddSchemaRule(NodePropertyExistenceConstraintRule(3L, 7, 8));

            // THEN
            ConstraintDescriptor unique1    = uniqueForLabel(1, 2);
            ConstraintDescriptor unique2    = uniqueForLabel(3, 4);
            ConstraintDescriptor existsRel  = ConstraintDescriptorFactory.existsForRelType(5, 6);
            ConstraintDescriptor existsNode = ConstraintDescriptorFactory.existsForLabel(7, 8);

            assertEquals(asSet(unique1, unique2, existsRel, existsNode), asSet(cache.Constraints()));

            assertEquals(asSet(unique1), asSet(cache.ConstraintsForLabel(1)));

            assertEquals(asSet(unique1), asSet(cache.ConstraintsForSchema(unique1.Schema())));

            assertEquals(asSet(), asSet(cache.ConstraintsForSchema(forLabel(1, 3))));

            assertEquals(asSet(existsRel), asSet(cache.ConstraintsForRelationshipType(5)));
        }
Example #3
0
        private void ShowUniqueConstraints(DbStructureVisitor visitor, KernelTransaction ktx, TokenNameLookup nameLookup)
        {
            IEnumerator <ConstraintDescriptor> constraints = ktx.SchemaRead().constraintsGetAll();

            while (constraints.MoveNext())
            {
                ConstraintDescriptor constraint = constraints.Current;
                string userDescription          = constraint.PrettyPrint(nameLookup);

                if (constraint is UniquenessConstraintDescriptor)
                {
                    visitor.VisitUniqueConstraint(( UniquenessConstraintDescriptor )constraint, userDescription);
                }
                else if (constraint is NodeExistenceConstraintDescriptor)
                {
                    NodeExistenceConstraintDescriptor existenceConstraint = ( NodeExistenceConstraintDescriptor )constraint;
                    visitor.VisitNodePropertyExistenceConstraint(existenceConstraint, userDescription);
                }
                else if (constraint is RelExistenceConstraintDescriptor)
                {
                    RelExistenceConstraintDescriptor existenceConstraint = ( RelExistenceConstraintDescriptor )constraint;
                    visitor.VisitRelationshipPropertyExistenceConstraint(existenceConstraint, userDescription);
                }
                else if (constraint is NodeKeyConstraintDescriptor)
                {
                    NodeKeyConstraintDescriptor nodeKeyConstraint = ( NodeKeyConstraintDescriptor )constraint;
                    visitor.VisitNodeKeyConstraint(nodeKeyConstraint, userDescription);
                }
                else
                {
                    throw new System.ArgumentException("Unknown constraint type: " + constraint.GetType() + ", " + "constraint: " + constraint);
                }
            }
        }
Example #4
0
 public override void ConstraintDoDrop(ConstraintDescriptor constraint)
 {
     ConstraintsChangesDiffSets().remove(constraint);
     if (constraint.EnforcesUniqueness())
     {
         IndexDoDrop(GetIndexForIndexBackedConstraint(( IndexBackedConstraintDescriptor )constraint));
     }
     Changed();
 }
Example #5
0
        private IEnumerable <ConstraintDefinition> AsConstraintDefinitions <T1>(IEnumerator <T1> constraints, TokenRead tokenRead) where T1 : Org.Neo4j.@internal.Kernel.Api.schema.constraints.ConstraintDescriptor
        {
            // Intentionally create an eager list so that used statement can be closed
            IList <ConstraintDefinition> definitions = new List <ConstraintDefinition>();

            while (constraints.MoveNext())
            {
                ConstraintDescriptor constraint = constraints.Current;
                definitions.Add(AsConstraintDefinition(constraint, tokenRead));
            }

            return(definitions);
        }
Example #6
0
        private static string ConstraintType(ConstraintDescriptor constraint)
        {
            switch (constraint.Type())
            {
            case EXISTS:
                return("Existence constraint");

            case UNIQUE:
                return("Uniqueness constraint");

            case UNIQUE_EXISTS:
                return("Node Key");

            default:
                throw new System.ArgumentException("Unknown constraint type: " + constraint.Type());
            }
        }
Example #7
0
        /// <summary>
        /// Get the constraint rule that matches the given ConstraintDescriptor </summary>
        /// <param name="descriptor"> the ConstraintDescriptor to match </param>
        /// <returns> the matching ConstrainRule </returns>
        /// <exception cref="SchemaRuleNotFoundException"> if no ConstraintRule matches the given descriptor </exception>
        /// <exception cref="DuplicateSchemaRuleException"> if two or more ConstraintRules match the given descriptor </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public org.neo4j.kernel.impl.store.record.ConstraintRule constraintsGetSingle(final org.neo4j.internal.kernel.api.schema.constraints.ConstraintDescriptor descriptor) throws org.neo4j.kernel.api.exceptions.schema.SchemaRuleNotFoundException, org.neo4j.kernel.api.exceptions.schema.DuplicateSchemaRuleException
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
        public virtual ConstraintRule ConstraintsGetSingle(ConstraintDescriptor descriptor)
        {
            IEnumerator <ConstraintRule> rules = LoadAllSchemaRules(descriptor.isSame, typeof(ConstraintRule), false);

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            if (!rules.hasNext())
            {
                throw new SchemaRuleNotFoundException(Org.Neo4j.Storageengine.Api.schema.SchemaRule_Kind.map(descriptor), descriptor.Schema());
            }

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ConstraintRule rule = rules.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            if (rules.hasNext())
            {
                throw new DuplicateSchemaRuleException(Org.Neo4j.Storageengine.Api.schema.SchemaRule_Kind.map(descriptor), descriptor.Schema());
            }
            return(rule);
        }
 public override void VisitRemovedConstraint(ConstraintDescriptor constraint)
 {
     _clearSchemaState = true;
     try
     {
         _recordState.dropSchemaRule(_schemaStorage.constraintsGetSingle(constraint));
     }
     catch (SchemaRuleNotFoundException)
     {
         throw new System.InvalidOperationException("Constraint to be removed should exist, since its existence should have been validated earlier " + "and the schema should have been locked.");
     }
     catch (DuplicateSchemaRuleException)
     {
         throw new System.InvalidOperationException("Multiple constraints found for specified label and property.");
     }
     if (constraint.EnforcesUniqueness())
     {
         // Remove the index for the constraint as well
         VisitRemovedIndex((( IndexBackedConstraintDescriptor )constraint).ownedIndexDescriptor());
     }
 }
Example #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void should_remove_constraints()
        public virtual void ShouldRemoveConstraints()
        {
            // GIVEN
            SchemaCache cache = NewSchemaCache();

            cache.AddSchemaRule(UniquenessConstraintRule(0L, 1, 2, 133L));
            cache.AddSchemaRule(UniquenessConstraintRule(1L, 3, 4, 133L));

            // WHEN
            cache.RemoveSchemaRule(0L);

            // THEN
            ConstraintDescriptor dropped = uniqueForLabel(1, 1);
            ConstraintDescriptor unique  = uniqueForLabel(3, 4);

            assertEquals(asSet(unique), asSet(cache.Constraints()));

            assertEquals(asSet(), asSet(cache.ConstraintsForLabel(1)));

            assertEquals(asSet(), asSet(cache.ConstraintsForSchema(dropped.Schema())));
        }
Example #10
0
        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 is NodeExistenceConstraintDescriptor || constraint is NodeKeyConstraintDescriptor || constraint is UniquenessConstraintDescriptor)
            {
                SchemaDescriptor schemaDescriptor = constraint.Schema();
                int[]            entityTokenIds   = schemaDescriptor.EntityTokenIds;
                Label[]          labels           = new Label[entityTokenIds.Length];
                for (int i = 0; i < entityTokenIds.Length; i++)
                {
                    labels[i] = label(lookup.LabelGetName(entityTokenIds[i]));
                }
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
                string[] propertyKeys = Arrays.stream(schemaDescriptor.PropertyIds).mapToObj(lookup.propertyKeyGetName).toArray(string[] ::new);
                if (constraint is NodeExistenceConstraintDescriptor)
                {
                    return(new NodePropertyExistenceConstraintDefinition(_actions, labels[0], propertyKeys));
                }
                else if (constraint is 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 is RelExistenceConstraintDescriptor)
            {
                RelationTypeSchemaDescriptor descriptor = ( RelationTypeSchemaDescriptor )constraint.Schema();
                return(new RelationshipPropertyExistenceConstraintDefinition(_actions, withName(lookup.RelationshipTypeGetName(descriptor.RelTypeId)), lookup.PropertyKeyGetName(descriptor.PropertyId)));
            }
            throw new System.ArgumentException("Unknown constraint " + constraint);
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void visitAddedConstraint(org.neo4j.internal.kernel.api.schema.constraints.ConstraintDescriptor constraint) throws org.neo4j.internal.kernel.api.exceptions.schema.CreateConstraintFailureException
        public override void VisitAddedConstraint(ConstraintDescriptor constraint)
        {
            _clearSchemaState = true;
            long constraintId = _schemaStorage.newRuleId();

            switch (constraint.Type())
            {
            case UNIQUE:
                VisitAddedUniquenessConstraint(( UniquenessConstraintDescriptor )constraint, constraintId);
                break;

            case UNIQUE_EXISTS:
                VisitAddedNodeKeyConstraint(( NodeKeyConstraintDescriptor )constraint, constraintId);
                break;

            case EXISTS:
                _recordState.createSchemaRule(_constraintSemantics.createExistenceConstraint(_schemaStorage.newRuleId(), constraint));
                break;

            default:
                throw new System.InvalidOperationException(constraint.Type().ToString());
            }
        }
Example #12
0
        private static IList <IDictionary <string, object> > Constraints(TokenRead tokens, SchemaRead schemaRead, Anonymizer anonymizer)
        {
            IList <IDictionary <string, object> > constraints = new List <IDictionary <string, object> >();

            SilentTokenNameLookup tokenLookup = new SilentTokenNameLookup(tokens);

            IEnumerator <ConstraintDescriptor> iterator = schemaRead.ConstraintsGetAll();

            while (iterator.MoveNext())
            {
                ConstraintDescriptor         constraint = iterator.Current;
                EntityType                   entityType = constraint.Schema().entityType();
                IDictionary <string, object> data       = new Dictionary <string, object>();

                data["properties"] = Map(constraint.Schema().PropertyIds, id => anonymizer.PropertyKey(tokenLookup.PropertyKeyGetName(id), id));
                data["type"]       = ConstraintType(constraint);
                int entityTokenId = constraint.Schema().EntityTokenIds[0];

                switch (entityType.innerEnumValue)
                {
                case EntityType.InnerEnum.NODE:
                    data["label"] = anonymizer.Label(tokenLookup.LabelGetName(entityTokenId), entityTokenId);
                    constraints.Add(data);
                    break;

                case EntityType.InnerEnum.RELATIONSHIP:
                    data["relationshipType"] = anonymizer.RelationshipType(tokenLookup.RelationshipTypeGetName(entityTokenId), entityTokenId);
                    constraints.Add(data);
                    break;

                default:
                    break;
                }
            }

            return(constraints);
        }
Example #13
0
 public DropConstraintFailureException(ConstraintDescriptor constraint, Exception cause) : base(org.neo4j.kernel.api.exceptions.Status_Schema.ConstraintDropFailed, cause, "Unable to drop constraint %s: %s", constraint, cause.Message)
 {
     this._constraint = constraint;
 }
Example #14
0
 public override bool ConstraintDoUnRemove(ConstraintDescriptor constraint)
 {
     return(ConstraintsChangesDiffSets().unRemove(constraint));
 }
 public UnableToValidateConstraintException(ConstraintDescriptor constraint, Exception cause) : base(constraint, Phase.Verification, format("Unable to validate constraint %s", constraint.UserDescription(SchemaUtil.idTokenNameLookup)), cause)
 {
 }
 public CreateConstraintFailureException(ConstraintDescriptor constraint, string cause) : base(org.neo4j.kernel.api.exceptions.Status_Schema.ConstraintCreationFailed, null, "Unable to create constraint %s: %s", constraint, cause)
 {
     this._constraint = constraint;
     this._cause      = cause;
 }
Example #17
0
 public override void VisitRemovedConstraint(ConstraintDescriptor constraint)
 {
     Actual.visitRemovedConstraint(constraint);
 }
Example #18
0
        public virtual GraphResult BuildSchemaGraph()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Map<String,VirtualNodeHack> nodes = new java.util.HashMap<>();
            IDictionary <string, VirtualNodeHack> nodes = new Dictionary <string, VirtualNodeHack>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Map<String,java.util.Set<VirtualRelationshipHack>> relationships = new java.util.HashMap<>();
            IDictionary <string, ISet <VirtualRelationshipHack> > relationships = new Dictionary <string, ISet <VirtualRelationshipHack> >();

            using (Statement statement = _kernelTransaction.acquireStatement())
            {
                Read            dataRead        = _kernelTransaction.dataRead();
                TokenRead       tokenRead       = _kernelTransaction.tokenRead();
                TokenNameLookup tokenNameLookup = new SilentTokenNameLookup(tokenRead);
                SchemaRead      schemaRead      = _kernelTransaction.schemaRead();
                using (Transaction transaction = _graphDatabaseAPI.beginTx())
                {
                    // add all labelsInDatabase
                    using (ResourceIterator <Label> labelsInDatabase = _graphDatabaseAPI.AllLabelsInUse.GetEnumerator())
                    {
                        while (labelsInDatabase.MoveNext())
                        {
                            Label label   = labelsInDatabase.Current;
                            int   labelId = tokenRead.NodeLabel(label.Name());
                            IDictionary <string, object> properties = new Dictionary <string, object>();

                            IEnumerator <IndexReference> indexReferences = schemaRead.IndexesGetForLabel(labelId);
                            List <string> indexes = new List <string>();
                            while (indexReferences.MoveNext())
                            {
                                IndexReference index = indexReferences.Current;
                                if (!index.Unique)
                                {
                                    string[] propertyNames = PropertyNameUtils.getPropertyKeys(tokenNameLookup, index.Properties());
                                    indexes.Add(string.join(",", propertyNames));
                                }
                            }
                            properties["indexes"] = indexes;

                            IEnumerator <ConstraintDescriptor> nodePropertyConstraintIterator = schemaRead.ConstraintsGetForLabel(labelId);
                            List <string> constraints = new List <string>();
                            while (nodePropertyConstraintIterator.MoveNext())
                            {
                                ConstraintDescriptor constraint = nodePropertyConstraintIterator.Current;
                                constraints.Add(constraint.PrettyPrint(tokenNameLookup));
                            }
                            properties["constraints"] = constraints;

                            GetOrCreateLabel(label.Name(), properties, nodes);
                        }
                    }

                    //add all relationships

                    using (ResourceIterator <RelationshipType> relationshipTypeIterator = _graphDatabaseAPI.AllRelationshipTypesInUse.GetEnumerator())
                    {
                        while (relationshipTypeIterator.MoveNext())
                        {
                            RelationshipType relationshipType        = relationshipTypeIterator.Current;
                            string           relationshipTypeGetName = relationshipType.Name();
                            int relId = tokenRead.RelationshipType(relationshipTypeGetName);
                            using (ResourceIterator <Label> labelsInUse = _graphDatabaseAPI.AllLabelsInUse.GetEnumerator())
                            {
                                IList <VirtualNodeHack> startNodes = new LinkedList <VirtualNodeHack>();
                                IList <VirtualNodeHack> endNodes   = new LinkedList <VirtualNodeHack>();

                                while (labelsInUse.MoveNext())
                                {
                                    Label  labelToken = labelsInUse.Current;
                                    string labelName  = labelToken.Name();
                                    IDictionary <string, object> properties = new Dictionary <string, object>();
                                    VirtualNodeHack node    = GetOrCreateLabel(labelName, properties, nodes);
                                    int             labelId = tokenRead.NodeLabel(labelName);

                                    if (dataRead.CountsForRelationship(labelId, relId, [email protected]_Fields.ANY_LABEL) > 0)
                                    {
                                        startNodes.Add(node);
                                    }
                                    if (dataRead.CountsForRelationship([email protected]_Fields.ANY_LABEL, relId, labelId) > 0)
                                    {
                                        endNodes.Add(node);
                                    }
                                }

                                foreach (VirtualNodeHack startNode in startNodes)
                                {
                                    foreach (VirtualNodeHack endNode in endNodes)
                                    {
                                        AddRelationship(startNode, endNode, relationshipTypeGetName, relationships);
                                    }
                                }
                            }
                        }
                    }
                    transaction.Success();
                    return(GetGraphResult(nodes, relationships));
                }
            }
        }
Example #19
0
 public override void VisitRemovedConstraint(ConstraintDescriptor element)
 {
 }
Example #20
0
 public virtual bool HasConstraintRule(ConstraintDescriptor descriptor)
 {
     return(_schemaCacheState.hasConstraintRule(descriptor));
 }
Example #21
0
 internal virtual bool HasConstraintRule(ConstraintDescriptor descriptor)
 {
     return(ConstraintsConflict.Contains(descriptor));
 }
Example #22
0
 public override bool ConstraintExists(ConstraintDescriptor descriptor)
 {
     return(_schemaCache.hasConstraintRule(descriptor));
 }
Example #23
0
 public override void ConstraintDoAdd(ConstraintDescriptor constraint)
 {
     ConstraintsChangesDiffSets().add(constraint);
     Changed();
 }
Example #24
0
 public override bool ConstraintExists(ConstraintDescriptor descriptor)
 {
     throw new System.NotSupportedException("Not implemented yet");
 }
Example #25
0
 public override long?IndexCreatedForConstraint(ConstraintDescriptor constraint)
 {
     return(_createdConstraintIndexesByConstraint == null ? null : _createdConstraintIndexesByConstraint.get(constraint));
 }