Exemple #1
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: public org.neo4j.graphdb.schema.Schema_IndexState getIndexState(final org.neo4j.graphdb.schema.IndexDefinition index)
        public override Org.Neo4j.Graphdb.schema.Schema_IndexState GetIndexState(IndexDefinition index)
        {
            KernelTransaction transaction = SafeAcquireTransaction(_transactionSupplier);

            try
            {
                using (Statement ignore = transaction.AcquireStatement())
                {
                    SchemaRead         schemaRead = transaction.SchemaRead();
                    IndexReference     reference  = GetIndexReference(schemaRead, transaction.TokenRead(), (IndexDefinitionImpl)index);
                    InternalIndexState indexState = schemaRead.IndexGetState(reference);
                    switch (indexState)
                    {
                    case InternalIndexState.POPULATING:
                        return(POPULATING);

                    case InternalIndexState.ONLINE:
                        return(ONLINE);

                    case InternalIndexState.FAILED:
                        return(FAILED);

                    default:
                        throw new System.ArgumentException(string.Format("Illegal index state {0}", indexState));
                    }
                }
            }
            catch (Exception e) when(e is SchemaRuleNotFoundException || e is IndexNotFoundKernelException)
            {
                throw NewIndexNotFoundException(index, e);
            }
        }
Exemple #2
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static org.neo4j.internal.kernel.api.IndexReference awaitOnline(org.neo4j.internal.kernel.api.SchemaRead schemRead, org.neo4j.internal.kernel.api.IndexReference index) throws org.neo4j.internal.kernel.api.exceptions.KernelException
        private static IndexReference AwaitOnline(SchemaRead schemRead, IndexReference index)
        {
            long start = DateTimeHelper.CurrentUnixTimeMillis();
            long end   = start + 20_000;

            while (DateTimeHelper.CurrentUnixTimeMillis() < end)
            {
                switch (schemRead.IndexGetState(index))
                {
                case ONLINE:
                    return(index);

                case FAILED:
                    throw new System.InvalidOperationException("Index failed instead of becoming ONLINE");

                default:
                    break;
                }

                try
                {
                    Thread.Sleep(100);
                }
                catch (InterruptedException)
                {
                    // ignored
                }
            }
            throw new System.InvalidOperationException("Index did not become ONLINE within reasonable time");
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private org.neo4j.internal.kernel.api.IndexReference getOrCreateUniquenessConstraintIndex(org.neo4j.internal.kernel.api.SchemaRead schemaRead, org.neo4j.internal.kernel.api.TokenRead tokenRead, org.neo4j.internal.kernel.api.schema.SchemaDescriptor schema, String provider) throws org.neo4j.internal.kernel.api.exceptions.schema.SchemaKernelException, org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        private IndexReference GetOrCreateUniquenessConstraintIndex(SchemaRead schemaRead, TokenRead tokenRead, SchemaDescriptor schema, string provider)
        {
            IndexReference descriptor = schemaRead.Index(schema);

            if (descriptor != IndexReference.NO_INDEX)
            {
                if (descriptor.Unique)
                {
                    // OK so we found a matching constraint index. We check whether or not it has an owner
                    // because this may have been a left-over constraint index from a previously failed
                    // constraint creation, due to crash or similar, hence the missing owner.
                    if (schemaRead.IndexGetOwningUniquenessConstraintId(descriptor) == null)
                    {
                        return(descriptor);
                    }
                    throw new AlreadyConstrainedException(ConstraintDescriptorFactory.uniqueForSchema(schema), SchemaKernelException.OperationContext.CONSTRAINT_CREATION, new SilentTokenNameLookup(tokenRead));
                }
                // There's already an index for this schema descriptor, which isn't of the type we're after.
                throw new AlreadyIndexedException(schema, CONSTRAINT_CREATION);
            }
            IndexDescriptor indexDescriptor = CreateConstraintIndex(schema, provider);
            IndexProxy      indexProxy      = _indexingService.getIndexProxy(indexDescriptor.Schema());

            return(indexProxy.Descriptor);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void batchInserterShouldUseConfiguredIndexProvider() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void BatchInserterShouldUseConfiguredIndexProvider()
        {
            Config        config   = Config.defaults(stringMap(default_schema_provider.name(), _schemaIndex.providerName()));
            BatchInserter inserter = NewBatchInserter(config);

            inserter.CreateDeferredSchemaIndex(TestLabels.LABEL_ONE).on("key").create();
            inserter.Shutdown();
            GraphDatabaseService db = GraphDatabaseService(config);

            AwaitIndexesOnline(db);
            try
            {
                using (Transaction tx = Db.beginTx())
                {
                    DependencyResolver             dependencyResolver             = (( GraphDatabaseAPI )db).DependencyResolver;
                    ThreadToStatementContextBridge threadToStatementContextBridge = dependencyResolver.ResolveDependency(typeof(ThreadToStatementContextBridge));
                    KernelTransaction kernelTransaction = threadToStatementContextBridge.GetKernelTransactionBoundToThisThread(true);
                    TokenRead         tokenRead         = kernelTransaction.TokenRead();
                    SchemaRead        schemaRead        = kernelTransaction.SchemaRead();
                    int            labelId    = tokenRead.NodeLabel(TestLabels.LABEL_ONE.name());
                    int            propertyId = tokenRead.PropertyKey("key");
                    IndexReference index      = schemaRead.Index(labelId, propertyId);
                    assertTrue(UnexpectedIndexProviderMessage(index), _schemaIndex.providerName().contains(index.ProviderKey()));
                    assertTrue(UnexpectedIndexProviderMessage(index), _schemaIndex.providerName().contains(index.ProviderVersion()));
                    tx.Success();
                }
            }
            finally
            {
                Db.shutdown();
            }
        }
Exemple #5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void testCreateIndexWithGivenProvider(String label, String... properties) throws org.neo4j.internal.kernel.api.exceptions.KernelException
        private void TestCreateIndexWithGivenProvider(string label, params string[] properties)
        {
            // given
            Transaction transaction = NewTransaction(AnonymousContext.writeToken());
            int         labelId     = transaction.TokenWrite().labelGetOrCreateForName(label);

            int[]     propertyKeyIds = CreateProperties(transaction, properties);
            TextValue value          = stringValue("some value");
            long      node           = CreateNodeWithPropertiesAndLabel(transaction, labelId, propertyKeyIds, value);

            Commit();

            // when
            NewTransaction(AnonymousContext.full());
            string pattern           = IndexPattern(label, properties);
            string specifiedProvider = NATIVE10.providerName();
            RawIterator <object[], ProcedureException> result = CallIndexProcedure(pattern, specifiedProvider);

            // then
            assertThat(Arrays.asList(result.Next()), contains(pattern, specifiedProvider, ExpectedSuccessfulCreationStatus));
            Commit();
            AwaitIndexOnline();

            // and then
            transaction = NewTransaction(AnonymousContext.read());
            SchemaRead     schemaRead = transaction.SchemaRead();
            IndexReference index      = schemaRead.Index(labelId, propertyKeyIds);

            AssertCorrectIndex(labelId, propertyKeyIds, UniquenessConstraint, index);
            AssertIndexData(transaction, propertyKeyIds, value, node, index);
            Commit();
        }
Exemple #6
0
        private SchemaRead SchemaWithIndexes(params IndexReference[] indexes)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.internal.kernel.api.SchemaRead schemaRead = mock(org.neo4j.internal.kernel.api.SchemaRead.class);
            SchemaRead schemaRead = mock(typeof(SchemaRead));

            when(schemaRead.IndexesGetAll()).thenReturn(Iterators.iterator(indexes));
            return(schemaRead);
        }
Exemple #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotTimeOutIfNoIndexes() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotTimeOutIfNoIndexes()
        {
            // Given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.internal.kernel.api.SchemaRead schemaRead = schemaWithIndexes();
            SchemaRead schemaRead = SchemaWithIndexes();

            // Then no exception
            Indexes.AwaitResampling(schemaRead, 0);
        }
Exemple #8
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static org.neo4j.internal.kernel.api.IndexReference getIndexReference(org.neo4j.internal.kernel.api.SchemaRead schemaRead, org.neo4j.internal.kernel.api.TokenRead tokenRead, IndexDefinitionImpl index) throws org.neo4j.kernel.api.exceptions.schema.SchemaRuleNotFoundException
        private static IndexReference GetIndexReference(SchemaRead schemaRead, TokenRead tokenRead, IndexDefinitionImpl index)
        {
            // Use the precise embedded index reference when available.
            IndexReference reference = index.IndexReference;

            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.PropertyKeysArrayShared);
            SchemaDescriptor schema;

            if (index.NodeIndex)
            {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                int[] labelIds = ResolveAndValidateTokens("Label", index.LabelArrayShared, Label::name, tokenRead.nodeLabel);

                if (index.MultiTokenIndex)
                {
                    schema = multiToken(labelIds, EntityType.NODE, propertyKeyIds);
                }
                else
                {
                    schema = forLabel(labelIds[0], propertyKeyIds);
                }
            }
            else if (index.RelationshipIndex)
            {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                int[] relTypes = ResolveAndValidateTokens("Relationship type", index.RelationshipTypesArrayShared, RelationshipType::name, tokenRead.relationshipType);

                if (index.MultiTokenIndex)
                {
                    schema = multiToken(relTypes, EntityType.RELATIONSHIP, propertyKeyIds);
                }
                else
                {
                    schema = forRelType(relTypes[0], propertyKeyIds);
                }
            }
            else
            {
                throw new System.ArgumentException("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(Org.Neo4j.Storageengine.Api.schema.SchemaRule_Kind.IndexRule, schema);
            }

            return(reference);
        }
Exemple #9
0
        private void AssertCorrectProvider(GraphDatabaseAPI db, Label label, string property)
        {
            KernelTransaction kernelTransaction = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge)).getKernelTransactionBoundToThisThread(false);
            TokenRead         tokenRead         = kernelTransaction.TokenRead();
            int            labelId    = tokenRead.NodeLabel(label.Name());
            int            propId     = tokenRead.PropertyKey(property);
            SchemaRead     schemaRead = kernelTransaction.SchemaRead();
            IndexReference index      = schemaRead.Index(labelId, propId);

            assertEquals("correct provider key", "lucene+native", index.ProviderKey());
            assertEquals("correct provider version", "1.0", index.ProviderVersion());
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void showIndices(DbStructureVisitor visitor, org.neo4j.kernel.api.KernelTransaction ktx, org.neo4j.internal.kernel.api.TokenNameLookup nameLookup) throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        private void ShowIndices(DbStructureVisitor visitor, KernelTransaction ktx, TokenNameLookup nameLookup)
        {
            SchemaRead schemaRead = ktx.SchemaRead();

            foreach (IndexReference reference in loop(sortByType(schemaRead.IndexesGetAll())))
            {
                string userDescription        = reference.Schema().userDescription(nameLookup);
                double uniqueValuesPercentage = schemaRead.IndexUniqueValuesSelectivity(reference);
                long   size = schemaRead.IndexSize(reference);
                visitor.VisitIndex(( IndexDescriptor )reference, userDescription, uniqueValuesPercentage, size);
            }
        }
