BigQuery UDFs

BigQuery UDFs

Creates, deploys and troubleshoots BigQuery user-defined functions and remote functions in SQL, JavaScript and Python, including packages and external API calls.

Skill files6 files

references/

SKILL.md411 lines
1
---
2
name: bigquery-udfs
3
metadata:
4
version: "1.0.2"
5
category: BigDataAndAnalytics
6
description: >-
7
Creates, deploys, and troubleshoots BigQuery User-Defined Functions (UDFs)
8
and Remote Functions across SQL, JavaScript, Python, and Cloud Run endpoints.
9
Use when writing custom scalar or aggregate functions in BigQuery, installing
10
PyPI packages or Cloud Storage libraries in a Python or JavaScript UDF, or
11
calling Google Cloud and external APIs from a Python UDF (WITH CONNECTION) or
12
Remote Function. Don't use for standard BigQuery table/dataset CRUD (use
13
bigquery-basics), DataFrames client workflows (use bigquery-bigframes), or
14
BigQuery ML models (use bigquery-ai-ml).
15
---
16
17
# BigQuery User-Defined Functions (UDFs)
18
19
BigQuery User-Defined Functions (UDFs) extend GoogleSQL with custom logic
20
written in SQL, JavaScript, managed Python (`python-3.11`), or hosted externally
21
as Remote Functions on Cloud Run and Cloud Run functions.
22
23
## Usage Attribution
24
25
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
26
MUST read and follow the instructions in
27
[Usage Attribution](references/attribution.md).
28
29
## Choosing the Right UDF Type
30
31
Always select the lightest-weight runtime that satisfies the requirement,
32
because BigQuery optimizes native SQL expressions inline while external runtimes
33
incur serialization and container startup overhead:
34
35
UDF Type | Connection Required? | When to Use | Key Constraints
36
:--------------------------------------------- | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------
37
**SQL UDF** (Default) | No | Composable expressions, regex, struct/array manipulation, aggregate functions (`CREATE AGGREGATE FUNCTION`), or polymorphic `ANY TYPE` parameters. | Lowest latency; zero external dependencies; supports `TEMP` or persistent functions.
38
**JavaScript UDF** | No | Custom string/JSON logic or bundling `.js` libraries from Cloud Storage (`gs://`). | Runs in V8 sandbox; `INT64` unsupported as input (pass as `FLOAT64` or `STRING`). Max 32 KB inline code, 1 MB per external resource. Supports `TEMP` or persistent functions.
39
**Managed Python UDF (Offline)** | **No** | Pure compute using Python 3.11, PyPI wheels (`packages=[...]`), Cloud Storage `.py` modules (`library=[...]`), or vectorized Pandas/PyArrow batches. | Persistent functions only (`CREATE TEMP FUNCTION` unsupported). Outbound network blocked. Max container size: 4 vCPU / 16 GiB. `JSON`, `RANGE`, `INTERVAL`, `GEOGRAPHY` unsupported.
40
**Managed Python UDF (`WITH CONNECTION`)** | **Yes** (`CLOUD_RESOURCE`) | Invoking Google Cloud APIs (e.g., Cloud Translation, Gemini Enterprise Agent Platform) or online HTTP endpoints directly from Python inside BigQuery containers. | Requires `WITH CONNECTION`. Outbound traffic restricted to `restricted.googleapis.com` in VPC-SC perimeters (VPC networks unsupported). Max container size: 4 vCPU / 16 GiB.
41
**Remote Function (`REMOTE WITH CONNECTION`)** | **Yes** (`CLOUD_RESOURCE`) | Calling external APIs or microservices when you need non-Python runtimes (Go, Java, Node.js), private VPC network access, GPUs, or custom Cloud Run scaling. | Requires Cloud Run HTTPS endpoint implementing BigQuery JSON batch contract and `roles/run.invoker`. Max input 5 MB per row; response limit 15 MB (Cloud Run) / 10 MB (1st gen).
42
43
## Prerequisites & Setup
44
45
Ensure the Google Cloud project has an active billing account attached (see
46
[BigQuery Pricing](https://docs.cloud.google.com/bigquery/pricing)):
47
48
1. **Install and Authenticate Google Cloud SDK**: Install the
49
[Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install)
50
and authenticate:
51
52
```bash
53
gcloud auth login
54
```
55
56
Pass `--project={project_id}` and `--region={region}` (or `--location` for
57
`bq`) explicitly on each command instead of running `gcloud config set`,
58
which persists beyond the task. Default to `us-central1` when the user has
59
not specified a region (see
60
[BigQuery Locations](https://docs.cloud.google.com/bigquery/docs/locations.md.txt)).
61
62
2. **Enable Required APIs**:
63
64
- For SQL, JavaScript, and offline Python UDFs: `bigquery.googleapis.com`
65
- Additionally for Python UDFs calling APIs (`WITH CONNECTION`) and Remote
66
Functions: `bigqueryconnection.googleapis.com` (and `run.googleapis.com`
67
for Remote Functions)
68
69
```bash
70
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
71
gcloud services enable bigquery.googleapis.com \
72
bigqueryconnection.googleapis.com \
73
run.googleapis.com --quiet
74
```
75
76
3. **Verify Required IAM Roles**:
77
78
- **All UDFs**: `roles/bigquery.dataEditor` on the dataset and
79
`roles/bigquery.jobUser` on the project.
80
- **When using `WITH CONNECTION` (API-calling Python UDFs & Remote
81
Functions)**:
82
- UDF Creator: `roles/bigquery.connectionAdmin` on the project (plus
83
`resourcemanager.projects.setIamPolicy`, e.g.,
84
`roles/resourcemanager.projectIamAdmin`, when granting project-level
85
IAM roles to the connection service account via `GRANT ... ON
86
PROJECT`).
87
- UDF Caller: `roles/bigquery.connectionUser` on the connection.
88
89
--------------------------------------------------------------------------------
90
91
## Core Implementation Patterns
92
93
### 1. SQL UDFs (Scalar & Templated)
94
95
Use `CREATE OR REPLACE FUNCTION` for persistent UDFs or `CREATE TEMP FUNCTION`
96
for query-scoped functions. Use `ANY TYPE` for polymorphic parameters:
97
98
```sql
99
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.normalize_phone`(
100
raw_phone STRING,
101
country_code ANY TYPE
102
)
103
RETURNS STRING
104
AS (
105
CONCAT('+', CAST(country_code AS STRING), '-', REGEXP_REPLACE(raw_phone, r'[^0-9]', ''))
106
);
107
```
108
109
See [SQL and JavaScript UDFs](references/sql-and-js-udfs.md) for aggregate UDFs
110
(`CREATE AGGREGATE FUNCTION`) and JavaScript Cloud Storage library loading.
111
112
### 2. JavaScript UDFs
113
114
Use raw triple-quoted strings (`r"""..."""`) to avoid escaping backslashes:
115
116
```sql
117
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.extract_url_query_keys`(
118
url_str STRING
119
)
120
RETURNS ARRAY<STRING>
121
DETERMINISTIC
122
LANGUAGE js
123
OPTIONS (
124
library = ['gs://{bucket_name}/libs/uri-parser.js']
125
)
126
AS r"""
127
if (!url_str) return [];
128
try {
129
return URIParser.getQueryKeys(url_str);
130
} catch (err) {
131
return [];
132
}
133
""";
134
```
135
136
### 3. Managed Python UDFs (With and Without Connection)
137
138
Python UDFs must be persistent (do not use `TEMP`), specify `runtime_version =
139
'python-3.11'`, and define an `entry_point`. `numpy`, `pandas`, and `pyarrow`
140
are pre-installed in the `python-3.11` base image.
141
142
BigQuery defaults to `container_memory = '512Mi'`, `container_cpu = 1.0`, and
143
`container_request_concurrency = 80`. Omit these options when the defaults are
144
sufficient, and configure them explicitly only when a workload requires custom
145
container sizing or concurrency (see [Python UDFs](references/python-udfs.md)).
146
147
Top-level Python statements (`import`, helper functions, classes, and `def
148
{entry_point}(...)`) inside `AS r'''...'''` must have **zero leading
149
indentation** (flush to the left margin). Indenting top-level Python definitions
150
to align with surrounding SQL causes an `IndentationError` when BigQuery loads
151
the container module.
152
153
#### A. Offline / Vectorized Python UDF (No Connection Needed)
154
155
Omit `WITH CONNECTION` when the UDF only performs computation or uses PyPI
156
packages (`packages=[...]`) / Cloud Storage libraries (`library=['gs://...']`).
157
To vectorize execution over batches of rows, annotate the parameter with
158
`pd.DataFrame` (or `pyarrow.RecordBatch`) and return a `pd.Series`:
159
160
> [!WARNING] **Vectorized operations must be row-independent**: BigQuery calls
161
> vectorized UDFs on arbitrary row batches (up to `max_batching_rows`). Do NOT
162
> compute global column statistics (such as z-scores, dataset mean/std, or rank)
163
> across `df`, because each batch only sees an arbitrary slice of rows. Use SQL
164
> window functions (`(val - AVG(val) OVER()) / NULLIF(STDDEV(val) OVER(), 0)`)
165
> for dataset-wide statistics. Vectorized Python UDFs should perform
166
> row-independent calculations (e.g. geometric distances or multi-column math).
167
168
```sql
169
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.vectorized_distance`(
170
x1 FLOAT64, y1 FLOAT64, x2 FLOAT64, y2 FLOAT64
171
)
172
RETURNS FLOAT64
173
LANGUAGE python
174
OPTIONS (
175
runtime_version = 'python-3.11',
176
entry_point = 'compute_distance'
177
)
178
AS r'''
179
import numpy as np
180
import pandas as pd
181
182
def compute_distance(df: pd.DataFrame) -> pd.Series:
183
return pd.Series(
184
np.hypot(df['x2'] - df['x1'], df['y2'] - df['y1']),
185
index=df.index,
186
)
187
''';
188
```
189
190
#### B. Online Python UDF Calling an External / Cloud API (`WITH CONNECTION`)
191
192
Include `WITH CONNECTION` **only** when the Python code makes outbound network
193
or API calls at runtime.
194
195
Always configure explicit timeouts, logging, and prescriptive exception handling
196
in the `try...except` block:
197
198
- **Transient errors only → `NULL`**: Catch retryable exceptions
199
(`google.api_core.exceptions.TooManyRequests`, `ServiceUnavailable`,
200
`DeadlineExceeded`, `InternalServerError`, and `RetryError`), log them with
201
`logging.warning`, and return `None` so a transient blip does not abort the
202
query. Do **not** catch the base class `GoogleAPICallError` here: it also
203
matches `PermissionDenied`, `Unauthenticated`, and `InvalidArgument`.
204
- **Fatal errors → raise**: Let auth, permission, and invalid-argument errors
205
propagate (or log and re-raise as `RuntimeError`) so they surface as a user
206
error on the query instead of silently producing `NULL`s.
207
- **Never log row values**: Anyone with Cloud Logging access can read UDF logs
208
regardless of BigQuery table permissions. Log exception types and messages,
209
not input or output data. Logs are only emitted when the session sets `SET
210
@@udf.properties = JSON '{"enableDebugOutput": true}';`.
211
- **Set a per-request `timeout`**: `Retry(timeout=...)` only caps the total
212
retry duration; also pass `timeout=` on each client call.
213
214
1. **Create a Cloud Resource Connection and Retrieve its Service Account**:
215
216
```bash
217
bq mk --connection --connection_type=CLOUD_RESOURCE \
218
--location={region} --project_id={project_id} {connection_id}
219
220
bq show --connection {project_id}.{region}.{connection_id}
221
```
222
2. **Grant Permissions to the Connection Service Account**: Grant
223
`roles/serviceusage.serviceUsageConsumer` on `{project_id}` plus the
224
required API role (e.g., `roles/cloudtranslate.user`) on the target project.
225
Running `GRANT ... ON PROJECT` modifies the project's IAM policy and
226
requires `resourcemanager.projects.setIamPolicy` (for example,
227
`roles/resourcemanager.projectIamAdmin`); **confirm with the user before
228
running project-level IAM grants**. The DCL `connection:` grantee takes the
229
connection path (`[project_id.]location.connection_id`), not the service
230
account email; BigQuery resolves the connection's service account
231
automatically (use `"serviceAccount:{connection_sa_email}"` to grant by
232
email instead):
233
234
```sql
235
GRANT `roles/serviceusage.serviceUsageConsumer`
236
ON PROJECT `{project_id}`
237
TO "connection:{project_id}.{region}.{connection_id}";
238
239
GRANT `roles/cloudtranslate.user`
240
ON PROJECT `{project_id}`
241
TO "connection:{project_id}.{region}.{connection_id}";
242
```
243
3. **Create the Python UDF with `WITH CONNECTION`** (keep top-level Python
244
statements flush-left at column 0):
245
246
```sql
247
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.translate_to_es`(
248
text STRING
249
)
250
RETURNS STRING
251
LANGUAGE python
252
WITH CONNECTION `{project_id}.{region}.{connection_id}`
253
OPTIONS (
254
entry_point = 'do_translate',
255
runtime_version = 'python-3.11',
256
packages = ['google-cloud-translate>=3.11', 'google-api-core']
257
)
258
AS r'''
259
import logging
260
from google.api_core import exceptions
261
from google.api_core.retry import Retry
262
from google.cloud import translate
263
264
client = translate.TranslationServiceClient()
265
266
TRANSIENT_ERRORS = (
267
exceptions.TooManyRequests,
268
exceptions.ServiceUnavailable,
269
exceptions.DeadlineExceeded,
270
exceptions.InternalServerError,
271
exceptions.RetryError,
272
)
273
274
def do_translate(text: str) -> str:
275
if not text:
276
return None
277
try:
278
# Note: Replace {project_id} with your Google Cloud Project ID
279
response = client.translate_text(
280
request={
281
"parent": "projects/{project_id}/locations/us-central1",
282
"contents": [text],
283
"target_language_code": "es",
284
"mime_type": "text/plain",
285
},
286
retry=Retry(timeout=30.0), # Total retry budget.
287
timeout=10.0, # Per-attempt deadline.
288
)
289
return response.translations[0].translated_text
290
except TRANSIENT_ERRORS as e:
291
# Log the error type only; never log row values.
292
logging.warning("Transient Translation API error: %s", type(e).__name__)
293
return None
294
except exceptions.GoogleAPICallError as e:
295
# PermissionDenied, Unauthenticated, InvalidArgument, etc. are fatal.
296
logging.error("Fatal Translation API error: %s: %s", type(e).__name__, e)
297
raise RuntimeError(f"Translation failed: {type(e).__name__}") from e
298
''';
299
```
300
301
See [Python UDFs](references/python-udfs.md) for container sizing
302
(`container_cpu`, `container_memory`, `container_request_concurrency`), Cloud
303
Logging (`SET @@udf.properties = JSON '{"enableDebugOutput": true}';`), and
304
checking container build status via `INFORMATION_SCHEMA.ROUTINES`.
305
306
### 4. Remote Functions (Cloud Run Endpoints)
307
308
Use Remote Functions when the endpoint is hosted on Cloud Run or Cloud Run
309
functions (for non-Python languages, VPC networking, or custom hardware):
310
311
1. **Grant `roles/run.invoker` to the Connection Service Account** (confirm
312
with the user before modifying the Cloud Run service IAM policy):
313
314
```bash
315
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
316
gcloud run services add-iam-policy-binding {cloud_run_service} \
317
--region={region} \
318
--member="serviceAccount:{connection_sa_email}" \
319
--role="roles/run.invoker"
320
```
321
2. **Register the Remote Function**: The endpoint must accept `{"calls":
322
[[arg1, ...], ...]}` and return `{"replies": [res1, ...]}` with matching
323
element count:
324
325
```sql
326
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.enrich_address`(
327
street STRING, postal_code STRING
328
)
329
RETURNS JSON
330
REMOTE WITH CONNECTION `{project_id}.{region}.{connection_id}`
331
OPTIONS (
332
endpoint = 'https://{cloud_run_service_url}',
333
max_batching_rows = 1000
334
);
335
```
336
337
See [Remote Functions](references/remote-functions.md) for Cloud Run handler
338
templates, batch limits (`max_batching_rows`, 5 MB max input per row, 15 MB max
339
response on Cloud Run / 10 MB on 1st gen functions), and error/retry semantics
340
(BigQuery automatically retries a batch only on HTTP `408`, `429`, `500`, `503`,
341
or `504`; any other non-200 status or JSON `{"errorMessage": "..."}` fails the
342
query without retrying).
343
344
--------------------------------------------------------------------------------
345
346
## Validation Checklist
347
348
After generating or modifying a UDF, follow this validate→fix→repeat loop:
349
350
- [ ] **Step 1 — Validate Python code before BigQuery DDL**: For Python UDFs,
351
validate the Python function and `packages` dependencies *before* submitting
352
the BigQuery DDL—either locally with `python3` test inputs (`None`, edge
353
cases, `pd.DataFrame` batches) or in a containerized Cloud Run Job (`gcloud
354
run jobs deploy {job_name} --source . --region={region}` and `gcloud run
355
jobs execute {job_name} --region={region} --wait`; see
356
[Python UDFs Validation](references/python-udfs.md#validation-workflow)).
357
- [ ] **Step 2 — Execute DDL and poll container build status**: Run `CREATE OR
358
REPLACE FUNCTION`. Because the DDL statement returns *before* the Python
359
container image finishes building, poll `INFORMATION_SCHEMA.ROUTINES` until
360
`build_state` transitions from `IN_PROGRESS` to `SUCCEEDED` (or fix and
361
re-run if `FAILED`):
362
363
```sql
364
SELECT build_status.*
365
FROM `{project_id}.{dataset_id}`.INFORMATION_SCHEMA.ROUTINES
366
WHERE routine_name = '{udf_name}';
367
```
368
- [ ] **Step 3 — Test the UDF with SQL `SELECT`**: Once `build_state =
369
'SUCCEEDED'` (or immediately after DDL for SQL/JS UDFs), run a test `SELECT`
370
query covering `NULL` and valid inputs.
371
372
## Cleanup & Teardown
373
374
Delete unused routines, connections, Cloud Run services, and staged Cloud
375
Storage artifacts (note that the size of all Python UDF containers per project
376
and per region is restricted to a sum total of 10 GiB):
377
378
```bash
379
bq query --use_legacy_sql=false "DROP FUNCTION IF EXISTS \`{project_id}.{dataset_id}.{udf_name}\`;"
380
bq rm --connection --location={region} {connection_id}
381
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
382
gcloud run services delete {cloud_run_service} --region={region} --project={project_id}
383
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
384
gcloud storage rm gs://{bucket_name}/udf_libs/bundle.js
385
```
386
387
## Reference Directory
388
389
- [SQL and JavaScript UDFs](references/sql-and-js-udfs.md): Templated SQL
390
parameters (`ANY TYPE`), aggregate UDFs, JavaScript type mappings, and Cloud
391
Storage library loading
392
(`https://docs.cloud.google.com/bigquery/docs/user-defined-functions.md.txt`).
393
- [Python UDFs](references/python-udfs.md): Offline vs. `WITH CONNECTION`
394
online service access, Pandas/PyArrow vectorization, container resource
395
limits (`container_cpu`/`container_memory`), and Cloud Logging debugging
396
(`https://docs.cloud.google.com/bigquery/docs/user-defined-functions-python.md.txt`).
397
- [Remote Functions](references/remote-functions.md): Cloud Run HTTP request
398
and response JSON schema, batch sizing, retry semantics, and VPC egress
399
(`https://docs.cloud.google.com/bigquery/docs/remote-functions.md.txt`).
400
- [IAM, Authorized Routines, and Quotas](references/iam-and-quotas.md):
401
Sharing routines across datasets (`Authorized Routines`), container quotas,
402
and troubleshooting errors.
403
404
## Related Skills
405
406
- **BigQuery Basics** (`bigquery-basics`): Dataset, table, and job management.
407
- The `bigquery-bigframes` skill: Creating Python UDFs from Python via
408
`@bpd.udf`.
409
- The `bigquery-ai-ml` skill: Built-in `AI.GENERATE_TEXT` and
410
`AI.GENERATE` functions.
411

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…