Skip to content

[WIP] fix(bigquery-jdbc): add bidirectional ProtoSchema codecs and bounds to BigQueryTypeRegistry - #15183

Open
Neenu1995 wants to merge 1 commit into
mainfrom
fix/swa-v2-1-type-registry-proto-codecs
Open

Neenu1995 wants to merge 1 commit into
mainfrom
fix/swa-v2-1-type-registry-proto-codecs

Conversation

@Neenu1995

Copy link
Copy Markdown
Contributor

Stack: PR 1 of 6 (base: main)
Bug: b/587340667, b/419328655

Summary

Extend TypeDescriptor and BigQueryTypeRegistry with bidirectional Storage Write API ProtoSchema encoding (ProtoFieldEncoder, resolveWriteApiColumns, encodeWriteApiRow), parameter bounds/type validation (WriteApiValidator, isCompatibleWithWriteApi), and symmetric Read/Write coercions.

Design Decisions

  • O(1) Descriptor Dispatch Instead of switch: Attach ProtoFieldEncoder, WriteApiValidator, and cross-type writeApiParamTypes directly to TypeDescriptor inside DESCRIPTORS_BY_ORDINAL[bqType.ordinal()], matching the driver's ResultSet coercion pattern with zero switch statements and routing ARRAY, STRUCT, and RANGE to SQL DML (supportsWriteApi() == false).
  • Symmetrical Read/Write Coercions & Shared Formatters: Add ByteString read coercion on BYTES, NUMERIC, and BIGNUMERIC plus ZetaSQL packed64 Long read coercion on DATETIME, and centralize strict Locale.ROOT formatters (DATE_DIGITS, TIME_MICROS, DATETIME_MICROS, formatInstantUtc) and extractInstant (excluding java.util.Date on write so Types.DATE bindings are preserved).
  • TIMESTAMP(12) SQL Backend Parity (b/419328655) & BigDecimal DoS Guard: Format TIMESTAMP(12) (FieldDescriptor.Type.STRING) at microsecond precision (formatInstantUtc(..., false)) to match BigQuery SQL parameter truncation, enforce asymmetric BIGNUMERIC_MIN and 0001..9999 proleptic Gregorian bounds, and check integer digits in O(1) before stripTrailingZeros() to prevent extreme negative-scale BigDecimal CPU/heap amplification.

…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).
@Neenu1995
Neenu1995 requested review from a team as code owners November 24, 2026 01:42

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1305 to +1320
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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;
  }

Comment on lines +1322 to +1327
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)));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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)));
  }

Comment on lines +1291 to +1303
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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;
  }

Comment on lines +1248 to +1272
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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;
  }

Comment on lines +1109 to +1123
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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;
  }

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant