Repository navigation
[WIP] fix(bigquery-jdbc): add bidirectional ProtoSchema codecs and bounds to BigQueryTypeRegistry - #15183
[WIP] fix(bigquery-jdbc): add bidirectional ProtoSchema codecs and bounds to BigQueryTypeRegistry#15183Neenu1995 wants to merge 1 commit into
Conversation
…o BigQueryTypeRegistry Stack: PR 1 of 6 (base: `main`) ### Summary - Extend `TypeDescriptor` and `BigQueryTypeRegistry` with bidirectional Storage Write API support (`ProtoFieldEncoder`, `WriteApiValidator`, and cross-type `writeApiParamTypes`) indexed in `O(1)` via `DESCRIPTORS_BY_ORDINAL` with zero `switch` dispatch, routing `ARRAY`, `STRUCT`, and `RANGE` to SQL DML (`supportsWriteApi() == false`). - Keep Read (`TypeCoercer`) and Write (`ProtoFieldEncoder`) symmetrical inside `BigQueryTypeRegistry`: add `ByteString` read coercion on `BYTES`, `NUMERIC`, and `BIGNUMERIC` plus ZetaSQL packed64 `Long` read coercion on `DATETIME`, share strict `Locale.ROOT` temporal formatters (`DATE_DIGITS`, `TIME_MICROS`, `DATETIME_MICROS`, `formatInstantUtc`) and `extractInstant`, and add `resolveWriteApiColumns` / `encodeWriteApiRow` / `isCompatibleWithWriteApi`. - Enforce `REQUIRED` nullability, `NUMERIC(P, S)` / `BIGNUMERIC(P, S)` precision & scale bounds (with an `O(1)` integer-digit check before `stripTrailingZeros()`/`compareTo()` to prevent extreme negative-scale `BigDecimal` DoS, plus asymmetric `BIGNUMERIC_MIN`), finite `FLOAT64`, and strict `0001..9999` proleptic Gregorian `DATE`/`DATETIME`/`TIMESTAMP` bounds. ### Testing - `make lint`, `mvn -B -ntp dependency:analyze -Pquick-build -DfailOnWarning=true -Dmdep.analyze.skip=false`, `mvn -q -Denforcer.skip=true -Dclirr.skip=true test-compile`, and `make unittest test=BigQueryTypeRegistryTest` (verifying 17-type Write API predicates, 14-type `encodeWriteApiRow` <-> `BigQueryTypeRegistry.convert` symmetry, `TIMESTAMP(12)`, non-ASCII columns, precision/scale/temporal bounds, extreme negative-scale `BigDecimal` DoS guard, and negative error paths).
There was a problem hiding this comment.
Code Review
This pull request introduces support for the BigQuery Storage Write API in the JDBC driver by adding ProtoSchema encoding, validation, and mapping logic for various BigQuery types in BigQueryTypeRegistry and TypeDescriptor, along with comprehensive unit tests. The review feedback highlights several critical improvements: adding support for java.sql.Timestamp when binding DATETIME and DATE parameters to prevent potential NullPointerExceptions and avoid inefficient string parsing; allowing pure java.util.Date instances for TIMESTAMP columns; and implementing an O(1) pre-check in isValidBigDecimalBounds to protect against positive-scale DoS attacks.
| private static LocalDateTime toWriteApiLocalDateTime( | ||
| Object val, StandardSQLTypeName paramSqlType) { | ||
| LocalDateTime ldt = null; | ||
| if (paramSqlType == StandardSQLTypeName.DATETIME && val instanceof LocalDateTime) { | ||
| ldt = ((LocalDateTime) val).truncatedTo(ChronoUnit.MICROS); | ||
| } else if (paramSqlType == StandardSQLTypeName.STRING | ||
| && val instanceof String | ||
| && ((String) val).length() == 26) { | ||
| try { | ||
| ldt = LocalDateTime.parse((String) val, DATETIME_MICROS); | ||
| } catch (DateTimeParseException ignored) { | ||
| return null; | ||
| } | ||
| } | ||
| return ldt != null && ldt.getYear() >= 1 && ldt.getYear() <= 9999 ? ldt : null; | ||
| } |
There was a problem hiding this comment.
In JDBC applications, java.sql.Timestamp is the standard type used to bind DATETIME parameters. Currently, toWriteApiLocalDateTime only supports LocalDateTime and String, which means isCompatibleWithWriteApi will return false for Timestamp values on DATETIME columns. We should add support for java.sql.Timestamp by converting it using .toLocalDateTime().
private static LocalDateTime toWriteApiLocalDateTime(
Object val, StandardSQLTypeName paramSqlType) {
LocalDateTime ldt = null;
if (paramSqlType == StandardSQLTypeName.DATETIME) {
if (val instanceof LocalDateTime) {
ldt = ((LocalDateTime) val).truncatedTo(ChronoUnit.MICROS);
} else if (val instanceof Timestamp) {
ldt = ((Timestamp) val).toLocalDateTime().truncatedTo(ChronoUnit.MICROS);
}
} else if (paramSqlType == StandardSQLTypeName.STRING
&& val instanceof String
&& ((String) val).length() == 26) {
try {
ldt = LocalDateTime.parse((String) val, DATETIME_MICROS);
} catch (DateTimeParseException ignored) {
return null;
}
}
return ldt != null && ldt.getYear() >= 1 && ldt.getYear() <= 9999 ? ldt : null;
}| private static Object encodeDatetimeProto(Object val, FieldDescriptor fd) { | ||
| StandardSQLTypeName pt = | ||
| val instanceof LocalDateTime ? StandardSQLTypeName.DATETIME : StandardSQLTypeName.STRING; | ||
| return CivilTimeEncoder.encodePacked64DatetimeMicrosLocalDateTime( | ||
| Objects.requireNonNull(toWriteApiLocalDateTime(val, pt))); | ||
| } |
There was a problem hiding this comment.
When val is a java.sql.Timestamp, val instanceof LocalDateTime evaluates to false, causing pt to be set to StandardSQLTypeName.STRING. This leads to toWriteApiLocalDateTime(val, STRING) returning null and throwing a NullPointerException during Objects.requireNonNull. We should update the condition to treat Timestamp as StandardSQLTypeName.DATETIME.
private static Object encodeDatetimeProto(Object val, FieldDescriptor fd) {
StandardSQLTypeName pt =
(val instanceof LocalDateTime || val instanceof Timestamp)
? StandardSQLTypeName.DATETIME
: StandardSQLTypeName.STRING;
return CivilTimeEncoder.encodePacked64DatetimeMicrosLocalDateTime(
Objects.requireNonNull(toWriteApiLocalDateTime(val, pt)));
}| private static LocalDate toWriteApiLocalDate(Object val) { | ||
| LocalDate ld = null; | ||
| if (val instanceof LocalDate) { | ||
| ld = (LocalDate) val; | ||
| } else if (val instanceof Date && val.toString().length() == 10) { | ||
| try { | ||
| ld = LocalDate.parse(val.toString(), DATE_DIGITS); | ||
| } catch (DateTimeParseException ignored) { | ||
| return null; | ||
| } | ||
| } | ||
| return ld != null && ld.getYear() >= 1 && ld.getYear() <= 9999 ? ld : null; | ||
| } |
There was a problem hiding this comment.
Using val.toString() and parsing it with DATE_DIGITS introduces unnecessary string formatting and parsing overhead for java.sql.Date. Since Java 8, java.sql.Date provides a direct .toLocalDate() method which is much more efficient. Additionally, we should support java.sql.Timestamp values as they are frequently bound to DATE columns in JDBC applications.
private static LocalDate toWriteApiLocalDate(Object val) {
LocalDate ld = null;
if (val instanceof LocalDate) {
ld = (LocalDate) val;
} else if (val instanceof Date) {
ld = ((Date) val).toLocalDate();
} else if (val instanceof Timestamp) {
ld = ((Timestamp) val).toLocalDateTime().toLocalDate();
}
return ld != null && ld.getYear() >= 1 && ld.getYear() <= 9999 ? ld : null;
}| private static boolean isValidBigDecimalBounds( | ||
| BigDecimal value, boolean numeric, Long columnPrecision, Long columnScale) { | ||
| BigDecimal minValue = numeric ? NUMERIC_MIN : BIGNUMERIC_MIN; | ||
| BigDecimal maxValue = numeric ? NUMERIC_MAX : BIGNUMERIC_MAX; | ||
| int maxScale = | ||
| getColumnTypeInfo(numeric ? StandardSQLTypeName.NUMERIC : StandardSQLTypeName.BIGNUMERIC) | ||
| .decimalDigits; | ||
| long intDigits = | ||
| value.signum() == 0 ? 0L : Math.max(0L, (long) value.precision() - (long) value.scale()); | ||
| if (intDigits > maxValue.precision() - maxValue.scale()) { | ||
| return false; | ||
| } | ||
| BigDecimal normalized = value.signum() == 0 ? BigDecimal.ZERO : value.stripTrailingZeros(); | ||
| if (normalized.scale() > maxScale | ||
| || (columnScale != null && normalized.scale() > columnScale)) { | ||
| return false; | ||
| } | ||
| if (columnPrecision != null) { | ||
| long effectiveScale = columnScale != null ? columnScale : 0L; | ||
| if (normalized.scale() > effectiveScale || intDigits > columnPrecision - effectiveScale) { | ||
| return false; | ||
| } | ||
| } | ||
| return normalized.compareTo(minValue) >= 0 && normalized.compareTo(maxValue) <= 0; | ||
| } |
There was a problem hiding this comment.
While the current implementation guards against negative-scale BigDecimal DoS attacks, it is still vulnerable to positive-scale DoS attacks (e.g., 1e-1000000000) because stripTrailingZeros() will be called on a huge scale. We can add an O(1) pre-check to verify if the minimum possible scale after stripping trailing zeros (scale - precision + 1) exceeds the maximum allowed scale, and return false early.
private static boolean isValidBigDecimalBounds(
BigDecimal value, boolean numeric, Long columnPrecision, Long columnScale) {
BigDecimal minValue = numeric ? NUMERIC_MIN : BIGNUMERIC_MIN;
BigDecimal maxValue = numeric ? NUMERIC_MAX : BIGNUMERIC_MAX;
int maxScale =
getColumnTypeInfo(numeric ? StandardSQLTypeName.NUMERIC : StandardSQLTypeName.BIGNUMERIC)
.decimalDigits;
long intDigits =
value.signum() == 0 ? 0L : Math.max(0L, (long) value.precision() - (long) value.scale());
if (intDigits > maxValue.precision() - maxValue.scale()) {
return false;
}
long limitScale = columnScale != null ? Math.min((long) maxScale, columnScale) : (long) maxScale;
if (value.signum() != 0 && (long) value.scale() - (long) value.precision() + 1L > limitScale) {
return false;
}
BigDecimal normalized = value.signum() == 0 ? BigDecimal.ZERO : value.stripTrailingZeros();
if (normalized.scale() > maxScale
|| (columnScale != null && normalized.scale() > columnScale)) {
return false;
}
if (columnPrecision != null) {
long effectiveScale = columnScale != null ? columnScale : 0L;
if (normalized.scale() > effectiveScale || intDigits > columnPrecision - effectiveScale) {
return false;
}
}
return normalized.compareTo(minValue) >= 0 && normalized.compareTo(maxValue) <= 0;
}| static Instant extractInstant(Object value) { | ||
| if (value instanceof Timestamp) { | ||
| return ((Timestamp) value).toInstant(); | ||
| } | ||
| if (value instanceof Instant) { | ||
| return (Instant) value; | ||
| } | ||
| if (value instanceof OffsetDateTime) { | ||
| return ((OffsetDateTime) value).toInstant(); | ||
| } | ||
| if (value instanceof ZonedDateTime) { | ||
| return ((ZonedDateTime) value).toInstant(); | ||
| } | ||
| return null; | ||
| } |
There was a problem hiding this comment.
To preserve Types.DATE bindings, java.util.Date was excluded from extractInstant. However, this also prevents pure java.util.Date instances (which are neither java.sql.Date nor java.sql.Time) from being supported for TIMESTAMP columns. We can safely support pure java.util.Date by checking value.getClass() == java.util.Date.class explicitly.
static Instant extractInstant(Object value) {
if (value instanceof Timestamp) {
return ((Timestamp) value).toInstant();
}
if (value instanceof Instant) {
return (Instant) value;
}
if (value instanceof OffsetDateTime) {
return ((OffsetDateTime) value).toInstant();
}
if (value instanceof ZonedDateTime) {
return ((ZonedDateTime) value).toInstant();
}
if (value != null && value.getClass() == java.util.Date.class) {
return ((java.util.Date) value).toInstant();
}
return null;
}
Stack: PR 1 of 6 (base:
main)Bug: b/587340667, b/419328655
Summary
Extend
TypeDescriptorandBigQueryTypeRegistrywith bidirectional Storage Write APIProtoSchemaencoding (ProtoFieldEncoder,resolveWriteApiColumns,encodeWriteApiRow), parameter bounds/type validation (WriteApiValidator,isCompatibleWithWriteApi), and symmetric Read/Write coercions.Design Decisions
O(1)Descriptor Dispatch Instead ofswitch: AttachProtoFieldEncoder,WriteApiValidator, and cross-typewriteApiParamTypesdirectly toTypeDescriptorinsideDESCRIPTORS_BY_ORDINAL[bqType.ordinal()], matching the driver'sResultSetcoercion pattern with zeroswitchstatements and routingARRAY,STRUCT, andRANGEto SQL DML (supportsWriteApi() == false).ByteStringread coercion onBYTES,NUMERIC, andBIGNUMERICplus ZetaSQL packed64Longread coercion onDATETIME, and centralize strictLocale.ROOTformatters (DATE_DIGITS,TIME_MICROS,DATETIME_MICROS,formatInstantUtc) andextractInstant(excludingjava.util.Dateon write soTypes.DATEbindings are preserved).TIMESTAMP(12)SQL Backend Parity (b/419328655) &BigDecimalDoS Guard: FormatTIMESTAMP(12)(FieldDescriptor.Type.STRING) at microsecond precision (formatInstantUtc(..., false)) to match BigQuery SQL parameter truncation, enforce asymmetricBIGNUMERIC_MINand0001..9999proleptic Gregorian bounds, and check integer digits inO(1)beforestripTrailingZeros()to prevent extreme negative-scaleBigDecimalCPU/heap amplification.