Search in sources :

Example 1 with SELECT1

use of com.google.cloud.spanner.MockSpannerTestUtil.SELECT1 in project java-spanner by googleapis.

the class DatabaseClientImplTest method singleUseBoundAsync.

@Test
public void singleUseBoundAsync() throws Exception {
    DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE));
    final AtomicInteger rowCount = new AtomicInteger();
    ApiFuture<Void> res;
    try (AsyncResultSet rs = client.singleUse(TimestampBound.ofExactStaleness(15L, TimeUnit.SECONDS)).executeQueryAsync(SELECT1)) {
        res = rs.setCallback(executor, resultSet -> {
            while (true) {
                switch(resultSet.tryNext()) {
                    case OK:
                        rowCount.incrementAndGet();
                        break;
                    case DONE:
                        return CallbackResponse.DONE;
                    case NOT_READY:
                        return CallbackResponse.CONTINUE;
                }
            }
        });
    }
    res.get();
    assertThat(rowCount.get()).isEqualTo(1);
}
Also used : LocalChannelProvider(com.google.api.gax.grpc.testing.LocalChannelProvider) Context(io.grpc.Context) QueryAnalyzeMode(com.google.cloud.spanner.ReadContext.QueryAnalyzeMode) NoCredentials(com.google.cloud.NoCredentials) Timestamp(com.google.cloud.Timestamp) SettableFuture(com.google.common.util.concurrent.SettableFuture) StatementResult(com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult) ReadRequest(com.google.spanner.v1.ReadRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Status(io.grpc.Status) READ_ONE_KEY_VALUE_RESULTSET(com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_RESULTSET) AfterClass(org.junit.AfterClass) ApiFutures(com.google.api.core.ApiFutures) SpannerApiFutures.get(com.google.cloud.spanner.SpannerApiFutures.get) READ_COLUMN_NAMES(com.google.cloud.spanner.MockSpannerTestUtil.READ_COLUMN_NAMES) DeleteSessionRequest(com.google.spanner.v1.DeleteSessionRequest) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Logger(java.util.logging.Logger) Executors(java.util.concurrent.Executors) ApiFuture(com.google.api.core.ApiFuture) Duration(org.threeten.bp.Duration) List(java.util.List) ExecuteSqlRequest(com.google.spanner.v1.ExecuteSqlRequest) ResourceNotFoundException(com.google.cloud.spanner.SpannerException.ResourceNotFoundException) QueryMode(com.google.spanner.v1.ExecuteSqlRequest.QueryMode) Mockito.mock(org.mockito.Mockito.mock) Priority(com.google.spanner.v1.RequestOptions.Priority) TransactionOption(com.google.cloud.spanner.Options.TransactionOption) BeforeClass(org.junit.BeforeClass) READ_TABLE_NAME(com.google.cloud.spanner.MockSpannerTestUtil.READ_TABLE_NAME) Stopwatch(com.google.common.base.Stopwatch) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Function(java.util.function.Function) InProcessServerBuilder(io.grpc.inprocess.InProcessServerBuilder) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) RetrySettings(com.google.api.gax.retrying.RetrySettings) CommitRequest(com.google.spanner.v1.CommitRequest) PooledSessionFuture(com.google.cloud.spanner.SessionPool.PooledSessionFuture) ImmutableList(com.google.common.collect.ImmutableList) GrpcStreamIterator(com.google.cloud.spanner.AbstractResultSet.GrpcStreamIterator) Server(io.grpc.Server) SimulatedExecutionTime(com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime) ExecutorService(java.util.concurrent.ExecutorService) READ_ONE_KEY_VALUE_STATEMENT(com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_STATEMENT) Before(org.junit.Before) QueryOptions(com.google.spanner.v1.ExecuteSqlRequest.QueryOptions) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) CallbackResponse(com.google.cloud.spanner.AsyncResultSet.CallbackResponse) AbstractMessage(com.google.protobuf.AbstractMessage) SpannerCallContextTimeoutConfigurator(com.google.cloud.spanner.SpannerOptions.SpannerCallContextTimeoutConfigurator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Assert.assertNull(org.junit.Assert.assertNull) RpcPriority(com.google.cloud.spanner.Options.RpcPriority) SELECT1(com.google.cloud.spanner.MockSpannerTestUtil.SELECT1) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 2 with SELECT1

use of com.google.cloud.spanner.MockSpannerTestUtil.SELECT1 in project java-spanner by googleapis.

the class DatabaseClientImplTest method singleUseAsync.

@Test
public void singleUseAsync() throws Exception {
    DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE));
    final AtomicInteger rowCount = new AtomicInteger();
    ApiFuture<Void> res;
    try (AsyncResultSet rs = client.singleUse().executeQueryAsync(SELECT1)) {
        res = rs.setCallback(executor, resultSet -> {
            while (true) {
                switch(resultSet.tryNext()) {
                    case OK:
                        rowCount.incrementAndGet();
                        break;
                    case DONE:
                        return CallbackResponse.DONE;
                    case NOT_READY:
                        return CallbackResponse.CONTINUE;
                }
            }
        });
    }
    res.get();
    assertThat(rowCount.get()).isEqualTo(1);
}
Also used : LocalChannelProvider(com.google.api.gax.grpc.testing.LocalChannelProvider) Context(io.grpc.Context) QueryAnalyzeMode(com.google.cloud.spanner.ReadContext.QueryAnalyzeMode) NoCredentials(com.google.cloud.NoCredentials) Timestamp(com.google.cloud.Timestamp) SettableFuture(com.google.common.util.concurrent.SettableFuture) StatementResult(com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult) ReadRequest(com.google.spanner.v1.ReadRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Status(io.grpc.Status) READ_ONE_KEY_VALUE_RESULTSET(com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_RESULTSET) AfterClass(org.junit.AfterClass) ApiFutures(com.google.api.core.ApiFutures) SpannerApiFutures.get(com.google.cloud.spanner.SpannerApiFutures.get) READ_COLUMN_NAMES(com.google.cloud.spanner.MockSpannerTestUtil.READ_COLUMN_NAMES) DeleteSessionRequest(com.google.spanner.v1.DeleteSessionRequest) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Logger(java.util.logging.Logger) Executors(java.util.concurrent.Executors) ApiFuture(com.google.api.core.ApiFuture) Duration(org.threeten.bp.Duration) List(java.util.List) ExecuteSqlRequest(com.google.spanner.v1.ExecuteSqlRequest) ResourceNotFoundException(com.google.cloud.spanner.SpannerException.ResourceNotFoundException) QueryMode(com.google.spanner.v1.ExecuteSqlRequest.QueryMode) Mockito.mock(org.mockito.Mockito.mock) Priority(com.google.spanner.v1.RequestOptions.Priority) TransactionOption(com.google.cloud.spanner.Options.TransactionOption) BeforeClass(org.junit.BeforeClass) READ_TABLE_NAME(com.google.cloud.spanner.MockSpannerTestUtil.READ_TABLE_NAME) Stopwatch(com.google.common.base.Stopwatch) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Function(java.util.function.Function) InProcessServerBuilder(io.grpc.inprocess.InProcessServerBuilder) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) RetrySettings(com.google.api.gax.retrying.RetrySettings) CommitRequest(com.google.spanner.v1.CommitRequest) PooledSessionFuture(com.google.cloud.spanner.SessionPool.PooledSessionFuture) ImmutableList(com.google.common.collect.ImmutableList) GrpcStreamIterator(com.google.cloud.spanner.AbstractResultSet.GrpcStreamIterator) Server(io.grpc.Server) SimulatedExecutionTime(com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime) ExecutorService(java.util.concurrent.ExecutorService) READ_ONE_KEY_VALUE_STATEMENT(com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_STATEMENT) Before(org.junit.Before) QueryOptions(com.google.spanner.v1.ExecuteSqlRequest.QueryOptions) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) CallbackResponse(com.google.cloud.spanner.AsyncResultSet.CallbackResponse) AbstractMessage(com.google.protobuf.AbstractMessage) SpannerCallContextTimeoutConfigurator(com.google.cloud.spanner.SpannerOptions.SpannerCallContextTimeoutConfigurator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Assert.assertNull(org.junit.Assert.assertNull) RpcPriority(com.google.cloud.spanner.Options.RpcPriority) SELECT1(com.google.cloud.spanner.MockSpannerTestUtil.SELECT1) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 3 with SELECT1

use of com.google.cloud.spanner.MockSpannerTestUtil.SELECT1 in project java-spanner by googleapis.

the class DatabaseClientImplTest method testDatabaseOrInstanceIsDeletedAndThenRecreated.

/**
 * Test showing that when a database is deleted while it is in use by a database client and then
 * re-created with the same name, will continue to return {@link DatabaseNotFoundException}s until
 * a new {@link DatabaseClient} is created.
 */
@Test
public void testDatabaseOrInstanceIsDeletedAndThenRecreated() throws Exception {
    StatusRuntimeException[] exceptions = new StatusRuntimeException[] { SpannerExceptionFactoryTest.newStatusResourceNotFoundException("Database", SpannerExceptionFactory.DATABASE_RESOURCE_TYPE, DATABASE_NAME), SpannerExceptionFactoryTest.newStatusResourceNotFoundException("Instance", SpannerExceptionFactory.INSTANCE_RESOURCE_TYPE, INSTANCE_NAME) };
    for (StatusRuntimeException exception : exceptions) {
        try (Spanner spanner = SpannerOptions.newBuilder().setProjectId(TEST_PROJECT).setChannelProvider(channelProvider).setCredentials(NoCredentials.getInstance()).build().getService()) {
            DatabaseClientImpl dbClient = (DatabaseClientImpl) spanner.getDatabaseClient(DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE));
            // Wait until all sessions have been created and prepared.
            Stopwatch watch = Stopwatch.createStarted();
            while (watch.elapsed(TimeUnit.SECONDS) < 5 && (dbClient.pool.getNumberOfSessionsBeingCreated() > 0)) {
                Thread.sleep(1L);
            }
            // Simulate that the database or instance has been deleted.
            mockSpanner.setStickyGlobalExceptions(true);
            mockSpanner.addException(exception);
            // All subsequent calls should fail with a DatabaseNotFoundException.
            try (ResultSet rs = dbClient.singleUse().executeQuery(SELECT1)) {
                assertThrows(ResourceNotFoundException.class, () -> rs.next());
            }
            assertThrows(ResourceNotFoundException.class, () -> dbClient.readWriteTransaction().run(transaction -> null));
            // Now simulate that the database has been re-created. The database client should still
            // throw DatabaseNotFoundExceptions, as it is not the same database. The server should not
            // receive any new requests.
            mockSpanner.reset();
            // All subsequent calls should fail with a DatabaseNotFoundException.
            assertThrows(ResourceNotFoundException.class, () -> dbClient.singleUse().executeQuery(SELECT1));
            assertThrows(ResourceNotFoundException.class, () -> dbClient.readWriteTransaction().run(transaction -> null));
            assertThat(mockSpanner.getRequests()).isEmpty();
            // Now get a new database client. Normally multiple calls to Spanner#getDatabaseClient will
            // return the same instance, but not when the instance has been invalidated by a
            // DatabaseNotFoundException.
            DatabaseClientImpl newClient = (DatabaseClientImpl) spanner.getDatabaseClient(DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE));
            assertThat(newClient).isNotSameInstanceAs(dbClient);
            // Executing a query should now work without problems.
            try (ResultSet rs = newClient.singleUse().executeQuery(SELECT1)) {
                while (rs.next()) {
                }
            }
            assertThat(mockSpanner.getRequests()).isNotEmpty();
        }
        mockSpanner.reset();
        mockSpanner.removeAllExecutionTimes();
    }
}
Also used : LocalChannelProvider(com.google.api.gax.grpc.testing.LocalChannelProvider) Context(io.grpc.Context) QueryAnalyzeMode(com.google.cloud.spanner.ReadContext.QueryAnalyzeMode) NoCredentials(com.google.cloud.NoCredentials) Timestamp(com.google.cloud.Timestamp) SettableFuture(com.google.common.util.concurrent.SettableFuture) StatementResult(com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult) ReadRequest(com.google.spanner.v1.ReadRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Status(io.grpc.Status) READ_ONE_KEY_VALUE_RESULTSET(com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_RESULTSET) AfterClass(org.junit.AfterClass) ApiFutures(com.google.api.core.ApiFutures) SpannerApiFutures.get(com.google.cloud.spanner.SpannerApiFutures.get) READ_COLUMN_NAMES(com.google.cloud.spanner.MockSpannerTestUtil.READ_COLUMN_NAMES) DeleteSessionRequest(com.google.spanner.v1.DeleteSessionRequest) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Logger(java.util.logging.Logger) Executors(java.util.concurrent.Executors) ApiFuture(com.google.api.core.ApiFuture) Duration(org.threeten.bp.Duration) List(java.util.List) ExecuteSqlRequest(com.google.spanner.v1.ExecuteSqlRequest) ResourceNotFoundException(com.google.cloud.spanner.SpannerException.ResourceNotFoundException) QueryMode(com.google.spanner.v1.ExecuteSqlRequest.QueryMode) Mockito.mock(org.mockito.Mockito.mock) Priority(com.google.spanner.v1.RequestOptions.Priority) TransactionOption(com.google.cloud.spanner.Options.TransactionOption) BeforeClass(org.junit.BeforeClass) READ_TABLE_NAME(com.google.cloud.spanner.MockSpannerTestUtil.READ_TABLE_NAME) Stopwatch(com.google.common.base.Stopwatch) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Function(java.util.function.Function) InProcessServerBuilder(io.grpc.inprocess.InProcessServerBuilder) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) RetrySettings(com.google.api.gax.retrying.RetrySettings) CommitRequest(com.google.spanner.v1.CommitRequest) PooledSessionFuture(com.google.cloud.spanner.SessionPool.PooledSessionFuture) ImmutableList(com.google.common.collect.ImmutableList) GrpcStreamIterator(com.google.cloud.spanner.AbstractResultSet.GrpcStreamIterator) Server(io.grpc.Server) SimulatedExecutionTime(com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime) ExecutorService(java.util.concurrent.ExecutorService) READ_ONE_KEY_VALUE_STATEMENT(com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_STATEMENT) Before(org.junit.Before) QueryOptions(com.google.spanner.v1.ExecuteSqlRequest.QueryOptions) TransactionContextFuture(com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture) CallbackResponse(com.google.cloud.spanner.AsyncResultSet.CallbackResponse) AbstractMessage(com.google.protobuf.AbstractMessage) SpannerCallContextTimeoutConfigurator(com.google.cloud.spanner.SpannerOptions.SpannerCallContextTimeoutConfigurator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Assert.assertNull(org.junit.Assert.assertNull) RpcPriority(com.google.cloud.spanner.Options.RpcPriority) SELECT1(com.google.cloud.spanner.MockSpannerTestUtil.SELECT1) ExecuteBatchDmlRequest(com.google.spanner.v1.ExecuteBatchDmlRequest) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) StatusRuntimeException(io.grpc.StatusRuntimeException) Stopwatch(com.google.common.base.Stopwatch) Test(org.junit.Test)

Aggregations

ApiFuture (com.google.api.core.ApiFuture)3 ApiFutures (com.google.api.core.ApiFutures)3 LocalChannelProvider (com.google.api.gax.grpc.testing.LocalChannelProvider)3 RetrySettings (com.google.api.gax.retrying.RetrySettings)3 NoCredentials (com.google.cloud.NoCredentials)3 Timestamp (com.google.cloud.Timestamp)3 GrpcStreamIterator (com.google.cloud.spanner.AbstractResultSet.GrpcStreamIterator)3 CallbackResponse (com.google.cloud.spanner.AsyncResultSet.CallbackResponse)3 TransactionContextFuture (com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture)3 SimulatedExecutionTime (com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime)3 StatementResult (com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult)3 READ_COLUMN_NAMES (com.google.cloud.spanner.MockSpannerTestUtil.READ_COLUMN_NAMES)3 READ_ONE_KEY_VALUE_RESULTSET (com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_RESULTSET)3 READ_ONE_KEY_VALUE_STATEMENT (com.google.cloud.spanner.MockSpannerTestUtil.READ_ONE_KEY_VALUE_STATEMENT)3 READ_TABLE_NAME (com.google.cloud.spanner.MockSpannerTestUtil.READ_TABLE_NAME)3 SELECT1 (com.google.cloud.spanner.MockSpannerTestUtil.SELECT1)3 RpcPriority (com.google.cloud.spanner.Options.RpcPriority)3 TransactionOption (com.google.cloud.spanner.Options.TransactionOption)3 QueryAnalyzeMode (com.google.cloud.spanner.ReadContext.QueryAnalyzeMode)3 PooledSessionFuture (com.google.cloud.spanner.SessionPool.PooledSessionFuture)3