Java Code Examples for com.google.cloud.spanner.Spanner#getDatabaseClient()

The following examples show how to use com.google.cloud.spanner.Spanner#getDatabaseClient() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void clientWithQueryOptions(DatabaseId db) {
  SpannerOptions options =
      SpannerOptions.newBuilder()
          .setDefaultQueryOptions(
              db, QueryOptions.newBuilder().setOptimizerVersion("1").build())
          .build();
  Spanner spanner = options.getService();
  DatabaseClient dbClient = spanner.getDatabaseClient(db);
  try (ResultSet resultSet =
      dbClient
          .singleUse()
          .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) {
    while (resultSet.next()) {
      System.out.printf(
          "%d %d %s\n", resultSet.getLong(0), resultSet.getLong(1), resultSet.getString(2));
    }
  }
}
 
Example 2
Source File: App.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (!(args.length == 3 || args.length == 4)) {
    printUsageAndExit();
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  try {
    String command = args[0];
    DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
    DatabaseClient dbClient = spanner.getDatabaseClient(db);
    DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
    switch (command) {
      case "create":
        create(dbAdminClient, db);
        break;
      default:
        printUsageAndExit();
    }
  } finally {
    spanner.close();
  }
  System.out.println("Closed client");
}
 
Example 3
Source File: CreateDatabase.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();

  try {

    DatabaseId db = DatabaseId.of(options.getProjectId(), args[0], args[1]);
    // [END init_client]
    // This will return the default project id based on the environment.
    String clientProject = spanner.getOptions().getProjectId();
    if (!db.getInstanceId().getProject().equals(clientProject)) {
      System.err.println("Invalid project specified. Project in the database id should match"
          + "the project name set in the environment variable GCLOUD_PROJECT. Expected: "
          + clientProject);
    }
    // [START init_client]
    DatabaseClient dbClient = spanner.getDatabaseClient(db);
    DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
    createDatabase(dbAdminClient, db);
  } finally {
    spanner.close();
  }
  
}
 
Example 4
Source File: SpannerSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length != 3) {
    printUsageAndExit();
  }
  // [START init_client]
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  try {
    String command = args[0];
    DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
    // [END init_client]
    // This will return the default project id based on the environment.
    String clientProject = spanner.getOptions().getProjectId();
    if (!db.getInstanceId().getProject().equals(clientProject)) {
      System.err.println(
          "Invalid project specified. Project in the database id should match the"
              + "project name set in the environment variable GOOGLE_CLOUD_PROJECT. Expected: "
              + clientProject);
      printUsageAndExit();
    }
    // Generate a backup id for the sample database.
    String backupName =
        String.format(
            "%s_%02d",
            db.getDatabase(), LocalDate.now().get(ChronoField.ALIGNED_WEEK_OF_YEAR));
    BackupId backup = BackupId.of(db.getInstanceId(), backupName);

    // [START init_client]
    DatabaseClient dbClient = spanner.getDatabaseClient(db);
    DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
    InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();
    // Use client here...
    // [END init_client]
    run(dbClient, dbAdminClient, instanceAdminClient, command, db, backup);
  } finally {
    spanner.close();
  }
  // [END init_client]
  System.out.println("Closed client");
}
 
Example 5
Source File: QuickstartSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

    if (args.length != 2) {
      System.err.println("Usage: QuickStartSample <instance_id> <database_id>");
      return;
    }
    // Instantiates a client
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();

    // Name of your instance & database.
    String instanceId = args[0];
    String databaseId = args[1];
    try {
      // Creates a database client
      DatabaseClient dbClient =
          spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
      // Queries the database
      ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));

      System.out.println("\n\nResults:");
      // Prints the results
      while (resultSet.next()) {
        System.out.printf("%d\n\n", resultSet.getLong(0));
      }
    } finally {
      // Closes the client which will free up the resources used
      spanner.close();
    }
  }
 
Example 6
Source File: App.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (!(args.length == 3 || args.length == 4)) {
    printUsageAndExit();
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  try {
    String command = args[0];
    DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
    DatabaseClient dbClient = spanner.getDatabaseClient(db);
    DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
    switch (command) {
      case "create":
        create(dbAdminClient, db);
        break;
      case "insert":
        String insertType;
        try {
          insertType = args[3];
        } catch (ArrayIndexOutOfBoundsException exception) {
          insertType = "";
        }
        insert(dbClient, insertType);
        break;
      default:
        printUsageAndExit();
    }
  } finally {
    spanner.close();
  }
  System.out.println("Closed client");
}
 
