Skip to content

Commit 64b9431

Browse files
authored
feat: JSON samples for Spanner JDBC (GoogleCloudPlatform#5883)
1 parent d9d8ee2 commit 64b9431

File tree

5 files changed

+228
-1
lines changed

5 files changed

+228
-1
lines changed

spanner/jdbc/pom.xml

+6
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@
4141
<dependency>
4242
<groupId>com.google.cloud</groupId>
4343
<artifactId>google-cloud-spanner-jdbc</artifactId>
44+
<version>2.4.0</version>
45+
</dependency>
46+
<dependency>
47+
<groupId>com.google.cloud</groupId>
48+
<artifactId>google-cloud-spanner</artifactId>
49+
<version>6.12.1</version>
4450
</dependency>
4551
<!--CSV parsing dependencies -->
4652
<dependency>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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.jdbc;
18+
19+
// [START spanner_jdbc_json_create_table]
20+
import java.sql.Connection;
21+
import java.sql.DriverManager;
22+
import java.sql.SQLException;
23+
24+
class JsonCreateTableExample {
25+
static void createTableWithJsonDataType() throws SQLException {
26+
// TODO(developer): Replace these variables before running the sample.
27+
String projectId = "my-project";
28+
String instanceId = "my-instance";
29+
String databaseId = "my-database";
30+
createTableWithJsonDataType(projectId, instanceId, databaseId);
31+
}
32+
33+
static void createTableWithJsonDataType(String projectId, String instanceId, String databaseId)
34+
throws SQLException {
35+
String connectionUrl =
36+
String.format(
37+
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
38+
projectId, instanceId, databaseId);
39+
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
40+
connection
41+
.createStatement()
42+
.execute(
43+
"CREATE TABLE Venues (\n"
44+
+ " VenueId INT64,\n"
45+
+ " VenueDetails JSON\n"
46+
+ ") PRIMARY KEY (VenueId)");
47+
System.out.println("Created table with JSON data type");
48+
}
49+
}
50+
}
51+
// [END spanner_jdbc_json_create_table]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
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.jdbc;
18+
19+
// [START spanner_jdbc_json_insert_data]
20+
import com.google.cloud.spanner.jdbc.JsonType;
21+
import java.sql.Connection;
22+
import java.sql.DriverManager;
23+
import java.sql.PreparedStatement;
24+
import java.sql.SQLException;
25+
import java.util.Arrays;
26+
import java.util.List;
27+
28+
class JsonInsertDataExample {
29+
// Class to contain Venue sample data.
30+
static class Venue {
31+
final long venueId;
32+
final String venueDetails;
33+
34+
Venue(long venueId, String venueDetails) {
35+
this.venueId = venueId;
36+
this.venueDetails = venueDetails;
37+
}
38+
}
39+
40+
static final List<Venue> VENUES =
41+
Arrays.asList(
42+
new Venue(
43+
4,
44+
"[{\"name\":\"room 1\",\"open\":\"true\"},"
45+
+ "{\"name\":\"room 2\",\"open\":\"false\"}]"),
46+
new Venue(19, "{\"rating\":\"9\",\"open\":\"true\"}"),
47+
new Venue(
48+
42,
49+
"{\"name\":null,"
50+
+ "\"open\":{\"Monday\":\"true\",\"Tuesday\":\"false\"},"
51+
+ "\"tags\":[\"large\",\"airy\"]}"));
52+
53+
static void insertJsonData() throws SQLException {
54+
// TODO(developer): Replace these variables before running the sample.
55+
String projectId = "my-project";
56+
String instanceId = "my-instance";
57+
String databaseId = "my-database";
58+
insertJsonData(projectId, instanceId, databaseId);
59+
}
60+
61+
static void insertJsonData(String projectId, String instanceId, String databaseId)
62+
throws SQLException {
63+
String connectionUrl =
64+
String.format(
65+
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
66+
projectId, instanceId, databaseId);
67+
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
68+
try (PreparedStatement ps =
69+
connection.prepareStatement("INSERT INTO Venues\n"
70+
+ "(VenueId, VenueDetails)\n"
71+
+ "VALUES\n"
72+
+ "(?, ?)")) {
73+
for (Venue venue : VENUES) {
74+
ps.setLong(1, venue.venueId);
75+
// Tell the JDBC driver that we want to set a JSON value and not a STRING value
76+
// by specifying the JsonType SQL type.
77+
ps.setObject(2, venue.venueDetails, JsonType.INSTANCE);
78+
ps.addBatch();
79+
}
80+
int[] updateCounts = ps.executeBatch();
81+
System.out.printf("Insert counts: %s%n", Arrays.toString(updateCounts));
82+
}
83+
}
84+
}
85+
}
86+
// [END spanner_jdbc_json_insert_data]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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.jdbc;
18+
19+
// [START spanner_jdbc_json_query_data]
20+
import com.google.cloud.spanner.jdbc.JsonType;
21+
import java.sql.Connection;
22+
import java.sql.DriverManager;
23+
import java.sql.PreparedStatement;
24+
import java.sql.ResultSet;
25+
import java.sql.SQLException;
26+
27+
class JsonQueryDataExample {
28+
static void queryJsonData() throws SQLException {
29+
// TODO(developer): Replace these variables before running the sample.
30+
String projectId = "my-project";
31+
String instanceId = "my-instance";
32+
String databaseId = "my-database";
33+
queryJsonData(projectId, instanceId, databaseId);
34+
}
35+
36+
static void queryJsonData(String projectId, String instanceId, String databaseId)
37+
throws SQLException {
38+
String connectionUrl =
39+
String.format(
40+
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
41+
projectId, instanceId, databaseId);
42+
String exampleJson = "{\"rating\": \"9\"}";
43+
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
44+
try (PreparedStatement ps =
45+
connection.prepareStatement(
46+
"SELECT VenueId, VenueDetails\n"
47+
+ "FROM Venues\n"
48+
+ "WHERE JSON_VALUE(VenueDetails, '$.rating') = "
49+
+ "JSON_VALUE(?, '$.rating')")) {
50+
// Instruct the JDBC driver to treat the parameter as JSON and not as a string.
51+
ps.setObject(1, exampleJson, JsonType.INSTANCE);
52+
try (ResultSet resultSet = ps.executeQuery()) {
53+
while (resultSet.next()) {
54+
System.out.printf(
55+
"VenueId: %s, VenueDetails: %s%n",
56+
resultSet.getLong("VenueId"), resultSet.getString("VenueDetails"));
57+
}
58+
}
59+
}
60+
}
61+
}
62+
}
63+
// [END spanner_jdbc_json_query_data]

