com.google.cloud.spanner.Database Java Examples

The following examples show how to use com.google.cloud.spanner.Database. 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: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void createDatabase(PrintWriter pw)
    throws InterruptedException, ExecutionException {
  Iterable<String> statements =
      Arrays.asList(
          "CREATE TABLE Singers (\n"
              + "  SingerId   INT64 NOT NULL,\n"
              + "  FirstName  STRING(1024),\n"
              + "  LastName   STRING(1024),\n"
              + "  SingerInfo BYTES(MAX)\n"
              + ") PRIMARY KEY (SingerId)",
          "CREATE TABLE Albums (\n"
              + "  SingerId     INT64 NOT NULL,\n"
              + "  AlbumId      INT64 NOT NULL,\n"
              + "  AlbumTitle   STRING(MAX)\n"
              + ") PRIMARY KEY (SingerId, AlbumId),\n"
              + "  INTERLEAVE IN PARENT Singers ON DELETE CASCADE");
  Database db =
      SpannerClient.getDatabaseAdminClient()
          .createDatabase(
              SpannerClient.getInstanceId(), SpannerClient.getDatabaseId(), statements)
          .get();
  pw.println("Created database [" + db.getId() + "]");
}
 
Example #2
Source File: SpannerTasks.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void createDatabase(PrintWriter pw)
    throws InterruptedException, ExecutionException {
  Iterable<String> statements =
      Arrays.asList(
          "CREATE TABLE Singers (\n"
              + "  SingerId   INT64 NOT NULL,\n"
              + "  FirstName  STRING(1024),\n"
              + "  LastName   STRING(1024),\n"
              + "  SingerInfo BYTES(MAX)\n"
              + ") PRIMARY KEY (SingerId)",
          "CREATE TABLE Albums (\n"
              + "  SingerId     INT64 NOT NULL,\n"
              + "  AlbumId      INT64 NOT NULL,\n"
              + "  AlbumTitle   STRING(MAX)\n"
              + ") PRIMARY KEY (SingerId, AlbumId),\n"
              + "  INTERLEAVE IN PARENT Singers ON DELETE CASCADE");
  Database db =
      SpannerClient.getDatabaseAdminClient()
          .createDatabase(
              SpannerClient.getInstanceId(), SpannerClient.getDatabaseId(), statements)
          .get();
  pw.println("Created database [" + db.getId() + "]");
}
 
Example #3
Source File: SpannerDatabaseAdminTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the configured database ID refers to an existing database. False
 * otherwise.
 * @return true if the database exists, and false if it does not.
 */
public boolean databaseExists() {
	for (Database db : this.databaseAdminClient.listDatabases(getInstanceId())
			.getValues()) {
		if (getDatabase().equals(db.getId().getDatabase())) {
			return true;
		}
	}
	return false;
}
 
Example #4
Source File: SpannerDatabaseAdminTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void executeDdlStrings_createsDatabaseIfMissing() throws Exception {
	when(this.mockDatabasePage.getValues()).thenReturn(Arrays.asList(
			new Database(this.databaseId, State.READY, this.databaseAdminClient)));

	OperationFuture<Void, UpdateDatabaseDdlMetadata> mockFuture = mock(OperationFuture.class);
	when(this.databaseAdminClient.updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null)).thenReturn(mockFuture);
	when(mockFuture.get()).thenReturn(null);

	this.spannerDatabaseAdminTemplate.executeDdlStrings(this.ddlList, true);

	verify(this.databaseAdminClient, times(0)).createDatabase("fakeinstance", "fakedb", Arrays.asList("describe Something"));
	verify(this.databaseAdminClient).updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null);
}
 
Example #5
Source File: SpannerDatabaseAdminTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void executeDdlStrings_doesNotCreateDatabaseIfAlreadyPresent() throws Exception {
	when(this.mockDatabasePage.getValues()).thenReturn(Arrays.asList());

	OperationFuture<Database, CreateDatabaseMetadata> mockFuture = mock(OperationFuture.class);
	when(this.databaseAdminClient.createDatabase("fakeinstance", "fakedb", this.ddlList)).thenReturn(mockFuture);
	when(mockFuture.get()).thenReturn(null);

	this.spannerDatabaseAdminTemplate.executeDdlStrings(this.ddlList, true);

	verify(this.databaseAdminClient).createDatabase("fakeinstance", "fakedb", Arrays.asList("describe Something"));
	verify(this.databaseAdminClient, times(0)).updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null);
}
 
