Search in sources :

Example 41 with InternalTransaction

use of org.neo4j.kernel.impl.coreapi.InternalTransaction in project neo4j by neo4j.

the class Neo4jTransactionalContextTest method rollsBackNewlyCreatedTransactionIfTerminationDetectedOnCloseDuringPeriodicCommit.

@SuppressWarnings("ConstantConditions")
@Test
void rollsBackNewlyCreatedTransactionIfTerminationDetectedOnCloseDuringPeriodicCommit() throws TransactionFailureException {
    // Given
    InternalTransaction userTransaction = mock(InternalTransaction.class, new ReturnsDeepStubs());
    KernelTransaction.Type transactionType = KernelTransaction.Type.IMPLICIT;
    SecurityContext securityContext = SecurityContext.AUTH_DISABLED;
    ClientConnectionInfo connectionInfo = ClientConnectionInfo.EMBEDDED_CONNECTION;
    when(userTransaction.transactionType()).thenReturn(transactionType);
    when(userTransaction.clientInfo()).thenReturn(connectionInfo);
    when(userTransaction.securityContext()).thenReturn(securityContext);
    when(userTransaction.terminationReason()).thenReturn(Optional.empty());
    GraphDatabaseQueryService queryService = mock(GraphDatabaseQueryService.class);
    KernelStatement initialStatement = mock(KernelStatement.class);
    KernelTransaction initialKTX = mockTransaction(initialStatement);
    QueryRegistry initialQueryRegistry = mock(QueryRegistry.class);
    ExecutingQuery executingQuery = mock(ExecutingQuery.class);
    KernelStatement secondStatement = mock(KernelStatement.class);
    KernelTransaction secondKTX = mockTransaction(secondStatement);
    QueryRegistry secondQueryRegistry = mock(QueryRegistry.class);
    when(transactionFactory.beginKernelTransaction(transactionType, securityContext, connectionInfo)).thenReturn(secondKTX);
    when(executingQuery.databaseId()).thenReturn(Optional.of(namedDatabaseId));
    Mockito.doThrow(RuntimeException.class).when(initialKTX).commit();
    when(initialStatement.queryRegistration()).thenReturn(initialQueryRegistry);
    when(userTransaction.kernelTransaction()).thenReturn(initialKTX, initialKTX, secondKTX);
    when(secondStatement.queryRegistration()).thenReturn(secondQueryRegistry);
    Neo4jTransactionalContext context = new Neo4jTransactionalContext(queryService, userTransaction, initialStatement, executingQuery, transactionFactory);
    // When
    assertThrows(RuntimeException.class, context::commitAndRestartTx);
    Object[] mocks = { userTransaction, initialQueryRegistry, initialKTX, secondQueryRegistry, secondKTX };
    InOrder order = Mockito.inOrder(mocks);
    // (0) Constructor
    order.verify(userTransaction).transactionType();
    order.verify(userTransaction).securityContext();
    order.verify(userTransaction).clientInfo();
    // not terminated check
    order.verify(userTransaction).terminationReason();
    // (1) Collect statistics
    order.verify(initialKTX).executionStatistics();
    // (3) Register new
    order.verify(secondKTX).acquireStatement();
    order.verify(secondQueryRegistry).registerExecutingQuery(executingQuery);
    // (4) Unregister, and close old
    order.verify(initialQueryRegistry).unregisterExecutingQuery(executingQuery);
    order.verify(userTransaction).rollback();
}
Also used : KernelTransaction(org.neo4j.kernel.api.KernelTransaction) InOrder(org.mockito.InOrder) KernelStatement(org.neo4j.kernel.impl.api.KernelStatement) GraphDatabaseQueryService(org.neo4j.kernel.GraphDatabaseQueryService) QueryRegistry(org.neo4j.kernel.api.QueryRegistry) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) ClientConnectionInfo(org.neo4j.internal.kernel.api.connectioninfo.ClientConnectionInfo) ExecutingQuery(org.neo4j.kernel.api.query.ExecutingQuery) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) MutableObject(org.apache.commons.lang3.mutable.MutableObject) ReturnsDeepStubs(org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs) Test(org.junit.jupiter.api.Test)

Example 42 with InternalTransaction

use of org.neo4j.kernel.impl.coreapi.InternalTransaction in project neo4j by neo4j.

the class Neo4jTransactionalContextTest method neverStopsExecutingQueryDuringCommitAndRestartTx.