spanner/jdbc/src/test/java/com/example/spanner/jdbc/JdbcExamplesIT.java

+22-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import com.google.cloud.spanner.connection.ConnectionOptions;
2929
import com.google.cloud.spanner.jdbc.CloudSpannerJdbcConnection;
3030
import java.io.ByteArrayOutputStream;
31-
import java.io.IOException;
3231
import java.io.PrintStream;
3332
import java.math.BigDecimal;
3433
import java.sql.Connection;
@@ -426,6 +425,28 @@ public void transactionWithRetryLoopUsingOnlyJdbc_shouldCommit() throws SQLExcep
426425
assertThat(out).contains("Transaction committed at [");
427426
}
428427

428+
@Test
429+
public void insertAndQueryJsonData_shouldReturnData() throws SQLException {
430+
String out =
431+
runExample(
432+
() ->
433+
JsonCreateTableExample.createTableWithJsonDataType(
434+
ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
435+
assertThat(out).contains("Created table with JSON data type");
436+
out =
437+
runExample(
438+
() ->
439+
JsonInsertDataExample.insertJsonData(
440+
ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
441+
assertThat(out).contains("Insert counts: [1, 1, 1]");
442+
out =
443+
runExample(
444+
() ->
445+
JsonQueryDataExample.queryJsonData(
446+
ServiceOptions.getDefaultProjectId(), instanceId, databaseId));
447+
assertThat(out).contains("VenueId: 19");
448+
}
449+
429450
static String formatForTest(String name) {
430451
return name + "-" + UUID.randomUUID().toString().substring(0, 20);
431452
}

0 commit comments

Comments
 (0)