Esempio n. 1
0
        private TopLevelTransaction ActiveTransaction()
        {
            ThreadToStatementContextBridge bridge = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));
            KernelTransaction kernelTransaction   = bridge.GetKernelTransactionBoundToThisThread(false);

            return(kernelTransaction == null ? null : new TopLevelTransaction(kernelTransaction));
        }
Esempio n. 2
0
        private static void CheckLabelCounts(GraphDatabaseAPI db)
        {
            using (Transaction ignored = Db.beginTx())
            {
                Dictionary <Label, long> counts = new Dictionary <Label, long>();
                foreach (Node node in Db.AllNodes)
                {
                    foreach (Label label in node.Labels)
                    {
                        long?count = counts[label];
                        if (count != null)
                        {
                            counts[label] = count + 1;
                        }
                        else
                        {
                            counts[label] = 1L;
                        }
                    }
                }

                ThreadToStatementContextBridge bridge = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));
                KernelTransaction kernelTransaction   = bridge.GetKernelTransactionBoundToThisThread(true);

                foreach (KeyValuePair <Label, long> entry in Counts.SetOfKeyValuePairs())
                {
                    assertEquals(entry.Value.longValue(), kernelTransaction.DataRead().countsForNode(kernelTransaction.TokenRead().nodeLabel(entry.Key.name())));
                }
            }
        }
Esempio n. 3
0
//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();
            }
        }
        private int GetPropertyIdByName(string name)
        {
            ThreadToStatementContextBridge transactionStatementContextBridge = TransactionStatementContextBridge;
            KernelTransaction ktx = transactionStatementContextBridge.GetKernelTransactionBoundToThisThread(true);

            using (Statement ignore = ktx.AcquireStatement())
            {
                return(ktx.TokenRead().propertyKey(name));
            }
        }
Esempio n. 5
0
        private static void CheckGlobalNodeCount(Store store, GraphDatabaseAPI db)
        {
            using (Transaction ignored = Db.beginTx())
            {
                ThreadToStatementContextBridge bridge = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));
                KernelTransaction kernelTransaction   = bridge.GetKernelTransactionBoundToThisThread(true);

                assertThat(kernelTransaction.DataRead().countsForNode(-1), @is(store.ExpectedNodeCount));
            }
        }
Esempio n. 6
0
 internal override void LockAcquired(bool exclusive, ResourceType resourceType, params long[] ids)
 {
     if (!Executed)
     {
         ThreadToStatementContextBridge bridge = outerInstance.DatabaseRule.resolveDependency(typeof(ThreadToStatementContextBridge));
         KernelTransaction ktx = bridge.GetKernelTransactionBoundToThisThread(true);
         ktx.SchemaRead().schemaStateFlush();
     }
     Executed = true;
 }
Esempio n. 7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAllowManyLabelsAndPropertyCursor()
        public virtual void ShouldAllowManyLabelsAndPropertyCursor()
        {
            int propertyCount = 10;
            int labelCount    = 15;

            GraphDatabaseAPI db = DbRule.GraphDatabaseAPI;
            Node             node;

            using (Transaction tx = Db.beginTx())
            {
                node = Db.createNode();
                for (int i = 0; i < propertyCount; i++)
                {
                    node.SetProperty("foo" + i, "bar");
                }
                for (int i = 0; i < labelCount; i++)
                {
                    node.AddLabel(label("label" + i));
                }
                tx.Success();
            }

            ISet <int> seenProperties = new HashSet <int>();
            ISet <int> seenLabels     = new HashSet <int>();

            using (Transaction tx = Db.beginTx())
            {
                DependencyResolver             resolver = Db.DependencyResolver;
                ThreadToStatementContextBridge bridge   = resolver.ResolveDependency(typeof(ThreadToStatementContextBridge));
                KernelTransaction ktx = bridge.GetKernelTransactionBoundToThisThread(true);
                using (NodeCursor nodes = ktx.Cursors().allocateNodeCursor(), PropertyCursor propertyCursor = ktx.Cursors().allocatePropertyCursor())
                {
                    ktx.DataRead().singleNode(node.Id, nodes);
                    while (nodes.Next())
                    {
                        nodes.Properties(propertyCursor);
                        while (propertyCursor.Next())
                        {
                            seenProperties.Add(propertyCursor.PropertyKey());
                        }

                        LabelSet labels = nodes.Labels();
                        for (int i = 0; i < labels.NumberOfLabels(); i++)
                        {
                            seenLabels.Add(labels.Label(i));
                        }
                    }
                }
                tx.Success();
            }

            assertEquals(propertyCount, seenProperties.Count);
            assertEquals(labelCount, seenLabels.Count);
        }