@Test
void neverStopsExecutingQueryDuringCommitAndRestartTx() throws TransactionFailureException {
    // Given
    KernelTransaction initialKTX = mockTransaction(statement);
    InternalTransaction userTransaction = mock(InternalTransaction.class, new ReturnsDeepStubs());
    KernelTransaction.Type transactionType = KernelTransaction.Type.IMPLICIT;
    SecurityContext securityContext = SecurityContext.AUTH_DISABLED;
    ClientConnectionInfo connectionInfo = ClientConnectionInfo.EMBEDDED_CONNECTION;
    when(userTransaction.transactionType()).thenReturn(transactionType);
    when(userTransaction.securityContext()).thenReturn(securityContext);
    when(userTransaction.terminationReason()).thenReturn(Optional.empty());
    when(userTransaction.clientInfo()).thenReturn(connectionInfo);
    QueryRegistry initialQueryRegistry = mock(QueryRegistry.class);
    ExecutingQuery executingQuery = mock(ExecutingQuery.class);
    KernelStatement secondStatement = mock(KernelStatement.class);
    KernelTransaction secondKTX = mockTransaction(secondStatement);
    QueryRegistry secondQueryRegistry = mock(QueryRegistry.class);
    when(transactionFactory.beginKernelTransaction(transactionType, securityContext, connectionInfo)).thenReturn(secondKTX);
    when(executingQuery.databaseId()).thenReturn(Optional.of(namedDatabaseId));
    when(statement.queryRegistration()).thenReturn(initialQueryRegistry);
    when(userTransaction.kernelTransaction()).thenReturn(initialKTX, initialKTX, secondKTX);
    when(secondStatement.queryRegistration()).thenReturn(secondQueryRegistry);
    Neo4jTransactionalContext context = new Neo4jTransactionalContext(queryService, userTransaction, statement, executingQuery, transactionFactory);
    // When
    context.commitAndRestartTx();
    // Then
    Object[] mocks = { userTransaction, initialKTX, initialQueryRegistry, secondQueryRegistry, secondKTX };
    InOrder order = Mockito.inOrder(mocks);
    // (0) Constructor
    order.verify(userTransaction).transactionType();
    order.verify(userTransaction).securityContext();
    order.verify(userTransaction).clientInfo();
    // not terminated check
    order.verify(userTransaction).terminationReason();
    // (1) Collect stats
    order.verify(initialKTX).executionStatistics();
    // (3) Register new
    order.verify(secondKTX).acquireStatement();
    order.verify(secondQueryRegistry).registerExecutingQuery(executingQuery);
    // (4) Unregister, and close old
    order.verify(initialQueryRegistry).unregisterExecutingQuery(executingQuery);
    order.verify(initialKTX).commit();
}
Also used : KernelTransaction(org.neo4j.kernel.api.KernelTransaction) InOrder(org.mockito.InOrder) KernelStatement(org.neo4j.kernel.impl.api.KernelStatement) QueryRegistry(org.neo4j.kernel.api.QueryRegistry) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) ClientConnectionInfo(org.neo4j.internal.kernel.api.connectioninfo.ClientConnectionInfo) ExecutingQuery(org.neo4j.kernel.api.query.ExecutingQuery) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) MutableObject(org.apache.commons.lang3.mutable.MutableObject) ReturnsDeepStubs(org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs) Test(org.junit.jupiter.api.Test)

Example 43 with InternalTransaction

use of org.neo4j.kernel.impl.coreapi.InternalTransaction in project neo4j by neo4j.

the class Neo4jTransactionalContextTest method shouldNotBePossibleToCloseMultipleTimes.

@Test
void shouldNotBePossibleToCloseMultipleTimes() {
    InternalTransaction tx = mock(InternalTransaction.class);
    Neo4jTransactionalContext context = newContext(tx);
    context.close();
    context.close();
    context.close();
}
Also used : InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) Test(org.junit.jupiter.api.Test)

Example 44 with InternalTransaction

use of org.neo4j.kernel.impl.coreapi.InternalTransaction in project neo4j by neo4j.

the class BuiltInDbmsProcedures method listQueries.

@SystemProcedure
@Description("List all queries currently executing at this instance that are visible to the user.")
@Procedure(name = "dbms.listQueries", mode = DBMS)
public Stream<QueryStatusResult> listQueries() throws InvalidArgumentsException {
    ZoneId zoneId = getConfiguredTimeZone();
    List<QueryStatusResult> result = new ArrayList<>();
    for (FabricTransaction tx : getFabricTransactions()) {
        for (ExecutingQuery query : getActiveFabricQueries(tx)) {
            String username = query.username();
            var action = new AdminActionOnResource(SHOW_TRANSACTION, ALL, new UserSegment(username));
            if (isSelfOrAllows(username, action)) {
                result.add(new QueryStatusResult(query, (InternalTransaction) transaction, zoneId, "none"));
            }
        }
    }
    for (DatabaseContext databaseContext : getDatabaseManager().registeredDatabases().values()) {
        if (databaseContext.database().isStarted()) {
            DatabaseScope dbScope = new DatabaseScope(databaseContext.database().getNamedDatabaseId().name());
            for (KernelTransactionHandle tx : getExecutingTransactions(databaseContext)) {
                if (tx.executingQuery().isPresent()) {
                    ExecutingQuery query = tx.executingQuery().get();
                    // Include both the executing query and any previous queries (parent queries of nested query) in the result.
                    while (query != null) {
                        String username = query.username();
                        var action = new AdminActionOnResource(SHOW_TRANSACTION, dbScope, new UserSegment(username));
                        if (isSelfOrAllows(username, action)) {
                            result.add(new QueryStatusResult(query, (InternalTransaction) transaction, zoneId, databaseContext.databaseFacade().databaseName()));
                        }
                        query = query.getPreviousQuery();
                    }
                }
            }
        }
    }
    return result.stream();
}
Also used : AdminActionOnResource(org.neo4j.internal.kernel.api.security.AdminActionOnResource) ZoneId(java.time.ZoneId) DatabaseScope(org.neo4j.internal.kernel.api.security.AdminActionOnResource.DatabaseScope) ArrayList(java.util.ArrayList) FabricTransaction(org.neo4j.fabric.transaction.FabricTransaction) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) KernelTransactionHandle(org.neo4j.kernel.api.KernelTransactionHandle) DatabaseContext(org.neo4j.dbms.database.DatabaseContext) ExecutingQuery(org.neo4j.kernel.api.query.ExecutingQuery) UserSegment(org.neo4j.internal.kernel.api.security.UserSegment) Description(org.neo4j.procedure.Description) SystemProcedure(org.neo4j.kernel.api.procedure.SystemProcedure) SystemProcedure(org.neo4j.kernel.api.procedure.SystemProcedure) Procedure(org.neo4j.procedure.Procedure)

