Skip to content

Commit 4984272

Browse files
samples: add transaction / request tagging samples (#1496)
* samples: add transaction / request tagging samples * fix: fix linting * test: fix tag sample it test * fix: remove hardcoded project * chore: fix comments Co-authored-by: Knut Olav Løite <[email protected]> * chore: fix table definition Co-authored-by: Knut Olav Løite <[email protected]> Co-authored-by: Knut Olav Løite <[email protected]>
1 parent cde8718 commit 4984272

File tree

2 files changed

+211
-0
lines changed

2 files changed

+211
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/*
2+
* Copyright 2021 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 com.google.cloud.spanner.DatabaseClient;
20+
import com.google.cloud.spanner.Options;
21+
import com.google.cloud.spanner.ResultSet;
22+
import com.google.cloud.spanner.Statement;
23+
24+
/**
25+
* Sample showing how to add transaction and query tags to Cloud Spanner operations.
26+
*/
27+
public class TagSample {
28+
29+
// [START spanner_set_transaction_tag]
30+
static void setTransactionTag(DatabaseClient databaseClient) {
31+
// Sets the transaction tag to "app=concert,env=dev".
32+
// This transaction tag will be applied to all the individual operations inside this
33+
// transaction.
34+
databaseClient
35+
.readWriteTransaction(Options.tag("app=concert,env=dev"))
36+
.run(transaction -> {
37+
// Sets the request tag to "app=concert,env=dev,action=update".
38+
// This request tag will only be set on this request.
39+
transaction.executeUpdate(
40+
Statement.of("UPDATE Venues"
41+
+ " SET Capacity = CAST(Capacity/4 AS INT64)"
42+
+ " WHERE OutdoorVenue = false"),
43+
Options.tag("app=concert,env=dev,action=update"));
44+
System.out.println("Venue capacities updated.");
45+
46+
Statement insertStatement = Statement.newBuilder(
47+
"INSERT INTO Venues"
48+
+ " (VenueId, VenueName, Capacity, OutdoorVenue, LastUpdateTime)"
49+
+ " VALUES ("
50+
+ " @venueId, @venueName, @capacity, @outdoorVenue, PENDING_COMMIT_TIMESTAMP()"
51+
+ " )")
52+
.bind("venueId")
53+
.to(81)
54+
.bind("venueName")
55+
.to("Venue 81")
56+
.bind("capacity")
57+
.to(1440)
58+
.bind("outdoorVenue")
59+
.to(true)
60+
.build();
61+
62+
// Sets the request tag to "app=concert,env=dev,action=insert".
63+
// This request tag will only be set on this request.
64+
transaction.executeUpdate(
65+
insertStatement,
66+
Options.tag("app=concert,env=dev,action=insert"));
67+
System.out.println("New venue inserted.");
68+
69+
return null;
70+
});
71+
}
72+
// [END spanner_set_transaction_tag]
73+
74+
// [START spanner_set_request_tag]
75+
static void setRequestTag(DatabaseClient databaseClient) {
76+
// Sets the request tag to "app=concert,env=dev,action=select".
77+
// This request tag will only be set on this request.
78+
try (ResultSet resultSet = databaseClient
79+
.singleUse()
80+
.executeQuery(
81+
Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"),
82+
Options.tag("app=concert,env=dev,action=select"))) {
83+
while (resultSet.next()) {
84+
System.out.printf(
85+
"SingerId: %d, AlbumId: %d, AlbumTitle: %s\n",
86+
resultSet.getLong(0),
87+
resultSet.getLong(1),
88+
resultSet.getString(2));
89+
}
90+
}
91+
}
92+
// [END spanner_set_request_tag]
93+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
/*
2+
* Copyright 2021 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 com.example.spanner.SampleRunner.runSample;
20+
import static org.junit.Assert.assertEquals;
21+
import static org.junit.Assert.assertTrue;
22+
23+
import com.google.cloud.spanner.DatabaseClient;
24+
import com.google.cloud.spanner.DatabaseId;
25+
import com.google.cloud.spanner.KeySet;
26+
import com.google.cloud.spanner.Mutation;
27+
import com.google.common.collect.ImmutableList;
28+
import java.util.Arrays;
29+
import java.util.Collections;
30+
import java.util.concurrent.TimeUnit;
31+
import org.junit.After;
32+
import org.junit.Before;
33+
import org.junit.BeforeClass;
34+
import org.junit.Test;
35+
import org.junit.runner.RunWith;
36+
import org.junit.runners.JUnit4;
37+
38+
/**
39+
* Integration tests for {@link TagSample}
40+
*/
41+
@RunWith(JUnit4.class)
42+
public class TagSampleIT extends SampleTestBase {
43+
44+
private static DatabaseId databaseId;
45+
46+
@BeforeClass
47+
public static void createTestDatabase() throws Exception {
48+
final String database = idGenerator.generateDatabaseId();
49+
databaseAdminClient
50+
.createDatabase(
51+
instanceId,
52+
database,
53+
ImmutableList.of(
54+
"CREATE TABLE Albums ("
55+
+ " SingerId INT64 NOT NULL,"
56+
+ " AlbumId INT64,"
57+
+ " AlbumTitle STRING(1024)"
58+
+ ") PRIMARY KEY (SingerId, AlbumId)",
59+
"CREATE TABLE Venues ("
60+
+ " VenueId INT64 NOT NULL,"
61+
+ " VenueName STRING(MAX),"
62+
+ " Capacity INT64,"
63+
+ " OutdoorVenue BOOL,"
64+
+ " LastUpdateTime TIMESTAMP OPTIONS (allow_commit_timestamp=true)"
65+
+ ") PRIMARY KEY (VenueId)"))
66+
.get(10, TimeUnit.MINUTES);
67+
databaseId = DatabaseId.of(projectId, instanceId, database);
68+
}
69+
70+
@Before
71+
public void insertTestData() {
72+
final DatabaseClient client = spanner.getDatabaseClient(databaseId);
73+
client.write(
74+
Arrays.asList(
75+
Mutation.newInsertOrUpdateBuilder("Albums")
76+
.set("SingerId")
77+
.to(1L)
78+
.set("AlbumId")
79+
.to(1L)
80+
.set("AlbumTitle")
81+
.to("title 1")
82+
.build(),
83+
Mutation.newInsertOrUpdateBuilder("Venues")
84+
.set("VenueId")
85+
.to(4L)
86+
.set("VenueName")
87+
.to("name")
88+
.set("Capacity")
89+
.to(4000000)
90+
.set("OutdoorVenue")
91+
.to(false)
92+
.build()));
93+
}
94+
95+
@After
96+
public void removeTestData() {
97+
final DatabaseClient client = spanner.getDatabaseClient(databaseId);
98+
client.write(Collections.singletonList(Mutation.delete("Albums", KeySet.all())));
99+
client.write(Collections.singleton(Mutation.delete("Venues", KeySet.all())));
100+
}
101+
102+
@Test
103+
public void testSetRequestTag() throws Exception {
104+
final DatabaseClient client = spanner.getDatabaseClient(databaseId);
105+
106+
final String out = runSample(() -> TagSample.setRequestTag(client));
107+
assertTrue(out.contains("SingerId: 1, AlbumId: 1, AlbumTitle: title 1"));
108+
}
109+
110+
@Test
111+
public void testSetTransactionTag() throws Exception {
112+
final DatabaseClient client = spanner.getDatabaseClient(databaseId);
113+
114+
final String out = runSample(() -> TagSample.setTransactionTag(client));
115+
assertTrue(out.contains("Venue capacities updated."));
116+
assertTrue(out.contains("New venue inserted."));
117+
}
118+
}

0 commit comments

Comments
 (0)