Search in sources :

Example 1 with ExecuteBatchDmlResponse

use of com.google.spanner.v1.ExecuteBatchDmlResponse in project java-spanner by googleapis.

the class TransactionContextImplTest method batchDml.

@SuppressWarnings("unchecked")
private void batchDml(int status) {
    SessionImpl session = mock(SessionImpl.class);
    when(session.getName()).thenReturn("test");
    SpannerRpc rpc = mock(SpannerRpc.class);
    ExecuteBatchDmlResponse response = ExecuteBatchDmlResponse.newBuilder().setStatus(Status.newBuilder().setCode(status).build()).build();
    Statement statement = Statement.of("UPDATE FOO SET BAR=1");
    when(rpc.executeBatchDml(Mockito.any(ExecuteBatchDmlRequest.class), Mockito.anyMap())).thenReturn(response);
    try (TransactionContextImpl impl = TransactionContextImpl.newBuilder().setSession(session).setRpc(rpc).setTransactionId(ByteString.copyFromUtf8("test")).setOptions(Options.fromTransactionOptions()).build()) {
        impl.batchUpdate(Collections.singletonList(statement));
    }
}
Also used : TransactionContextImpl(com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl) ExecuteBatchDmlResponse(com.google.spanner.v1.ExecuteBatchDmlResponse) SpannerRpc(com.google.cloud.spanner.spi.v1.SpannerRpc) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest)

Example 2 with ExecuteBatchDmlResponse

use of com.google.spanner.v1.ExecuteBatchDmlResponse in project java-spanner by googleapis.

the class SpannerClientTest method executeBatchDmlTest.

@Test
public void executeBatchDmlTest() throws Exception {
    ExecuteBatchDmlResponse expectedResponse = ExecuteBatchDmlResponse.newBuilder().addAllResultSets(new ArrayList<ResultSet>()).setStatus(Status.newBuilder().build()).build();
    mockSpanner.addResponse(expectedResponse);
    ExecuteBatchDmlRequest request = ExecuteBatchDmlRequest.newBuilder().setSession(SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()).setTransaction(TransactionSelector.newBuilder().build()).addAllStatements(new ArrayList<ExecuteBatchDmlRequest.Statement>()).setSeqno(109325920).setRequestOptions(RequestOptions.newBuilder().build()).build();
    ExecuteBatchDmlResponse actualResponse = client.executeBatchDml(request);
    Assert.assertEquals(expectedResponse, actualResponse);
    List<AbstractMessage> actualRequests = mockSpanner.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    ExecuteBatchDmlRequest actualRequest = ((ExecuteBatchDmlRequest) actualRequests.get(0));
    Assert.assertEquals(request.getSession(), actualRequest.getSession());
    Assert.assertEquals(request.getTransaction(), actualRequest.getTransaction());
    Assert.assertEquals(request.getStatementsList(), actualRequest.getStatementsList());
    Assert.assertEquals(request.getSeqno(), actualRequest.getSeqno());
    Assert.assertEquals(request.getRequestOptions(), actualRequest.getRequestOptions());
    Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Also used : AbstractMessage(com.google.protobuf.AbstractMessage) PartialResultSet(com.google.spanner.v1.PartialResultSet) ResultSet(com.google.spanner.v1.ResultSet) ArrayList(java.util.ArrayList) ExecuteBatchDmlResponse(com.google.spanner.v1.ExecuteBatchDmlResponse) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest) Test(org.junit.Test)

Example 3 with ExecuteBatchDmlResponse

use of com.google.spanner.v1.ExecuteBatchDmlResponse in project java-spanner by googleapis.

the class MockSpannerServiceImpl method executeBatchDml.

