Skip to content

Commit 74a586f

Browse files
arpan14olavloitegcf-owl-bot[bot]
authored
docs: samples and tests for auto-generated createDatabase and createInstance APIs. (#2764)
* fix: prevent illegal negative timeout values into thread sleep() method while retrying exceptions in unit tests. * For details on issue see - #2206 * Fixing lint issues. * chore: adding a few samples with auto-gen clients. * chore: adding integration tests for samples. * chore: fixing the end-point for staging. * chore: modified test for CreateDatabaseWithDefaultLeaderSample. * chore: adding sample and integration test for CreateInstanceSample. * chore: adding license headers. * chore: fix lint errors. * chore: rename file and add sample tags. * chore: address comments. * Update samples/snippets/src/main/java/com/example/spanner/v2/CreateDatabaseWithDefaultLeaderSample.java Co-authored-by: Knut Olav Løite <koloite@gmail.com> * chore: rename file path. * chore: remove admin settings. * chore: address comments. * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Knut Olav Løite <koloite@gmail.com> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 21f5eba commit 74a586f

File tree

11 files changed

+463
-13
lines changed

11 files changed

+463
-13
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,8 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-spanner/tree/
330330
| Update Jsonb Data Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/UpdateJsonbDataSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/UpdateJsonbDataSample.java) |
331331
| Update Numeric Data Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/UpdateNumericDataSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/UpdateNumericDataSample.java) |
332332
| Update Using Dml Returning Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/UpdateUsingDmlReturningSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/UpdateUsingDmlReturningSample.java) |
333+
| Create Database With Default Leader Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/admin/generated/CreateDatabaseWithDefaultLeaderSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/admin/generated/CreateDatabaseWithDefaultLeaderSample.java) |
334+
| Create Instance Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/admin/generated/CreateInstanceExample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-spanner&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/spanner/admin/generated/CreateInstanceExample.java) |
333335

334336

335337

samples/install-without-bom/pom.xml

+3-3
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,9 @@
142142
<version>3.1.2</version>
143143
<configuration>
144144
<systemPropertyVariables>
145-
<spanner.test.instance>spanner-testing-east1</spanner.test.instance>
146-
<spanner.test.instance.mr>spanner-mr-testing</spanner.test.instance.mr>
147-
<spanner.test.instance.config>nam6</spanner.test.instance.config>
145+
<spanner.test.instance>java-client-integration-test</spanner.test.instance>
146+
<spanner.test.instance.mr>java-client-mr-integration-test</spanner.test.instance.mr>
147+
<spanner.test.instance.config>nam15</spanner.test.instance.config>
148148
<spanner.test.key.location>us-east1</spanner.test.key.location>
149149
<spanner.test.key.ring>cmek-test-key-ring</spanner.test.key.ring>
150150
<spanner.test.key.name>cmek-test-key</spanner.test.key.name>

samples/snapshot/pom.xml

+4-3
Original file line numberDiff line numberDiff line change
@@ -141,13 +141,14 @@
141141
<version>3.1.2</version>
142142
<configuration>
143143
<systemPropertyVariables>
144-
<spanner.test.instance>spanner-testing-east1</spanner.test.instance>
145-
<spanner.test.instance.mr>spanner-mr-testing</spanner.test.instance.mr>
146-
<spanner.test.instance.config>nam6</spanner.test.instance.config>
144+
<spanner.test.instance>java-client-integration-test</spanner.test.instance>
145+
<spanner.test.instance.mr>java-client-mr-integration-test</spanner.test.instance.mr>
146+
<spanner.test.instance.config>nam15</spanner.test.instance.config>
147147
<spanner.test.key.location>us-east1</spanner.test.key.location>
148148
<spanner.test.key.ring>cmek-test-key-ring</spanner.test.key.ring>
149149
<spanner.test.key.name>cmek-test-key</spanner.test.key.name>
150150
<spanner.sample.database>mysample</spanner.sample.database>
151+
<spanner.sample.instance>mysample-instance</spanner.sample.instance>
151152
<spanner.quickstart.database>quick-db</spanner.quickstart.database>
152153
</systemPropertyVariables>
153154
</configuration>