Example 7
Source File: DatabaseSelect.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

    if (args.length != 2) {
      System.err.println("Usage: QuickStartSample <instance_id> <database_id>");
      return;
    }
    // Instantiates a client
    SpannerOptions options = SpannerOptions.newBuilder().build();
    Spanner spanner = options.getService();

    // Name of your instance & database.
    String instanceId = args[0];
    String databaseId = args[1];
    try {
      // Creates a database client
      DatabaseClient dbClient =
          spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
      // Queries the database
      try (ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"))) {
        System.out.println("\n\nResults:");
        // Prints the results
        while (resultSet.next()) {
          System.out.printf("%d\n\n", resultSet.getLong(0));
        }
      }
    } finally {
      // Closes the client which will free up the resources used
      spanner.close();
    }
  }
 
Example 8
Source File: SpannerSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
DatabaseClient getDatabaseClient() {
  // [START get_db_client]
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  final String project = "test-project";
  final String instance = "test-instance";
  final String database = "example-db";
  DatabaseId db = DatabaseId.of(project, instance, database);
  DatabaseClient dbClient = spanner.getDatabaseClient(db);
  // [END get_db_client]

  return dbClient;
}
 
Example 9
Source File: ExposedSpannerAccessor.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
public static ExposedSpannerAccessor create(SpannerConfig spannerConfig) {
  SpannerOptions.Builder builder = SpannerOptions.newBuilder();

  ValueProvider<Duration> commitDeadline = spannerConfig.getCommitDeadline();
  if (commitDeadline != null && commitDeadline.get().getMillis() > 0) {

    // In Spanner API version 1.21 or above, we can set the deadline / total Timeout on an API
    // call using the following code:
    //
    // UnaryCallSettings.Builder commitSettings =
    // builder.getSpannerStubSettingsBuilder().commitSettings();
    // RetrySettings.Builder commitRetrySettings = commitSettings.getRetrySettings().toBuilder()
    // commitSettings.setRetrySettings(
    //     commitRetrySettings.setTotalTimeout(
    //         Duration.ofMillis(getCommitDeadlineMillis().get()))
    //     .build());
    //
    // However, at time of this commit, the Spanner API is at only at v1.6.0, where the only
    // method to set a deadline is with GRPC Interceptors, so we have to use that...
    SpannerInterceptorProvider interceptorProvider =
        SpannerInterceptorProvider.createDefault()
            .with(new CommitDeadlineSettingInterceptor(commitDeadline.get()));
    builder.setInterceptorProvider(interceptorProvider);
  }

  ValueProvider<String> projectId = spannerConfig.getProjectId();
  if (projectId != null) {
    builder.setProjectId(projectId.get());
  }
  ServiceFactory<Spanner, SpannerOptions> serviceFactory = spannerConfig.getServiceFactory();
  if (serviceFactory != null) {
    builder.setServiceFactory(serviceFactory);
  }
  ValueProvider<String> host = spannerConfig.getHost();
  if (host != null) {
    builder.setHost(host.get());
  }
  String userAgentString = USER_AGENT_PREFIX + "/" + ReleaseInfo.getReleaseInfo().getVersion();
  builder.setHeaderProvider(FixedHeaderProvider.create("user-agent", userAgentString));

  SessionPoolOptions.Builder sessionPoolOptions = SessionPoolOptions.newBuilder();
  sessionPoolOptions.setMinSessions(1);
  sessionPoolOptions.setMaxSessions(3);
  builder.setSessionPoolOption(sessionPoolOptions.build());

  SpannerOptions options = builder.build();

  Spanner spanner = options.getService();
  String instanceId = spannerConfig.getInstanceId().get();
  String databaseId = spannerConfig.getDatabaseId().get();
  DatabaseClient databaseClient =
      spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
  BatchClient batchClient =
      spanner.getBatchClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
  DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient();

  return new ExposedSpannerAccessor(spanner, databaseClient, databaseAdminClient, batchClient);
}
 
Example 10
Source File: IntegrationTestConfiguration.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
public DatabaseClient spannerDatabaseClient(Spanner spanner, DatabaseId databaseId) {
	return spanner.getDatabaseClient(databaseId);
}
 