Exemple #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void awaitIndexOnline(org.neo4j.internal.kernel.api.SchemaRead schemaRead, org.neo4j.internal.kernel.api.IndexReference index) throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        public static void AwaitIndexOnline(SchemaRead schemaRead, IndexReference index)
        {
            long start = DateTimeHelper.CurrentUnixTimeMillis();

            while (schemaRead.IndexGetState(index) != InternalIndexState.ONLINE)
            {
                if (start + 1000 * 10 < DateTimeHelper.CurrentUnixTimeMillis())
                {
                    throw new Exception("Index didn't come online within a reasonable time.");
                }
            }
        }
Exemple #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup()
        public virtual void Setup()
        {
            _transaction   = mock(typeof(KernelTransaction));
            _tokenRead     = mock(typeof(TokenRead));
            _schemaRead    = mock(typeof(SchemaRead));
            _procedure     = new IndexProcedures(_transaction, null);
            _descriptor    = SchemaDescriptorFactory.forLabel(123, 456);
            _anyDescriptor = SchemaDescriptorFactory.forLabel(0, 0);
            _anyIndex      = forSchema(_anyDescriptor);
            when(_transaction.tokenRead()).thenReturn(_tokenRead);
            when(_transaction.schemaRead()).thenReturn(_schemaRead);
        }