Esempio n. 8
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static void addIndex(org.neo4j.graphdb.GraphDatabaseService database) throws org.neo4j.internal.kernel.api.exceptions.schema.SchemaKernelException
        private static void AddIndex(GraphDatabaseService database)
        {
            using (Transaction transaction = database.BeginTx())
            {
                DependencyResolver             resolver        = (( GraphDatabaseAPI )database).DependencyResolver;
                ThreadToStatementContextBridge statementBridge = resolver.ProvideDependency(typeof(ThreadToStatementContextBridge)).get();
                KernelTransaction     kernelTransaction        = statementBridge.GetKernelTransactionBoundToThisThread(true);
                LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel(0, 0);
                Config config = resolver.ResolveDependency(typeof(Config));
                kernelTransaction.IndexUniqueCreate(descriptor, config.Get(GraphDatabaseSettings.default_schema_provider));
                transaction.Success();
            }
        }
Esempio n. 9
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void getOrCreateIds() throws org.neo4j.internal.kernel.api.exceptions.KernelException
        private void getOrCreateIds()
        {
            using (Transaction tx = _graphDb.beginTx())
            {
                ThreadToStatementContextBridge bridge = _graphDb.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));

                TokenWrite tokenWrite = bridge.GetKernelTransactionBoundToThisThread(true).tokenWrite();
                _labelId          = tokenWrite.LabelGetOrCreateForName("Person");
                _relTypeId        = tokenWrite.RelationshipTypeGetOrCreateForName("Knows");
                _propertyKeyId    = tokenWrite.PropertyKeyGetOrCreateForName("name");
                _relPropertyKeyId = tokenWrite.PropertyKeyGetOrCreateForName("duration");
                tx.Success();
            }
        }
Esempio n. 10
0
        public Neo4jTransactionalContext(GraphDatabaseQueryService graph, ThreadToStatementContextBridge txBridge, PropertyContainerLocker locker, InternalTransaction initialTransaction, Statement initialStatement, ExecutingQuery executingQuery, Kernel kernel)
        {
            this._graph                  = graph;
            this._txBridge               = txBridge;
            this._locker                 = locker;
            this.TransactionType         = initialTransaction.TransactionType();
            this.SecurityContextConflict = initialTransaction.SecurityContext();
            this._executingQuery         = executingQuery;

            this._transaction       = initialTransaction;
            this._kernelTransaction = txBridge.GetKernelTransactionBoundToThisThread(true);
            this._statement         = initialStatement;
            this._kernel            = kernel;
        }
Esempio n. 11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void checkKernelStatementOnCheck()
        public virtual void CheckKernelStatementOnCheck()
        {
            InternalTransaction initialTransaction = mock(typeof(InternalTransaction), new ReturnsDeepStubs());
            Kernel kernel = mock(typeof(Kernel));
            ThreadToStatementContextBridge txBridge = mock(typeof(ThreadToStatementContextBridge));
            KernelTransaction kernelTransaction     = MockTransaction(_initialStatement);

            when(txBridge.GetKernelTransactionBoundToThisThread(true)).thenReturn(kernelTransaction);

            Neo4jTransactionalContext transactionalContext = new Neo4jTransactionalContext(null, txBridge, null, initialTransaction, _initialStatement, null, kernel);

            transactionalContext.Check();

            verify(kernelTransaction).assertOpen();
        }
        private IDictionary <string, int> GetLabelIdsByName(params string[] names)
        {
            ThreadToStatementContextBridge transactionStatementContextBridge = TransactionStatementContextBridge;
            IDictionary <string, int>      labelNameIdMap = new Dictionary <string, int>();
            KernelTransaction ktx = transactionStatementContextBridge.GetKernelTransactionBoundToThisThread(true);

            using (Statement ignore = ktx.AcquireStatement())
            {
                TokenRead tokenRead = ktx.TokenRead();
                foreach (string name in names)
                {
                    labelNameIdMap[name] = tokenRead.NodeLabel(name);
                }
            }
            return(labelNameIdMap);
        }
