Repository navigation
Add bigquery table function and BigQuery table engine - #110166
Conversation
Allows reading from and writing to Google BigQuery tables, including public datasets, over the BigQuery v2 REST API: - The table structure is inferred from the BigQuery schema (`tables.get`), with `RECORD` mapped to `Tuple`, `REPEATED` to `Array`, `NUMERIC` and `BIGNUMERIC` to `Decimal`, `TIMESTAMP` and `DATETIME` to `DateTime64(6, 'UTC')`, `TIME` to `Time64(6)` and `BYTES` to `String`. - Reading uses `tabledata.list` with pagination, int64 timestamps and column pruning through `selectedFields`. - Writing uses streaming inserts (`tabledata.insertAll`) in batches of 500 rows, failing on any rejected row. - Three authentication methods (exactly one must be provided): a ready-made OAuth access token, a service account key in JSON format (a JWT is signed with RS256 and exchanged at the key's `token_uri`), and an OAuth client with a refresh token as in Application Default Credentials. `fetchGCPOAuthToken` got an overridable token endpoint and a new JWT-bearer variant for that. - Credential arguments are masked in query logs and `SHOW CREATE`. - A new `BIGQUERY` source access type controls access. The integration test runs against a mock of the BigQuery REST API covering schema inference, all type conversions, paging, column pruning, inserts, both OAuth token flows and error paths. Co-Authored-By: Claude Fable 5 <[email protected]>
The type names in the `DESCRIBE` output are TSV-escaped, and the `selectedFields` parameter is intentionally omitted when all columns of the table are selected. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [0426182] Summary: ✅
AI ReviewSummaryThis PR adds the Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1174/1255 (93.55%) · Uncovered code |
The constant is referenced only inside the `#if USE_SSL` branch of `makeServiceAccountAssertion`, so builds without SSL (e.g. the fast test) failed with `-Wunused-const-variable`. Co-Authored-By: Claude Fable 5 <[email protected]>
The `cppcoreguidelines-init-variables` check in the arm_tidy build rejects the uninitialized declaration even though every branch assigns it. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Validated against real BigQuery endpoints (in addition to the mock-based integration tests):
|
The new `BigQuery` table engine was not present in the `engine_to_type` map in `commandSelector.cpp`, so the ArrowFlight SQL `CommandGetTableTypes` reply reported it as `UNKNOWN TABLE TYPE`. This broke the integration test `test_arrowflight_interface/test_sql_server.py::test_get_table_types`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A BigQuery `REPEATED` field was mapped to `Array(base)` with a non-`Nullable`
element type. A `NULL` element returned by `tabledata.list` (as `{"v": null}`)
was then coerced to a default via `insertDefault`, so a value like `[1, NULL, 2]`
was silently materialized as `[1, 0, 2]`, and there was no way to write such rows
either (`checkColumnMatchesSchema` rejects `Array(Nullable(T))` against an inferred
`Array(T)` schema).
Map scalar `REPEATED` fields to `Array(Nullable(T))` so that `NULL` elements are
preserved losslessly on both reads and writes. `RECORD` elements are left as a
plain `Tuple` because `Nullable(Tuple)` is gated behind the
`enable_nullable_tuple_type` setting which is off by default.
Adds an integration test with a `NULL` array element and updates the schema
inference expectations and the documentation.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…llable(Tuple))` The `field.repeated` branch of `computeClickHouseType` wrapped the element type in `Nullable` whenever `canBeInsideNullable` was true. For a `RECORD` element that base type is `DataTypeTuple`, whose `canBeInsideNullable` returns `true` unconditionally, so a repeated `RECORD` was inferred as `Array(Nullable(Tuple(...)))`. That contradicts the documented mapping (a `REPEATED RECORD` maps to `Array(Tuple(...))`) and the `test_schema_inference` expectation, and it is not usable end to end: `Nullable(Tuple)` is gated behind the `enable_nullable_tuple_type` setting which is off by default, so explicit DDL parsing rejects it and `SHOW CREATE TABLE` becomes unreplayable. Exclude `RECORD` from the repeated-element `Nullable` wrapping, mirroring the non-repeated branch, so a `REPEATED RECORD` keeps a plain `Tuple` element. This fixes the failing `test_schema_inference` integration test. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110166&sha=036114a633e12ce76aa0fbc81446445d78561082&name_0=PR Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
By default a BigQuery `NULLABLE RECORD` is inferred as a plain `Tuple`, so a whole-record `NULL` collapses into a tuple of default values (`Nullable(Tuple)` is gated behind the `enable_nullable_tuple_type` setting which is off by default). This left no lossless way to read or write `NULL` records. `checkColumnMatchesSchema` required the declared column type to exactly equal the inferred type, which rejected an explicitly declared `Nullable(Tuple(...))` (or `Array(Nullable(Tuple(...)))`) - the lossless opt-in other readers such as Arrow/Parquet allow behind the same setting. Relax the check to also accept a declared type that differs from the inferred type only by `Nullable` wrappers placed directly around a `Tuple`. The read (`insertNonRepeatedValue`) and write (`nonRepeatedJSONValue`) paths already honor `Nullable` columns, so with the opt-in a `NULL` record is read as `NULL` and written as a JSON `null` instead of being coerced to a default tuple. The default inference is unchanged, so the documented mapping and DDL replay stay stable. Adds integration coverage (`test_nullable_record_opt_in`: lossless read, write round-trip, `Array(Nullable(Tuple))` acceptance, and rejection of a non-record nullability mismatch) and documents the opt-in. Addresses the AI review on #110166 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
No behavior change; wraps the long `node.query(...)` calls added in the previous commit the way `black` formats the rest of the file. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ialized views, token caching Address the four findings from the latest review round of the `bigquery` table function / `BigQuery` table engine: - Infer a BigQuery `NULLABLE RECORD` as `Nullable(Tuple(...))` (and a `REPEATED RECORD` as `Array(Nullable(Tuple(...)))`) instead of a plain `Tuple`, so a whole-record `NULL` round-trips as `NULL` rather than collapsing into a `Tuple` of default values. Reading and writing such columns through the table function needs no extra setting; persisting them with the engine requires `enable_nullable_tuple_type`, as for any `Nullable(Tuple)` column. `checkColumnMatchesSchema` still accepts a declared plain `Tuple(...)` (lossy) as well as the exact type, comparing both sides after stripping `Nullable` wrappers around a `Tuple`. Resolves the design point in #110166 (comment) ("Allow and use Nullable(Tuple(...)). They are production-ready now."). - Validate the default Google token endpoint against the remote host filter on the `refresh_token` auth path, so it cannot bypass the admin host allowlist (`remote_host_filter` / `remote_url_allow_hosts`) when `token_url` is left empty. - Reject a `MATERIALIZED_VIEW` up front in `fetchTableSchema` with the same clear error as `VIEW` / `EXTERNAL`, matching the documented contract, and cover it with a test. - Share a `BigQueryTokenProvider` across queries on `StorageBigQuery`, so an OAuth access token is minted once and reused until it expires instead of on every read and write (which each build their own `BigQueryClient`). The provider takes the context per call, so one instance can serve queries that run with different contexts. The `test_storage_bigquery` integration test and the `bigquery.md` docs are updated accordingly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lection dependency Two review findings on the `bigquery` table function / `BigQuery` table engine: 1. Reuse the schema snapshot and token across a table-function query. `TableFunctionBigQuery` fetched the schema (`tables.get`) during analysis but kept only the `ColumnsDescription`, so `StorageBigQuery` fetched the schema again on the first read or write. A single `SELECT` / `INSERT INTO FUNCTION bigquery(...)` could therefore analyze against one schema and execute against another if the table changed in between, and auth-backed queries paid an extra token + `tables.get` round-trip. The table function now keeps the fetched `BigQueryFields` and a shared `BigQueryTokenProvider` and passes both into `StorageBigQuery`, so execution reuses the same schema snapshot and access token. 2. Register the named-collection dependency for the table engine. `CREATE TABLE ... ENGINE = BigQuery(my_collection)` resolved the named collection without passing the table id to `tryGetNamedCollectionWithOverrides`, so `NamedCollectionFactory` recorded no dependency and `DROP NAMED COLLECTION` was not blocked while the table still used it. The table id is now threaded through `BigQueryConfiguration::fromArguments` (only for the persistent engine, not the transient table function), matching every other permanent external engine. Added integration tests `test_named_collection_dependency` and `test_table_function_reuses_schema_snapshot` (the mock server now also counts `tables.get` requests). All 17 tests in `test_storage_bigquery` pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…BLE ... AS bigquery(...)` A permanent table created from the table function persists a `StorageTableFunctionProxy`, but the named collection it was configured from was not registered as a dependency, so `DROP NAMED COLLECTION` succeeded while the table existed and the next access failed. `ITableFunction` now reports the used named collection name (empty by default; `bigquery` overrides it), and both permanent creation sites - `InterpreterCreateQuery` for `CREATE`/`ATTACH` and `DatabaseOnDisk::createTableFromAST` for loading stored metadata at server startup - register the dependency, matching the table engine behavior. #110166 (comment)
|
🕵 The single CI red on 99897d7 is unrelated to this PR: Stress test (arm_tsan) aborted with The named-collection dependency review comment is addressed in a526bd8. |
…llection form `tryGetNamedCollectionWithOverrides` applies repeated `key = value` overrides with last-wins semantics, so `bigquery(collection, table = 'a', table = 'b')` silently targeted `b`, while the plain-argument form (and the documentation) rejects a repeated key. Pre-scan the override keys and throw `BAD_ARGUMENTS` when the same key is given twice, for both the table function and the `BigQuery` engine. #110166 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 CI failures on a526bd8 are unrelated to this PR:
The new review finding (duplicate named-collection overrides) is implemented in 432ea43, and master is merged in fec233e. |
Only `NULLABLE`, `REQUIRED` and `REPEATED` are valid BigQuery field modes, but `parseField` silently treated any other string as a nullable scalar because both flags stayed false, turning malformed or newly-added metadata enum values into the wrong inferred type and wrong read/write semantics. A missing mode still defaults to `NULLABLE`, but a present mode outside the documented enum is now rejected with `INCORRECT_DATA`. #110166 (comment)
|
🕵 CI status on fec233e: both reds are unrelated to this PR (zero BigQuery frames in either):
The new AI review finding (unknown BigQuery field modes silently treated as nullable scalars) is implemented in 0426182. |
|
Confirmed: #113925 covers it. The
Distribution agrees: 48 Measured on one host with the reproducer from #113925:
My local release arm is amd64, but the mechanism is architecture independent and the The differing reaching frame is inlining: Nothing is owed beyond #113925. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Ok, the code is acceptable.
|
Hi @alexey-milovidov — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
|
On the fix you asked for here: rather than keep the design question open, I am taking the fuzzer-side option, which is the one with no user-visible behaviour change. A cloned Refusing two writers on one Log-family target at INSERT planning time is the other option, and it is user-visible, so I am not bundling it into this. #74080 is the reason it deserves its own decision rather than being folded in here. I will link the PR in this thread. |
|
The fix for the I did not take the second option of refusing two writers on one |
On the async read path (allow_asynchronous_read_from_io_pool_for_merge_tree = 1) with requested_num_streams != 1, ReadFromMergeTree set requested_num_streams = std::max(requested_num_streams, max_streams_for_merge_tree_reading). A near-UINT64_MAX setting value then reached pipes.reserve(num_streams) in groupPartitionsByStreams (and spreadMarkRanges / groupStreamsByPartition), throwing std::length_error and aborting the server in debug/sanitizer builds. Clamp the setting at ingestion to 256 * getNumberOfCPUCoresToUse(), the same ceiling max_threads gets. Default (0) and documented semantics are unchanged. Found by the AST fuzzer (STID 2508-3132), reproduced on unrelated PRs ClickHouse#110073, ClickHouse#110166, ClickHouse#99495. Closes ClickHouse#110932. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Closes: #25173
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the
bigquerytable function and theBigQuerytable engine for reading from and writing to Google BigQuery tables, including public datasets. The table structure is inferred from the BigQuery table schema. Authentication supports an OAuth access token, a service account key in JSON format, and an OAuth client with a refresh token.Documentation entry for user-facing changes
Reading uses the BigQuery v2 REST API
tabledata.list(native tables; views and external tables are rejected with a clear error), with pagination,formatOptions.useInt64Timestamp=truefor exact timestamps, and column pruning throughselectedFields. Writing uses streaming inserts (tabledata.insertAll) in batches of 500 rows and fails on any rejected row. The gRPC Storage Read/Write API from the issue can be a future performance optimization on top of this interface.Type mapping:
RECORD/STRUCTtoTuple,REPEATEDtoArray,NULLABLEtoNullable,NUMERIC/BIGNUMERICtoDecimal(including parameterized precision and scale),TIMESTAMP/DATETIMEtoDateTime64(6, 'UTC'),TIMEtoTime64(6),DATEtoDate32,BYTEStoString(base64-decoded),GEOGRAPHY/JSON/INTERVAL/RANGEtoString.Authentication (exactly one method must be provided; also via named collections):
access_token— a ready-made OAuth 2.0 access token (e.g. fromgcloud auth print-access-token);service_account_key— the content of a service account key file in JSON format; a JWT is signed with RS256 (reusingKeyPairandrsaSHA256Sign) and exchanged for an access token at the key'stoken_uri, with caching and refresh;client_id+client_secret+refresh_token— Application Default Credentials style, reusingfetchGCPOAuthTokenfrom the BigLake integration (extended with an overridable token endpoint, plus a new JWT-bearer variant).Credential arguments are masked in query logs and
SHOW CREATE TABLE. A newBIGQUERYsource access type controls access via grants.The integration test
test_storage_bigqueryruns against a mock of the BigQuery REST API covering schema inference for all types (including nested and repeated records), paging, column pruning and ordering, insert round-trips (includingNaN/Infinity, binary data and 500-row batching), both OAuth token flows (with JWT claim validation), named collections, the table engine (including inference atCREATEand secret masking), and error paths. A stateless test covers argument validation.