Skip to content

Commit 159a10b

Browse files
committed
feat(bigquery): add bigquery_create_procedure sample to create a SQL stored procedure
Problem: The BigQuery documentation (https://cloud.google.com/bigquery/docs/procedures) needs a standalone, tested Python code sample demonstrating how to create a SQL stored procedure (region tag `bigquery_create_procedure`). Solution: - Add `create_procedure(project_id: str, dataset_id: str) -> None` in `bigquery/stored_procedures/bigquery_create_procedure.py` (Create a reusable multi-statement GoogleSQL stored procedure inside a BigQuery dataset using CREATE OR REPLACE PROCEDURE.) - Add unit tests (`bigquery/stored_procedures/bigquery_create_procedure_test.py`) covering both the success path and API error handling (`GoogleAPICallError`)
1 parent 186be98 commit 159a10b

5 files changed

Lines changed: 173 additions & 0 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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_create_procedure]
16+
import sys
17+
18+
from google.api_core import exceptions
19+
from google.cloud import bigquery
20+
21+
22+
def create_procedure(
23+
project_id: str,
24+
dataset_id: str,
25+
) -> None:
26+
"""Creates a GoogleSQL stored procedure in a BigQuery dataset.
27+
28+
Args:
29+
project_id: Google Cloud project ID (for example, 'example-project').
30+
dataset_id: BigQuery dataset ID where the procedure is created
31+
(for example, 'example_dataset').
32+
"""
33+
client = bigquery.Client(project=project_id)
34+
# Use a fixed procedure identifier inside the caller-supplied dataset.
35+
# The procedure body queries the public Shakespeare dataset in bigquery-public-data
36+
# (https://cloud.google.com/bigquery/public-data).
37+
procedure_id = "example_procedure"
38+
routine_ref = f"{project_id}.{dataset_id}.{procedure_id}"
39+
sql = f"""
40+
CREATE OR REPLACE PROCEDURE `{routine_ref}`(
41+
target_corpus STRING,
42+
OUT total_words INT64
43+
)
44+
BEGIN
45+
SET total_words = (
46+
SELECT COALESCE(SUM(word_count), 0)
47+
FROM `bigquery-public-data.samples.shakespeare`
48+
WHERE corpus = target_corpus
49+
);
50+
END;
51+
"""
52+
53+
try:
54+
print(f"Creating stored procedure: {routine_ref}")
55+
query_job = client.query(sql)
56+
query_job.result()
57+
except exceptions.NotFound as err:
58+
print(
59+
f"error: dataset '{dataset_id}' not found in project '{project_id}' "
60+
f"when creating stored procedure '{procedure_id}': {err.message}",
61+
file=sys.stderr,
62+
)
63+
return
64+
except exceptions.GoogleAPICallError as err:
65+
print(
66+
f"error: failed to create stored procedure '{procedure_id}' in dataset "
67+
f"'{dataset_id}' for project '{project_id}': {err.message}",
68+
file=sys.stderr,
69+
)
70+
return
71+
72+
print(f"Resource ID: {routine_ref}")
73+
print(f"Job ID: {query_job.job_id}")
74+
print(f"Procedure ID: {procedure_id}")
75+
print(f"Statement Type: {query_job.statement_type}")
76+
77+
78+
# [END bigquery_create_procedure]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
import bigquery_create_procedure
18+
from google.api_core import exceptions
19+
import pytest
20+
21+
22+
def test_create_procedure_success(
23+
monkeypatch: pytest.MonkeyPatch,
24+
capsys: pytest.CaptureFixture[str],
25+
) -> None:
26+
mock_client = mock.MagicMock()
27+
mock_job = mock.MagicMock()
28+
mock_job.job_id = "example-job-123"
29+
mock_job.statement_type = "SCRIPT"
30+
mock_job.result.return_value = []
31+
mock_client.query.return_value = mock_job
32+
monkeypatch.setattr(
33+
bigquery_create_procedure.bigquery,
34+
"Client",
35+
lambda project=None: mock_client,
36+
)
37+
38+
bigquery_create_procedure.create_procedure(
39+
project_id="example-project",
40+
dataset_id="example_dataset",
41+
)
42+
43+
captured = capsys.readouterr()
44+
assert "Resource ID:" in captured.out
45+
assert "example-project" in captured.out
46+
assert mock_client.query.called
47+
48+
49+
def test_create_procedure_error(
50+
monkeypatch: pytest.MonkeyPatch,
51+
capsys: pytest.CaptureFixture[str],
52+
) -> None:
53+
mock_client = mock.MagicMock()
54+
mock_job = mock.MagicMock()
55+
mock_job.result.side_effect = exceptions.NotFound("resource error")
56+
mock_client.query.return_value = mock_job
57+
monkeypatch.setattr(
58+
bigquery_create_procedure.bigquery,
59+
"Client",
60+
lambda project=None: mock_client,
61+
)
62+
63+
bigquery_create_procedure.create_procedure(
64+
project_id="example-project",
65+
dataset_id="example_dataset",
66+
)
67+
68+
captured = capsys.readouterr()
69+
assert "error:" in captured.err
70+
assert "example-project" in captured.err
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
TEST_CONFIG_OVERRIDE = {
16+
# You can opt out from the test for specific Python versions.
17+
"ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11"],
18+
# Enforce type hints on new samples.
19+
"enforce_type_hints": True,
20+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
21+
"pip_version_override": None,
22+
"envs": {},
23+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytest==9.0.3; python_version >= "3.10"
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
google-cloud-bigquery==3.47.0

0 commit comments

Comments
 (0)