Esempio n. 13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotAllowCreationOfConstraintsWhenInHA() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotAllowCreationOfConstraintsWhenInHA()
        {
            //noinspection deprecation
            GraphDatabaseAPI db = new FakeHaDatabase(this);
            ThreadToStatementContextBridge stmtBridge = Db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));

            using (Transaction ignored = Db.beginTx())
            {
                KernelTransaction ktx = stmtBridge.GetKernelTransactionBoundToThisThread(true);
                try
                {
                    ktx.SchemaWrite().uniquePropertyConstraintCreate(forLabel(1, 1));
                    fail("expected exception here");
                }
                catch (InvalidTransactionTypeKernelException e)
                {
                    assertThat(e.Message, containsString("HA"));
                }
            }

            Db.shutdown();
        }
Esempio n. 14
0
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: private java.util.Set<org.neo4j.kernel.api.index.IndexEntryUpdate<?>> createSomeBananas(org.neo4j.graphdb.Label label)
        private ISet <IndexEntryUpdate <object> > CreateSomeBananas(Label label)
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Set<org.neo4j.kernel.api.index.IndexEntryUpdate<?>> updates = new java.util.HashSet<>();
            ISet <IndexEntryUpdate <object> > updates = new HashSet <IndexEntryUpdate <object> >();

            using (Transaction tx = _db.beginTx())
            {
                ThreadToStatementContextBridge ctxSupplier = _db.DependencyResolver.resolveDependency(typeof(ThreadToStatementContextBridge));
                KernelTransaction ktx = ctxSupplier.GetKernelTransactionBoundToThisThread(true);

                int labelId       = ktx.TokenRead().nodeLabel(label.Name());
                int propertyKeyId = ktx.TokenRead().propertyKey(_key);
                LabelSchemaDescriptor schemaDescriptor = SchemaDescriptorFactory.forLabel(labelId, propertyKeyId);
                foreach (int number in new int[] { 4, 10 })
                {
                    Node node = _db.createNode(label);
                    node.SetProperty(_key, number);
                    updates.Add(IndexEntryUpdate.add(node.Id, schemaDescriptor, Values.of(number)));
                }
                tx.Success();
                return(updates);
            }
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void launchCustomIndexPopulation(java.util.Map<String,int> labelNameIdMap, int propertyId, Runnable customAction) throws Exception
        private void LaunchCustomIndexPopulation(IDictionary <string, int> labelNameIdMap, int propertyId, ThreadStart customAction)
        {
            NeoStores      neoStores      = NeoStores;
            LabelScanStore labelScanStore = LabelScanStore;
            ThreadToStatementContextBridge transactionStatementContextBridge = TransactionStatementContextBridge;

            using (Transaction transaction = EmbeddedDatabase.beginTx(), KernelTransaction ktx = transactionStatementContextBridge.GetKernelTransactionBoundToThisThread(true))
            {
                DynamicIndexStoreView storeView = DynamicIndexStoreViewWrapper(customAction, neoStores, labelScanStore);

                IndexProviderMap providerMap     = IndexProviderMap;
                JobScheduler     scheduler       = JobScheduler;
                TokenNameLookup  tokenNameLookup = new SilentTokenNameLookup(ktx.TokenRead());

                NullLogProvider nullLogProvider = NullLogProvider.Instance;
                _indexService = IndexingServiceFactory.createIndexingService(Config.defaults(), scheduler, providerMap, storeView, tokenNameLookup, GetIndexRules(neoStores), nullLogProvider, nullLogProvider, IndexingService.NO_MONITOR, SchemaState, false);
                _indexService.start();

                _rules = CreateIndexRules(labelNameIdMap, propertyId);

                _indexService.createIndexes(_rules);
                transaction.Success();
            }
        }
