Search in sources :

Example 36 with Database

use of com.google.spanner.admin.database.v1.Database in project java-spanner by googleapis.

the class CreateDatabaseWithEncryptionKey method createDatabaseWithEncryptionKey.

static void createDatabaseWithEncryptionKey(DatabaseAdminClient adminClient, String projectId, String instanceId, String databaseId, String kmsKeyName) {
    final Database databaseToCreate = adminClient.newDatabaseBuilder(DatabaseId.of(projectId, instanceId, databaseId)).setEncryptionConfig(EncryptionConfigs.customerManagedEncryption(kmsKeyName)).build();
    final OperationFuture<Database, CreateDatabaseMetadata> operation = adminClient.createDatabase(databaseToCreate, Arrays.asList("CREATE TABLE Singers (" + "  SingerId   INT64 NOT NULL," + "  FirstName  STRING(1024)," + "  LastName   STRING(1024)," + "  SingerInfo BYTES(MAX)" + ") PRIMARY KEY (SingerId)", "CREATE TABLE Albums (" + "  SingerId     INT64 NOT NULL," + "  AlbumId      INT64 NOT NULL," + "  AlbumTitle   STRING(MAX)" + ") PRIMARY KEY (SingerId, AlbumId)," + "  INTERLEAVE IN PARENT Singers ON DELETE CASCADE"));
    try {
        System.out.println("Waiting for operation to complete...");
        Database createdDatabase = operation.get(120, TimeUnit.SECONDS);
        System.out.printf("Database %s created with encryption key %s%n", createdDatabase.getId(), createdDatabase.getEncryptionConfig().getKmsKeyName());
    } catch (ExecutionException e) {
        // If the operation failed during execution, expose the cause.
        throw SpannerExceptionFactory.asSpannerException(e.getCause());
    } catch (InterruptedException e) {
        // and the thread is interrupted, either before or during the activity.
        throw SpannerExceptionFactory.propagateInterrupt(e);
    } catch (TimeoutException e) {
        // If the operation timed out propagates the timeout
        throw SpannerExceptionFactory.propagateTimeout(e);
    }
}
Also used : Database(com.google.cloud.spanner.Database) CreateDatabaseMetadata(com.google.spanner.admin.database.v1.CreateDatabaseMetadata) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 37 with Database

use of com.google.spanner.admin.database.v1.Database in project java-spanner by googleapis.

the class UpdateDatabaseWithDefaultLeaderSample method updateDatabaseWithDefaultLeader.

static void updateDatabaseWithDefaultLeader(String projectId, String instanceId, String databaseId, String defaultLeader) {
    try (Spanner spanner = SpannerOptions.newBuilder().setProjectId(projectId).build().getService()) {
        final DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient();
        final OperationFuture<Void, UpdateDatabaseDdlMetadata> operation = databaseAdminClient.updateDatabaseDdl(instanceId, databaseId, Collections.singletonList(String.format("ALTER DATABASE `%s` SET OPTIONS (default_leader = '%s')", databaseId, defaultLeader)), null);
        operation.get();
        System.out.println("Updated default leader to " + defaultLeader);
    } catch (ExecutionException e) {
        // If the operation failed during execution, expose the cause.
        throw (SpannerException) e.getCause();
    } catch (InterruptedException e) {
        // and the thread is interrupted, either before or during the activity.
        throw SpannerExceptionFactory.propagateInterrupt(e);
    }
}
Also used : UpdateDatabaseDdlMetadata(com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata) DatabaseAdminClient(com.google.cloud.spanner.DatabaseAdminClient) ExecutionException(java.util.concurrent.ExecutionException) Spanner(com.google.cloud.spanner.Spanner)

Example 38 with Database

use of com.google.spanner.admin.database.v1.Database in project java-spanner by googleapis.

the class GapicSpannerRpc method updateDatabaseDdl.