Example #6
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 #7
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 #8
Source File: DatabaseAdminClientSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example to getDatabase. */
// [TARGET getDatabase(String, String)]
// [VARIABLE my_instance_id]
// [VARIABLE my_database_id]
public Database getDatabase(String instanceId, String databaseId) {
  // [START getDatabase]
  Database db = dbAdminClient.getDatabase(instanceId, databaseId);
  // [END getDatabase]
  return db;
}
 
Example #9
Source File: DatabaseAdminClientSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example to get the list of Cloud Spanner database in the given instance. */
// [TARGET listDatabases(String, ListOption...)]
// [VARIABLE my_instance_id]
public List<Database> listDatabases(String instanceId) {
  // [START listDatabases]
  Page<Database> page = dbAdminClient.listDatabases(instanceId, Options.pageSize(1));
  List<Database> dbs = new ArrayList<>();
  while (page != null) {
    Database db = Iterables.getOnlyElement(page.getValues());
    dbs.add(db);
    page = page.getNextPage();
  }
  // [END listDatabases]
  return dbs;
}
 
Example #10
Source File: CreateDatabase.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
static void createDatabase(DatabaseAdminClient dbAdminClient, DatabaseId id) {
  Operation<Database, CreateDatabaseMetadata> op = dbAdminClient.createDatabase(
      id.getInstanceId().getInstance(), id.getDatabase(),
      Arrays.asList("CREATE TABLE DPH (\n" + "  subject STRING(MAX) NOT NULL,\n"
          + "  col_0  ARRAY<STRING(MAX)>, \n" + "  col_1  ARRAY<STRING(MAX)>, \n"
          + "  col_2  STRING(MAX), \n" + "  col_3  STRING(MAX), \n" + "  col_4  STRING(MAX), \n"
          + "  col_5  STRING(MAX), \n" + "  col_6  STRING(MAX), \n"
          + "  col_7  ARRAY<STRING(MAX)>, \n" + "  col_8  STRING(MAX), \n"
          + "  col_9  STRING(MAX), \n" + "  col_10  STRING(MAX), \n" + "  col_11  STRING(MAX), \n"
          + "  col_12  STRING(MAX), \n" + "  col_13  STRING(MAX), \n"
          + "  col_14  ARRAY<STRING(MAX)>, \n" + "  col_15  STRING(MAX), \n"
          + "  col_16  STRING(MAX)) \n" + " PRIMARY KEY (subject)"));
  Database db = op.waitFor().getResult();
  System.out.println("Created database [" + db.getId() + "]");
}
 
Example #11
Source File: SpannerGroupWriteIT.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  instanceId = System.getProperty("spanner.test.instance");
  databaseId = "df-spanner-gwrite-it-" + random.nextInt(1000000000);

  spannerOptions = SpannerOptions.getDefaultInstance();
  spanner = spannerOptions.getService();

  DatabaseAdminClient adminClient = spanner.getDatabaseAdminClient();

  try {
    adminClient.dropDatabase(instanceId, databaseId);
  } catch (SpannerException e) {
    // Does not exist, ignore.
  }

  OperationFuture<Database, CreateDatabaseMetadata> op =
      adminClient.createDatabase(
          instanceId,
          databaseId,
          Arrays.asList(
              "CREATE TABLE users ("
                  + "id STRING(MAX) NOT NULL, state STRING(MAX) NOT NULL) PRIMARY KEY (id)",
              "CREATE TABLE PendingReviews (id INT64, action STRING(MAX), "
                  + "note STRING(MAX), userId STRING(MAX),) PRIMARY KEY (id)"));

  op.get();

  DatabaseClient dbClient = getDbClient();

  List<Mutation> mutations = new ArrayList<>();
  for (int i = 0; i < 20; i++) {
    mutations.add(
        Mutation.newInsertBuilder("users")
            .set("id")
            .to(Integer.toString(i))
            .set("state")
            .to("ACTIVE")
            .build());
  }
  TransactionRunner runner = dbClient.readWriteTransaction();
  runner.run(
      new TransactionRunner.TransactionCallable<Void>() {

        @Nullable
        @Override
        public Void run(TransactionContext tx) {
          tx.buffer(mutations);
          return null;
        }
      });

  String content =
      IntStream.range(0, 10).mapToObj(Integer::toString).collect(Collectors.joining("\n"));
  tempPath = Files.createTempFile("suspicious-ids", "txt");
  Files.write(tempPath, content.getBytes());
}
 