samples/snippets/pom.xml

+3-3
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,9 @@
178178
<version>3.1.2</version>
179179
<configuration>
180180
<systemPropertyVariables>
181-
<spanner.test.instance>spanner-testing-east1</spanner.test.instance>
182-
<spanner.test.instance.mr>spanner-mr-testing</spanner.test.instance.mr>
183-
<spanner.test.instance.config>nam6</spanner.test.instance.config>
181+
<spanner.test.instance>java-client-integration-test</spanner.test.instance>
182+
<spanner.test.instance.mr>java-client-mr-integration-test</spanner.test.instance.mr>
183+
<spanner.test.instance.config>nam15</spanner.test.instance.config>
184184
<spanner.test.key.location>us-east1</spanner.test.key.location>
185185
<spanner.test.key.ring>cmek-test-key-ring</spanner.test.key.ring>
186186
<spanner.test.key.name>cmek-test-key</spanner.test.key.name>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright 2023 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.spanner.admin.generated;
18+
19+
//[START spanner_create_database_with_default_leader]
20+
21+
import com.google.cloud.spanner.SpannerException;
22+
import com.google.cloud.spanner.SpannerExceptionFactory;
23+
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
24+
import com.google.common.collect.ImmutableList;
25+
import com.google.spanner.admin.database.v1.CreateDatabaseRequest;
26+
import com.google.spanner.admin.database.v1.Database;
27+
import java.io.IOException;
28+
import java.util.concurrent.ExecutionException;
29+
30+
public class CreateDatabaseWithDefaultLeaderSample {
31+
32+
static void createDatabaseWithDefaultLeader() throws IOException {
33+
// TODO(developer): Replace these variables before running the sample.
34+
final String instanceName = "projects/my-project/instances/my-instance-id";
35+
final String databaseId = "my-database-name";
36+
final String defaultLeader = "my-default-leader";
37+
createDatabaseWithDefaultLeader(instanceName, databaseId, defaultLeader);
38+
}
39+
40+
static void createDatabaseWithDefaultLeader(String instanceName, String databaseId,
41+
String defaultLeader) throws IOException {
42+
DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create();
43+
44+
try {
45+
Database createdDatabase =
46+
databaseAdminClient.createDatabaseAsync(
47+
CreateDatabaseRequest.newBuilder()
48+
.setParent(instanceName)
49+
.setCreateStatement("CREATE DATABASE `" + databaseId + "`")
50+
.addAllExtraStatements(
51+
ImmutableList.of("CREATE TABLE Singers ("
52+
+ " SingerId INT64 NOT NULL,"
53+
+ " FirstName STRING(1024),"
54+
+ " LastName STRING(1024),"
55+
+ " SingerInfo BYTES(MAX)"
56+
+ ") PRIMARY KEY (SingerId)",
57+
"CREATE TABLE Albums ("
58+
+ " SingerId INT64 NOT NULL,"
59+
+ " AlbumId INT64 NOT NULL,"
60+
+ " AlbumTitle STRING(MAX)"
61+
+ ") PRIMARY KEY (SingerId, AlbumId),"
62+
+ " INTERLEAVE IN PARENT Singers ON DELETE CASCADE",
63+
"ALTER DATABASE " + "`" + databaseId + "`"
64+
+ " SET OPTIONS ( default_leader = '" + defaultLeader + "' )"))
65+
.build()).get();
66+
System.out.println("Created database [" + createdDatabase.getName() + "]");
67+
System.out.println("\tDefault leader: " + createdDatabase.getDefaultLeader());
68+
} catch (ExecutionException e) {
69+
// If the operation failed during execution, expose the cause.
70+
throw (SpannerException) e.getCause();
71+
} catch (InterruptedException e) {
72+
// Throw when a thread is waiting, sleeping, or otherwise occupied,
73+
// and the thread is interrupted, either before or during the activity.
74+
throw SpannerExceptionFactory.propagateInterrupt(e);
75+
}
76+
}
77+
}
78+
//[END spanner_create_database_with_default_leader]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* Copyright 2023 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.spanner.admin.generated;
18+
19+
//[START spanner_create_instance]
20+
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
21+
import com.google.spanner.admin.instance.v1.CreateInstanceRequest;
22+
import com.google.spanner.admin.instance.v1.Instance;
23+
import com.google.spanner.admin.instance.v1.InstanceConfigName;
24+
import com.google.spanner.admin.instance.v1.ProjectName;
25+
import java.io.IOException;
26+
import java.util.concurrent.ExecutionException;
27+
28+
class CreateInstanceExample {
29+
30+
static void createInstance() throws IOException {
31+
// TODO(developer): Replace these variables before running the sample.
32+
String projectId = "my-project";
33+
String instanceId = "my-instance";
34+
createInstance(projectId, instanceId);
35+
}
36+
37+
static void createInstance(String projectId, String instanceId) throws IOException {
38+
InstanceAdminClient instanceAdminClient = InstanceAdminClient.create();
39+
40+
// Set Instance configuration.
41+
int nodeCount = 2;
42+
String displayName = "Descriptive name";
43+
44+
// Create an Instance object that will be used to create the instance.
45+
Instance instance =
46+
Instance.newBuilder()
47+
.setDisplayName(displayName)
48+
.setNodeCount(nodeCount)
49+
.setConfig(
50+
InstanceConfigName.of(projectId, "regional-us-central1").toString())
51+
.build();
52+
try {
53+
// Wait for the createInstance operation to finish.
54+
Instance createdInstance = instanceAdminClient.createInstanceAsync(
55+
CreateInstanceRequest.newBuilder()
56+
.setParent(ProjectName.of(projectId).toString())
57+
.setInstanceId(instanceId)
58+
.setInstance(instance)
59+
.build()).get();
60+
System.out.printf("Instance %s was successfully created%n", createdInstance.getName());
61+
} catch (ExecutionException e) {
62+
System.out.printf(
63+
"Error: Creating instance %s failed with error message %s%n",
64+
instance.getName(), e.getMessage());
65+
} catch (InterruptedException e) {
66+
System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
67+
}
68+
}
69+
}
70+
//[END spanner_create_instance]