/**
 * If the update database ddl operation returns an ALREADY_EXISTS error, meaning the operation id
 * used is already in flight, this method will simply resume the original operation. The returned
 * future will be completed when the original operation finishes.
 *
 * <p>This mechanism is necessary, because the update database ddl can be retried. If a retryable
 * failure occurs, the backend has already started processing the update database ddl operation
 * with the given id and the library issues a retry, an ALREADY_EXISTS error will be returned. If
 * we were to bubble this error up, it would be confusing for the caller, who used originally
 * called the method with a new operation id.
 */
@Override
public OperationFuture<Empty, UpdateDatabaseDdlMetadata> updateDatabaseDdl(final String databaseName, final Iterable<String> updateDatabaseStatements, @Nullable final String updateId) throws SpannerException {
    acquireAdministrativeRequestsRateLimiter();
    final UpdateDatabaseDdlRequest request = UpdateDatabaseDdlRequest.newBuilder().setDatabase(databaseName).addAllStatements(updateDatabaseStatements).setOperationId(MoreObjects.firstNonNull(updateId, "")).build();
    final GrpcCallContext context = newCallContext(null, databaseName, request, DatabaseAdminGrpc.getUpdateDatabaseDdlMethod());
    final OperationCallable<UpdateDatabaseDdlRequest, Empty, UpdateDatabaseDdlMetadata> callable = databaseAdminStub.updateDatabaseDdlOperationCallable();
    return runWithRetryOnAdministrativeRequestsExceeded(() -> {
        OperationFuture<Empty, UpdateDatabaseDdlMetadata> operationFuture = callable.futureCall(request, context);
        try {
            operationFuture.getInitialFuture().get();
        } catch (InterruptedException e) {
            throw newSpannerException(e);
        } catch (ExecutionException e) {
            Throwable t = e.getCause();
            SpannerException se = SpannerExceptionFactory.asSpannerException(t);
            if (se instanceof AdminRequestsPerMinuteExceededException) {
                // Propagate this to trigger a retry.
                throw se;
            }
            if (t instanceof AlreadyExistsException) {
                String operationName = OPERATION_NAME_TEMPLATE.instantiate("database", databaseName, "operation", updateId);
                return callable.resumeFutureCall(operationName, context);
            }
        }
        return operationFuture;
    });
}
Also used : AlreadyExistsException(com.google.api.gax.rpc.AlreadyExistsException) AdminRequestsPerMinuteExceededException(com.google.cloud.spanner.AdminRequestsPerMinuteExceededException) UpdateDatabaseDdlRequest(com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) Empty(com.google.protobuf.Empty) GrpcCallContext(com.google.api.gax.grpc.GrpcCallContext) UpdateDatabaseDdlMetadata(com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata) SpannerExceptionFactory.newSpannerException(com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException) SpannerException(com.google.cloud.spanner.SpannerException) ExecutionException(java.util.concurrent.ExecutionException)

Example 39 with Database

use of com.google.spanner.admin.database.v1.Database in project java-spanner by googleapis.

the class GapicSpannerRpc method createDatabase.

