Skip to content

Commit 7be4df1

Browse files
rajatbhattaarpan14gcf-owl-bot[bot]
authored
samples: add support for BatchWriteAtLeastOnce (#2506)
* samples: add support for BatchWriteAtleastOnce * samples: add support for BatchWriteAtleastOnce * samples: add support for BatchWriteAtleastOnce * modify sample based on new design * remove host * chore: review comments. * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * chore: fix review comments. --------- Co-authored-by: Arpan Mishra <[email protected]> Co-authored-by: Arpan Mishra <[email protected]> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent e8ed980 commit 7be4df1

File tree

3 files changed

+196
-0
lines changed

3 files changed

+196
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-spanner/tree/
270270
| Async Runner Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/AsyncRunnerExample.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/AsyncRunnerExample.java) |
271271
| Async Transaction Manager Example | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/AsyncTransactionManagerExample.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/AsyncTransactionManagerExample.java) |
272272
| Batch Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/BatchSample.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/BatchSample.java) |
273+
| Batch Write At Least Once Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/BatchWriteAtLeastOnceSample.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/BatchWriteAtLeastOnceSample.java) |
273274
| Copy Backup Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/CopyBackupSample.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/CopyBackupSample.java) |
274275
| Create Backup With Encryption Key | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/CreateBackupWithEncryptionKey.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/CreateBackupWithEncryptionKey.java) |
275276
| Create Database With Default Leader Sample | [source code](https://github.com/googleapis/java-spanner/blob/main/samples/snippets/src/main/java/com/example/spanner/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/CreateDatabaseWithDefaultLeaderSample.java) |
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
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;
18+
19+
// [START spanner_batch_write_at_least_once]
20+
21+
import com.google.api.gax.rpc.ServerStream;
22+
import com.google.cloud.spanner.DatabaseClient;
23+
import com.google.cloud.spanner.DatabaseId;
24+
import com.google.cloud.spanner.Mutation;
25+
import com.google.cloud.spanner.MutationGroup;
26+
import com.google.cloud.spanner.Options;
27+
import com.google.cloud.spanner.Spanner;
28+
import com.google.cloud.spanner.SpannerOptions;
29+
import com.google.common.collect.ImmutableList;
30+
import com.google.rpc.Code;
31+
import com.google.spanner.v1.BatchWriteResponse;
32+
33+
public class BatchWriteAtLeastOnceSample {
34+
35+
/***
36+
* Assume DDL for the underlying database:
37+
* <pre>{@code
38+
* CREATE TABLE Singers (
39+
* SingerId INT64 NOT NULL,
40+
* FirstName STRING(1024),
41+
* LastName STRING(1024),
42+
* ) PRIMARY KEY (SingerId)
43+
*
44+
* CREATE TABLE Albums (
45+
* SingerId INT64 NOT NULL,
46+
* AlbumId INT64 NOT NULL,
47+
* AlbumTitle STRING(1024),
48+
* ) PRIMARY KEY (SingerId, AlbumId),
49+
* INTERLEAVE IN PARENT Singers ON DELETE CASCADE
50+
* }</pre>
51+
*/
52+
53+
private static final MutationGroup MUTATION_GROUP1 =
54+
MutationGroup.of(
55+
Mutation.newInsertOrUpdateBuilder("Singers")
56+
.set("SingerId")
57+
.to(16)
58+
.set("FirstName")
59+
.to("Scarlet")
60+
.set("LastName")
61+
.to("Terry")
62+
.build());
63+
private static final MutationGroup MUTATION_GROUP2 =
64+
MutationGroup.of(
65+
Mutation.newInsertOrUpdateBuilder("Singers")
66+
.set("SingerId")
67+
.to(17)
68+
.set("FirstName")
69+
.to("Marc")
70+
.build(),
71+
Mutation.newInsertOrUpdateBuilder("Singers")
72+
.set("SingerId")
73+
.to(18)
74+
.set("FirstName")
75+
.to("Catalina")
76+
.set("LastName")
77+
.to("Smith")
78+
.build(),
79+
Mutation.newInsertOrUpdateBuilder("Albums")
80+
.set("SingerId")
81+
.to(17)
82+
.set("AlbumId")
83+
.to(1)
84+
.set("AlbumTitle")
85+
.to("Total Junk")
86+
.build(),
87+
Mutation.newInsertOrUpdateBuilder("Albums")
88+
.set("SingerId")
89+
.to(18)
90+
.set("AlbumId")
91+
.to(2)
92+
.set("AlbumTitle")
93+
.to("Go, Go, Go")
94+
.build());
95+
96+
static void batchWriteAtLeastOnce() {
97+
// TODO(developer): Replace these variables before running the sample.
98+
final String projectId = "my-project";
99+
final String instanceId = "my-instance";
100+
final String databaseId = "my-database";
101+
batchWriteAtLeastOnce(projectId, instanceId, databaseId);
102+
}
103+
104+
static void batchWriteAtLeastOnce(String projectId, String instanceId, String databaseId) {
105+
try (Spanner spanner =
106+
SpannerOptions.newBuilder().setProjectId(projectId).build().getService()) {
107+
DatabaseId dbId = DatabaseId.of(projectId, instanceId, databaseId);
108+
final DatabaseClient dbClient = spanner.getDatabaseClient(dbId);
109+
110+
// Creates and issues a BatchWrite RPC request that will apply the mutation groups
111+
// non-atomically and respond back with a stream of BatchWriteResponse.
112+
ServerStream<BatchWriteResponse> responses =
113+
dbClient.batchWriteAtLeastOnce(
114+
ImmutableList.of(MUTATION_GROUP1, MUTATION_GROUP2),
115+
Options.tag("batch-write-tag"));
116+
117+
// Iterates through the results in the stream response and prints the MutationGroup indexes,
118+
// commit timestamp and status.
119+
for (BatchWriteResponse response : responses) {
120+
if (response.getStatus().getCode() == Code.OK_VALUE) {
121+
System.out.printf(
122+
"Mutation group indexes %s have been applied with commit timestamp %s",
123+
response.getIndexesList(), response.getCommitTimestamp());
124+
} else {
125+
System.out.printf(
126+
"Mutation group indexes %s could not be applied with error code %s and "
127+
+ "error message %s", response.getIndexesList(),
128+
Code.forNumber(response.getStatus().getCode()), response.getStatus().getMessage());
129+
}
130+
}
131+
}
132+
}
133+
}
134+
135+
// [END spanner_batch_write_at_least_once]
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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;
18+
19+
import static org.junit.Assert.assertTrue;
20+
21+
import com.google.cloud.spanner.DatabaseId;
22+
import com.google.common.collect.ImmutableList;
23+
import java.util.concurrent.ExecutionException;
24+
import org.junit.Before;
25+
import org.junit.Test;
26+
27+
public class BatchWriteAtLeastOnceSampleIT extends SampleTestBase {
28+
private static String databaseId;
29+
30+
@Before
31+
public void setup() throws ExecutionException, InterruptedException {
32+
databaseId = idGenerator.generateDatabaseId();
33+
databaseAdminClient
34+
.createDatabase(
35+
databaseAdminClient
36+
.newDatabaseBuilder(DatabaseId.of(projectId, instanceId, databaseId))
37+
.build(),
38+
ImmutableList.of(
39+
"CREATE TABLE Singers ("
40+
+ " SingerId INT64 NOT NULL,"
41+
+ " FirstName STRING(1024),"
42+
+ " LastName STRING(1024)"
43+
+ ") PRIMARY KEY (SingerId)",
44+
"CREATE TABLE Albums ("
45+
+ " SingerId INT64 NOT NULL,"
46+
+ " AlbumId INT64 NOT NULL,"
47+
+ " AlbumTitle STRING(1024)"
48+
+ ") PRIMARY KEY (SingerId, AlbumId),"
49+
+ " INTERLEAVE IN PARENT Singers ON DELETE CASCADE"))
50+
.get();
51+
}
52+
53+
@Test
54+
public void testBatchWriteAtLeastOnce() throws Exception {
55+
final String out =
56+
SampleRunner.runSample(() -> BatchWriteAtLeastOnceSample.batchWriteAtLeastOnce(
57+
projectId, instanceId, databaseId));
58+
assertTrue(out.contains("have been applied with commit timestamp"));
59+
}
60+
}

0 commit comments

Comments
 (0)