@Override
public void executeBatchDml(ExecuteBatchDmlRequest request, StreamObserver<ExecuteBatchDmlResponse> responseObserver) {
    requests.add(request);
    Preconditions.checkNotNull(request.getSession());
    Session session = sessions.get(request.getSession());
    if (session == null) {
        setSessionNotFound(request.getSession(), responseObserver);
        return;
    }
    sessionLastUsed.put(session.getName(), Instant.now());
    try {
        executeBatchDmlExecutionTime.simulateExecutionTime(exceptions, stickyGlobalExceptions, freezeLock);
        // Get or start transaction
        ByteString transactionId = getTransactionId(session, request.getTransaction());
        if (isPartitionedDmlTransaction(transactionId)) {
            throw Status.FAILED_PRECONDITION.withDescription("This transaction is a partitioned DML transaction and cannot be used for batch DML updates.").asRuntimeException();
        }
        simulateAbort(session, transactionId);
        List<StatementResult> results = new ArrayList<>();
        com.google.rpc.Status status = com.google.rpc.Status.newBuilder().setCode(Code.OK_VALUE).build();
        resultLoop: for (com.google.spanner.v1.ExecuteBatchDmlRequest.Statement statement : request.getStatementsList()) {
            try {
                Statement spannerStatement = buildStatement(statement.getSql(), statement.getParamTypesMap(), statement.getParams());
                StatementResult res = getResult(spannerStatement);
                switch(res.getType()) {
                    case EXCEPTION:
                        status = com.google.rpc.Status.newBuilder().setCode(res.getException().getStatus().getCode().value()).setMessage(res.getException().getMessage()).build();
                        break resultLoop;
                    case RESULT_SET:
                        throw Status.INVALID_ARGUMENT.withDescription("Not a DML statement: " + statement.getSql()).asRuntimeException();
                    case UPDATE_COUNT:
                        results.add(res);
                        break;
                    default:
                        throw new IllegalStateException("Unknown result type: " + res.getType());
                }
            } catch (StatusRuntimeException e) {
                status = com.google.rpc.Status.newBuilder().setCode(e.getStatus().getCode().value()).setMessage(e.getMessage()).build();
                break;
            } catch (Exception e) {
                status = com.google.rpc.Status.newBuilder().setCode(Code.UNKNOWN_VALUE).setMessage(e.getMessage()).build();
                break;
            }
        }
        ExecuteBatchDmlResponse.Builder builder = ExecuteBatchDmlResponse.newBuilder();
        for (StatementResult res : results) {
            builder.addResultSets(ResultSet.newBuilder().setStats(ResultSetStats.newBuilder().setRowCountExact(res.getUpdateCount()).build()).setMetadata(ResultSetMetadata.newBuilder().setTransaction(ignoreNextInlineBeginRequest.getAndSet(false) ? Transaction.getDefaultInstance() : Transaction.newBuilder().setId(transactionId).build()).build()).build());
        }
        builder.setStatus(status);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    } catch (StatusRuntimeException e) {
        responseObserver.onError(e);
    } catch (Throwable t) {
        responseObserver.onError(Status.INTERNAL.asRuntimeException());
    }
}
Also used : ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) StatusRuntimeException(io.grpc.StatusRuntimeException) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecuteBatchDmlResponse(com.google.spanner.v1.ExecuteBatchDmlResponse) Session(com.google.spanner.v1.Session)

Example 4 with ExecuteBatchDmlResponse

use of com.google.spanner.v1.ExecuteBatchDmlResponse in project java-spanner by googleapis.

the class TransactionRunnerImplTest method batchDmlException.

@SuppressWarnings("unchecked")
private long[] batchDmlException(int status) {
    Preconditions.checkArgument(status != Code.OK_VALUE);
    TransactionContextImpl transaction = TransactionContextImpl.newBuilder().setSession(session).setTransactionId(ByteString.copyFromUtf8(UUID.randomUUID().toString())).setOptions(Options.fromTransactionOptions()).setRpc(rpc).build();
    when(session.newTransaction(Options.fromTransactionOptions())).thenReturn(transaction);
    when(session.beginTransactionAsync()).thenReturn(ApiFutures.immediateFuture(ByteString.copyFromUtf8(UUID.randomUUID().toString())));
    when(session.getName()).thenReturn(SessionId.of("p", "i", "d", "test").getName());
    TransactionRunnerImpl runner = new TransactionRunnerImpl(session);
    runner.setSpan(mock(Span.class));
    ExecuteBatchDmlResponse response1 = ExecuteBatchDmlResponse.newBuilder().addResultSets(ResultSet.newBuilder().setStats(ResultSetStats.newBuilder().setRowCountExact(1L)).build()).setStatus(com.google.rpc.Status.newBuilder().setCode(status).build()).build();
    ExecuteBatchDmlResponse response2 = ExecuteBatchDmlResponse.newBuilder().addResultSets(ResultSet.newBuilder().setStats(ResultSetStats.newBuilder().setRowCountExact(1L)).build()).addResultSets(ResultSet.newBuilder().setStats(ResultSetStats.newBuilder().setRowCountExact(1L)).build()).setStatus(com.google.rpc.Status.newBuilder().setCode(Code.OK_VALUE).build()).build();
    when(rpc.executeBatchDml(Mockito.any(ExecuteBatchDmlRequest.class), Mockito.anyMap())).thenReturn(response1, response2);
    CommitResponse commitResponse = CommitResponse.newBuilder().setCommitTimestamp(Timestamp.getDefaultInstance()).build();
    when(rpc.commitAsync(Mockito.any(CommitRequest.class), Mockito.anyMap())).thenReturn(ApiFutures.immediateFuture(commitResponse));
    final Statement statement = Statement.of("UPDATE FOO SET BAR=1");
    final AtomicInteger numCalls = new AtomicInteger(0);
    long[] updateCount = runner.run(transaction1 -> {
        numCalls.incrementAndGet();
        return transaction1.batchUpdate(Arrays.asList(statement, statement));
    });
    if (status == Code.ABORTED_VALUE) {
        // Assert that the method ran twice because the first response aborted.
        assertThat(numCalls.get()).isEqualTo(2);
    }
    return updateCount;
}
Also used : TransactionContextImpl(com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl) CommitRequest(com.google.spanner.v1.CommitRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CommitResponse(com.google.spanner.v1.CommitResponse) ExecuteBatchDmlResponse(com.google.spanner.v1.ExecuteBatchDmlResponse) Span(io.opencensus.trace.Span) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest)

