com.google.cloud.spanner.Spanner Java Examples

The following examples show how to use com.google.cloud.spanner.Spanner. 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: 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 #2
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 #3
Source File: CloudSpannerDriver.java    From spanner-jdbc with MIT License 6 votes vote down vote up
/**
 * Closes all connections to Google Cloud Spanner that have been opened by this driver during the
 * lifetime of this application. You should call this method when you want to shutdown your
 * application, as this frees up all connections and sessions to Google Cloud Spanner. Failure to
 * do so, will keep sessions open server side and can eventually lead to resource exhaustion. Any
 * open JDBC connection to Cloud Spanner opened by this driver will also be closed by this method.
 * This method is also called automatically in a shutdown hook when the JVM is stopped orderly.
 */
public synchronized void closeSpanner() {
  try {
    for (Entry<Spanner, List<CloudSpannerConnection>> entry : connections.entrySet()) {
      List<CloudSpannerConnection> list = entry.getValue();
      for (CloudSpannerConnection con : list) {
        if (!con.isClosed()) {
          con.rollback();
          con.markClosed();
        }
      }
      entry.getKey().close();
    }
    connections.clear();
    spanners.clear();
  } catch (SQLException e) {
    throw SpannerExceptionFactory.newSpannerException(e);
  }
}
 
Example #4
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 #5
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 #6
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 #7
Source File: FakeServiceFactory.java    From beam with Apache License 2.0 5 votes vote down vote up
public FakeServiceFactory() {
  synchronized (lock) {
    index = count++;
    mockSpanners.add(mock(Spanner.class, withSettings().serializable()));
    mockDatabaseClients.add(mock(DatabaseClient.class, withSettings().serializable()));
    mockBatchClients.add(mock(BatchClient.class, withSettings().serializable()));
  }
  when(mockSpanner().getDatabaseClient(Matchers.any(DatabaseId.class)))
      .thenReturn(mockDatabaseClient());
  when(mockSpanner().getBatchClient(Matchers.any(DatabaseId.class)))
      .thenReturn(mockBatchClient());
}
 
Example #8
Source File: SpannerAccessor.java    From beam with Apache License 2.0 5 votes vote down vote up
private SpannerAccessor(
    Spanner spanner,
    DatabaseClient databaseClient,
    DatabaseAdminClient databaseAdminClient,
    BatchClient batchClient,
    SpannerConfig spannerConfig) {
  this.spanner = spanner;
  this.databaseClient = databaseClient;
  this.databaseAdminClient = databaseAdminClient;
  this.batchClient = batchClient;
  this.spannerConfig = spannerConfig;
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: CloudSpannerDriver.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private Spanner createSpanner(SpannerKey key) {
  Builder builder = SpannerOptions.newBuilder();
  if (key.projectId != null)
    builder.setProjectId(key.projectId);
  if (key.credentials != null)
    builder.setCredentials(key.credentials);
  else if (!hasDefaultCredentials())
    builder.setCredentials(NoCredentials.getInstance());
  if (key.host != null)
    builder.setHost(key.host);
  SpannerOptions options = builder.build();
  return options.getService();
}
 
Example #15
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 #16
Source File: ExportTimestampTest.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
private Ddl readDdl(String db) {
  SpannerOptions spannerOptions = SpannerOptions.newBuilder().build();
  Spanner client = spannerOptions.getService();
  Ddl ddl;
  try (ReadOnlyTransaction ctx = spannerServer.getDbClient(db).readOnlyTransaction()) {
    ddl = new InformationSchemaScanner(ctx).scan();
  }
  return ddl;
}
 
Example #17
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 #18
Source File: ExposedSpannerAccessor.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
private ExposedSpannerAccessor(
    Spanner spanner,
    DatabaseClient databaseClient,
    DatabaseAdminClient databaseAdminClient,
    BatchClient batchClient) {
  this.spanner = spanner;
  this.databaseClient = databaseClient;
  this.databaseAdminClient = databaseAdminClient;
  this.batchClient = batchClient;
}
 
Example #19
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 #20
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 #21
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");
}
 
Example #22
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 #23
Source File: BatchSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * This example showcases how to create a batch client, partition a query, and concurrently read
 * from multiple partitions.
 */
public static void main(String[] args) throws InterruptedException {
  if (args.length != 2) {
    System.err.println("Usage: BatchSample <instance_id> <database_id>");
    return;
  }

  /*
   * CREATE TABLE Singers (
   *   SingerId   INT64 NOT NULL,
   *   FirstName  STRING(1024),
   *   LastName   STRING(1024),
   *   SingerInfo BYTES(MAX),
   * ) PRIMARY KEY (SingerId);
   */

  String instanceId = args[0];
  String databaseId = args[1];

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

  // [START spanner_batch_client]
  int numThreads = Runtime.getRuntime().availableProcessors();
  ExecutorService executor = Executors.newFixedThreadPool(numThreads);

  // Statistics
  int totalPartitions;
  AtomicInteger totalRecords = new AtomicInteger(0);

  try {
    BatchClient batchClient =
        spanner.getBatchClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));

    final BatchReadOnlyTransaction txn =
        batchClient.batchReadOnlyTransaction(TimestampBound.strong());

    // A Partition object is serializable and can be used from a different process.
    List<Partition> partitions =
        txn.partitionQuery(
            PartitionOptions.getDefaultInstance(),
            Statement.of("SELECT SingerId, FirstName, LastName FROM Singers"));

    totalPartitions = partitions.size();

    for (final Partition p : partitions) {
      executor.execute(
          () -> {
            try (ResultSet results = txn.execute(p)) {
              while (results.next()) {
                long singerId = results.getLong(0);
                String firstName = results.getString(1);
                String lastName = results.getString(2);
                System.out.println("[" + singerId + "] " + firstName + " " + lastName);
                totalRecords.getAndIncrement();
              }
            }
          });
    }
  } finally {
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.HOURS);
    spanner.close();
  }

  double avgRecordsPerPartition = 0.0;
  if (totalPartitions != 0) {
    avgRecordsPerPartition = (double) totalRecords.get() / totalPartitions;
  }
  System.out.println("totalPartitions=" + totalPartitions);
  System.out.println("totalRecords=" + totalRecords);
  System.out.println("avgRecordsPerPartition=" + avgRecordsPerPartition);
  // [END spanner_batch_client]
}
 
Example #24
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 #25
Source File: HelloSpanner.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static Spanner createSpanner() {
  return SpannerOptions.newBuilder().build().getService();
}
 
Example #26
Source File: FakeServiceFactory.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public Spanner create(SpannerOptions serviceOptions) {
  return mockSpanner();
}
 
Example #27
Source File: FakeServiceFactory.java    From beam with Apache License 2.0 4 votes vote down vote up
Spanner mockSpanner() {
  synchronized (lock) {
    return mockSpanners.get(index);
  }
}
 
Example #28
Source File: SpannerIO.java    From beam with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
CreateTransaction withServiceFactory(ServiceFactory<Spanner, SpannerOptions> serviceFactory) {
  SpannerConfig config = getSpannerConfig();
  return withSpannerConfig(config.withServiceFactory(serviceFactory));
}
 
Example #29
Source File: GcpSpannerAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public Spanner spanner(SpannerOptions spannerOptions) {
	return spannerOptions.getService();
}
 
Example #30
Source File: LocalSpannerIO.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
Read withServiceFactory(ServiceFactory<Spanner, SpannerOptions> serviceFactory) {
  SpannerConfig config = getSpannerConfig();
  return withSpannerConfig(config.withServiceFactory(serviceFactory));
}