Example 45 with InternalTransaction

use of org.neo4j.kernel.impl.coreapi.InternalTransaction in project neo4j by neo4j.

the class IndexStatisticsTest method assertIndexedNodesMatchesStoreNodes.

private void assertIndexedNodesMatchesStoreNodes(IndexDescriptor index) throws Exception {
    int nodesInStore = 0;
    Label label = Label.label(PERSON_LABEL);
    try (Transaction transaction = db.beginTx()) {
        KernelTransaction ktx = ((InternalTransaction) transaction).kernelTransaction();
        List<String> mismatches = new ArrayList<>();
        int propertyKeyId = ktx.tokenRead().propertyKey(NAME_PROPERTY);
        IndexReadSession indexSession = ktx.dataRead().indexReadSession(index);
        try (NodeValueIndexCursor cursor = ktx.cursors().allocateNodeValueIndexCursor(ktx.cursorContext(), ktx.memoryTracker())) {
            // Node --> Index
            for (Node node : filter(n -> n.hasLabel(label) && n.hasProperty(NAME_PROPERTY), transaction.getAllNodes())) {
                nodesInStore++;
                String name = (String) node.getProperty(NAME_PROPERTY);
                ktx.dataRead().nodeIndexSeek(indexSession, cursor, unconstrained(), PropertyIndexQuery.exact(propertyKeyId, name));
                boolean found = false;
                while (cursor.next()) {
                    long indexedNode = cursor.nodeReference();
                    if (indexedNode == node.getId()) {
                        if (found) {
                            mismatches.add("Index has multiple entries for " + name + " and " + indexedNode);
                        }
                        found = true;
                    }
                }
                if (!found) {
                    mismatches.add("Index is missing entry for " + name + " " + node);
                }
            }
            if (!mismatches.isEmpty()) {
                fail(String.join(format("%n"), mismatches));
            }
            // Node count == indexed node count
            ktx.dataRead().nodeIndexSeek(indexSession, cursor, unconstrained(), PropertyIndexQuery.exists(propertyKeyId));
            int nodesInIndex = 0;
            while (cursor.next()) {
                nodesInIndex++;
            }
            assertEquals(nodesInStore, nodesInIndex);
        }
    }
}
Also used : KernelTransaction(org.neo4j.kernel.api.KernelTransaction) NodeValueIndexCursor(org.neo4j.internal.kernel.api.NodeValueIndexCursor) Node(org.neo4j.graphdb.Node) Label(org.neo4j.graphdb.Label) SchemaDescriptor.forLabel(org.neo4j.internal.schema.SchemaDescriptor.forLabel) ArrayList(java.util.ArrayList) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) IndexReadSession(org.neo4j.internal.kernel.api.IndexReadSession) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) Transaction(org.neo4j.graphdb.Transaction) KernelTransaction(org.neo4j.kernel.api.KernelTransaction)

Aggregations

InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)126 Transaction (org.neo4j.graphdb.Transaction)58 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)53 Test (org.junit.jupiter.api.Test)46 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)20 MethodSource (org.junit.jupiter.params.provider.MethodSource)18 Node (org.neo4j.graphdb.Node)16 NodeValueIndexCursor (org.neo4j.internal.kernel.api.NodeValueIndexCursor)15 ArrayList (java.util.ArrayList)13 Test (org.junit.Test)12 Result (org.neo4j.graphdb.Result)12 TokenRead (org.neo4j.internal.kernel.api.TokenRead)11 IndexDescriptor (org.neo4j.internal.schema.IndexDescriptor)10 IndexReadSession (org.neo4j.internal.kernel.api.IndexReadSession)8 ExecutingQuery (org.neo4j.kernel.api.query.ExecutingQuery)7 Relationship (org.neo4j.graphdb.Relationship)6 GraphDatabaseQueryService (org.neo4j.kernel.GraphDatabaseQueryService)6 GraphDatabaseFacade (org.neo4j.kernel.impl.factory.GraphDatabaseFacade)6 GraphDatabaseAPI (org.neo4j.kernel.internal.GraphDatabaseAPI)6 ReturnsDeepStubs (org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs)5