Example 11
Source File: SpannerAccessor.java    From beam with Apache License 2.0 4 votes vote down vote up
private static SpannerAccessor createAndConnect(SpannerConfig spannerConfig) {
  SpannerOptions.Builder builder = SpannerOptions.newBuilder();

  ValueProvider<Duration> commitDeadline = spannerConfig.getCommitDeadline();
  if (commitDeadline != null && commitDeadline.get().getMillis() > 0) {

    // Set the GRPC deadline on the Commit API call.
    UnaryCallSettings.Builder commitSettings =
        builder.getSpannerStubSettingsBuilder().commitSettings();
    RetrySettings.Builder commitRetrySettings = commitSettings.getRetrySettings().toBuilder();
    commitSettings.setRetrySettings(
        commitRetrySettings
            .setTotalTimeout(org.threeten.bp.Duration.ofMillis(commitDeadline.get().getMillis()))
            .setMaxRpcTimeout(org.threeten.bp.Duration.ofMillis(commitDeadline.get().getMillis()))
            .setInitialRpcTimeout(
                org.threeten.bp.Duration.ofMillis(commitDeadline.get().getMillis()))
            .build());
  }

  ValueProvider<String> projectId = spannerConfig.getProjectId();
  if (projectId != null) {
    builder.setProjectId(projectId.get());
  }
  ServiceFactory<Spanner, SpannerOptions> serviceFactory = spannerConfig.getServiceFactory();
  if (serviceFactory != null) {
    builder.setServiceFactory(serviceFactory);
  }
  ValueProvider<String> host = spannerConfig.getHost();
  if (host != null) {
    builder.setHost(host.get());
  }
  String userAgentString = USER_AGENT_PREFIX + "/" + ReleaseInfo.getReleaseInfo().getVersion();
  builder.setHeaderProvider(FixedHeaderProvider.create("user-agent", userAgentString));
  SpannerOptions options = builder.build();

  Spanner spanner = options.getService();
  String instanceId = spannerConfig.getInstanceId().get();
  String databaseId = spannerConfig.getDatabaseId().get();
  DatabaseClient databaseClient =
      spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
  BatchClient batchClient =
      spanner.getBatchClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
  DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient();

  return new SpannerAccessor(
      spanner, databaseClient, databaseAdminClient, batchClient, spannerConfig);
}
 
Example 12
Source File: TracingSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length != 2) {
    System.err.println("Usage: TracingSample <instance_id> <database_id>");
    return;
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();

  // Installs a handler for /tracez page.
  ZPageHandlers.startHttpServerAndRegisterAll(8080);
  // Installs an exporter for stack driver traces.
  StackdriverExporter.createAndRegister();
  Tracing.getExportComponent()
      .getSampledSpanStore()
      .registerSpanNamesForCollection(Arrays.asList(SAMPLE_SPAN));

  // Installs an exporter for stack driver stats.
  StackdriverStatsExporter.createAndRegister();
  RpcViews.registerAllCumulativeViews();

  // Name of your instance & database.
  String instanceId = args[0];
  String databaseId = args[1];
  try {
    // Creates a database client
    DatabaseClient dbClient =
        spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
    // Queries the database
    try (Scope ss =
        Tracing.getTracer()
            .spanBuilderWithExplicitParent(SAMPLE_SPAN, null)
            .setSampler(Samplers.alwaysSample())
            .startScopedSpan()) {
      ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));

      System.out.println("\n\nResults:");
      // Prints the results
      while (resultSet.next()) {
        System.out.printf("%d\n\n", resultSet.getLong(0));
      }
    }
  } finally {
    // Closes the client which will free up the resources used
    spanner.close();
  }
}
 
Example 13
Source File: App.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (!(args.length == 3 || args.length == 4)) {
    printUsageAndExit();
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  try {
    String command = args[0];
    DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
    DatabaseClient dbClient = spanner.getDatabaseClient(db);
    DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
    switch (command) {
      case "create":
        create(dbAdminClient, db);
        break;
      case "insert":
        String insertType;
        try {
          insertType = args[3];
        } catch (ArrayIndexOutOfBoundsException exception) {
          insertType = "";
        }
        insert(dbClient, insertType);
        break;
      case "query":
        if (args.length == 4) {
          int timespan = 0;
          try {
            timespan = Integer.parseInt(args[3]);
          } catch (NumberFormatException e) {
            System.err.println("query command's 'timespan' parameter must be a valid integer.");
            System.exit(1);
          }
          query(dbClient, timespan);
        } else {
          query(dbClient);
        }
        break;
      case "delete":
        delete(dbAdminClient, db);
        break;
      default:
        printUsageAndExit();
    }
  } finally {
    spanner.close();
  }
  System.out.println("Closed client");
}
 
Example 14
Source File: App.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (!(args.length == 3 || args.length == 4)) {
    printUsageAndExit();
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  try {
    String command = args[0];
    DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
    DatabaseClient dbClient = spanner.getDatabaseClient(db);
    DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
    switch (command) {
      case "create":
        create(dbAdminClient, db);
        break;
      case "insert":
        String insertType;
        try {
          insertType = args[3];
        } catch (ArrayIndexOutOfBoundsException exception) {
          insertType = "";
        }
        insert(dbClient, insertType);
        break;
      case "query":
        if (args.length == 4) {
          int timespan = 0;
          try {
            timespan = Integer.parseInt(args[3]);
          } catch (NumberFormatException e) {
            System.err.println("query command's 'timespan' parameter must be a valid integer.");
            System.exit(1);
          }
          query(dbClient, timespan);
        } else {
          query(dbClient);
        }
        break;
      default:
        printUsageAndExit();
    }
  } finally {
    spanner.close();
  }
  System.out.println("Closed client");
}