Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
17 changes: 15 additions & 2 deletions java-bigquery-jdbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
<github.global.server>github</github.global.server>
<site.installationModule>google-cloud-bigquery-jdbc</site.installationModule>
<skipShade>false</skipShade>
<!-- Default for @{argLine} in the failsafe configuration below, so a plain build resolves it
to nothing while jacoco:prepare-agent (make full-coverage) can still inject its agent. -->
<argLine></argLine>
</properties>

<build>
Expand Down Expand Up @@ -65,6 +68,15 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<forkCount>1</forkCount>
<!--
The presubmit suite runs every IT class in one forked JVM and Arrow result sets allocate
off-heap. Without bounds, a memory overrun kills the build container (exit 137) with no
test attributed. Capping heap and direct memory turns that into an OutOfMemoryError on
the offending test so JUnit can attribute it cleanly. Applies on every JDK, including
the java11 CI image where the [17,) profile is off.
-->
<argLine>@{argLine} -Xmx1536m -XX:MaxDirectMemorySize=1g</argLine>
<systemPropertyVariables>
<JDBC_TESTS>true</JDBC_TESTS>
<!-- Test-only: keeps integration runs from emitting driver usage telemetry. -->
Expand Down Expand Up @@ -513,14 +525,15 @@
so BigQueryJdbcCustomLoggerTest can read the JDK-internal child-logger list and
assert that driver objects do not leak logger registrations.
-->
<argLine>--add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED --add-opens=java.logging/java.util.logging=ALL-UNNAMED</argLine>
<argLine>@{argLine} --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED --add-opens=java.logging/java.util.logging=ALL-UNNAMED</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<argLine>--add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED</argLine>
<!-- Profile argLine replaces the base one; repeat the memory bounds from above. -->
<argLine>@{argLine} -Xmx1536m -XX:MaxDirectMemorySize=1g --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED</argLine>
</configuration>
</plugin>
</plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ public abstract class BigQueryBaseResultSet extends BigQueryNoOpsResultSet
protected final boolean isNested;
protected boolean isClosed = false;
protected boolean wasNull = false;
// getMetaData() is commonly called inside row loops; cache the immutable wrapper and record
// the adoption signal once per result set. ResultSet is single-threaded by JDBC contract.
private ResultSetMetaData cachedMetaData;
private int fetchSize = -1;
private Job job;
private SQLWarning warnings;
Expand Down Expand Up @@ -258,21 +261,26 @@ public boolean wasNull() throws SQLException {
@Override
public ResultSetMetaData getMetaData() throws SQLException {
checkClosed();
String connectionId = this.statement != null ? this.statement.connectionId : null;
ResultSetMetaData metaData;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
if (this.isNested) {
metaData = BigQueryResultSetMetadata.of(this.schemaFieldList, this.statement);
} else {
metaData = BigQueryResultSetMetadata.of(this.schema.getFields(), this.statement);
if (this.cachedMetaData == null) {
String connectionId = this.statement != null ? this.statement.connectionId : null;
ResultSetMetaData metaData;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
if (this.isNested) {
metaData = BigQueryResultSetMetadata.of(this.schemaFieldList, this.statement);
} else {
metaData = BigQueryResultSetMetadata.of(this.schema.getFields(), this.statement);
}
}
this.cachedMetaData =
BigQueryJdbcContextProxy.wrap(metaData, ResultSetMetaData.class, connectionId);
// Always a user call: no driver code invokes ResultSet.getMetaData(), so this is recorded
// regardless of whether the owning statement is internal (e.g. the result set that
// DatabaseMetaData.getExportedKeys hands back to the user).
TelemetryManager.recordFeatureUsage(
DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL,
"DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL");
}

TelemetryManager.recordFeatureUsage(
DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL,
"DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL");

return BigQueryJdbcContextProxy.wrap(metaData, ResultSetMetaData.class, connectionId);
return this.cachedMetaData;
}

@Override
Expand All @@ -290,7 +298,7 @@ public int getConcurrency() throws SQLException {
@Override
public Statement getStatement() throws SQLException {
checkClosed();
if (this.statement == null) {
if (this.statement == null || this.statement.isInternal()) {
return null;
}
Statement proxy = this.statement.getLogicalStatementProxy();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;

Expand Down Expand Up @@ -256,7 +257,13 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
private Context otelContext;
Tracer tracer =
OpenTelemetry.noop().getTracer(BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME);
DatabaseMetaData databaseMetaData;

private volatile DatabaseMetaData databaseMetaData;
private final Object metaDataLock = new Object();

// A Connection may be used from several threads; compareAndSet keeps the adoption signal at
// exactly one record per connection without a lock.
private final AtomicBoolean metadataRetrievalRecorded = new AtomicBoolean();
Boolean reqGoogleDriveScope;
private final Properties clientInfo = new Properties();
private boolean isReadOnlyTokenUsed = false;
Expand Down Expand Up @@ -523,6 +530,38 @@ public Statement createStatement() throws SQLException {
return currentStatement;
}

/**
* Creates a {@code Statement} for the driver's own use (for example the {@code isValid}
* health-check query). Identical to {@link #createStatement()} except that neither the statement
* nor anything it executes is reported as user activity in usage telemetry.
*/
BigQueryStatement createStatementInternal() throws SQLException {
checkClosed();
BigQueryStatement statement = new BigQueryStatement(this, false);
LOG.fine("Internal Statement %s created.", statement);
addOpenStatements(statement);
return statement;
}

/**
* Creates a {@code PreparedStatement} for the driver's own metadata queries. Identical to {@link
* #prepareStatement(String)} except that neither the statement, its parameter bindings, nor
* anything it executes is reported as user activity in usage telemetry.
*/
BigQueryPreparedStatement prepareStatementInternal(String sql) throws SQLException {
return prepareStatementInternal(sql, false);
}

BigQueryPreparedStatement prepareStatementInternal(String sql, boolean skipDryRun)
throws SQLException {
checkClosed();
BigQueryPreparedStatement statement =
new BigQueryPreparedStatement(this, sql, skipDryRun, false);
LOG.fine("Internal Prepared Statement %s created.", statement);
addOpenStatements(statement);
return statement;
}

/**
* Creates and returns a new {@code Statement} object for executing BigQuery SQL queries. This
* method is similar to {@link BigQueryConnection#createStatement()}, but it overrides the type
Expand Down Expand Up @@ -899,7 +938,8 @@ public boolean isValid(int timeout) throws SQLException {
throw new BigQueryJdbcException("timeout must be >= 0");
}
if (!isClosed()) {
try (Statement statement = createStatement();
// Internal statement: a pool health-check must not count as user statements or SELECTs.
try (Statement statement = createStatementInternal();
ResultSet rs = statement.executeQuery("SELECT 1")) {
LOG.finer("Running validation query");
if (rs.next()) {
Expand Down Expand Up @@ -1183,13 +1223,31 @@ private static SQLException accumulateException(SQLException current, SQLExcepti

@Override
public DatabaseMetaData getMetaData() throws SQLException {
if (databaseMetaData == null) {
databaseMetaData = new BigQueryDatabaseMetaData(this);
checkClosed();
DatabaseMetaData metaData = getMetaDataInternal();
// Adoption signal, recorded once per connection on the first user call. Tied to this flag
// rather than to instance creation so the driver's own startup lookup does not consume it.
if (this.metadataRetrievalRecorded.compareAndSet(false, true)) {
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL);
}
return metaData;
}

TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL);

return databaseMetaData;
/**
* Same instance as {@link #getMetaData()} without the usage-telemetry record. Driver-internal.
*/
DatabaseMetaData getMetaDataInternal() {
DatabaseMetaData result = this.databaseMetaData;
if (result == null) {
synchronized (this.metaDataLock) {
result = this.databaseMetaData;
if (result == null) {
result = new BigQueryDatabaseMetaData(this);
this.databaseMetaData = result;
}
}
}
return result;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1568,7 +1568,8 @@ void appendGraphTableRows(
validateCatalogIdentifier(project);
String formattedSql = replaceSqlParameters(getGraphTablesSqlContent(), project, scope);

try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) {
try (PreparedStatement statement =
this.connection.prepareStatementInternal(formattedSql, true)) {
statement.setString(1, effectiveSchemaPattern == null ? "%" : effectiveSchemaPattern);
statement.setString(2, effectiveTablePattern);

Expand Down Expand Up @@ -1868,7 +1869,8 @@ void appendGraphColumnRows(
}

String formattedSql = replaceSqlParameters(getGraphColumnsSqlContent(), project, scope);
try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) {
try (PreparedStatement statement =
this.connection.prepareStatementInternal(formattedSql, true)) {
statement.setString(1, effectiveSchemaLike);
statement.setString(2, effectiveTableLike);
statement.setString(3, effectiveColumnLike);
Expand Down Expand Up @@ -2460,7 +2462,8 @@ private void appendGraphPrimaryKeys(
validateCatalogIdentifier(project);
String formattedSql = replaceSqlParameters(getGraphPrimaryKeysSqlContent(), project, scope);

try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) {
try (PreparedStatement statement =
this.connection.prepareStatementInternal(formattedSql, true)) {
statement.setString(1, table); // exact "<graph>.<element>"
try (ResultSet rs = statement.executeQuery()) {
while (rs.next()) {
Expand Down Expand Up @@ -2623,7 +2626,7 @@ public ResultSet getExportedKeys(String catalog, String schema, String table)
validateSchemaIdentifier(schema);
String sql = getExportedKeysSqlContent();
String formattedSql = replaceSqlParameters(sql, catalog, schema);
PreparedStatement stmt = this.connection.prepareStatement(formattedSql, true);
PreparedStatement stmt = this.connection.prepareStatementInternal(formattedSql, true);
if (stmt == null) {
throw new BigQueryJdbcException("Failed to prepare statement for getExportedKeys");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public Connection connect(String url, Properties info) throws SQLException {
ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj);
}
BigQueryConnection connection = new BigQueryConnection(connectionUri, ds);
DatabaseMetaData metaData = connection.getMetaData();
DatabaseMetaData metaData = connection.getMetaDataInternal();
LOG.info(
"Driver info : { {Database Product Name : %s}, "
+ "{Database Product Version : %s}, "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@ class BigQueryParameterHandler {
new BigQueryJdbcCustomLogger(BigQueryParameterHandler.class.getName());
private final int parametersArraySize;
private final boolean enableTimestampPicos;
private final boolean recordTelemetry;

/**
* DRIVER_FEATURE_PARAMETER_BINDING is an adoption signal, recorded once per handler (i.e. per
* prepared statement) rather than once per setX call. Handlers are confined to one statement,
* which JDBC defines as single-threaded, so a plain field is sufficient.
*/
private boolean bindingRecorded;

private void recordBinding() {
if (this.recordTelemetry && !this.bindingRecorded) {
this.bindingRecorded = true;
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING);
}
}

final ArrayList<BigQueryJdbcParameter> parametersList;
// TIMESTAMP is rendered in UTC with a trailing 'Z': the instant is preserved, the output does not
// depend on the JVM zone, and QueryParameterValue's validator accepts 'Z' but rejects "-05:00".
Expand Down Expand Up @@ -100,16 +116,30 @@ static Tuple<Object, Class<?>> bindingForJavaTime(Object value) {
}

BigQueryParameterHandler(int parameterCount, boolean enableTimestampPicos) {
this(parameterCount, new ArrayList<>(parameterCount), enableTimestampPicos);
this(parameterCount, enableTimestampPicos, true);
}

BigQueryParameterHandler(
int parameterCount, boolean enableTimestampPicos, boolean recordTelemetry) {
this(parameterCount, new ArrayList<>(parameterCount), enableTimestampPicos, recordTelemetry);
}

BigQueryParameterHandler(
int parameterCount,
ArrayList<BigQueryJdbcParameter> parametersList,
boolean enableTimestampPicos) {
this(parameterCount, parametersList, enableTimestampPicos, true);
}

BigQueryParameterHandler(
int parameterCount,
ArrayList<BigQueryJdbcParameter> parametersList,
boolean enableTimestampPicos,
boolean recordTelemetry) {
this.parametersArraySize = parameterCount;
this.parametersList = parametersList;
this.enableTimestampPicos = enableTimestampPicos;
this.recordTelemetry = recordTelemetry;
}

// Indicates whether the parameter is input, output or both
Expand Down Expand Up @@ -271,7 +301,7 @@ void setNullParameter(int parameterIndex, Class<?> declaredJavaType) {
parameter.setParamType(BigQueryStatementParameterType.UNSPECIFIED);
parameter.setScale(-1);

TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING);
recordBinding();

LOG.finest("Parameter set { %s }", parameter.toString());
}
Expand All @@ -289,7 +319,7 @@ void setParameter(int parameterIndex, Object value, Class type) {
parameter.setParamType(BigQueryStatementParameterType.UNSPECIFIED);
parameter.setScale(-1);

TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING);
recordBinding();

LOG.finest("Parameter set { %s }", parameter.toString());
}
Expand Down Expand Up @@ -385,7 +415,7 @@ void setParameter(
parametersList.add(parameter);
}

TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING);
recordBinding();

LOG.finest("Parameter set { %s }", parameter.toString());
}
Expand All @@ -411,7 +441,7 @@ void setParameter(
parameter.setParamType(paramType);
parameter.setScale(scale);

TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING);
recordBinding();

LOG.finest("Parameter set { %s }", parameter.toString());
}
Expand Down
Loading
Loading