Exemple #13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAwaitIndexResamplingForHeavyLoad() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAwaitIndexResamplingForHeavyLoad()
        {
            // Given
            IndexReference index = mock(typeof(IndexReference));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.internal.kernel.api.SchemaRead schemaRead = schemaWithIndexes(index);
            SchemaRead schemaRead = SchemaWithIndexes(index);

            SetUpdates(schemaRead, 1, 2, 3, 2);                 // <- updates went down but didn't reach the first seen value

            // Then no exception
            Indexes.AwaitResampling(schemaRead, 60);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(expected = org.neo4j.graphdb.NotInTransactionException.class) public void shouldThrowNotInTransactionWhenTransactionClosedAndAttemptingOperations() throws org.neo4j.internal.kernel.api.exceptions.KernelException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldThrowNotInTransactionWhenTransactionClosedAndAttemptingOperations()
        {
            KernelTransaction transaction = newTransaction(AnonymousContext.write());

            Read       read       = transaction.DataRead();
            Write      write      = transaction.DataWrite();
            SchemaRead schemaRead = transaction.SchemaRead();

            transaction.Success();
            transaction.Close();

            TransactionOperation.operate(read, write, schemaRead);
        }
Exemple #15
0
        /// <summary>
        /// For each index, await a resampling event unless it has zero pending updates.
        /// </summary>
        /// <param name="schemaRead"> backing schema read </param>
        /// <param name="timeout"> timeout in seconds. If this limit is passed, a TimeoutException is thrown. </param>
        /// <exception cref="TimeoutException"> if all indexes are not resampled within the timeout. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void awaitResampling(org.neo4j.internal.kernel.api.SchemaRead schemaRead, long timeout) throws java.util.concurrent.TimeoutException
        public static void AwaitResampling(SchemaRead schemaRead, long timeout)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Iterator<org.neo4j.internal.kernel.api.IndexReference> indexes = schemaRead.indexesGetAll();
            IEnumerator <IndexReference> indexes = schemaRead.IndexesGetAll();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.register.Register_DoubleLongRegister register = org.neo4j.register.Registers.newDoubleLongRegister();
            Org.Neo4j.Register.Register_DoubleLongRegister register = Registers.newDoubleLongRegister();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long t0 = System.currentTimeMillis();
            long t0 = DateTimeHelper.CurrentUnixTimeMillis();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long timeoutMillis = 1000 * timeout;
            long timeoutMillis = 1000 * timeout;

            while (indexes.MoveNext())
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.internal.kernel.api.IndexReference index = indexes.Current;
                IndexReference index = indexes.Current;
                try
                {
                    long readUpdates = readUpdates(index, schemaRead, register);
                    long updateCount = readUpdates;
                    bool hasTimedOut = false;

                    while (updateCount > 0 && updateCount <= readUpdates && !hasTimedOut)
                    {
                        Thread.Sleep(10);
                        hasTimedOut = DateTimeHelper.CurrentUnixTimeMillis() - t0 >= timeoutMillis;
                        updateCount = Math.Max(updateCount, readUpdates);
                        readUpdates = readUpdates(index, schemaRead, register);
                    }

                    if (hasTimedOut)
                    {
                        throw new TimeoutException(string.Format("Indexes were not resampled within {0} {1}", timeout, TimeUnit.SECONDS));
                    }
                }
                catch (InterruptedException e)
                {
                    Thread.CurrentThread.Interrupt();
                    throw new Exception(e);
                }
                catch (IndexNotFoundKernelException e)
                {
                    throw new ConcurrentModificationException("Index was dropped while awaiting resampling", e);
                }
            }
        }