Esempio n. 16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("ConstantConditions") @Test public void neverStopsExecutingQueryDuringCommitAndRestartTx()
        public virtual void NeverStopsExecutingQueryDuringCommitAndRestartTx()
        {
            // Given
            KernelTransaction   initialKTX         = MockTransaction(_initialStatement);
            InternalTransaction initialTransaction = mock(typeof(InternalTransaction), new ReturnsDeepStubs());

            KernelTransaction.Type transactionType = KernelTransaction.Type.@implicit;
            SecurityContext        securityContext = SecurityContext.AUTH_DISABLED;

            when(initialTransaction.TransactionType()).thenReturn(transactionType);
            when(initialTransaction.SecurityContext()).thenReturn(securityContext);
            when(initialTransaction.TerminationReason()).thenReturn(null);
            QueryRegistryOperations        initialQueryRegistry = mock(typeof(QueryRegistryOperations));
            ExecutingQuery                 executingQuery       = mock(typeof(ExecutingQuery));
            PropertyContainerLocker        locker   = null;
            ThreadToStatementContextBridge txBridge = mock(typeof(ThreadToStatementContextBridge));

            Statement           secondStatement   = mock(typeof(Statement));
            KernelTransaction   secondKTX         = MockTransaction(secondStatement);
            InternalTransaction secondTransaction = mock(typeof(InternalTransaction));

            when(secondTransaction.TerminationReason()).thenReturn(null);
            QueryRegistryOperations secondQueryRegistry = mock(typeof(QueryRegistryOperations));

            when(executingQuery.QueryText()).thenReturn("X");
            when(executingQuery.QueryParameters()).thenReturn(EMPTY_MAP);
            when(_initialStatement.queryRegistration()).thenReturn(initialQueryRegistry);
            when(_queryService.beginTransaction(transactionType, securityContext)).thenReturn(secondTransaction);
            when(txBridge.GetKernelTransactionBoundToThisThread(true)).thenReturn(initialKTX, initialKTX, secondKTX);
            when(secondStatement.QueryRegistration()).thenReturn(secondQueryRegistry);

            Kernel kernel = mock(typeof(Kernel));
            Neo4jTransactionalContext context = new Neo4jTransactionalContext(_queryService, txBridge, locker, initialTransaction, _initialStatement, executingQuery, kernel);

            // When
            context.CommitAndRestartTx();

            // Then
            object[] mocks = new object[] { txBridge, initialTransaction, initialKTX, initialQueryRegistry, secondQueryRegistry, secondKTX };
            InOrder  order = Mockito.inOrder(mocks);

            // (0) Constructor
            order.verify(initialTransaction).transactionType();
            order.verify(initialTransaction).securityContext();
            order.verify(txBridge).getKernelTransactionBoundToThisThread(true);
            order.verify(initialTransaction).terminationReason();                 // not terminated check

            // (1) Collect stats
            order.verify(initialKTX).executionStatistics();

            // (2) Unbind old
            order.verify(txBridge).getKernelTransactionBoundToThisThread(true);
            order.verify(txBridge).unbindTransactionFromCurrentThread();

            // (3) Register and unbind new
            order.verify(txBridge).getKernelTransactionBoundToThisThread(true);
            order.verify(secondKTX).acquireStatement();
            order.verify(secondQueryRegistry).registerExecutingQuery(executingQuery);
            order.verify(txBridge).unbindTransactionFromCurrentThread();

            // (4) Rebind, unregister, and close old
            order.verify(txBridge).bindTransactionToCurrentThread(initialKTX);
            order.verify(initialQueryRegistry).unregisterExecutingQuery(executingQuery);
            order.verify(initialTransaction).success();
            order.verify(initialTransaction).close();
            order.verify(txBridge).unbindTransactionFromCurrentThread();

            // (5) Rebind new
            order.verify(txBridge).bindTransactionToCurrentThread(secondKTX);
            verifyNoMoreInteractions(mocks);
        }
