com.google.cloud.spanner.SpannerOptions Java Examples

The following examples show how to use com.google.cloud.spanner.SpannerOptions. 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: Poller.java    From spanner-event-exporter with Apache License 2.0 6 votes vote down vote up
private DatabaseClient configureDb() {
  final SpannerOptions options = SpannerOptions.newBuilder().build();
  spanner = options.getService();
  final DatabaseId db = DatabaseId.of(PROJECT_ID, instanceName, dbName);
  final String clientProject = spanner.getOptions().getProjectId();

  if (!db.getInstanceId().getProject().equals(clientProject)) {
    log.error(
        "Invalid project specified. Project in the database id should match"
            + "the project name set in the environment variable GCLOUD_PROJECT. Expected: "
            + clientProject);

    stop();
    System.exit(1);
  }

  final DatabaseClient dbClient = spanner.getDatabaseClient(db);

  return dbClient;
}
 
Example #2
Source File: HelloSpanner.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
DatabaseClient get() throws Throwable {
  if (!initialized) {
    synchronized (lock) {
      if (!initialized) {
        try {
          DatabaseId db =
              DatabaseId.of(
                  SpannerOptions.getDefaultProjectId(),
                  SPANNER_INSTANCE_ID,
                  SPANNER_DATABASE_ID);
          client = createSpanner().getDatabaseClient(db);
        } catch (Throwable t) {
          error = t;
        }
        initialized = true;
      }
    }
  }
  if (error != null) {
    throw error;
  }
  return client;
}
 
Example #3
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 #4
Source File: GcpSpannerAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public SpannerOptions spannerOptions(SessionPoolOptions sessionPoolOptions) {
	Builder builder = SpannerOptions.newBuilder()
			.setProjectId(this.projectId)
			.setHeaderProvider(new UserAgentHeaderProvider(this.getClass()))
			.setCredentials(this.credentials);
	if (this.numRpcChannels >= 0) {
		builder.setNumChannels(this.numRpcChannels);
	}
	if (this.prefetchChunks >= 0) {
		builder.setPrefetchChunks(this.prefetchChunks);
	}
	builder.setSessionPoolOption(sessionPoolOptions);
	return builder.build();
}
 
Example #5
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 #6
Source File: InstanceConfigIT.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@Test
public void testEuropeWestSingleNodeConfig() {
  String credentialsPath = "cloudspanner-emulator-key.json";
  String projectId = "test-project";
  GoogleCredentials credentials = null;
  try {
    credentials = CloudSpannerConnection.getCredentialsFromFile(credentialsPath);
  } catch (IOException e) {
    throw new RuntimeException("Could not read key file " + credentialsPath, e);
  }
  Builder builder = SpannerOptions.newBuilder();
  builder.setProjectId(projectId);
  builder.setCredentials(credentials);
  builder.setHost(CloudSpannerIT.getHost());

  SpannerOptions options = builder.build();
  Spanner spanner = options.getService();

  InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();
  InstanceConfig config = instanceAdminClient.getInstanceConfig("regional-europe-west1");
  assertEquals("regional-europe-west1", config.getId().getInstanceConfig());
  spanner.close();
}
 
Example #7
Source File: CloudSpannerIT.java    From spanner-jdbc with MIT License 6 votes vote down vote up
public CloudSpannerIT() {
  // generate a unique instance id for this test run
  Random rnd = new Random();
  this.instanceId = "test-instance-" + rnd.nextInt(1000000);
  this.credentialsPath = getKeyFile();
  GoogleCredentials credentials = null;
  try {
    credentials = CloudSpannerConnection.getCredentialsFromFile(credentialsPath);
  } catch (IOException e) {
    throw new RuntimeException("Could not read key file " + credentialsPath, e);
  }
  Builder builder = SpannerOptions.newBuilder();
  builder.setProjectId(getProject());
  builder.setCredentials(credentials);
  builder.setHost(getHost());

  SpannerOptions options = builder.build();
  spanner = options.getService();
}
 