Exemple #16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldTimeout() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldTimeout()
        {
            // Given
            IndexReference index = mock(typeof(IndexReference));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.internal.kernel.api.SchemaRead schemaRead = schemaWithIndexes(index);
            SchemaRead schemaRead = SchemaWithIndexes(index);

            SetUpdates(schemaRead, 1, 1, 1);

            // Then
            Exception.expect(typeof(TimeoutException));
            Indexes.AwaitResampling(schemaRead, 1);
        }
Exemple #17
0
        public override IEnumerable <IndexDefinition> GetIndexes()
        {
            KernelTransaction transaction = _transactionSupplier.get();
            SchemaRead        schemaRead  = transaction.SchemaRead();

            using (Statement ignore = transaction.AcquireStatement())
            {
                IList <IndexDefinition> definitions = new List <IndexDefinition>();

                IEnumerator <IndexReference> indexes = schemaRead.IndexesGetAll();
                AddDefinitions(definitions, transaction.TokenRead(), IndexReference.sortByType(indexes));
                return(definitions);
            }
        }
Exemple #18
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static org.neo4j.kernel.api.KernelTransaction mockKernelTransaction() throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException
        private static KernelTransaction MockKernelTransaction()
        {
            SchemaRead schemaRead = mock(typeof(SchemaRead));

            when(schemaRead.IndexGetState(any(typeof(IndexReference)))).thenReturn(InternalIndexState.FAILED);
            when(schemaRead.IndexGetFailure(any(typeof(IndexReference)))).thenReturn(Exceptions.stringify(_cause));

            KernelTransaction kt = mock(typeof(KernelTransaction));

            when(kt.TokenRead()).thenReturn(mock(typeof(TokenRead)));
            when(kt.SchemaRead()).thenReturn(schemaRead);
            when(kt.Terminated).thenReturn(false);
            when(kt.AcquireStatement()).thenReturn(mock(typeof(Statement)));
            return(kt);
        }
        private SchemaRead SchemaRead()
        {
            SchemaRead schemaRead = mock(typeof(SchemaRead));

            when(schemaRead.Index(_descriptor)).thenReturn(IndexReference.NO_INDEX);
            try
            {
                when(schemaRead.IndexGetCommittedId(_indexReference)).thenReturn(INDEX_ID);
            }
            catch (SchemaKernelException e)
            {
                throw new AssertionError(e);
            }
            return(schemaRead);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldProvideResultInOrderIfCapable() throws org.neo4j.internal.kernel.api.exceptions.KernelException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldProvideResultInOrderIfCapable()
        {
            int label = Token.nodeLabel("Node");
            int prop  = Token.propertyKey("prop");

            RandomValues   randomValues = RandomRule.randomValues();
            IndexReference index        = SchemaRead.index(label, prop);

            for (int i = 0; i < _nIterations; i++)
            {
                ValueType    type  = randomValues.Among(_targetedTypes);
                IndexOrder[] order = index.OrderCapability(type.valueGroup.category());
                foreach (IndexOrder indexOrder in order)
                {
                    if (indexOrder == IndexOrder.NONE)
                    {
                        continue;
                    }
                    NodeValueTuple from = new NodeValueTuple(this, long.MinValue, randomValues.NextValueOfType(type));
                    NodeValueTuple to   = new NodeValueTuple(this, long.MaxValue, randomValues.NextValueOfType(type));
                    if (COMPARATOR.compare(from, to) > 0)
                    {
                        NodeValueTuple tmp = from;
                        from = to;
                        to   = tmp;
                    }
                    bool fromInclusive = randomValues.NextBoolean();
                    bool toInclusive   = randomValues.NextBoolean();
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: org.neo4j.internal.kernel.api.IndexQuery.RangePredicate<?> range = org.neo4j.internal.kernel.api.IndexQuery.range(prop, from.getOnlyValue(), fromInclusive, to.getOnlyValue(), toInclusive);
                    IndexQuery.RangePredicate <object> range = IndexQuery.range(prop, from.OnlyValue, fromInclusive, to.OnlyValue, toInclusive);

                    using (NodeValueIndexCursor node = Cursors.allocateNodeValueIndexCursor())
                    {
                        Read.nodeIndexSeek(index, node, indexOrder, false, range);

                        IList <long> expectedIdsInOrder = expectedIdsInOrder(from, fromInclusive, to, toInclusive, indexOrder);
                        IList <long> actualIdsInOrder   = new List <long>();
                        while (node.Next())
                        {
                            actualIdsInOrder.Add(node.NodeReference());
                        }

                        assertEquals(expectedIdsInOrder, actualIdsInOrder, "actual node ids not in same order as expected");
                    }
                }
            }
        }
Exemple #21
0
        public virtual IEnumerable <ConstraintDefinition> getConstraints(RelationshipType type)
        {
            KernelTransaction transaction = SafeAcquireTransaction(_transactionSupplier);

            using (Statement ignore = transaction.AcquireStatement())
            {
                TokenRead  tokenRead  = transaction.TokenRead();
                SchemaRead schemaRead = transaction.SchemaRead();
                int        typeId     = tokenRead.RelationshipType(type.Name());
                if (typeId == [email protected]_Fields.NO_TOKEN)
                {
                    return(emptyList());
                }
                return(AsConstraintDefinitions(schemaRead.ConstraintsGetForRelationshipType(typeId), tokenRead));
            }
        }
Exemple #22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldListAll() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldListAll()
        {
            // given
            SchemaWrite    schemaWrite = SchemaWriteInNewTransaction();
            IndexReference index1      = schemaWrite.IndexCreate(_descriptor);
            IndexReference index2      = (( IndexBackedConstraintDescriptor )schemaWrite.UniquePropertyConstraintCreate(_descriptor2)).ownedIndexDescriptor();

            Commit();

            // then/when
            SchemaRead             schemaRead = NewTransaction().schemaRead();
            IList <IndexReference> indexes    = Iterators.asList(schemaRead.IndexesGetAll());

            assertThat(indexes, containsInAnyOrder(index1, index2));
            Commit();
        }
Exemple #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void addIndexRuleInATransaction() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void AddIndexRuleInATransaction()
        {
            // GIVEN
            SchemaWrite schemaWriteOperations = SchemaWriteInNewTransaction();

            // WHEN
            IndexReference expectedRule = schemaWriteOperations.IndexCreate(_descriptor);

            Commit();

            // THEN
            SchemaRead schemaRead = NewTransaction().schemaRead();

            assertEquals(asSet(expectedRule), asSet(schemaRead.IndexesGetForLabel(_labelId)));
            assertEquals(expectedRule, schemaRead.Index(_descriptor.LabelId, _descriptor.PropertyIds));
            Commit();
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setupGraph() throws java.io.IOException, org.neo4j.internal.kernel.api.exceptions.KernelException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SetupGraph()
        {
            if (TestSupport == null)
            {
                Folder.create();
                TestSupport = NewTestSupport();
                TestSupport.setup(Folder.Root, this.createTestGraph);
            }
            Kernel kernel = TestSupport.kernelToTest();

            Tx         = kernel.BeginTransaction(Transaction_Type.Implicit, LoginContext.AUTH_DISABLED);
            Token      = Tx.token();
            Read       = Tx.dataRead();
            IndexRead  = Tx.indexRead();
            SchemaRead = Tx.schemaRead();
            Cursors    = new ManagedTestCursors(Tx.cursors());
        }
Exemple #25
0
        public override string GetIndexFailure(IndexDefinition index)
        {
            KernelTransaction transaction = SafeAcquireTransaction(_transactionSupplier);

            try
            {
                using (Statement ignore = transaction.AcquireStatement())
                {
                    SchemaRead     schemaRead = transaction.SchemaRead();
                    IndexReference descriptor = GetIndexReference(schemaRead, transaction.TokenRead(), (IndexDefinitionImpl)index);
                    return(schemaRead.IndexGetFailure(descriptor));
                }
            }
            catch (Exception e) when(e is SchemaRuleNotFoundException || e is IndexNotFoundKernelException)
            {
                throw NewIndexNotFoundException(index, e);
            }
        }
Exemple #26
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: public Iterable<org.neo4j.graphdb.schema.IndexDefinition> getIndexes(final org.neo4j.graphdb.Label label)
        public override IEnumerable <IndexDefinition> GetIndexes(Label label)
        {
            KernelTransaction transaction = _transactionSupplier.get();

            using (Statement ignore = transaction.AcquireStatement())
            {
                TokenRead  tokenRead  = transaction.TokenRead();
                SchemaRead schemaRead = transaction.SchemaRead();
                IList <IndexDefinition> definitions = new List <IndexDefinition>();
                int labelId = tokenRead.NodeLabel(label.Name());
                if (labelId == [email protected]_Fields.NO_TOKEN)
                {
                    return(emptyList());
                }
                IEnumerator <IndexReference> indexes = schemaRead.IndexesGetForLabel(labelId);
                AddDefinitions(definitions, tokenRead, IndexReference.sortByType(indexes));
                return(definitions);
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldGetAllSinglePropertyValues() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldGetAllSinglePropertyValues()
        {
            int            label = Token.nodeLabel("Node");
            int            prop  = Token.propertyKey("prop");
            IndexReference index = SchemaRead.index(label, prop);

            using (NodeValueIndexCursor node = Cursors.allocateNodeValueIndexCursor())
            {
                Read.nodeIndexScan(index, node, IndexOrder.NONE, true);

                IList <Value> values = new List <Value>();
                while (node.Next())
                {
                    values.Add(node.PropertyValue(0));
                }

                values.sort(Values.COMPARATOR);
                for (int i = 0; i < _singlePropValues.Count; i++)
                {
                    assertEquals(_singlePropValues[i], values[i]);
                }
            }
        }
Exemple #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static void checkIndexCounts(Store store, org.neo4j.kernel.internal.GraphDatabaseAPI db) throws org.neo4j.internal.kernel.api.exceptions.KernelException
        private static void CheckIndexCounts(Store store, GraphDatabaseAPI db)
        {
            InwardKernel kernel = Db.DependencyResolver.resolveDependency(typeof(InwardKernel));

            using (KernelTransaction tx = kernel.BeginTransaction(@implicit, AnonymousContext.read()), Statement ignore = tx.AcquireStatement())
            {
                SchemaRead schemaRead = tx.SchemaRead();
                IEnumerator <IndexReference> indexes  = IndexReference.sortByType(GetAllIndexes(schemaRead));
                Register_DoubleLongRegister  register = Registers.newDoubleLongRegister();
                for (int i = 0; indexes.MoveNext(); i++)
                {
                    IndexReference reference = indexes.Current;

                    // wait index to be online since sometimes we need to rebuild the indexes on migration
                    AwaitOnline(schemaRead, reference);

                    AssertDoubleLongEquals(store.IndexCounts[i][0], store.IndexCounts[i][1], schemaRead.IndexUpdatesAndSize(reference, register));
                    AssertDoubleLongEquals(store.IndexCounts[i][2], store.IndexCounts[i][3], schemaRead.IndexSample(reference, register));
                    double selectivity = schemaRead.IndexUniqueValuesSelectivity(reference);
                    assertEquals(store.IndexSelectivity[i], selectivity, 0.0000001d);
                }
            }
        }
Exemple #29
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));
                }
            }
        }
Exemple #30
0
 private static IEnumerator <IndexReference> GetAllIndexes(SchemaRead schemaRead)
 {
     return(schemaRead.IndexesGetAll());
 }