Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add JSON type support #1799

Merged
merged 6 commits into from
Jan 27, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions google-cloud-bigquery/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@
<groupId>org.threeten</groupId>
<artifactId>threetenbp</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
<artifactId>json</artifactId>
</dependency>

<!-- auto-value creates a class that uses an annotation from error_prone_annotations -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ public LegacySQLTypeName apply(String constant) {
/** A record type with a nested schema. */
public static final LegacySQLTypeName RECORD =
type.createAndRegister("RECORD").setStandardType(StandardSQLTypeName.STRUCT);
/** Represents JSON data */
public static final LegacySQLTypeName JSON =
type.createAndRegister("JSON").setStandardType(StandardSQLTypeName.JSON);

private static Map<StandardSQLTypeName, LegacySQLTypeName> standardToLegacyMap = new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.json.JSONObject;
import org.threeten.bp.Instant;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;
Expand All @@ -61,6 +62,7 @@
* <li>Float: StandardSQLTypeName.FLOAT64
* <li>BigDecimal: StandardSQLTypeName.NUMERIC
* <li>BigNumeric: StandardSQLTypeName.BIGNUMERIC
* <li>JSON: StandardSQLTypeName.JSON
* </ul>
*
* <p>No other types are supported through that entry point. The other types can be created by
Expand Down Expand Up @@ -254,6 +256,22 @@ public static QueryParameterValue string(String value) {
return of(value, StandardSQLTypeName.STRING);
}

/**
* Creates a {@code QueryParameterValue} object with a type of JSON. Currently, this is only
* supported in INSERT, not in query as a filter
*/
public static QueryParameterValue json(String value) {
return of(value, StandardSQLTypeName.JSON);
}

/**
* Creates a {@code QueryParameterValue} object with a type of JSON. Currently, this is only
* supported in INSERT, not in query as a filter
*/
public static QueryParameterValue json(JSONObject value) {
return of(value, StandardSQLTypeName.JSON);
}

/** Creates a {@code QueryParameterValue} object with a type of BYTES. */
public static QueryParameterValue bytes(byte[] value) {
return of(value, StandardSQLTypeName.BYTES);
Expand Down Expand Up @@ -347,6 +365,10 @@ private static <T> StandardSQLTypeName classToType(Class<T> type) {
return StandardSQLTypeName.NUMERIC;
} else if (Date.class.isAssignableFrom(type)) {
return StandardSQLTypeName.DATE;
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
} else if (String.class.isAssignableFrom(type)) {
return StandardSQLTypeName.JSON;
} else if (JSONObject.class.isAssignableFrom(type)) {
return StandardSQLTypeName.JSON;
}
throw new IllegalArgumentException("Unsupported object type for QueryParameter: " + type);
}
Expand Down Expand Up @@ -384,6 +406,9 @@ private static <T> String valueToStringOrNull(T value, StandardSQLTypeName type)
break;
case STRING:
return value.toString();
case JSON:
if (value instanceof String || value instanceof JSONObject) return value.toString();
break;
case STRUCT:
throw new IllegalArgumentException("Cannot convert STRUCT to String value");
case ARRAY:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,7 @@ public enum StandardSQLTypeName {
/** Represents a year, month, day, hour, minute, second, and subsecond (microsecond precision). */
DATETIME,
/** Represents a set of geographic points, represented as a Well Known Text (WKT) string. */
GEOGRAPHY
GEOGRAPHY,
/** Represents JSON data */
JSON
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.threeten.bp.Instant;
Expand Down Expand Up @@ -193,6 +194,23 @@ public void testString() {
assertThat(value.getArrayValues()).isNull();
}

@Test
public void testJson() {
QueryParameterValue value =
QueryParameterValue.json("{\"class\" : {\"students\" : [{\"name\" : \"Jane\"}]}}");
JSONObject jsonObject = new JSONObject().put("class", "student");
QueryParameterValue value1 = QueryParameterValue.json(jsonObject);
assertThat(value.getValue())
.isEqualTo("{\"class\" : {\"students\" : [{\"name\" : \"Jane\"}]}}");
assertThat(value1.getValue()).isEqualTo("{\"class\":\"student\"}");
assertThat(value.getType()).isEqualTo(StandardSQLTypeName.JSON);
assertThat(value1.getType()).isEqualTo(StandardSQLTypeName.JSON);
assertThat(value.getArrayType()).isNull();
assertThat(value1.getArrayType()).isNull();
assertThat(value.getArrayValues()).isNull();
assertThat(value1.getArrayType()).isNull();
}

@Test
public void testBytes() {
QueryParameterValue value = QueryParameterValue.bytes(new byte[] {1, 3});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
Expand Down Expand Up @@ -707,6 +708,88 @@ public void testCreateTableWithRangePartitioning() {
}
}

@Test
public void testJsonType() throws InterruptedException {
String tableName = "test_create_table_jsontype";
TableId tableId = TableId.of(DATASET, tableName);
Schema schema = Schema.of(Field.of("jsonField", StandardSQLTypeName.JSON));
StandardTableDefinition standardTableDefinition = StandardTableDefinition.of(schema);
try {
// Create a table with a JSON column
Table createdTable = bigquery.create(TableInfo.of(tableId, standardTableDefinition));
assertNotNull(createdTable);

// Insert 4 rows of JSON data into the JSON column
Map<String, Object> jsonRow1 =
Collections.singletonMap(
"jsonField", "{\"student\" : {\"name\" : \"Jane\", \"id\": 10}}");
Map<String, Object> jsonRow2 =
Collections.singletonMap("jsonField", "{\"student\" : {\"name\" : \"Joy\", \"id\": 11}}");
Map<String, Object> jsonRow3 =
Collections.singletonMap(
"jsonField", "{\"student\" : {\"name\" : \"Alice\", \"id\": 12}}");
Map<String, Object> jsonRow4 =
Collections.singletonMap(
"jsonField", "{\"student\" : {\"name\" : \"Bijoy\", \"id\": 14}}");
InsertAllRequest request =
InsertAllRequest.newBuilder(tableId)
.addRow(jsonRow1)
.addRow(jsonRow2)
.addRow(jsonRow3)
.addRow(jsonRow4)
.build();
InsertAllResponse response = bigquery.insertAll(request);
assertFalse(response.hasErrors());
assertEquals(0, response.getInsertErrors().size());

// Query the JSON column with string positional query parameter
String sql =
"SELECT jsonField.class.student.id FROM "
+ tableId.getTable()
+ " WHERE JSON_VALUE(jsonField, \"$.class.student.name\") = ? ";
QueryParameterValue stringParameter = QueryParameterValue.string("Jane");
QueryJobConfiguration queryJobConfiguration =
QueryJobConfiguration.newBuilder(sql)
.setDefaultDataset(DatasetId.of(DATASET))
.setUseLegacySql(false)
.addPositionalParameter(stringParameter)
.build();
TableResult result = bigquery.query(queryJobConfiguration);
for (FieldValueList values : result.iterateAll()) {
assertEquals("10", values.get(0).getValue());
}

// Insert another JSON row parsed from a String with json positional query parameter
String dml = "INSERT INTO " + tableId.getTable() + " (jsonField) VALUES(?)";
QueryParameterValue jsonParameter =
QueryParameterValue.json("{\"class\" : {\"student\" : [{\"name\" : \"Amy\"}]}}");
QueryJobConfiguration dmlQueryJobConfiguration =
QueryJobConfiguration.newBuilder(dml)
.setDefaultDataset(DatasetId.of(DATASET))
.setUseLegacySql(false)
.addPositionalParameter(jsonParameter)
.build();
bigquery.query(dmlQueryJobConfiguration);
Page<FieldValueList> rows = bigquery.listTableData(tableId);
assertEquals(5, Iterables.size(rows.getValues()));

// Insert another JSON row parsed from a JsonObject with json positional query parameter
JSONObject jsonObject = new JSONObject().put("class", "student");
QueryParameterValue jsonParameter1 = QueryParameterValue.json(jsonObject);
QueryJobConfiguration dmlQueryJobConfiguration1 =
QueryJobConfiguration.newBuilder(dml)
.setDefaultDataset(DatasetId.of(DATASET))
.setUseLegacySql(false)
.addPositionalParameter(jsonParameter1)
.build();
bigquery.query(dmlQueryJobConfiguration1);
Page<FieldValueList> rows1 = bigquery.listTableData(tableId);
assertEquals(6, Iterables.size(rows1.getValues()));
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
} finally {
assertTrue(bigquery.delete(tableId));
}
}

@Test
public void testCreateTableWithConstraints() {
String tableName = "test_create_table_with_constraints";
Expand Down
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@
<version>${google-api-services-bigquery.version}</version>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>

<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
Expand Down