Example #8
Source File: JdbcExamplesIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void createTestDatabase() throws Exception {
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  dbClient = spanner.getDatabaseAdminClient();
  if (instanceId == null) {
    Iterator<Instance> iterator =
        spanner.getInstanceAdminClient().listInstances().iterateAll().iterator();
    if (iterator.hasNext()) {
      instanceId = iterator.next().getId().getInstance();
    }
  }
  dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId);
  dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase());
  dbClient.createDatabase(instanceId, databaseId, Collections.emptyList()).get();
  CreateTableExample.createTable(options.getProjectId(), instanceId, databaseId);
}
 
Example #9
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 #10
Source File: SpannerBenchWrapperImpl.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
public SpannerBenchWrapperImpl() {
  SpannerOptions options = SpannerOptions.newBuilder().setProjectId("test-project-id").build();
  spanner = options.getService();

  dbClient =
      spanner.getDatabaseClient(
          DatabaseId.of(options.getProjectId(), "test-instance", "test-db"));
}
 
Example #11
Source File: SpannerReadIT.java    From beam with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  PipelineOptionsFactory.register(SpannerTestPipelineOptions.class);
  options = TestPipeline.testingPipelineOptions().as(SpannerTestPipelineOptions.class);

  project = options.getInstanceProjectId();
  if (project == null) {
    project = options.as(GcpOptions.class).getProject();
  }

  spanner = SpannerOptions.newBuilder().setProjectId(project).build().getService();

  databaseName = generateDatabaseName();

  databaseAdminClient = spanner.getDatabaseAdminClient();

  // Delete database if exists.
  databaseAdminClient.dropDatabase(options.getInstanceId(), databaseName);

  OperationFuture<Database, CreateDatabaseMetadata> op =
      databaseAdminClient.createDatabase(
          options.getInstanceId(),
          databaseName,
          Collections.singleton(
              "CREATE TABLE "
                  + options.getTable()
                  + " ("
                  + "  Key           INT64,"
                  + "  Value         STRING(MAX),"
                  + ") PRIMARY KEY (Key)"));
  op.get();
  makeTestData();
}
 
Example #12
Source File: SpannerWriteIT.java    From beam with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  PipelineOptionsFactory.register(SpannerTestPipelineOptions.class);
  options = TestPipeline.testingPipelineOptions().as(SpannerTestPipelineOptions.class);

  project = options.getInstanceProjectId();
  if (project == null) {
    project = options.as(GcpOptions.class).getProject();
  }

  spanner = SpannerOptions.newBuilder().setProjectId(project).build().getService();

  databaseName = generateDatabaseName();

  databaseAdminClient = spanner.getDatabaseAdminClient();

  // Delete database if exists.
  databaseAdminClient.dropDatabase(options.getInstanceId(), databaseName);

  OperationFuture<Database, CreateDatabaseMetadata> op =
      databaseAdminClient.createDatabase(
          options.getInstanceId(),
          databaseName,
          Collections.singleton(
              "CREATE TABLE "
                  + options.getTable()
                  + " ("
                  + "  Key           INT64,"
                  + "  Value         STRING(MAX) NOT NULL,"
                  + ") PRIMARY KEY (Key)"));
  op.get();
}
 
Example #13
Source File: SpannerClient.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void connect() throws IOException {
  if (INSTANCE_ID == null) {
    if (sc != null) {
      sc.log("environment variable SPANNER_INSTANCE need to be defined.");
    }
    return;
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  PROJECT_ID = options.getProjectId();
  spanner = options.getService();
  databaseAdminClient = spanner.getDatabaseAdminClient();
}
 
Example #14
Source File: SpannerClient.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void connect() throws IOException {
  if (INSTANCE_ID == null) {
    if (sc != null) {
      sc.log("environment variable SPANNER_INSTANCE need to be defined.");
    }
    return;
  }
  SpannerOptions options = SpannerOptions.newBuilder().build();
  PROJECT_ID = options.getProjectId();
  spanner = options.getService();
  databaseAdminClient = spanner.getDatabaseAdminClient();
}
 
Example #15
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs the {@link ClientLibraryOperations} object.
 */
public ClientLibraryOperations() {
  SpannerOptions spannerOptions = SpannerOptions.newBuilder().setProjectId(PROJECT_ID).build();
  this.spanner = spannerOptions.getService();

  this.databaseAdminClient = this.spanner.getDatabaseAdminClient();
  this.databaseClient = this.spanner.getDatabaseClient(
        DatabaseId.of(PROJECT_ID, INSTANCE_NAME, DATABASE_NAME));
}
 
Example #16
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 #17
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 #18
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 #19
Source File: SpannerSampleIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  SpannerOptions options = SpannerOptions.newBuilder().build();
  spanner = options.getService();
  dbClient = spanner.getDatabaseAdminClient();
  dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId);
  dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase());
  dbClient.dropDatabase(
      dbId.getInstanceId().getInstance(), SpannerSample.createRestoredSampleDbId(dbId));
}
 