samples/snippets/src/test/java/com/example/spanner/SampleIdGenerator.java

+20-2
Original file line numberDiff line numberDiff line change
@@ -26,24 +26,38 @@
2626
*/
2727
public class SampleIdGenerator {
2828

29+
private static final int INSTANCE_NAME_MAX_LENGTH = 30;
2930
private static final int DATABASE_NAME_MAX_LENGTH = 30;
3031
private static final int BACKUP_NAME_MAX_LENGTH = 30;
3132
private static final int INSTANCE_CONFIG_ID_MAX_LENGTH = 30;
33+
private final List<String> instanceIds;
3234
private final List<String> databaseIds;
3335
private final List<String> backupIds;
3436
private final List<String> instanceConfigIds;
3537
private final String baseDatabaseId;
3638
private final String baseBackupId;
3739
private final String baseInstanceConfigId;
40+
private final String baseInstanceId;
3841

39-
public SampleIdGenerator(
40-
String baseDatabaseId, String baseBackupId, String baseInstanceConfigId) {
42+
public SampleIdGenerator(String baseDatabaseId, String baseBackupId,
43+
String baseInstanceConfigId, String baseInstanceId) {
4144
this.baseDatabaseId = baseDatabaseId;
4245
this.baseBackupId = baseBackupId;
4346
this.baseInstanceConfigId = baseInstanceConfigId;
47+
this.baseInstanceId = baseInstanceId;
4448
this.databaseIds = new ArrayList<>();
4549
this.backupIds = new ArrayList<>();
4650
this.instanceConfigIds = new ArrayList<>();
51+
this.instanceIds = new ArrayList<>();
52+
}
53+
54+
public String generateInstanceId() {
55+
final String instanceId =
56+
(baseInstanceId + "-" + UUID.randomUUID().toString().replaceAll("-", ""))
57+
.substring(0, INSTANCE_NAME_MAX_LENGTH);
58+
59+
instanceIds.add(instanceId);
60+
return instanceId;
4761
}
4862

4963
public String generateDatabaseId() {
@@ -81,6 +95,10 @@ public List<String> getBackupIds() {
8195
return backupIds;
8296
}
8397

98+
public List<String> getInstanceIds() {
99+
return instanceIds;
100+
}
101+
84102
public List<String> getInstanceConfigIds() {
85103
return instanceConfigIds;
86104
}

samples/snippets/src/test/java/com/example/spanner/SampleTestBase.java

+19-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525

2626
/** Base class for sample integration tests. */
2727
public class SampleTestBase {
28-
28+
private static final String BASE_INSTANCE_ID =
29+
System.getProperty("spanner.sample.instance", "mysample-instance");
2930
private static final String BASE_DATABASE_ID =
3031
System.getProperty("spanner.sample.database", "sampledb");
3132
private static final String BASE_BACKUP_ID = "samplebk";
@@ -56,11 +57,27 @@ public static void beforeClass() {
5657
spanner = options.getService();
5758
databaseAdminClient = spanner.getDatabaseAdminClient();
5859
instanceAdminClient = spanner.getInstanceAdminClient();
59-
idGenerator = new SampleIdGenerator(BASE_DATABASE_ID, BASE_BACKUP_ID, BASE_INSTANCE_CONFIG_ID);
60+
idGenerator = new SampleIdGenerator(
61+
BASE_DATABASE_ID, BASE_BACKUP_ID, BASE_INSTANCE_CONFIG_ID, BASE_INSTANCE_ID);
6062
}
6163

6264
@AfterClass
6365
public static void afterClass() {
66+
for (String instanceId : idGenerator.getInstanceIds()) {
67+
System.out.println("Trying to drop " + instanceId);
68+
try {
69+
// If the database is not found, it is ignored (no exception is thrown)
70+
instanceAdminClient.deleteInstance(instanceId);
71+
} catch (Exception e) {
72+
System.out.println(
73+
"Failed to drop instance "
74+
+ instanceId
75+
+ " due to "
76+
+ e.getMessage()
77+
+ ", skipping...");
78+
}
79+
}
80+
6481
for (String databaseId : idGenerator.getDatabaseIds()) {
6582
System.out.println("Trying to drop " + databaseId);
6683
try {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* Copyright 2023 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.spanner.admin.generated;
18+
19+
import static org.junit.Assert.assertTrue;
20+
21+
import com.example.spanner.SampleRunner;
22+
import com.google.spanner.admin.instance.v1.InstanceConfig;
23+
import com.google.spanner.admin.instance.v1.InstanceName;
24+
import org.junit.Test;
25+
import org.junit.runner.RunWith;
26+
import org.junit.runners.JUnit4;
27+
28+
@RunWith(JUnit4.class)
29+
public class CreateDatabaseWithDefaultLeaderSampleIT extends SampleTestBaseV2 {
30+
31+
@Test
32+
public void testCreateDatabaseWithDefaultLeader() throws Exception {
33+
final String databaseId = idGenerator.generateDatabaseId();
34+
35+
// Finds possible default leader
36+
37+
final String instanceConfigId = instanceAdminClient.getInstance(
38+
InstanceName.of(projectId, multiRegionalInstanceId)).getConfig();
39+
final InstanceConfig config = instanceAdminClient.getInstanceConfig(instanceConfigId);
40+
assertTrue(
41+
"Expected instance config " + instanceConfigId + " to have at least one leader option",
42+
config.getLeaderOptionsCount() > 0
43+
);
44+
final String defaultLeader = config.getLeaderOptions(0);
45+
46+
// Runs sample
47+
final String out = SampleRunner.runSample(() ->
48+
CreateDatabaseWithDefaultLeaderSample.createDatabaseWithDefaultLeader(
49+
getInstanceName(projectId, multiRegionalInstanceId),
50+
databaseId,
51+
defaultLeader
52+
)
53+
);
54+
55+
assertTrue(
56+
"Expected created database to have default leader " + defaultLeader + "."
57+
+ " Output received was " + out,
58+
out.contains("Default leader: " + defaultLeader)
59+
);
60+
}
61+
}

0 commit comments

Comments
 (0)