Example 5 with ExecuteBatchDmlResponse

use of com.google.spanner.v1.ExecuteBatchDmlResponse in project grpc-gcp-java by GoogleCloudPlatform.

the class SpannerIntegrationTest method testExecuteBatchDmlFuture.

@Test
public void testExecuteBatchDmlFuture() throws Exception {
    SpannerFutureStub stub = getSpannerFutureStub();
    List<String> futureNames = createFutureSessions(stub);
    for (String futureName : futureNames) {
        TransactionOptions options = TransactionOptions.newBuilder().setReadWrite(TransactionOptions.ReadWrite.getDefaultInstance()).build();
        TransactionSelector selector = TransactionSelector.newBuilder().setBegin(options).build();
        // Will use only one session for the whole batch.
        ListenableFuture<ExecuteBatchDmlResponse> responseFuture = stub.executeBatchDml(ExecuteBatchDmlRequest.newBuilder().setSession(futureName).setTransaction(selector).addStatements(Statement.newBuilder().setSql("select * FROM Users").build()).build());
        // The ChannelRef which is bound with the current affinity key.
        GcpManagedChannel.ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName);
        // Verify the channel is in use.
        assertEquals(1, currentChannel.getActiveStreamsCount());
        ExecuteBatchDmlResponse response = responseFuture.get();
        assertEquals(0, currentChannel.getActiveStreamsCount());
    }
    deleteFutureSessions(stub, futureNames);
}
Also used : TransactionOptions(com.google.spanner.v1.TransactionOptions) TransactionSelector(com.google.spanner.v1.TransactionSelector) SpannerFutureStub(com.google.spanner.v1.SpannerGrpc.SpannerFutureStub) ExecuteBatchDmlResponse(com.google.spanner.v1.ExecuteBatchDmlResponse) Test(org.junit.Test)

Aggregations

ExecuteBatchDmlResponse (com.google.spanner.v1.ExecuteBatchDmlResponse)5 ExecuteBatchDmlRequest (com.google.spanner.v1.ExecuteBatchDmlRequest)3 TransactionContextImpl (com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl)2 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 SpannerRpc (com.google.cloud.spanner.spi.v1.SpannerRpc)1 AbstractMessage (com.google.protobuf.AbstractMessage)1 ByteString (com.google.protobuf.ByteString)1 CommitRequest (com.google.spanner.v1.CommitRequest)1 CommitResponse (com.google.spanner.v1.CommitResponse)1 PartialResultSet (com.google.spanner.v1.PartialResultSet)1 ResultSet (com.google.spanner.v1.ResultSet)1 Session (com.google.spanner.v1.Session)1 SpannerFutureStub (com.google.spanner.v1.SpannerGrpc.SpannerFutureStub)1 TransactionOptions (com.google.spanner.v1.TransactionOptions)1 TransactionSelector (com.google.spanner.v1.TransactionSelector)1 StatusRuntimeException (io.grpc.StatusRuntimeException)1 Span (io.opencensus.trace.Span)1 TimeoutException (java.util.concurrent.TimeoutException)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1