Example #20
Source File: AppTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  dbClient = spanner.getDatabaseAdminClient();
  dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId);
  dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase());
}
 
Example #21
Source File: SpannerSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
BatchClient getBatchClient() {
  // [START get_batch_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);
  BatchClient batchClient = spanner.getBatchClient(db);
  // [END get_batch_client]

  return batchClient;
}
 
Example #22
Source File: SpannerSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
InstanceAdminClient getInstanceAdminClient() {
  // [START get_instance_admin_client]
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();
  // [END get_instance_admin_client]

  return instanceAdminClient;
}
 
Example #23
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 #24
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 #25
Source File: SpannerSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
DatabaseAdminClient getDatabaseAdminClient() {
  // [START get_dbadmin_client]
  SpannerOptions options = SpannerOptions.newBuilder().build();
  Spanner spanner = options.getService();
  DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();
  // [END get_dbadmin_client]

  return dbAdminClient;
}
 
Example #26
Source File: GcpSpannerEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmulatorAutoConfigurationDisabled() {
	this.contextRunner
			.run(context -> {
				SpannerOptions spannerOptions = context.getBean(SpannerOptions.class);
				assertThat(spannerOptions.getEndpoint()).isEqualTo("spanner.googleapis.com:443");
			});
}
 
Example #27
Source File: GcpSpannerEmulatorAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public SpannerOptions spannerOptions() {
	Assert.notNull(this.properties.getEmulatorHost(), "`spring.cloud.gcp.spanner.emulator-host` must be set.");
	return SpannerOptions.newBuilder()
			.setProjectId(this.properties.getProjectId())
			.setCredentials(NoCredentials.getInstance())
			.setEmulatorHost(this.properties.getEmulatorHost()).build();
}
 
Example #28
Source File: GcpSpannerEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmulatorAutoConfigurationEnabled() {
	this.contextRunner.withPropertyValues("spring.cloud.gcp.spanner.emulator.enabled=true")
			.run(context -> {
				SpannerOptions spannerOptions = context.getBean(SpannerOptions.class);
				assertThat(spannerOptions.getEndpoint()).isEqualTo("localhost:9010");
			});
}
 
Example #29
Source File: GcpSpannerEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmulatorAutoConfigurationEnabledCustomHostPort() {
	this.contextRunner.withPropertyValues("spring.cloud.gcp.spanner.emulator.enabled=true",
			"spring.cloud.gcp.spanner.emulator-host=localhost:9090")
			.run(context -> {
				SpannerOptions spannerOptions = context.getBean(SpannerOptions.class);
				assertThat(spannerOptions.getEndpoint()).isEqualTo("localhost:9090");
			});
}
 
Example #30
Source File: AbstractSpecificIntegrationTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private static void createSpanner() throws IOException {
  // generate a unique instance id for this test run
  Random rnd = new Random();
  instanceId = "test-instance-" + rnd.nextInt(1000000);
  credentialsPath = getKeyFile();
  projectId = getProject();
  GoogleCredentials credentials = CloudSpannerConnection.getCredentialsFromFile(credentialsPath);
  Builder builder = SpannerOptions.newBuilder();
  builder.setProjectId(projectId);
  builder.setCredentials(credentials);
  builder.setHost(getHost());

  SpannerOptions options = builder.build();
  spanner = options.getService();
}