Example #12
Source File: SpannerReadIT.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws InterruptedException, ExecutionException {
  instanceId = System.getProperty("spanner.test.instance");
  databaseId = "df-spanner-read-it-" + random.nextInt(1000000000);

  spannerOptions = SpannerOptions.getDefaultInstance();
  spanner = spannerOptions.getService();

  DatabaseAdminClient adminClient = spanner.getDatabaseAdminClient();

  try {
    adminClient.dropDatabase(instanceId, databaseId);
  } catch (SpannerException e) {
    // Does not exist, ignore.
  }

  OperationFuture<Database, CreateDatabaseMetadata> op =
      adminClient.createDatabase(
          instanceId,
          databaseId,
          Arrays.asList(
              "CREATE TABLE Singers "
                  + "(singerId INT64 NOT NULL, firstName STRING(MAX) NOT NULL, "
                  + "lastName STRING(MAX) NOT NULL,) PRIMARY KEY (singerId)",
              "CREATE TABLE Albums (singerId INT64 NOT NULL, albumId INT64 NOT NULL, "
                  + "albumTitle STRING(MAX) NOT NULL,) PRIMARY KEY (singerId, albumId)"));

  op.get();

  List<Mutation> mutations =
      Arrays.asList(
          Mutation.newInsertBuilder("singers")
              .set("singerId")
              .to(1L)
              .set("firstName")
              .to("John")
              .set("lastName")
              .to("Lennon")
              .build(),
          Mutation.newInsertBuilder("singers")
              .set("singerId")
              .to(2L)
              .set("firstName")
              .to("Paul")
              .set("lastName")
              .to("Mccartney")
              .build(),
          Mutation.newInsertBuilder("singers")
              .set("singerId")
              .to(3L)
              .set("firstName")
              .to("George")
              .set("lastName")
              .to("Harrison")
              .build(),
          Mutation.newInsertBuilder("singers")
              .set("singerId")
              .to(4L)
              .set("firstName")
              .to("Ringo")
              .set("lastName")
              .to("Starr")
              .build(),
          Mutation.newInsertBuilder("albums")
              .set("singerId")
              .to(1L)
              .set("albumId")
              .to(1L)
              .set("albumTitle")
              .to("Imagine")
              .build(),
          Mutation.newInsertBuilder("albums")
              .set("singerId")
              .to(2L)
              .set("albumId")
              .to(1L)
              .set("albumTitle")
              .to("Pipes of Peace")
              .build());

  DatabaseClient dbClient = getDbClient();

  TransactionRunner runner = dbClient.readWriteTransaction();
  runner.run(
      new TransactionRunner.TransactionCallable<Void>() {
        @Nullable
        @Override
        public Void run(TransactionContext tx) {
          tx.buffer(mutations);
          return null;
        }
      });
}
 
Example #13
Source File: SpannerWriteIT.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {

  instanceId = System.getProperty("spanner.test.instance");
  databaseId = "df-spanner-write-it-" + random.nextInt(1000000000);

  spannerOptions = SpannerOptions.getDefaultInstance();
  spanner = spannerOptions.getService();

  DatabaseAdminClient adminClient = spanner.getDatabaseAdminClient();

  try {
    adminClient.dropDatabase(instanceId, databaseId);
  } catch (SpannerException e) {
    // Does not exist, ignore.
  }

  OperationFuture<Database, CreateDatabaseMetadata> op =
      adminClient.createDatabase(
          instanceId,
          databaseId,
          Arrays.asList(
              "CREATE TABLE Singers "
                  + "(singerId INT64 NOT NULL, "
                  + "firstName STRING(MAX) NOT NULL, lastName STRING(MAX) NOT NULL,) "
                  + "PRIMARY KEY (singerId)",
              "CREATE TABLE Albums (singerId INT64 NOT NULL, "
                  + "albumId INT64 NOT NULL, albumTitle STRING(MAX) NOT NULL,) "
                  + "PRIMARY KEY (singerId, albumId)"));

  op.get();

  String singers =
      Stream.of("1\tJohn\tLennon", "2\tPaul\tMccartney", "3\tGeorge\tHarrison", "4\tRingo\tStarr")
          .collect(Collectors.joining("\n"));
  singersPath = Files.createTempFile("singers", "txt");
  Files.write(singersPath, singers.getBytes());

  String albums =
      Stream.of("1\t1\tImagine", "2\t1\tPipes of Peace", "3\t1\tDark Horse")
          .collect(Collectors.joining("\n"));
  albumsPath = Files.createTempFile("albums", "txt");
  Files.write(albumsPath, albums.getBytes());
}