Skip to content
Open
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
9 changes: 9 additions & 0 deletions google/cloud/odbc/bq_driver/internal/odbc_conn_handle.cc
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,15 @@ void ConnectionHandle::SetUp(Section& dsn_section,
std::string allow_htapi = dsn_section["ALLOWHTAPIFORLARGERESULTS"];
dsn_.allow_htapi = (allow_htapi == "1");

std::string htapi_activation_threshold =

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.

why do we need this new param? and is it supported by existing driver?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, it is a standard property supported by the existing driver.

We need it for:

  • Compatibility: Drop-in parity for existing DSNs, connection strings, and BI tools that already use this property.
  • Performance: Keeps small queries on the fast REST path (avoiding the ~3s Storage API session setup overhead) while transitioning large queries (1M+ rows) to HTAPI.

dsn_section["HTAPI_ACTIVATIONTHRESHOLD"];
if (!htapi_activation_threshold.empty()) {
auto status = ParseStringToInt64(htapi_activation_threshold);
if (status) {
dsn_.htapi_activation_threshold = status.GetValue();
}
}

dsn_.large_table_expiration_time =
dsn_section["LARGERESULTSTEMPTABLEEXPIRATIONTIME"];
if (dsn_.large_table_expiration_time.empty()) {
Expand Down
1 change: 1 addition & 0 deletions google/cloud/odbc/bq_driver/internal/odbc_conn_handle.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ struct Dsn {
bool use_default_large_results_dataset = true;
std::string large_results_dataset_id;
bool allow_htapi = false;
int64_t htapi_activation_threshold = 3;
std::string large_table_expiration_time = kDefaultLargeResultsTableExpiration;

/////////////////////////////////////////////////////////////////
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ TEST(ConnectionHandle, DsnSetupHtapiDefaultValues) {
Dsn actual = conn_handle.GetDsn();
EXPECT_TRUE(actual.use_default_large_results_dataset);
EXPECT_FALSE(actual.allow_htapi);
EXPECT_EQ(actual.htapi_activation_threshold, 3);
EXPECT_EQ(actual.large_results_dataset_id, kDefaultDestDatasetId);
EXPECT_EQ(actual.large_table_expiration_time,
kDefaultLargeResultsTableExpiration);
Expand All @@ -130,6 +131,7 @@ TEST(ConnectionHandle, DsnSetupHtapiBasic) {
dsn_section["USEDEFAULTLARGERESULTSDATASET"] = "0";
dsn_section["LARGERESULTSDATASETID"] = "large_dataset";
dsn_section["ALLOWHTAPIFORLARGERESULTS"] = "1";
dsn_section["HTAPI_ACTIVATIONTHRESHOLD"] = "0";
dsn_section["LARGERESULTSTEMPTABLEEXPIRATIONTIME"] = "36000";

conn_handle.SetUp(dsn_section, kDsnName);
Expand All @@ -138,6 +140,7 @@ TEST(ConnectionHandle, DsnSetupHtapiBasic) {
EXPECT_FALSE(actual.use_default_large_results_dataset);
EXPECT_EQ(actual.large_results_dataset_id, "large_dataset");
EXPECT_TRUE(actual.allow_htapi);
EXPECT_EQ(actual.htapi_activation_threshold, 0);
EXPECT_EQ(actual.large_table_expiration_time, "36000");
}

Expand Down
95 changes: 83 additions & 12 deletions google/cloud/odbc/bq_driver/internal/odbc_internal_commons.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
#include "google/cloud/odbc/bq_client_interface/utils.h"
#include "google/cloud/odbc/bq_driver/internal/trace_utils.h"
#include "google/cloud/odbc/bq_driver/internal/utils.h"
#include "absl/strings/ascii.h"
#include "absl/strings/numbers.h"
#include <cmath>
#include <ctime>
#include <iomanip>
Expand Down Expand Up @@ -561,17 +563,26 @@ StatusRecordOr<ResultSet> ProcessResultSetRows(
col_schema.is_mode_repeated = (table_field_schema.mode == "REPEATED");
result_set.row_schema.emplace_back(col_schema);
}

// Precompute col_types for faster lookup inside the loop
std::vector<BQDataType> col_types(schema.fields.size());
for (int i = 0; i < schema.fields.size(); ++i) {
if (result_set.row_schema[i].is_mode_repeated) {
col_types[i] = BQDataType::kArray;
} else {
col_types[i] = result_set.row_schema[i].col_type;
}
}

// Populate the data for each row.
result_set.rows.reserve(rows.size());
for (auto const& row : rows) {
DSRow rs_row;
rs_row.reserve(col_types.size());
int i = 0;
for (auto const& col : row.columns) {
BQDataType col_type;
if (result_set.row_schema[i].is_mode_repeated)
col_type = kArray;
else
col_type = result_set.row_schema[i].col_type;
std::string data = col.value;
BQDataType col_type = col_types[i];
std::string const& data = col.value;
if (col.is_null) {
rs_row.emplace_back(kNullValue);
} else if (!data.empty()) {
Expand Down Expand Up @@ -662,10 +673,14 @@ StatusRecordOr<ResultSet> ProcessResultSetRows(
}
case BQDataType::kBool: {
bool bool_val = false;
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
if (data == "1" || data == "true" || data == "yes") {
std::string lower_data = data;
std::transform(lower_data.begin(), lower_data.end(),
lower_data.begin(), ::tolower);
if (lower_data == "1" || lower_data == "true" ||
lower_data == "yes") {
bool_val = true;
} else if (data == "0" || data == "false" || data == "no") {
} else if (lower_data == "0" || lower_data == "false" ||
lower_data == "no") {
bool_val = false;
}
BooleanToDSValue(bool_val, row_val);
Expand All @@ -681,15 +696,15 @@ StatusRecordOr<ResultSet> ProcessResultSetRows(
"Invalid or unsupported col BQ data type"};
}
}
rs_row.emplace_back(row_val);
rs_row.emplace_back(std::move(row_val));
} else {
DSValue empty_value;
StringToDSValue("", empty_value);
rs_row.emplace_back(empty_value);
rs_row.emplace_back(std::move(empty_value));
}
i++;
}
result_set.rows.emplace_back(rs_row);
result_set.rows.emplace_back(std::move(rs_row));
}
return result_set;
}
Expand Down Expand Up @@ -1041,6 +1056,44 @@ StatusRecordOr<std::vector<QueryParameter>> ConstructStringQueryParameters(
return query_params;
}

int64_t ExtractQueryLimit(absl::string_view query) {

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.

no unit test cases for this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

added unit testcase

std::string upper_query = absl::AsciiStrToUpper(query);
absl::string_view upper_view{upper_query};
std::size_t pos = upper_view.rfind("LIMIT");
while (pos != absl::string_view::npos) {
if (pos == 0 ||
std::isspace(static_cast<unsigned char>(upper_view[pos - 1])) ||
upper_view[pos - 1] == ')' || upper_view[pos - 1] == ';') {
std::size_t after_limit = pos + 5;
if (after_limit < upper_view.size() &&
std::isspace(static_cast<unsigned char>(upper_view[after_limit]))) {
while (
after_limit < upper_view.size() &&
std::isspace(static_cast<unsigned char>(upper_view[after_limit]))) {
after_limit++;
}
std::size_t digit_end = after_limit;
while (
digit_end < upper_view.size() &&
std::isdigit(static_cast<unsigned char>(upper_view[digit_end]))) {
digit_end++;
}
if (digit_end > after_limit) {
int64_t limit_val = 0;
if (absl::SimpleAtoi(
upper_view.substr(after_limit, digit_end - after_limit),
&limit_val)) {
return limit_val;
}
}
}
}
if (pos == 0) break;
pos = upper_view.rfind("LIMIT", pos - 1);
}
return -1;
}

PostQueryRequest ConstructBasicPostQueryRequest(
ConnectionHandle const& conn_handle, std::string const& query_str,
int query_timeout, std::string location) {
Expand Down Expand Up @@ -1068,6 +1121,24 @@ PostQueryRequest ConstructBasicPostQueryRequest(
if (is_job_creation_required) {
query_request.set_job_creation_mode(JobCreationMode::Required());
}
#if (!defined(_WIN32) || defined(_WIN64)) && !defined(NO_ARROW)
if (conn_handle.GetDsn().allow_htapi) {
int64_t block_size = conn_handle.GetDsn().row_fetched_per_block > 0
? conn_handle.GetDsn().row_fetched_per_block
: 100000;
int64_t activation_threshold =
conn_handle.GetDsn().htapi_activation_threshold;
int64_t row_threshold = (activation_threshold > 0)
? (activation_threshold * block_size)
: block_size;
int64_t query_limit = ExtractQueryLimit(query_str);

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.

what about cases when there's no limit?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

When there is no LIMIT clause, ExtractQueryLimit returns -1.

The condition (query_limit < 0 || query_limit > row_threshold) explicitly catches this (query_limit < 0) and treats it as an unbounded query, setting max_results(1) so the full result set is streamed directly via the High-Throughput Storage Read API (Arrow) instead of buffering large JSON pages over REST.

// If the query has no LIMIT clause (unbounded, returns -1) or exceeds the
// threshold, set max_results(1) so the full dataset is fetched via HTAPI.
if (query_limit < 0 || query_limit > row_threshold) {
query_request.set_max_results(1);

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.

as discussed last time , why do we need to set this max results ?

@Anshu6250 Anshu6250 Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I have updated this specifically to address Sachin's feedback:

  • Performance Justification: Without this, BigQuery serializes megabytes of REST JSON before HTAPI engages, causing TTFB on 1M queries to take ~17.5s. With max_results(1), TTFB drops to ~4.3s (73% faster).
  • Not Hardcoded: It is dynamically gated by HTAPI_ActivationThreshold and query limits. Small queries (≤ 100k rows) do not set this and remain on the fast REST path.
  • Avoids Page-Size Assumptions: Setting 1 ensures BigQuery immediately returns the destination table metadata regardless of column count/size, allowing the driver to cleanly hand off the entire result set to the Storage Read API (Arrow).

}
}
#endif
if (!default_dataset.empty()) {
DatasetReference ds_ref;
// Set dataset info.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "google/cloud/odbc/internal/odbc_includes.h"
#include "google/cloud/odbc/internal/sql_state_constants.h"
#include "google/cloud/odbc/internal/status_record_or.h"
#include "absl/strings/string_view.h"
#include "absl/types/variant.h"
#if (!defined(_WIN32) || defined(_WIN64)) && !defined(NO_ARROW)
#include <arrow/api.h>
Expand Down Expand Up @@ -641,6 +642,8 @@ odbc_internal::StatusRecordOr<
ConstructStringQueryParameters(
std::map<std::string, std::string> const& params);

int64_t ExtractQueryLimit(absl::string_view query);

google::cloud::bigquery_v2_minimal_internal::PostQueryRequest
ConstructBasicPostQueryRequest(ConnectionHandle const& conn_handle,
std::string const& query_str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,96 @@ TEST(ConstructBasicPostQueryRequest, BasicUseSession) {
returned.query_request().connection_properties()[0].value);
}

TEST(ExtractQueryLimitTest, BasicLimit) {
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT 100"), 100);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT 1000000"), 1000000);
}

TEST(ExtractQueryLimitTest, CaseInsensitive) {
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table limit 50"), 50);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LiMiT 25"), 25);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table Limit 1"), 1);
}

TEST(ExtractQueryLimitTest, WithSemicolonAndWhitespace) {
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT 42;"), 42);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT 42 ;"), 42);
EXPECT_EQ(ExtractQueryLimit("SELECT *\nFROM table\nLIMIT 500\n;"), 500);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT\t123\t;"), 123);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT 10; \n"), 10);
}

