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 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -61,6 +61,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 +255,14 @@ public static QueryParameterValue string(String value) {
return of(value, StandardSQLTypeName.STRING);
}

/**
* Creates a {@code QueryParameterValue} object with a type of JSON. This is only supported in
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
* 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 BYTES. */
public static QueryParameterValue bytes(byte[] value) {
return of(value, StandardSQLTypeName.BYTES);
Expand Down Expand Up @@ -347,6 +356,8 @@ 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;
}
throw new IllegalArgumentException("Unsupported object type for QueryParameter: " + type);
}
Expand Down Expand Up @@ -384,6 +395,10 @@ private static <T> String valueToStringOrNull(T value, StandardSQLTypeName type)
break;
case STRING:
return value.toString();
case JSON:
if (value instanceof String) {
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
return value.toString();
}
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 @@ -193,6 +193,17 @@ public void testString() {
assertThat(value.getArrayValues()).isNull();
}

@Test
public void testJson() {
QueryParameterValue value =
QueryParameterValue.json("{\"class\" : {\"students\" : [{\"name\" : \"Jane\"}]}}");
assertThat(value.getValue())
.isEqualTo("{\"class\" : {\"students\" : [{\"name\" : \"Jane\"}]}}");
assertThat(value.getType()).isEqualTo(StandardSQLTypeName.JSON);
assertThat(value.getArrayType()).isNull();
assertThat(value.getArrayValues()).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 @@ -707,6 +707,60 @@ 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 data into JSON column
Map<String, Object> jsonRow = new HashMap<>();
jsonRow.put("jsonField", "{\"class\" : {\"students\" : [{\"name\" : \"Jane\"}]}}");
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
InsertAllRequest request = InsertAllRequest.newBuilder(tableId).addRow(jsonRow).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 JSON_VALUE(jsonField, \"$.class.students[0].name\") FROM "
stephaniewang526 marked this conversation as resolved.
Show resolved Hide resolved
+ tableId.getTable()
+ " WHERE JSON_VALUE(jsonField, \"$.class.students[0].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("Jane", values.get(0).getValue());
}

// Add a new JSON row with json positional query parameter
String dml = "INSERT INTO " + tableId.getTable() + " (jsonField) VALUES(?)";
QueryParameterValue jsonParameter =
QueryParameterValue.json("{\"class\" : {\"students\" : [{\"name\" : \"Joy\"}]}}");
QueryJobConfiguration dmlQueryJobConfiguration =
QueryJobConfiguration.newBuilder(dml)
.setDefaultDataset(DatasetId.of(DATASET))
.setUseLegacySql(false)
.addPositionalParameter(jsonParameter)
.build();
bigquery.query(dmlQueryJobConfiguration);
Page<FieldValueList> rows = bigquery.listTableData(tableId);
assertEquals(2, Iterables.size(rows.getValues()));
} finally {
assertTrue(bigquery.delete(tableId));
}
}

@Test
public void testCreateTableWithConstraints() {
String tableName = "test_create_table_with_constraints";
Expand Down