Skip to content

Commit ee41a8c

Browse files
iennaechalmerlowe
andauthored
feat(bigquery): add bigquery_upgrade_manifest_biglake_table sample to… (#14748)
* feat(bigquery): add bigquery_upgrade_manifest_biglake_table sample to upgrade a manifest external table to BigLake with automatic metadata caching Problem: The BigQuery documentation (https://cloud.google.com/bigquery/docs/query-open-table-format-using-manifest-files) needs a standalone, tested Python code sample demonstrating how to upgrade a manifest external table to BigLake with automatic metadata caching (region tag `bigquery_upgrade_manifest_biglake_table`). Solution: - Add `upgrade_manifest_biglake_table(project_id: str, dataset_id: str, table_id: str, connection_id: str, manifest_uri: str) -> None` in `bigquery/biglake/bigquery_upgrade_manifest_biglake_table.py` (Upgrade a manifest-backed external table to a BigLake table with AUTOMATIC metadata caching and connection binding.) - Add unit tests (`bigquery/biglake/bigquery_upgrade_manifest_biglake_table_test.py`) covering both the success path and API error handling (`GoogleAPICallError`) * fix(bigquery): report applied metadata cache settings in upgrade_manifest_biglake_table Problem: Review feedback on this sample pointed out two issues: - It printed "Metadata Cache Mode: AUTOMATIC" as a hardcoded string, so neither the sample nor its test verified that BigQuery applied the setting. - The verification query selected id, label and score, which only exist in our test data, so the sample failed against any other manifest table. Solution: - After the CREATE statement, read the table back with client.get_table() and print the metadataCacheMode from its external data configuration and the table's max_staleness. ExternalConfig has no metadata_cache_mode property in google-cloud-bigquery 3.47.0, so the value is read from the public to_api_repr() output. - Use SELECT * ... LIMIT 10 so the query works with any schema. - The test mocks get_table(), asserts it is called with the table ID, and checks the reported cache mode and max staleness. * fix: Apply suggestion from @chalmerlowe Co-authored-by: Chalmer Lowe <chalmer.lowe@gmail.com> * test(bigquery): use autospec and real SDK objects in upgrade_manifest_biglake_table test Problem: Review feedback showed the test mostly verified its own mocks. MagicMock accepts any attribute, so a typo in the sample or a change in the SDK still passed. The get_table() result was a MagicMock whose to_api_repr() returned a dictionary the test wrote itself, so the assertion on the cache mode checked that dictionary rather than the sample's lookups on bigquery.Table. The test also did not check that the DDL ran before the SELECT, and the not-found test only exercised the mock now that the sample no longer handles errors. Solution: - Patch Client with autospec=True and spec_set=True, and create the query jobs with mock.create_autospec(bigquery.QueryJob, instance=True, spec_set=True), so only real attributes and methods are accepted. - Return a real bigquery.Table built with Table.from_api_repr() (no network call) from get_table(), so the sample's external_data_configuration and max_staleness lookups run against the SDK class. - Assert the client was created with the project, that the CREATE OR REPLACE EXTERNAL TABLE statement ran first and the SELECT second, and that get_table() was called with the table ID. - Remove the not-found test, since the sample has no error handling of its own to test. A deliberate typo in the sample (table.max_stalenes) now fails the test with AttributeError; the previous MagicMock-based test passed. --------- Co-authored-by: Chalmer Lowe <chalmer.lowe@gmail.com>
1 parent 50901ac commit ee41a8c

2 files changed

Lines changed: 165 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START bigquery_upgrade_manifest_biglake_table]
16+
from google.cloud import bigquery
17+
18+
19+
def upgrade_manifest_biglake_table(
20+
project_id: str,
21+
dataset_id: str,
22+
table_id: str,
23+
connection_id: str,
24+
manifest_uri: str,
25+
) -> None:
26+
"""Upgrades a manifest external table to a BigLake table with metadata caching.
27+
28+
Args:
29+
project_id: Google Cloud project ID (for example, 'example-project').
30+
dataset_id: BigQuery dataset ID containing the external table
31+
(for example, 'example_dataset').
32+
table_id: BigQuery external table ID to upgrade
33+
(for example, 'example_manifest_table').
34+
connection_id: Fully qualified BigQuery Cloud Resource connection ID
35+
(for example, 'example-project.us.example_biglake_conn').
36+
manifest_uri: Cloud Storage URI of the SymLinkTextInputFormat manifest file
37+
(for example, 'gs://example-bucket/manifests/symlink.manifest').
38+
"""
39+
client = bigquery.Client(project=project_id)
40+
table_ref = f"{project_id}.{dataset_id}.{table_id}"
41+
# Upgrading the manifest external table with a Cloud Resource connection and AUTOMATIC metadata
42+
# caching accelerates open-table-format reads and enforces BigLake governance.
43+
ddl_sql = f"""
44+
CREATE OR REPLACE EXTERNAL TABLE `{table_ref}`
45+
WITH CONNECTION `{connection_id}`
46+
OPTIONS (
47+
format = 'PARQUET',
48+
uris = ['{manifest_uri}'],
49+
file_set_spec_type = 'NEW_LINE_DELIMITED_MANIFEST',
50+
max_staleness = INTERVAL 1 HOUR,
51+
metadata_cache_mode = 'AUTOMATIC'
52+
);
53+
"""
54+
select_sql = f"""
55+
SELECT *
56+
FROM `{table_ref}`
57+
LIMIT 10;
58+
"""
59+
60+
print(
61+
f"Upgrading manifest external table to BigLake with metadata caching: {table_ref}"
62+
)
63+
client.query(ddl_sql).result()
64+
65+
# Read the table back to confirm the metadata caching settings BigQuery applied.
66+
table = client.get_table(table_ref)
67+
external_config = table.external_data_configuration.to_api_repr()
68+
metadata_cache_mode = external_config.get("metadataCacheMode")
69+
70+
query_job = client.query(select_sql)
71+
rows = list(query_job.result())
72+
73+
print(f"Resource ID: {table_ref}")
74+
print(f"Connection ID: {connection_id}")
75+
print(f"Job ID: {query_job.job_id}")
76+
print(f"Manifest URI: {manifest_uri}")
77+
print(f"Metadata Cache Mode: {metadata_cache_mode}")
78+
print(f"Max Staleness: {table.max_staleness}")
79+
print(f"Rows Returned: {len(rows)}")
80+
81+
82+
# [END bigquery_upgrade_manifest_biglake_table]
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from unittest import mock
16+
17+
from google.cloud import bigquery
18+
import pytest
19+
20+
from .. import bigquery_upgrade_manifest_biglake_table
21+
22+
23+
def test_upgrade_manifest_biglake_table_success(
24+
capsys: pytest.CaptureFixture[str],
25+
) -> None:
26+
with mock.patch.object(
27+
bigquery_upgrade_manifest_biglake_table.bigquery,
28+
"Client",
29+
autospec=True,
30+
spec_set=True,
31+
) as mock_client_cls:
32+
mock_client = mock_client_cls.return_value
33+
mock_ddl_job = mock.create_autospec(
34+
bigquery.QueryJob, instance=True, spec_set=True
35+
)
36+
mock_ddl_job.result.return_value = []
37+
mock_select_job = mock.create_autospec(
38+
bigquery.QueryJob, instance=True, spec_set=True
39+
)
40+
mock_select_job.job_id = "example-job-123"
41+
mock_select_job.result.return_value = [{}, {}, {}]
42+
mock_client.query.side_effect = [mock_ddl_job, mock_select_job]
43+
mock_client.get_table.return_value = bigquery.Table.from_api_repr(
44+
{
45+
"tableReference": {
46+
"projectId": "example-project",
47+
"datasetId": "example_dataset",
48+
"tableId": "example_manifest_table",
49+
},
50+
"maxStaleness": "0-0 0 1:0:0",
51+
"externalDataConfiguration": {
52+
"sourceFormat": "PARQUET",
53+
"metadataCacheMode": "AUTOMATIC",
54+
},
55+
}
56+
)
57+
58+
bigquery_upgrade_manifest_biglake_table.upgrade_manifest_biglake_table(
59+
project_id="example-project",
60+
dataset_id="example_dataset",
61+
table_id="example_manifest_table",
62+
connection_id="example-project.us.example_biglake_conn",
63+
manifest_uri="gs://example-bucket/manifests/symlink.manifest",
64+
)
65+
66+
mock_client_cls.assert_called_once_with(project="example-project")
67+
assert mock_client.query.call_count == 2
68+
assert (
69+
"CREATE OR REPLACE EXTERNAL TABLE"
70+
in mock_client.query.call_args_list[0].args[0]
71+
)
72+
assert "SELECT *" in mock_client.query.call_args_list[1].args[0]
73+
mock_client.get_table.assert_called_once_with(
74+
"example-project.example_dataset.example_manifest_table"
75+
)
76+
captured = capsys.readouterr()
77+
assert (
78+
"Resource ID: example-project.example_dataset.example_manifest_table"
79+
in captured.out
80+
)
81+
assert "Metadata Cache Mode: AUTOMATIC" in captured.out
82+
assert "Max Staleness: 0-0 0 1:0:0" in captured.out
83+
assert "Rows Returned: 3" in captured.out

0 commit comments

Comments
 (0)