@Override
public OperationFuture<Database, CreateDatabaseMetadata> createDatabase(final String instanceName, String createDatabaseStatement, Iterable<String> additionalStatements, com.google.cloud.spanner.Database databaseInfo) throws SpannerException {
    final String databaseId = databaseInfo.getId().getDatabase();
    CreateDatabaseRequest.Builder requestBuilder = CreateDatabaseRequest.newBuilder().setParent(instanceName).setCreateStatement(createDatabaseStatement).addAllExtraStatements(additionalStatements);
    if (databaseInfo.getEncryptionConfig() != null) {
        requestBuilder.setEncryptionConfig(EncryptionConfigProtoMapper.encryptionConfig(databaseInfo.getEncryptionConfig()));
    }
    if (databaseInfo.getDialect() != null) {
        requestBuilder.setDatabaseDialect(databaseInfo.getDialect().toProto());
    }
    final CreateDatabaseRequest request = requestBuilder.build();
    OperationFutureCallable<CreateDatabaseRequest, Database, CreateDatabaseMetadata> callable = new OperationFutureCallable<>(databaseAdminStub.createDatabaseOperationCallable(), request, DatabaseAdminGrpc.getCreateDatabaseMethod(), instanceName, nextPageToken -> listDatabaseOperations(instanceName, 0, String.format("(metadata.@type:type.googleapis.com/%s) AND (name:%s/operations/)", CreateDatabaseMetadata.getDescriptor().getFullName(), String.format("%s/databases/%s", instanceName, databaseId)), nextPageToken), input -> {
        if (input.getDone() && input.hasResponse()) {
            try {
                Timestamp createTime = input.getResponse().unpack(Database.class).getCreateTime();
                if (Timestamp.getDefaultInstance().equals(createTime)) {
                    // method to indicate that there is no known create time.
                    return null;
                }
            } catch (InvalidProtocolBufferException e) {
                return null;
            }
        }
        return null;
    });
    return RetryHelper.runWithRetries(callable, databaseAdminStubSettings.createDatabaseOperationSettings().getInitialCallSettings().getRetrySettings(), new OperationFutureRetryAlgorithm<>(), NanoClock.getDefaultClock());
}
Also used : CreateDatabaseRequest(com.google.spanner.admin.database.v1.CreateDatabaseRequest) Database(com.google.spanner.admin.database.v1.Database) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) CreateDatabaseMetadata(com.google.spanner.admin.database.v1.CreateDatabaseMetadata) Timestamp(com.google.protobuf.Timestamp)

Example 40 with Database

use of com.google.spanner.admin.database.v1.Database in project java-spanner by googleapis.

the class GapicSpannerRpc method listDatabases.

@Override
public Paginated<Database> listDatabases(String instanceName, int pageSize, @Nullable String pageToken) throws SpannerException {
    acquireAdministrativeRequestsRateLimiter();
    ListDatabasesRequest.Builder requestBuilder = ListDatabasesRequest.newBuilder().setParent(instanceName).setPageSize(pageSize);
    if (pageToken != null) {
        requestBuilder.setPageToken(pageToken);
    }
    final ListDatabasesRequest request = requestBuilder.build();
    final GrpcCallContext context = newCallContext(null, instanceName, request, DatabaseAdminGrpc.getListDatabasesMethod());
    ListDatabasesResponse response = runWithRetryOnAdministrativeRequestsExceeded(() -> get(databaseAdminStub.listDatabasesCallable().futureCall(request, context)));
    return new Paginated<>(response.getDatabasesList(), response.getNextPageToken());
}
Also used : GrpcCallContext(com.google.api.gax.grpc.GrpcCallContext) ListDatabasesRequest(com.google.spanner.admin.database.v1.ListDatabasesRequest) ListDatabasesResponse(com.google.spanner.admin.database.v1.ListDatabasesResponse)

Aggregations

Test (org.junit.Test)53 CreateDatabaseMetadata (com.google.spanner.admin.database.v1.CreateDatabaseMetadata)32 Database (com.google.cloud.spanner.Database)31 ArrayList (java.util.ArrayList)25 AbstractMessage (com.google.protobuf.AbstractMessage)24 ExecutionException (java.util.concurrent.ExecutionException)22 Database (com.google.spanner.admin.database.v1.Database)21 Operation (com.google.longrunning.Operation)18 ByteString (com.google.protobuf.ByteString)16 DatabaseAdminClient (com.google.cloud.spanner.DatabaseAdminClient)13 SpannerException (com.google.cloud.spanner.SpannerException)12 Database (org.molgenis.emx2.Database)12 CreateBackupMetadata (com.google.spanner.admin.database.v1.CreateBackupMetadata)11 DatabaseName (com.google.spanner.admin.database.v1.DatabaseName)10 RestoreDatabaseMetadata (com.google.spanner.admin.database.v1.RestoreDatabaseMetadata)9 Timestamp (com.google.cloud.Timestamp)8 Spanner (com.google.cloud.spanner.Spanner)8 RestoreDatabaseRequest (com.google.spanner.admin.database.v1.RestoreDatabaseRequest)7 UpdateDatabaseDdlMetadata (com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata)7 StatusRuntimeException (io.grpc.StatusRuntimeException)7