Esempio n. 17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("ConstantConditions") @Test public void rollsBackNewlyCreatedTransactionIfTerminationDetectedOnCloseDuringPeriodicCommit()
        public virtual void RollsBackNewlyCreatedTransactionIfTerminationDetectedOnCloseDuringPeriodicCommit()
        {
            // Given
            InternalTransaction initialTransaction = mock(typeof(InternalTransaction), new ReturnsDeepStubs());

            KernelTransaction.Type transactionType = KernelTransaction.Type.@implicit;
            SecurityContext        securityContext = SecurityContext.AUTH_DISABLED;

            when(initialTransaction.TransactionType()).thenReturn(transactionType);
            when(initialTransaction.SecurityContext()).thenReturn(securityContext);
            when(initialTransaction.TerminationReason()).thenReturn(null);

            GraphDatabaseQueryService queryService              = mock(typeof(GraphDatabaseQueryService));
            Statement                      initialStatement     = mock(typeof(Statement));
            KernelTransaction              initialKTX           = MockTransaction(initialStatement);
            QueryRegistryOperations        initialQueryRegistry = mock(typeof(QueryRegistryOperations));
            ExecutingQuery                 executingQuery       = mock(typeof(ExecutingQuery));
            PropertyContainerLocker        locker   = new PropertyContainerLocker();
            ThreadToStatementContextBridge txBridge = mock(typeof(ThreadToStatementContextBridge));

            Statement           secondStatement   = mock(typeof(Statement));
            KernelTransaction   secondKTX         = MockTransaction(secondStatement);
            InternalTransaction secondTransaction = mock(typeof(InternalTransaction));

            when(secondTransaction.TerminationReason()).thenReturn(null);
            QueryRegistryOperations secondQueryRegistry = mock(typeof(QueryRegistryOperations));

            when(executingQuery.QueryText()).thenReturn("X");
            when(executingQuery.QueryParameters()).thenReturn(EMPTY_MAP);
            Mockito.doThrow(typeof(Exception)).when(initialTransaction).close();
            when(initialStatement.QueryRegistration()).thenReturn(initialQueryRegistry);
            when(queryService.BeginTransaction(transactionType, securityContext)).thenReturn(secondTransaction);
            when(txBridge.GetKernelTransactionBoundToThisThread(true)).thenReturn(initialKTX, initialKTX, secondKTX);
            when(txBridge.Get()).thenReturn(secondStatement);
            when(secondStatement.QueryRegistration()).thenReturn(secondQueryRegistry);

            Kernel kernel = mock(typeof(Kernel));
            Neo4jTransactionalContext context = new Neo4jTransactionalContext(queryService, txBridge, locker, initialTransaction, initialStatement, executingQuery, kernel);

            // When
            try
            {
                context.CommitAndRestartTx();
                throw new AssertionError("Expected RuntimeException to be thrown");
            }
            catch (Exception)
            {
                // Then
                object[] mocks = new object[] { txBridge, initialTransaction, initialQueryRegistry, initialKTX, secondQueryRegistry, secondKTX, secondTransaction };
                InOrder  order = Mockito.inOrder(mocks);

                // (0) Constructor
                order.verify(initialTransaction).transactionType();
                order.verify(initialTransaction).securityContext();
                order.verify(txBridge).getKernelTransactionBoundToThisThread(true);
                order.verify(initialTransaction).terminationReason();                           // not terminated check

                // (1) Collect statistics
                order.verify(initialKTX).executionStatistics();

                // (2) Unbind old
                order.verify(txBridge).getKernelTransactionBoundToThisThread(true);
                order.verify(txBridge).unbindTransactionFromCurrentThread();

                // (3) Register and unbind new
                order.verify(txBridge).getKernelTransactionBoundToThisThread(true);
                order.verify(secondKTX).acquireStatement();
                order.verify(secondQueryRegistry).registerExecutingQuery(executingQuery);
                order.verify(txBridge).unbindTransactionFromCurrentThread();

                // (4) Rebind, unregister, and close old
                order.verify(txBridge).bindTransactionToCurrentThread(initialKTX);
                order.verify(initialQueryRegistry).unregisterExecutingQuery(executingQuery);
                order.verify(initialTransaction).success();
                order.verify(initialTransaction).close();
                order.verify(txBridge).bindTransactionToCurrentThread(secondKTX);
                order.verify(secondTransaction).failure();
                order.verify(secondTransaction).close();
                order.verify(txBridge).unbindTransactionFromCurrentThread();

                verifyNoMoreInteractions(mocks);
            }
        }