Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-udfs@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin bigquery-udfs v1.0.0 follows the Agent Plugins spec.
gh skills-hub install bigquery-udfs Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/bigquery-udfs/ Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-udfs for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 18.8 KB
---
name: bigquery-udfs
metadata:
version: "1.0.2"
category: BigDataAndAnalytics
description: >-
Creates, deploys, and troubleshoots BigQuery User-Defined Functions (UDFs)
and Remote Functions across SQL, JavaScript, Python, and Cloud Run endpoints.
Use when writing custom scalar or aggregate functions in BigQuery, installing
PyPI packages or Cloud Storage libraries in a Python or JavaScript UDF, or
calling Google Cloud and external APIs from a Python UDF (WITH CONNECTION) or
Remote Function. Don't use for standard BigQuery table/dataset CRUD (use
bigquery-basics), DataFrames client workflows (use bigquery-bigframes), or
BigQuery ML models (use bigquery-ai-ml).
---
# BigQuery User-Defined Functions (UDFs)
BigQuery User-Defined Functions (UDFs) extend GoogleSQL with custom logic
written in SQL, JavaScript, managed Python (`python-3.11`), or hosted externally
as Remote Functions on Cloud Run and Cloud Run functions.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Choosing the Right UDF Type
Always select the lightest-weight runtime that satisfies the requirement,
because BigQuery optimizes native SQL expressions inline while external runtimes
incur serialization and container startup overhead:
UDF Type | Connection Required? | When to Use | Key Constraints
:--------------------------------------------- | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------
**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.
**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.
**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.
**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.
**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).
## Prerequisites & Setup
Ensure the Google Cloud project has an active billing account attached (see
[BigQuery Pricing](https://docs.cloud.google.com/bigquery/pricing)):
1. **Install and Authenticate Google Cloud SDK**: Install the
[Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install)
and authenticate:
```bash
gcloud auth login
```
Pass `--project={project_id}` and `--region={region}` (or `--location` for
`bq`) explicitly on each command instead of running `gcloud config set`,
which persists beyond the task. Default to `us-central1` when the user has
not specified a region (see
[BigQuery Locations](https://docs.cloud.google.com/bigquery/docs/locations.md.txt)).
2. **Enable Required APIs**:
- For SQL, JavaScript, and offline Python UDFs: `bigquery.googleapis.com`
- Additionally for Python UDFs calling APIs (`WITH CONNECTION`) and Remote
Functions: `bigqueryconnection.googleapis.com` (and `run.googleapis.com`
for Remote Functions)
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
gcloud services enable bigquery.googleapis.com \
bigqueryconnection.googleapis.com \
run.googleapis.com --quiet
```
3. **Verify Required IAM Roles**:
- **All UDFs**: `roles/bigquery.dataEditor` on the dataset and
`roles/bigquery.jobUser` on the project.
- **When using `WITH CONNECTION` (API-calling Python UDFs & Remote
Functions)**:
- UDF Creator: `roles/bigquery.connectionAdmin` on the project (plus
`resourcemanager.projects.setIamPolicy`, e.g.,
`roles/resourcemanager.projectIamAdmin`, when granting project-level
IAM roles to the connection service account via `GRANT ... ON
PROJECT`).
- UDF Caller: `roles/bigquery.connectionUser` on the connection.
--------------------------------------------------------------------------------
## Core Implementation Patterns
### 1. SQL UDFs (Scalar & Templated)
Use `CREATE OR REPLACE FUNCTION` for persistent UDFs or `CREATE TEMP FUNCTION`
for query-scoped functions. Use `ANY TYPE` for polymorphic parameters:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.normalize_phone`(
raw_phone STRING,
country_code ANY TYPE
)
RETURNS STRING
AS (
CONCAT('+', CAST(country_code AS STRING), '-', REGEXP_REPLACE(raw_phone, r'[^0-9]', ''))
);
```
See [SQL and JavaScript UDFs](references/sql-and-js-udfs.md) for aggregate UDFs
(`CREATE AGGREGATE FUNCTION`) and JavaScript Cloud Storage library loading.
### 2. JavaScript UDFs
Use raw triple-quoted strings (`r"""..."""`) to avoid escaping backslashes:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.extract_url_query_keys`(
url_str STRING
)
RETURNS ARRAY<STRING>
DETERMINISTIC
LANGUAGE js
OPTIONS (
library = ['gs://{bucket_name}/libs/uri-parser.js']
)
AS r"""
if (!url_str) return [];
try {
return URIParser.getQueryKeys(url_str);
} catch (err) {
return [];
}
""";
```
### 3. Managed Python UDFs (With and Without Connection)
Python UDFs must be persistent (do not use `TEMP`), specify `runtime_version =
'python-3.11'`, and define an `entry_point`. `numpy`, `pandas`, and `pyarrow`
are pre-installed in the `python-3.11` base image.
BigQuery defaults to `container_memory = '512Mi'`, `container_cpu = 1.0`, and
`container_request_concurrency = 80`. Omit these options when the defaults are
sufficient, and configure them explicitly only when a workload requires custom
container sizing or concurrency (see [Python UDFs](references/python-udfs.md)).
Top-level Python statements (`import`, helper functions, classes, and `def
{entry_point}(...)`) inside `AS r'''...'''` must have **zero leading
indentation** (flush to the left margin). Indenting top-level Python definitions
to align with surrounding SQL causes an `IndentationError` when BigQuery loads
the container module.
#### A. Offline / Vectorized Python UDF (No Connection Needed)
Omit `WITH CONNECTION` when the UDF only performs computation or uses PyPI
packages (`packages=[...]`) / Cloud Storage libraries (`library=['gs://...']`).
To vectorize execution over batches of rows, annotate the parameter with
`pd.DataFrame` (or `pyarrow.RecordBatch`) and return a `pd.Series`:
> [!WARNING] **Vectorized operations must be row-independent**: BigQuery calls
> vectorized UDFs on arbitrary row batches (up to `max_batching_rows`). Do NOT
> compute global column statistics (such as z-scores, dataset mean/std, or rank)
> across `df`, because each batch only sees an arbitrary slice of rows. Use SQL
> window functions (`(val - AVG(val) OVER()) / NULLIF(STDDEV(val) OVER(), 0)`)
> for dataset-wide statistics. Vectorized Python UDFs should perform
> row-independent calculations (e.g. geometric distances or multi-column math).
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.vectorized_distance`(
x1 FLOAT64, y1 FLOAT64, x2 FLOAT64, y2 FLOAT64
)
RETURNS FLOAT64
LANGUAGE python
OPTIONS (
runtime_version = 'python-3.11',
entry_point = 'compute_distance'
)
AS r'''
import numpy as np
import pandas as pd
def compute_distance(df: pd.DataFrame) -> pd.Series:
return pd.Series(
np.hypot(df['x2'] - df['x1'], df['y2'] - df['y1']),
index=df.index,
)
''';
```
#### B. Online Python UDF Calling an External / Cloud API (`WITH CONNECTION`)
Include `WITH CONNECTION` **only** when the Python code makes outbound network
or API calls at runtime.
Always configure explicit timeouts, logging, and prescriptive exception handling
in the `try...except` block:
- **Transient errors only → `NULL`**: Catch retryable exceptions
(`google.api_core.exceptions.TooManyRequests`, `ServiceUnavailable`,
`DeadlineExceeded`, `InternalServerError`, and `RetryError`), log them with
`logging.warning`, and return `None` so a transient blip does not abort the
query. Do **not** catch the base class `GoogleAPICallError` here: it also
matches `PermissionDenied`, `Unauthenticated`, and `InvalidArgument`.
- **Fatal errors → raise**: Let auth, permission, and invalid-argument errors
propagate (or log and re-raise as `RuntimeError`) so they surface as a user
error on the query instead of silently producing `NULL`s.
- **Never log row values**: Anyone with Cloud Logging access can read UDF logs
regardless of BigQuery table permissions. Log exception types and messages,
not input or output data. Logs are only emitted when the session sets `SET
@@udf.properties = JSON '{"enableDebugOutput": true}';`.
- **Set a per-request `timeout`**: `Retry(timeout=...)` only caps the total
retry duration; also pass `timeout=` on each client call.
1. **Create a Cloud Resource Connection and Retrieve its Service Account**:
```bash
bq mk --connection --connection_type=CLOUD_RESOURCE \
--location={region} --project_id={project_id} {connection_id}
bq show --connection {project_id}.{region}.{connection_id}
```
2. **Grant Permissions to the Connection Service Account**: Grant
`roles/serviceusage.serviceUsageConsumer` on `{project_id}` plus the
required API role (e.g., `roles/cloudtranslate.user`) on the target project.
Running `GRANT ... ON PROJECT` modifies the project's IAM policy and
requires `resourcemanager.projects.setIamPolicy` (for example,
`roles/resourcemanager.projectIamAdmin`); **confirm with the user before
running project-level IAM grants**. The DCL `connection:` grantee takes the
connection path (`[project_id.]location.connection_id`), not the service
account email; BigQuery resolves the connection's service account
automatically (use `"serviceAccount:{connection_sa_email}"` to grant by
email instead):
```sql
GRANT `roles/serviceusage.serviceUsageConsumer`
ON PROJECT `{project_id}`
TO "connection:{project_id}.{region}.{connection_id}";
GRANT `roles/cloudtranslate.user`
ON PROJECT `{project_id}`
TO "connection:{project_id}.{region}.{connection_id}";
```
3. **Create the Python UDF with `WITH CONNECTION`** (keep top-level Python
statements flush-left at column 0):
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.translate_to_es`(
text STRING
)
RETURNS STRING
LANGUAGE python
WITH CONNECTION `{project_id}.{region}.{connection_id}`
OPTIONS (
entry_point = 'do_translate',
runtime_version = 'python-3.11',
packages = ['google-cloud-translate>=3.11', 'google-api-core']
)
AS r'''
import logging
from google.api_core import exceptions
from google.api_core.retry import Retry
from google.cloud import translate
client = translate.TranslationServiceClient()
TRANSIENT_ERRORS = (
exceptions.TooManyRequests,
exceptions.ServiceUnavailable,
exceptions.DeadlineExceeded,
exceptions.InternalServerError,
exceptions.RetryError,
)
def do_translate(text: str) -> str:
if not text:
return None
try:
# Note: Replace {project_id} with your Google Cloud Project ID
response = client.translate_text(
request={
"parent": "projects/{project_id}/locations/us-central1",
"contents": [text],
"target_language_code": "es",
"mime_type": "text/plain",
},
retry=Retry(timeout=30.0), # Total retry budget.
timeout=10.0, # Per-attempt deadline.
)
return response.translations[0].translated_text
except TRANSIENT_ERRORS as e:
# Log the error type only; never log row values.
logging.warning("Transient Translation API error: %s", type(e).__name__)
return None
except exceptions.GoogleAPICallError as e:
# PermissionDenied, Unauthenticated, InvalidArgument, etc. are fatal.
logging.error("Fatal Translation API error: %s: %s", type(e).__name__, e)
raise RuntimeError(f"Translation failed: {type(e).__name__}") from e
''';
```
See [Python UDFs](references/python-udfs.md) for container sizing
(`container_cpu`, `container_memory`, `container_request_concurrency`), Cloud
Logging (`SET @@udf.properties = JSON '{"enableDebugOutput": true}';`), and
checking container build status via `INFORMATION_SCHEMA.ROUTINES`.
### 4. Remote Functions (Cloud Run Endpoints)
Use Remote Functions when the endpoint is hosted on Cloud Run or Cloud Run
functions (for non-Python languages, VPC networking, or custom hardware):
1. **Grant `roles/run.invoker` to the Connection Service Account** (confirm
with the user before modifying the Cloud Run service IAM policy):
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
gcloud run services add-iam-policy-binding {cloud_run_service} \
--region={region} \
--member="serviceAccount:{connection_sa_email}" \
--role="roles/run.invoker"
```
2. **Register the Remote Function**: The endpoint must accept `{"calls":
[[arg1, ...], ...]}` and return `{"replies": [res1, ...]}` with matching
element count:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.enrich_address`(
street STRING, postal_code STRING
)
RETURNS JSON
REMOTE WITH CONNECTION `{project_id}.{region}.{connection_id}`
OPTIONS (
endpoint = 'https://{cloud_run_service_url}',
max_batching_rows = 1000
);
```
See [Remote Functions](references/remote-functions.md) for Cloud Run handler
templates, batch limits (`max_batching_rows`, 5 MB max input per row, 15 MB max
response on Cloud Run / 10 MB on 1st gen functions), and error/retry semantics
(BigQuery automatically retries a batch only on HTTP `408`, `429`, `500`, `503`,
or `504`; any other non-200 status or JSON `{"errorMessage": "..."}` fails the
query without retrying).
--------------------------------------------------------------------------------
## Validation Checklist
After generating or modifying a UDF, follow this validate→fix→repeat loop:
- [ ] **Step 1 — Validate Python code before BigQuery DDL**: For Python UDFs,
validate the Python function and `packages` dependencies *before* submitting
the BigQuery DDL—either locally with `python3` test inputs (`None`, edge
cases, `pd.DataFrame` batches) or in a containerized Cloud Run Job (`gcloud
run jobs deploy {job_name} --source . --region={region}` and `gcloud run
jobs execute {job_name} --region={region} --wait`; see
[Python UDFs Validation](references/python-udfs.md#validation-workflow)).
- [ ] **Step 2 — Execute DDL and poll container build status**: Run `CREATE OR
REPLACE FUNCTION`. Because the DDL statement returns *before* the Python
container image finishes building, poll `INFORMATION_SCHEMA.ROUTINES` until
`build_state` transitions from `IN_PROGRESS` to `SUCCEEDED` (or fix and
re-run if `FAILED`):
```sql
SELECT build_status.*
FROM `{project_id}.{dataset_id}`.INFORMATION_SCHEMA.ROUTINES
WHERE routine_name = '{udf_name}';
```
- [ ] **Step 3 — Test the UDF with SQL `SELECT`**: Once `build_state =
'SUCCEEDED'` (or immediately after DDL for SQL/JS UDFs), run a test `SELECT`
query covering `NULL` and valid inputs.
## Cleanup & Teardown
Delete unused routines, connections, Cloud Run services, and staged Cloud
Storage artifacts (note that the size of all Python UDF containers per project
and per region is restricted to a sum total of 10 GiB):
```bash
bq query --use_legacy_sql=false "DROP FUNCTION IF EXISTS \`{project_id}.{dataset_id}.{udf_name}\`;"
bq rm --connection --location={region} {connection_id}
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
gcloud run services delete {cloud_run_service} --region={region} --project={project_id}
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
gcloud storage rm gs://{bucket_name}/udf_libs/bundle.js
```
## Reference Directory
- [SQL and JavaScript UDFs](references/sql-and-js-udfs.md): Templated SQL
parameters (`ANY TYPE`), aggregate UDFs, JavaScript type mappings, and Cloud
Storage library loading
(`https://docs.cloud.google.com/bigquery/docs/user-defined-functions.md.txt`).
- [Python UDFs](references/python-udfs.md): Offline vs. `WITH CONNECTION`
online service access, Pandas/PyArrow vectorization, container resource
limits (`container_cpu`/`container_memory`), and Cloud Logging debugging
(`https://docs.cloud.google.com/bigquery/docs/user-defined-functions-python.md.txt`).
- [Remote Functions](references/remote-functions.md): Cloud Run HTTP request
and response JSON schema, batch sizing, retry semantics, and VPC egress
(`https://docs.cloud.google.com/bigquery/docs/remote-functions.md.txt`).
- [IAM, Authorized Routines, and Quotas](references/iam-and-quotas.md):
Sharing routines across datasets (`Authorized Routines`), container quotas,
and troubleshooting errors.
## Related Skills
- **BigQuery Basics** (`bigquery-basics`): Dataset, table, and job management.
- The `bigquery-bigframes` skill: Creating Python UDFs from Python via
`@bpd.udf`.
- The `bigquery-ai-ml` skill: Built-in `AI.GENERATE_TEXT` and
`AI.GENERATE` functions.
attribution.md 1.8 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-udfs)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include `agent-skills/1.0 (skill:bigquery-udfs)` in the `User-Agent`
header. If a `User-Agent` header is already specified, append this string to
the end of it rather than overwriting existing `User-Agent` data — the
collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
tokens, so any rewording breaks attribution:
```text
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:bigquery-udfs)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
iam-and-quotas.md 7.2 KB
# BigQuery UDF IAM, Authorized Routines, and Quotas Reference
## Table of Contents
- [1. IAM Roles Matrix by UDF Type](#iam-matrix)
- [2. Sharing UDFs Across Datasets (Authorized Routines)](#authorized-routines)
- [3. Quotas, Limits & Troubleshooting Common Errors](#quotas-troubleshooting)
--------------------------------------------------------------------------------
## 1. IAM Roles Matrix by UDF Type {#iam-matrix}
<a id="iam-matrix"></a>
Grant the least-privilege predefined IAM roles based on whether the principal
authors the UDF or invokes an existing UDF:
Persona & Action | SQL / JS / Offline Python UDF | Python UDF (`WITH CONNECTION`) | Remote Function (`REMOTE WITH CONNECTION`)
:------------------------------------------------ | :------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- | :-----------------------------------------
**UDF Author** (Create / Replace UDF) | `roles/bigquery.dataEditor` (dataset) + `roles/bigquery.jobUser` (project) | Same + `roles/bigquery.connectionAdmin` (project); `roles/resourcemanager.projectIamAdmin` if running `GRANT ... ON PROJECT` | Same + `roles/bigquery.connectionAdmin` (project)
**UDF Caller** (Invoke in `SELECT`) | `roles/bigquery.dataViewer` (dataset) + `roles/bigquery.user` (project) | Same + `roles/bigquery.connectionUser` (connection) | Same + `roles/bigquery.connectionUser` (connection)
**Connection Service Account** (`connection-...`) | N/A (No connection used) | `roles/serviceusage.serviceUsageConsumer` (query project) + Target API role (e.g., `roles/cloudtranslate.user`) | `roles/run.invoker` on the Cloud Run service (or `roles/cloudfunctions.invoker`)
> [!NOTE] If a JavaScript or Python UDF loads files from Cloud Storage via
> `OPTIONS(library=['gs://...'])`, the user creating or running the UDF also
> requires `roles/storage.objectViewer` (`storage.objects.get`) on the bucket.
--------------------------------------------------------------------------------
## 2. Sharing UDFs Across Datasets (Authorized Routines) {#authorized-routines}
<a id="authorized-routines"></a>
Authorize a SQL UDF (or table function / stored procedure whose SQL body
references tables) to read tables in a protected source dataset without granting
end users direct `roles/bigquery.dataViewer` access to the underlying tables:
1. **Create the UDF in a Shared Dataset (`{shared_dataset_id}`)**:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{shared_dataset_id}.get_masked_salary`(
emp_id INT64
)
RETURNS FLOAT64
AS ((
SELECT ROUND(salary, -3)
FROM `{project_id}.{sensitive_dataset_id}.employees`
WHERE employee_id = emp_id
));
```
2. **Authorize the Routine on `{sensitive_dataset_id}`**: Updating the source
dataset's `access` array requires `bigquery.datasets.update` (for example,
`roles/bigquery.dataOwner` on `{sensitive_dataset_id}`, which is not
included in `roles/bigquery.dataEditor`). Confirm with the user before
modifying dataset ACLs, then update the `access` array using `bq show
--format=prettyjson` and `bq update --source` to add an entry with
`"routine"`:
```json
{
"routine": {
"projectId": "{project_id}",
"datasetId": "{shared_dataset_id}",
"routineId": "get_masked_salary"
}
}
```
3. **Grant End Users Access to `{shared_dataset_id}`**: Grant
`roles/bigquery.dataViewer` on `{shared_dataset_id}` to the caller.
> [!WARNING] **Modifying a routine invalidates its authorization**: Every time
> you update an authorized routine via `CREATE OR REPLACE FUNCTION` (or `bq
> update`), BigQuery invalidates its existing dataset authorization and callers
> fail with `Access Denied: Table ...` until you re-authorize the routine on
> `{sensitive_dataset_id}`. For immediate effect without propagation delay,
> remove the stale routine entry from `{sensitive_dataset_id}`'s `access` array
> before re-adding it.
--------------------------------------------------------------------------------
## 3. Quotas, Limits & Troubleshooting Common Errors {#quotas-troubleshooting}
<a id="quotas-troubleshooting"></a>
Resource / Limit | Quota / Threshold | Remediation / Best Practice
:------------------------------------------ | :----------------------------------------------------------------------------------------------------------------- | :--------------------------
**Python UDF Container Size / Storage** | **10 GiB** sum total per project per region (applies to built container image size, not runtime RAM) | Drop unused Python UDFs (`DROP FUNCTION`) to free container image quota.
**Python UDF Container Specs** | Max **4 vCPU** and **16 GiB** memory | Use vectorized execution (`pd.DataFrame` / `pa.RecordBatch`) or offload heavier workloads to a Remote Function.
**JavaScript UDF Limits** | 5 MB output/row; 32 KB inline code; 1 MB/file; 50 files; ~5 min timeout | Split large lookups into BigQuery tables; bundle JS libraries under 1 MB.
**Python UDF Quotas** | 30 creates/updates/min; 10 concurrent queries per project | Stagger DDL deploys; pool concurrent query traffic across projects.
**Remote Function HTTP Response & Timeout** | 15 MB (Cloud Run / 2nd gen) / 10 MB (1st gen); 20 min (Cloud Run) / 9 min (1st gen) timeout; 10 concurrent queries | Lower `max_batching_rows` in `OPTIONS(...)` if row payloads are large.
### Common Error Diagnosis
- **`Connection timeout` inside a Python UDF**: The Python code attempted an
outbound network request without a `WITH CONNECTION` clause (or inside a
VPC-SC perimeter to an unsupported host). Attach `WITH CONNECTION` and grant
`roles/serviceusage.serviceUsageConsumer` to the connection service account.
- **`Access Denied: Response code 403` on Remote Function**: The connection
service account (`bq show --connection`) is missing `roles/run.invoker` on
the target Cloud Run service.
- **`Invalid CPU/Memory combination` on Python UDF**: Verify `container_cpu`
and `container_memory` against the compatibility matrix in
[python-udfs.md](python-udfs.md).
- **`Flight error: ... unexpected indent` on Python UDF**: Module-level Python
code (`import`, `def`) inside `AS r'''...'''` has leading indentation. Flush
all top-level statements to column 0 (no leading spaces).
- **Query invoking a Python UDF remains queued in `RUNNING`**: The first query
after creating/updating a Python UDF waits for the container image build to
complete (check `build_status.build_state` in
`INFORMATION_SCHEMA.ROUTINES`).
python-udfs.md 19.2 KB
# BigQuery Managed Python UDFs Reference
## Table of Contents
- [1. Runtime Environment & Limitations](#runtime-environment)
- [2. Data Type Mappings](#data-type-mappings)
- [3. Vectorized Execution (Pandas & PyArrow)](#vectorized-execution)
- [4. Third-Party Dependencies (PyPI & GCS)](#dependencies)
- [5. Container Resource Limits](#resource-limits)
- [6. Calling Online Services & APIs](#calling-apis)
- [7. End-to-End Validation & Debugging](#validation-workflow)
--------------------------------------------------------------------------------
## 1. Runtime Environment & Limitations {#runtime-environment}
<a id="runtime-environment"></a>
BigQuery builds and executes Python UDFs on managed containers using the
`python-3.11` base image.
### Pre-installed Packages (`python-3.11`)
Do not list these packages in `OPTIONS(packages=[...])`. Listing one without a
version is a no-op (BigQuery uses the pre-installed version); only list it with
an explicit version specifier (e.g., `'pandas==2.2.2'`) when you need a
different version, which triggers an install during the container build:
Package | Pre-installed Version
:------------------------ | :-----------------------------------
`numpy` | `1.26.3`
`pandas` | `2.1.4`
`pyarrow` | `14.0.2`
`python-dateutil` | `2.8.2`
`absl-py` | `2.0.0`
`pytz` / `tzdata` / `six` | `2023.3.post1` / `2023.4` / `1.16.0`
### Hard Constraints
- **No temporary functions**: Never use `CREATE TEMP FUNCTION` or `TEMPORARY`
with `LANGUAGE python`; BigQuery requires a persistent dataset target to
store and track the built container artifact.
- **Unsupported BigQuery types**: Do not use `JSON`, `RANGE`, `INTERVAL`, or
`GEOGRAPHY` as parameter or `RETURNS` types. Pass JSON payloads as `STRING`
and parse with Python's `json.loads()` inside the UDF.
- **No query result caching**: Queries invoking a Python UDF are never cached
because Python UDFs are always treated as non-deterministic.
- **No Materialized Views or CMEK**: Do not reference Python UDFs in
materialized views or encrypt them with CMEK.
- **Regional Container Size Quota**: The size of all Python UDF containers per
project and per region is restricted to a sum total of **10 GiB**. Note that
this limit is for the **container size** (the built container image storage
footprint on disk), not the runtime container execution memory
(`container_memory`). Drop unused Python UDFs to reclaim quota.
- **Zero top-level indentation**: Module-level Python lines (`import`, helper
functions, classes, and `def {entry_point}(...)`) inside `AS r'''...'''`
must have **zero leading spaces** (flush to the left margin). Indenting
module-level Python to match SQL indentation causes `IndentationError`.
--------------------------------------------------------------------------------
## 2. Data Type Mappings {#data-type-mappings}
<a id="data-type-mappings"></a>
Match the Python type annotation and return value to whether you are authoring a
standard row-by-row UDF or a vectorized (`pandas` / `pyarrow`) UDF:
BigQuery Type | Standard UDF (Python) | Vectorized UDF (`pandas`) | Vectorized UDF (`pyarrow`)
:------------ | :-------------------------- | :------------------------------------ | :-------------------------
`BOOL` | `bool` | `BooleanDtype` | `DataType(bool)`
`INT64` | `int` | `Int64Dtype` | `DataType(int64)`
`FLOAT64` | `float` | `FloatDtype` | `DataType(double)`
`STRING` | `str` | `StringDtype` | `DataType(string)`
`BYTES` | `bytes` | `binary[pyarrow]` | `DataType(binary)`
`DATE` | `datetime.date` | `date32[pyarrow]` | `DataType(date32[day])`
`TIME` | `datetime.time` | `time64[pyarrow]` | `Time64Type(time64[us])`
`DATETIME` | `datetime.datetime` (no tz) | `timestamp[us][pyarrow]` | `TimestampType(timestamp[us])`
`TIMESTAMP` | `datetime.datetime` (`UTC` on input; any tz on return, converted to `UTC`) | `timestamp[us, tz=UTC][pyarrow]` | `TimestampType(timestamp[us], tz)`
`ARRAY<T>` | `list` | `list<...>[pyarrow]` (`ArrowDtype`) | `ListType`
`STRUCT<...>` | `dict` | `struct<...>[pyarrow]` (`ArrowDtype`) | `StructType`
--------------------------------------------------------------------------------
## 3. Vectorized Execution (Pandas & PyArrow) {#vectorized-execution}
<a id="vectorized-execution"></a>
Prefer vectorized execution for analytical transformations over large tables
because processing batches of rows eliminates per-row Python call overhead.
> [!WARNING] **Vectorized operations must be row-independent**: BigQuery calls
> vectorized UDFs on arbitrary batches of rows (up to `max_batching_rows`). Do
> NOT compute global column statistics (such as z-scores, dataset mean/std, or
> rank) across `df`, because each batch only sees an arbitrary slice of rows.
> Use SQL window functions (`(val - AVG(val) OVER()) / NULLIF(STDDEV(val)
> OVER(), 0)`) for dataset-wide statistics. Vectorized Python UDFs should
> perform row-independent calculations (e.g. `df['x'] * df['y']` or geometric
> formulas).
### Pandas Vectorization (`pd.DataFrame`)
1. Annotate the single entrypoint parameter as `df: pd.DataFrame`.
2. Access SQL arguments by their column names in `df['{param_name}']`.
3. Return a `pd.Series` or single-column `pd.DataFrame` with the exact same row
count as `df`:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.multiply_vectorized`(
x FLOAT64, y FLOAT64
)
RETURNS FLOAT64
LANGUAGE python
OPTIONS (
runtime_version = 'python-3.11',
entry_point = 'vectorized_multiply'
)
AS r'''
import pandas as pd
def vectorized_multiply(df: pd.DataFrame) -> pd.Series:
return df['x'] * df['y']
''';
```
### Apache Arrow Vectorization (`pa.RecordBatch`)
Annotate the single entrypoint parameter as `batch: pa.RecordBatch` for
zero-copy columnar compute with `pyarrow.compute`:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.multiply_arrow`(
x FLOAT64, y FLOAT64
)
RETURNS FLOAT64
LANGUAGE python
OPTIONS (
runtime_version = 'python-3.11',
entry_point = 'vectorized_multiply_arrow'
)
AS r'''
import pyarrow as pa
import pyarrow.compute as pc
def vectorized_multiply_arrow(batch: pa.RecordBatch):
return pc.multiply(batch.column('x'), batch.column('y'))
''';
```
--------------------------------------------------------------------------------
## 4. Third-Party Dependencies (PyPI & Cloud Storage) {#dependencies}
<a id="dependencies"></a>
### Installing PyPI Packages (`packages`)
Specify wheel-compatible packages in `OPTIONS(packages=[...])` using PEP 440
version specifiers. Source-only (`sdist`) packages without binary wheels fail
container build:
```sql
OPTIONS (
entry_point = 'area_handler',
runtime_version = 'python-3.11',
packages = ['scipy==1.15.3', 'pydantic>=2.0,<3.0']
)
```
### Importing Custom `.py` Files from Cloud Storage (`library`)
1. Ensure the user creating the UDF has `storage.objects.get` permission on the
Cloud Storage object.
2. Ensure every folder segment and filename after `gs://{bucket_name}/` is a
valid Python identifier (`[A-Za-z_][A-Za-z0-9_]*`, no hyphens).
3. Import the file using dot-separated path notation relative to the bucket
root:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.run_custom_lib`(
a FLOAT64, b STRING
)
RETURNS STRING
LANGUAGE python
OPTIONS (
entry_point = 'compute',
runtime_version = 'python-3.11',
library = ['gs://{bucket_name}/my_pkg/utils/helper.py']
)
AS r'''
import my_pkg.utils.helper as helper
def compute(a: float, b: str) -> str:
return helper.transform(a, b)
''';
```
--------------------------------------------------------------------------------
## 5. Container Resource Limits (CPU, Memory, Concurrency) {#resource-limits}
<a id="resource-limits"></a>
By default, BigQuery allocates `container_memory = '512Mi'`, `container_cpu =
1.0`, and `container_request_concurrency = 80` to each Python UDF container.
Omit these options when default resources are sufficient, and specify them in
`OPTIONS(...)` only when tuning container memory, CPU, or concurrency for
resource-intensive workloads.
> [!IMPORTANT] If you set `container_cpu < 1.0` without explicitly setting
> `container_request_concurrency`, BigQuery automatically drops concurrency to
> `1` at runtime.
Always select a valid `(container_memory, container_cpu)` pair from the table
below, or the `CREATE FUNCTION` statement will fail validation:
`container_memory` (`Mi`, `M`, `Gi`, `G`) | Minimum `container_cpu` | Maximum `container_cpu`
:---------------------------------------- | :---------------------- | :----------------------
`256Mi` to `512Mi` | `0.33` | `2`
`> 512Mi` to `1Gi` | `0.5` | `2`
`> 1Gi` to `< 2Gi` | `1` | `2`
`2Gi` to `4Gi` | `1` | `4`
`> 4Gi` to `8Gi` | `2` | `4`
`> 8Gi` to `16Gi` | `4` | `4`
- **Allowed `container_cpu` values**: Either a fractional float in `[0.33,
1.0]` or one of the discrete integers `{1, 2, 4}` (values above `1` other
than `2` or `4`, such as `3`, are rejected).
- **Allowed `container_request_concurrency` bounds**: Integer in `[1, 1000]`
(default `80` when `container_cpu >= 1.0`, or `1` when `container_cpu <
1.0`).
Example configuring high-memory containers:
```sql
OPTIONS (
entry_point = 'heavy_transform',
runtime_version = 'python-3.11',
container_memory = '8Gi',
container_cpu = 2,
container_request_concurrency = 16
)
```
> [!NOTE] Runtime `container_memory` (RAM allocated to an executing container
> instance, up to 16 GiB) is distinct from the 10 GiB regional container quota.
> The 10 GiB limit is for the **container size** (the sum total storage size of
> all built Python UDF container images per project and region).
--------------------------------------------------------------------------------
## 6. Calling Online Services & APIs (`WITH CONNECTION`) {#calling-apis}
<a id="calling-apis"></a>
By default (without `WITH CONNECTION`), Python UDF containers run in a
network-isolated sandbox where all outbound traffic is blocked and times out.
### When & How to Configure `WITH CONNECTION`
Attach a `CLOUD_RESOURCE` connection whenever the Python UDF invokes Google
Cloud APIs or external HTTP services at runtime:
1. **Create the Connection**:
```sql
CREATE CONNECTION IF NOT EXISTS `{project_id}.{region}.{connection_id}`
OPTIONS (connection_type = 'CLOUD_RESOURCE');
```
2. **Retrieve the Connection Service Account**:
```bash
bq show --connection {project_id}.{region}.{connection_id}
```
3. **Grant Required IAM Roles to the Connection Service Account**: Running
`GRANT ... ON PROJECT` modifies the project's IAM policy and requires
`resourcemanager.projects.setIamPolicy` (for example,
`roles/resourcemanager.projectIamAdmin`); **confirm with the user before
running project-level IAM grants**:
- Grant `roles/serviceusage.serviceUsageConsumer` on `{query_project_id}`.
The `connection:` grantee takes the connection path, not the service
account email (use `"serviceAccount:{connection_sa_email}"` to grant by
email):
```sql
GRANT `roles/serviceusage.serviceUsageConsumer`
ON PROJECT `{query_project_id}`
TO "connection:{project_id}.{region}.{connection_id}";
```
- Grant the target API role (e.g., `roles/cloudtranslate.user` or
`roles/aiplatform.user`) on the target service project.
4. **Enforce Timeouts, Logging, and Prescriptive Exception Handling in
Python**:
- Initialize SDK clients in the global scope (outside `entry_point`) so
connections are reused across invocations and batches.
- Pass an explicit per-attempt `timeout=` on each client call.
`Retry(timeout=...)` only caps the total retry duration, not each
attempt.
- Differentiate transient errors from unrecoverable user/configuration
errors:
- **Transient errors** (`google.api_core.exceptions.TooManyRequests`,
`ServiceUnavailable`, `DeadlineExceeded`, `InternalServerError`,
`RetryError`): log a warning and return `None` (`NULL`) so transient
row-level issues do not fail the overall query job.
- **Unrecoverable / Fatal errors** (`PermissionDenied`,
`Unauthenticated`, `InvalidArgument`, bad configuration): log the
error and raise (such as `RuntimeError`). BigQuery surfaces
unhandled Python exceptions directly as user query errors
(`Encounter an error when invoking the function: ...`) along with
the stack trace.
- Do **not** catch the base class `GoogleAPICallError` as "transient";
it also matches the fatal errors above and silently converts auth
failures into `NULL`s.
- Log with `logging.warning(...)` / `logging.error(...)`. Logs are written
to `bigquery.googleapis.com/ManagedRoutineInvocation` **only** when the
session enables `SET @@udf.properties = JSON '{"enableDebugOutput":
true}';` (logging is off by default to prevent data exfiltration).
- **Never log row values** (inputs or outputs). Anyone with Cloud Logging
access can read UDF logs regardless of their BigQuery table permissions;
log exception types and messages instead.
### VPC Service Controls (VPC-SC) Constraints
- **Without `WITH CONNECTION`**: All outbound traffic is blocked.
- **With `WITH CONNECTION` inside a VPC-SC perimeter**: Public internet access
is blocked; the UDF can only reach Google Cloud services supported by VPC-SC
over `restricted.googleapis.com`. Ensure both the query project and target
service project are inside the same perimeter (or bridged) and add the
target API (e.g., `translate.googleapis.com`) to the perimeter's restricted
services.
--------------------------------------------------------------------------------
## 7. End-to-End Validation & Debugging Workflow {#validation-workflow}
<a id="validation-workflow"></a>
Always validate a Python UDF in three sequential stages, because BigQuery
container builds take 1–3+ minutes per iteration and the `CREATE FUNCTION` DDL
statement returns **before** the container build actually completes.
### Stage 1: Validate the Python Code Before Running BigQuery DDL
Verify syntax, data handling (`None`/NULLs, edge cases), and PyPI wheel
compatibility before creating the routine in BigQuery:
#### Option A: Local Validation with Test Input
Extract the entrypoint function into a local test script and verify both valid
and `None` inputs using Python 3.11:
```bash
python3 -c "
import pandas as pd
# Paste UDF function body here
def vectorized_multiply(df: pd.DataFrame) -> pd.Series:
return df['x'] * df['y']
test_df = pd.DataFrame({'x': [2.0, 4.0, None], 'y': [3.0, 5.0, 10.0]})
out = vectorized_multiply(test_df)
assert len(out) == len(test_df), 'Output Series length must match input'
print('Local validation passed:', out.tolist())
"
```
#### Option B: Container & Cloud API Validation via Cloud Run Jobs
When validating Linux wheel builds (`requirements.txt`), container memory
limits, or Google Cloud API calls in a serverless container environment (see
[Build and create a Python job in Cloud Run](https://docs.cloud.google.com/run/docs/quickstarts/jobs/build-create-python.md.txt)):
> [!NOTE] This Cloud Run Job buildpack execution serves as an approximation of
> the BigQuery UDF container, since it validates wheel resolution and network
> connectivity, though it does not share BigQuery's exact internal base image or
> pre-installed package versions.
1. Create a temporary directory with `main.py` (invoking your UDF entrypoint on
sample inputs), `requirements.txt` (matching `OPTIONS(packages=[...])`),
`.python-version` (containing `3.11` to pin buildpack resolution), and a
`Procfile` (no file extension):
```text
web: python3 main.py
```
```bash
echo "3.11" > .python-version
```
2. Build and deploy the source to a Cloud Run Job, then execute it
synchronously:
```bash
gcloud services enable run.googleapis.com cloudbuild.googleapis.com --quiet
gcloud run jobs deploy bq-udf-validator \
--source . \
--tasks 1 \
--max-retries 0 \
--region={region} \
--project={project_id}
gcloud run jobs execute bq-udf-validator --region={region} --wait
```
3. Clean up the temporary validation job after verification:
```bash
gcloud run jobs delete bq-udf-validator --region={region} --quiet
```
--------------------------------------------------------------------------------
### Stage 2: Execute DDL and Poll Container Build Status
Running `CREATE OR REPLACE FUNCTION` for a Python UDF returns `DONE` as soon as
the metadata is registered—**before** the container image finishes building. Do
**not** assume the UDF is ready to use solely because the DDL command succeeded.
1. **Submit the `CREATE OR REPLACE FUNCTION` DDL**:
```bash
bq query --use_legacy_sql=false "{create_function_ddl}"
```
2. **Poll `INFORMATION_SCHEMA.ROUTINES` Until `build_state` Reaches Terminal**:
Repeatedly query `build_status` until `build_state` transitions from
`IN_PROGRESS` to either `SUCCEEDED` or `FAILED`:
```sql
SELECT
routine_name,
build_status.build_state,
build_status.build_state_update_time,
build_status.build_duration_seconds,
build_status.image_size_bytes
FROM
`{project_id}.{dataset_id}`.INFORMATION_SCHEMA.ROUTINES
WHERE
routine_name = '{udf_name}';
```
--------------------------------------------------------------------------------
### Stage 3: Test the UDF in BigQuery & Debug with Cloud Logging
Once `build_status.build_state` is confirmed as `SUCCEEDED`, execute a test
query in BigQuery covering `NULL` and valid inputs.
If runtime debugging is needed (note that `print()` does not log and is
ignored):
1. Enable debug output for your session and run a bounded test query:
```sql
SET @@udf.properties = JSON '{"enableDebugOutput": true}';
SELECT
`{project_id}.{dataset_id}.{udf_name}`(NULL) AS null_case,
`{project_id}.{dataset_id}.{udf_name}`('sample_input') AS valid_case;
```
2. Use Python's standard `logging` module (`logging.info`, `logging.warning`,
`logging.error`) inside your UDF:
```python
import logging
def parse_record(raw: str) -> str:
try:
return raw.strip() if raw is not None else None
except Exception as e:
logging.error(f"Failed to parse record: {e}")
return None
```
3. Query logs in Cloud Logging using resource type
`bigquery.googleapis.com/ManagedRoutineInvocation` and filter by
`resource.labels.routine_id="{udf_name}"`.
remote-functions.md 7.0 KB
# BigQuery Remote Functions Reference
## Table of Contents
- [1. Architecture & JSON Request/Response Contract](#architecture-contract)
- [2. Cloud Run Endpoint Implementation](#endpoint-implementation)
- [3. Creating & Configuring the BigQuery Remote Function](#creating-remote-function)
- [4. Performance, Batching & Retry Handling](#performance-batching)
--------------------------------------------------------------------------------
## 1. Architecture & JSON Request/Response Contract {#architecture-contract}
<a id="architecture-contract"></a>
BigQuery Remote Functions send batches of row arguments via HTTP `POST` to an
external HTTPS endpoint hosted on Cloud Run or Cloud Run functions using a
`CLOUD_RESOURCE` connection service account.
### Request JSON Schema (Sent by BigQuery)
BigQuery sends a `Content-Type: application/json` body with the following keys:
```json
{
"requestId": "124ab1c",
"caller": "//bigquery.googleapis.com/projects/my-project/jobs/bquxjob_1234",
"sessionUser": "user@example.com",
"userDefinedContext": {
"env": "prod",
"mode": "strict"
},
"calls": [
["row1_arg1", 42],
["row2_arg1", null]
]
}
```
### Response JSON Schema (Returned by Your Endpoint)
The HTTP endpoint must return HTTP `200 OK` with a `replies` array whose length
**strictly matches** the number of elements in `calls`:
```json
{
"replies": [
{"status": "enriched", "score": 0.95},
null
]
}
```
- **Error Reporting**: If a non-retryable error occurs, return an HTTP `4xx`
code other than `408` or `429` (e.g., `400 Bad Request`) with
`{"errorMessage": "Detailed reason"}` (must be under 1 KB) so BigQuery
surfaces the message immediately without retrying.
- **Retry Triggering**: BigQuery automatically retries requests that return
HTTP `408`, `429`, `500`, `503`, or `504` (other HTTP codes like `501` or
`502` are not retried and will fail the query).
--------------------------------------------------------------------------------
## 2. Cloud Run Endpoint Implementation (Python Functions Framework) {#endpoint-implementation}
<a id="endpoint-implementation"></a>
Deploy a stateless HTTP handler that processes `calls` in order and preserves
exact array length:
```python
import functions_framework
from flask import jsonify, make_response
@functions_framework.http
def handle_bq_remote_udf(request):
try:
body = request.get_json(silent=True)
if not body or "calls" not in body:
return make_response(
jsonify({"errorMessage": "Missing 'calls' in request."}),
400,
)
context = body.get("userDefinedContext", {})
calls = body["calls"]
replies = []
for row_args in calls:
street, postal_code = row_args[0], row_args[1]
if street is None and postal_code is None:
replies.append(None)
else:
replies.append({
"normalized": f"{street or ''} {postal_code or ''}".strip(),
"env": context.get("env", "default"),
})
return jsonify({"replies": replies})
except Exception as exc:
return make_response(
jsonify({"errorMessage": f"Permanent execution error: {exc}"}),
400,
)
```
Deploy the service to Cloud Run with `--no-allow-unauthenticated`:
```bash
gcloud run deploy {cloud_run_service} \
--source=. \
--function=handle_bq_remote_udf \
--region={region} \
--no-allow-unauthenticated
```
--------------------------------------------------------------------------------
## 3. Creating & Configuring the BigQuery Remote Function {#creating-remote-function}
<a id="creating-remote-function"></a>
1. **Create the Cloud Resource Connection** (must be in the same location as
the BigQuery dataset containing the remote function):
```bash
bq mk --connection --connection_type=CLOUD_RESOURCE \
--location={region} --project_id={project_id} {connection_id}
```
2. **Grant `roles/run.invoker` to the Connection's Service Account**: Retrieve
the service account via `bq show --connection
{project_id}.{region}.{connection_id}` and bind `roles/run.invoker` on the
Cloud Run service (**confirm with the user before modifying the Cloud Run
service IAM policy**):
```bash
gcloud run services add-iam-policy-binding {cloud_run_service} \
--region={region} \
--member="serviceAccount:{connection_sa_email}" \
--role="roles/run.invoker"
```
3. **Create the Remote Function in BigQuery** (`ARRAY`, `STRUCT`, `INTERVAL`,
and `GEOGRAPHY` parameters and return values are unsupported; serialize
complex structures as `JSON`):
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.enrich_address`(
street STRING,
postal_code STRING
)
RETURNS JSON
REMOTE WITH CONNECTION `{project_id}.{region}.{connection_id}`
OPTIONS (
endpoint = 'https://{cloud_run_service_url}',
max_batching_rows = 1000,
user_defined_context = [
('env', 'prod'),
('mode', 'strict')
]
);
```
--------------------------------------------------------------------------------
## 4. Performance, Batching & Retry Handling {#performance-batching}
<a id="performance-batching"></a>
- **Idempotency & Retry Cap**: BigQuery retries failed batches up to **20
times** and may resend the same batch (with the same `requestId`) even after
your endpoint returns HTTP `200 OK` if the network response is interrupted.
Design remote endpoints to be idempotent (or deduplicate side effects using
`requestId`).
- **Batch Sizing (`max_batching_rows`)**: BigQuery batches rows up to
`max_batching_rows` (or determines batch size automatically) to avoid HTTP
endpoint timeouts. Set `max_batching_rows` (e.g. between `500` and `5000`)
when calling downstream rate-limited APIs to avoid Cloud Run request
timeouts. Key limits to note:
- **Maximum input size**: 5 MB total size of all input arguments from a
single row.
- **HTTP response size limit**: 15 MB for Cloud Run / 2nd gen (10 MB for
1st gen).
- **HTTP invocation timeout**: Up to 20 minutes for Cloud Run / 2nd gen (9
minutes for 1st gen).
- **Concurrency**: Up to 10 concurrent queries containing remote functions
per project.
- **Cloud Run Concurrency & Max Instances**: Configure `--concurrency` and
`--max-instances` on the Cloud Run service to match downstream quota limits
so parallel BigQuery slots do not overwhelm external databases or APIs.
- **VPC Egress for Private Network Targets**: Configure Direct VPC Egress
(`--network` / `--subnet`) or a Serverless VPC Access connector
(`--vpc-connector`) on the Cloud Run service when the remote function needs
to reach private IP endpoints inside a VPC network.
- **Filter Before Calling**: Push `WHERE` predicates into a subquery or CTE
before invoking a Remote Function so the endpoint is only called on filtered
rows.
sql-and-js-udfs.md 6.6 KB
# BigQuery SQL and JavaScript UDFs Reference
## Table of Contents
- [1. SQL Scalar & Templated UDFs (ANY TYPE)](#sql-templated)
- [2. SQL & JavaScript Aggregate UDFs](#aggregate-udfs)
- [3. JavaScript UDF Type Mapping & Precision Rules](#js-types)
- [4. Loading External JavaScript Libraries from Cloud Storage](#js-libraries)
--------------------------------------------------------------------------------
## 1. SQL Scalar & Templated UDFs (`ANY TYPE`) {#sql-templated}
<a id="sql-templated"></a>
Prefer SQL UDFs whenever logic can be expressed in GoogleSQL, because the query
optimizer inlines SQL UDF bodies directly into the execution plan with zero
serialization overhead.
### Templated Parameters (`ANY TYPE`)
Use `ANY TYPE` to write polymorphic functions that accept multiple data types. A
templated function can declare an explicit return type (e.g. `RETURNS STRING`),
or omit `RETURNS` when the return type depends on the argument types, allowing
BigQuery to infer it per call site:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.clamp_value`(
x ANY TYPE,
min_val ANY TYPE,
max_val ANY TYPE
)
AS (
GREATEST(min_val, LEAST(max_val, x))
);
```
### Subquery Expressions in SQL UDFs
SQL UDFs can reference tables or views using scalar subqueries `(SELECT ...)`:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.lookup_country_name`(
iso_code STRING
)
RETURNS STRING
AS ((
SELECT country_name
FROM `{project_id}.{dataset_id}.iso_countries`
WHERE code = iso_code
LIMIT 1
));
```
--------------------------------------------------------------------------------
## 2. SQL & JavaScript Aggregate UDFs {#aggregate-udfs}
<a id="aggregate-udfs"></a>
Use `CREATE OR REPLACE AGGREGATE FUNCTION` to compute a single result across a
group of rows.
### SQL Aggregate UDF
Mark non-aggregated parameters (constants across each group) with `NOT
AGGREGATE`:
```sql
CREATE OR REPLACE AGGREGATE FUNCTION `{project_id}.{dataset_id}.scaled_sum`(
val FLOAT64,
scale_factor FLOAT64 NOT AGGREGATE
)
RETURNS FLOAT64
AS (
SUM(val) * scale_factor
);
```
### JavaScript Aggregate UDF Lifecycle
JavaScript aggregate UDFs must implement four lifecycle functions
(`initialState`, `aggregate`, `merge`, and `finalize`) to support distributed
parallel execution across BigQuery slots:
```sql
CREATE OR REPLACE AGGREGATE FUNCTION `{project_id}.{dataset_id}.geometric_mean`(
x FLOAT64
)
RETURNS FLOAT64
LANGUAGE js
AS r"""
export function initialState() {
return { logSum: 0.0, count: 0 };
}
export function aggregate(state, x) {
if (x !== null && x > 0) {
state.logSum += Math.log(x);
state.count += 1;
}
}
export function merge(state, partialState) {
state.logSum += partialState.logSum;
state.count += partialState.count;
}
export function finalize(state) {
return state.count === 0 ? null : Math.exp(state.logSum / state.count);
}
""";
```
--------------------------------------------------------------------------------
## 3. JavaScript UDF Type Mapping & Precision Rules {#js-types}
<a id="js-types"></a>
BigQuery maps SQL types to JavaScript V8 objects according to strict rules.
> [!WARNING] BigQuery does **not** support `INT64` as an input parameter type in
> JavaScript UDFs because JavaScript `Number` (IEEE 754 double) loses integer
> precision beyond `2^53 - 1`. Pass 64-bit integers as `FLOAT64` or `STRING`
> (and parse with JavaScript `BigInt(str)`). Note that BigQuery **does** support
> `INT64` as a return type (returning either a Number or String from JS).
BigQuery Data Type | JavaScript Data Type | Notes
:----------------------- | :-------------------------------------------------------- | :----
`BOOL` | `Boolean` | Direct mapping
`INT64` | Unsupported input; supported return type (`Number`/`str`) | For input, cast to `STRING` or `FLOAT64` in SQL. Supported as return type (return Number/String).
`FLOAT64` | `Number` | IEEE 754 double-precision float
`NUMERIC` / `BIGNUMERIC` | `Number` or `String` | Encoded as `Number` only when integral and within `[-2^53, 2^53]`; otherwise `String` (including all fractional values). Coerce explicitly in JS (e.g. `Number(x)` or a decimal library).
`STRING` | `String` | UTF-8 string
`BYTES` | base64-encoded `String` | Base64 string in scalar JS UDFs (`Uint8Array` in aggregate UDFs)
`DATE` | `Date` | JavaScript `Date` object
`TIMESTAMP` | `Date` with `microsecond` field | Contains `microsecond` fraction of timestamp
`JSON` | Object / Array / Value | Numbers in [-2^53, 2^53] exact; others rounded
`ARRAY<T>` | `Array` | Nested arrays are unsupported in BigQuery
`STRUCT<...>` | `Object` | Struct field names map to JS object keys
> [!NOTE] Encodings differ in JavaScript Aggregate UDFs (`CREATE AGGREGATE
> FUNCTION ... LANGUAGE js`): `INT64` maps to JavaScript `BigInt`, and `BYTES`
> maps to `Uint8Array`.
### Determinism Option
Specify `DETERMINISTIC` if the JavaScript UDF always produces the same output
for the same inputs (allowing BigQuery to cache results), or `NOT DETERMINISTIC`
if it uses `Math.random()` or `Date.now()`.
--------------------------------------------------------------------------------
## 4. Loading External JavaScript Libraries from Cloud Storage {#js-libraries}
<a id="js-libraries"></a>
Bundle third-party npm packages into a single self-contained file (using
`esbuild` or `webpack` with IIFE/global output) and upload the bundle to Cloud
Storage:
1. **Bundle the Library Locally**:
```bash
npx esbuild index.js --bundle --format=iife --global-name=MyLib --outfile=bundle.js
gcloud storage cp bundle.js gs://{bucket_name}/udf_libs/bundle.js
```
2. **Reference the Bundle via `OPTIONS(library=[...])`**:
```sql
CREATE OR REPLACE FUNCTION `{project_id}.{dataset_id}.parse_with_bundle`(
input_str STRING
)
RETURNS STRING
DETERMINISTIC
LANGUAGE js
OPTIONS (
library = ['gs://{bucket_name}/udf_libs/bundle.js']
)
AS r"""
if (!input_str) return null;
return MyLib.transform(input_str);
""";
```
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE