Search in sources :

Example 6 with TransactionalContext

use of org.neo4j.kernel.impl.query.TransactionalContext in project neo4j by neo4j.

the class TransactionHandleTest method shouldLogMessageIfCommitErrorOccurs.

@Test
public void shouldLogMessageIfCommitErrorOccurs() throws Exception {
    // given
    TransitionalPeriodTransactionMessContainer kernel = mockKernel();
    TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(explicit, AUTH_DISABLED, -1);
    doThrow(new NullPointerException()).when(transactionContext).commit();
    LogProvider logProvider = mock(LogProvider.class);
    Log log = mock(Log.class);
    when(logProvider.getLog(TransactionHandle.class)).thenReturn(log);
    TransactionRegistry registry = mock(TransactionRegistry.class);
    QueryExecutionEngine engine = mock(QueryExecutionEngine.class);
    Result executionResult = mock(Result.class);
    TransactionalContext transactionalContext = prepareKernelWithQuerySession(kernel);
    when(engine.executeQuery("query", map(), transactionalContext)).thenReturn(executionResult);
    when(registry.begin(any(TransactionHandle.class))).thenReturn(1337L);
    GraphDatabaseQueryService queryService = mock(GraphDatabaseQueryService.class);
    TransactionHandle handle = new TransactionHandle(kernel, engine, queryService, registry, uriScheme, false, AUTH_DISABLED, anyLong(), logProvider);
    ExecutionResultSerializer output = mock(ExecutionResultSerializer.class);
    // when
    Statement statement = new Statement("query", map(), false, (ResultDataContent[]) null);
    handle.commit(statements(statement), output, mock(HttpServletRequest.class));
    // then
    verify(log).error(eq("Failed to commit transaction."), any(NullPointerException.class));
    verify(registry).forget(1337L);
    InOrder outputOrder = inOrder(output);
    outputOrder.verify(output).statementResult(executionResult, false, (ResultDataContent[]) null);
    outputOrder.verify(output).notifications(anyCollectionOf(Notification.class));
    outputOrder.verify(output).errors(argThat(hasErrors(Status.Transaction.TransactionCommitFailed)));
    outputOrder.verify(output).finish();
    verifyNoMoreInteractions(output);
}
Also used : InOrder(org.mockito.InOrder) Log(org.neo4j.logging.Log) GraphDatabaseQueryService(org.neo4j.kernel.GraphDatabaseQueryService) Notification(org.neo4j.graphdb.Notification) Result(org.neo4j.graphdb.Result) QueryExecutionEngine(org.neo4j.kernel.impl.query.QueryExecutionEngine) HttpServletRequest(javax.servlet.http.HttpServletRequest) LogProvider(org.neo4j.logging.LogProvider) NullLogProvider(org.neo4j.logging.NullLogProvider) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) Test(org.junit.Test)

Example 7 with TransactionalContext

use of org.neo4j.kernel.impl.query.TransactionalContext in project neo4j by neo4j.

the class TransactionHandleTest method shouldLogMessageIfCypherSyntaxErrorOccurs.

@Test
public void shouldLogMessageIfCypherSyntaxErrorOccurs() throws Exception {
    // given
    TransitionalPeriodTransactionMessContainer kernel = mockKernel();
    QueryExecutionEngine executionEngine = mock(QueryExecutionEngine.class);
    TransactionalContext transactionalContext = prepareKernelWithQuerySession(kernel);
    when(executionEngine.executeQuery("matsch (n) return n", map(), transactionalContext)).thenThrow(new QueryExecutionKernelException(new SyntaxException("did you mean MATCH?")));
    TransactionRegistry registry = mock(TransactionRegistry.class);
    when(registry.begin(any(TransactionHandle.class))).thenReturn(1337L);
    GraphDatabaseQueryService queryService = mock(GraphDatabaseQueryService.class);
    TransactionHandle handle = new TransactionHandle(kernel, executionEngine, queryService, registry, uriScheme, false, AUTH_DISABLED, anyLong(), NullLogProvider.getInstance());
    ExecutionResultSerializer output = mock(ExecutionResultSerializer.class);
    // when
    Statement statement = new Statement("matsch (n) return n", map(), false, (ResultDataContent[]) null);
    handle.commit(statements(statement), output, mock(HttpServletRequest.class));
    // then
    verify(registry).forget(1337L);
    InOrder outputOrder = inOrder(output);
    outputOrder.verify(output).errors(argThat(hasErrors(Status.Statement.SyntaxError)));
    outputOrder.verify(output).finish();
    verifyNoMoreInteractions(output);
}
Also used : QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) InOrder(org.mockito.InOrder) GraphDatabaseQueryService(org.neo4j.kernel.GraphDatabaseQueryService) QueryExecutionEngine(org.neo4j.kernel.impl.query.QueryExecutionEngine) HttpServletRequest(javax.servlet.http.HttpServletRequest) SyntaxException(org.neo4j.cypher.SyntaxException) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) Test(org.junit.Test)

Example 8 with TransactionalContext

use of org.neo4j.kernel.impl.query.TransactionalContext in project neo4j by neo4j.

the class CypherService method cypher.

@POST
@SuppressWarnings({ "unchecked", "ParameterCanBeLocal" })
public Response cypher(String body, @Context HttpServletRequest request, @QueryParam(INCLUDE_STATS_PARAM) boolean includeStats, @QueryParam(INCLUDE_PLAN_PARAM) boolean includePlan, @QueryParam(PROFILE_PARAM) boolean profile) throws BadInputException {
    usage.get(features).flag(http_cypher_endpoint);
    Map<String, Object> command = input.readMap(body);
    if (!command.containsKey(QUERY_KEY)) {
        return output.badRequest(new InvalidArgumentsException("You have to provide the 'query' parameter."));
    }
    String query = (String) command.get(QUERY_KEY);
    Map<String, Object> params;
    try {
        params = (Map<String, Object>) (command.containsKey(PARAMS_KEY) && command.get(PARAMS_KEY) != null ? command.get(PARAMS_KEY) : new HashMap<String, Object>());
    } catch (ClassCastException e) {
        return output.badRequest(new IllegalArgumentException("Parameters must be a JSON map"));
    }
    try {
        QueryExecutionEngine executionEngine = cypherExecutor.getExecutionEngine();
        boolean periodicCommitQuery = executionEngine.isPeriodicCommit(query);
        CommitOnSuccessfulStatusCodeRepresentationWriteHandler handler = (CommitOnSuccessfulStatusCodeRepresentationWriteHandler) output.getRepresentationWriteHandler();
        if (periodicCommitQuery) {
            handler.closeTransaction();
        }
        TransactionalContext tc = cypherExecutor.createTransactionContext(query, params, request);
        Result result;
        if (profile) {
            result = executionEngine.profileQuery(query, params, tc);
            includePlan = true;
        } else {
            result = executionEngine.executeQuery(query, params, tc);
            includePlan = result.getQueryExecutionType().requestedExecutionPlanDescription();
        }
        if (periodicCommitQuery) {
            handler.setTransaction(database.beginTx());
        }
        return output.ok(new CypherResultRepresentation(result, includeStats, includePlan));
    } catch (Throwable e) {
        if (e.getCause() instanceof CypherException) {
            return output.badRequest(e.getCause());
        } else {
            return output.badRequest(e);
        }
    }
}
Also used : CypherResultRepresentation(org.neo4j.server.rest.repr.CypherResultRepresentation) HashMap(java.util.HashMap) Result(org.neo4j.graphdb.Result) QueryExecutionEngine(org.neo4j.kernel.impl.query.QueryExecutionEngine) CommitOnSuccessfulStatusCodeRepresentationWriteHandler(org.neo4j.server.rest.transactional.CommitOnSuccessfulStatusCodeRepresentationWriteHandler) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) CypherException(org.neo4j.cypher.CypherException) InvalidArgumentsException(org.neo4j.server.rest.repr.InvalidArgumentsException) POST(javax.ws.rs.POST)

Example 9 with TransactionalContext

use of org.neo4j.kernel.impl.query.TransactionalContext in project neo4j by neo4j.

the class TransactionHandle method executeStatements.

private void executeStatements(StatementDeserializer statements, ExecutionResultSerializer output, List<Neo4jError> errors, HttpServletRequest request) {
    try {
        boolean hasPrevious = false;
        while (statements.hasNext()) {
            Statement statement = statements.next();
            try {
                boolean hasPeriodicCommit = engine.isPeriodicCommit(statement.statement());
                if ((statements.hasNext() || hasPrevious) && hasPeriodicCommit) {
                    throw new QueryExecutionKernelException(new InvalidSemanticsException("Cannot execute another statement after executing " + "PERIODIC COMMIT statement in the same transaction"));
                }
                if (!hasPrevious && hasPeriodicCommit) {
                    context.closeTransactionForPeriodicCommit();
                }
                hasPrevious = true;
                TransactionalContext tc = txManagerFacade.create(request, queryService, type, securityContext, statement.statement(), statement.parameters());
                Result result = safelyExecute(statement, hasPeriodicCommit, tc);
                output.statementResult(result, statement.includeStats(), statement.resultDataContents());
                output.notifications(result.getNotifications());
            } catch (KernelException | CypherException | AuthorizationViolationException | WriteOperationsNotAllowedException e) {
                errors.add(new Neo4jError(e.status(), e));
                break;
            } catch (DeadlockDetectedException e) {
                errors.add(new Neo4jError(Status.Transaction.DeadlockDetected, e));
            } catch (IOException e) {
                errors.add(new Neo4jError(Status.Network.CommunicationError, e));
                break;
            } catch (Exception e) {
                Throwable cause = e.getCause();
                if (cause instanceof Status.HasStatus) {
                    errors.add(new Neo4jError(((Status.HasStatus) cause).status(), cause));
                } else {
                    errors.add(new Neo4jError(Status.Statement.ExecutionFailed, e));
                }
                break;
            }
        }
        addToCollection(statements.errors(), errors);
    } catch (Throwable e) {
        errors.add(new Neo4jError(Status.General.UnknownError, e));
    }
}
Also used : InvalidSemanticsException(org.neo4j.cypher.InvalidSemanticsException) Status(org.neo4j.kernel.api.exceptions.Status) QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) DeadlockDetectedException(org.neo4j.kernel.DeadlockDetectedException) IOException(java.io.IOException) QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) TransactionFailureException(org.neo4j.kernel.api.exceptions.TransactionFailureException) CypherException(org.neo4j.cypher.CypherException) DeadlockDetectedException(org.neo4j.kernel.DeadlockDetectedException) IOException(java.io.IOException) KernelException(org.neo4j.kernel.api.exceptions.KernelException) InvalidSemanticsException(org.neo4j.cypher.InvalidSemanticsException) AuthorizationViolationException(org.neo4j.graphdb.security.AuthorizationViolationException) WriteOperationsNotAllowedException(org.neo4j.graphdb.security.WriteOperationsNotAllowedException) Result(org.neo4j.graphdb.Result) WriteOperationsNotAllowedException(org.neo4j.graphdb.security.WriteOperationsNotAllowedException) Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext) CypherException(org.neo4j.cypher.CypherException) QueryExecutionKernelException(org.neo4j.kernel.impl.query.QueryExecutionKernelException) KernelException(org.neo4j.kernel.api.exceptions.KernelException) AuthorizationViolationException(org.neo4j.graphdb.security.AuthorizationViolationException)

Example 10 with TransactionalContext

use of org.neo4j.kernel.impl.query.TransactionalContext in project neo4j by neo4j.

the class Start method getResult.

private Result getResult(String query, Session session) throws ShellException, RemoteException, QueryExecutionKernelException {
    Map<String, Object> parameters = getParameters(session);
    TransactionalContext tc = createTransactionContext(query, parameters, session);
    return getEngine().executeQuery(query, parameters, tc);
}
Also used : TransactionalContext(org.neo4j.kernel.impl.query.TransactionalContext)

Aggregations

TransactionalContext (org.neo4j.kernel.impl.query.TransactionalContext)20 Result (org.neo4j.graphdb.Result)16 Test (org.junit.Test)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 QueryExecutionEngine (org.neo4j.kernel.impl.query.QueryExecutionEngine)10 InOrder (org.mockito.InOrder)9 Notification (org.neo4j.graphdb.Notification)7 GraphDatabaseQueryService (org.neo4j.kernel.GraphDatabaseQueryService)6 BoltResult (org.neo4j.bolt.v1.runtime.spi.BoltResult)5 QueryStatistics (org.neo4j.graphdb.QueryStatistics)4 QueryExecutionKernelException (org.neo4j.kernel.impl.query.QueryExecutionKernelException)3 Map (java.util.Map)2 Matchers.anyString (org.mockito.Matchers.anyString)2 CypherException (org.neo4j.cypher.CypherException)2 SyntaxException (org.neo4j.cypher.SyntaxException)2 Type (org.neo4j.kernel.api.KernelTransaction.Type)2 KernelException (org.neo4j.kernel.api.exceptions.KernelException)2 SecurityContext (org.neo4j.kernel.api.security.SecurityContext)2 InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)2 NullLogProvider (org.neo4j.logging.NullLogProvider)2