TEST(ExtractQueryLimitTest, NoLimitReturnsMinusOne) {
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table"), -1);
EXPECT_EQ(ExtractQueryLimit(""), -1);
EXPECT_EQ(ExtractQueryLimit("SELECT 1"), -1);
}

TEST(ExtractQueryLimitTest, ColumnOrTableContainingWordLimit) {
EXPECT_EQ(ExtractQueryLimit("SELECT limit_col, delimiter FROM table"), -1);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM my_limit_table"), -1);
EXPECT_EQ(ExtractQueryLimit("SELECT delimiter FROM limit_tbl"), -1);
EXPECT_EQ(ExtractQueryLimit("SELECT unlimited FROM table"), -1);
}

TEST(ExtractQueryLimitTest, SubqueryWithOuterLimit) {
EXPECT_EQ(ExtractQueryLimit(
"SELECT * FROM (SELECT * FROM table LIMIT 10) LIMIT 500"),
500);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM (SELECT 1 LIMIT 5) t LIMIT 20;"),
20);
}

TEST(ExtractQueryLimitTest, InvalidOrMissingNumber) {
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT abc"), -1);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT"), -1);
EXPECT_EQ(ExtractQueryLimit("SELECT * FROM table LIMIT -5"), -1);
}

TEST(ConstructBasicPostQueryRequest, MaxResultsSetForLargeQueryWithHtapi) {
ConnectionHandle conn_handle;
Section dsn_section;
dsn_section["ALLOWHTAPIFORLARGERESULTS"] = "1";
conn_handle.SetUp(dsn_section, "name");

#if (!defined(_WIN32) || defined(_WIN64)) && !defined(NO_ARROW)
// Unbounded query should set max_results to 1
PostQueryRequest unbounded =
ConstructBasicPostQueryRequest(conn_handle, "SELECT * FROM table");
EXPECT_EQ(unbounded.query_request().max_results(), 1);

// Large query (> 300,000 with default threshold 3 * 100k) should set
// max_results to 1
PostQueryRequest large_query = ConstructBasicPostQueryRequest(
conn_handle, "SELECT * FROM table LIMIT 1000000");
EXPECT_EQ(large_query.query_request().max_results(), 1);
#endif
}

TEST(ConstructBasicPostQueryRequest, MaxResultsNotSetForSmallQueryWithHtapi) {
ConnectionHandle conn_handle;
Section dsn_section;
dsn_section["ALLOWHTAPIFORLARGERESULTS"] = "1";
conn_handle.SetUp(dsn_section, "name");

// Query <= threshold (e.g. 10k <= 300k) should NOT set max_results (defaults
// to 0)
PostQueryRequest small_query = ConstructBasicPostQueryRequest(
conn_handle, "SELECT * FROM table LIMIT 10000");
EXPECT_EQ(small_query.query_request().max_results(), 0);
}

TEST(ConstructBasicPostQueryRequest, MaxResultsNotSetWhenHtapiDisabled) {
ConnectionHandle conn_handle;
Section dsn_section;
dsn_section["ALLOWHTAPIFORLARGERESULTS"] = "0";
conn_handle.SetUp(dsn_section, "name");

PostQueryRequest unbounded =
ConstructBasicPostQueryRequest(conn_handle, "SELECT * FROM table");
EXPECT_EQ(unbounded.query_request().max_results(), 0);
}

TEST(ConstructnamedPostQueryRequestTest, Success) {
PostQueryRequest expected;
std::string named_query =
Expand Down
Loading