Skip to content

Add biquery query parameter option to support parametrize query#39389

Open
i05nagai wants to merge 1 commit into
apache:masterfrom
i05nagai:feature/go-sdk-bq
Open

Add biquery query parameter option to support parametrize query#39389
i05nagai wants to merge 1 commit into
apache:masterfrom
i05nagai:feature/go-sdk-bq

Conversation

@i05nagai

Copy link
Copy Markdown

Addresses: #29382
Also addresses: #25096

Description

This PR supports QueryParameter for BigQueryIO in Go.
Since QueryParameter includes interface{} field, I followed the same implementation pattern in mongodb package by adding encoded QueryParameters to queryFn.

Tests

I successfully ran integrated tests with

go test -v ./test/integration/io/bigqueryio \
      --runner=direct \
      --project=${PROJECT_ID} \
      --bq_dataset=${DATASET_ID}

I am not sure if I should add integration tests for my change or I should make integration tests runnable with dataflow runner.
If it's required, I'll update my PR.


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enables parameterized queries for BigQueryIO in the Go SDK. By allowing users to pass query parameters, it improves security and flexibility when interacting with BigQuery. The changes include the necessary infrastructure to serialize these parameters for execution within the Beam pipeline, alongside updates to integration test utilities to better support project-specific configurations.

Highlights

  • Parameterized Query Support: Added support for parameterized queries in BigQueryIO by introducing WithQueryParameters and handling the serialization of bigquery.QueryParameter objects.
  • Serialization Infrastructure: Implemented new encoding and decoding logic for query parameters using JSON to ensure compatibility with Beam's serialization requirements.
  • Integration Test Improvements: Updated integration test helpers to explicitly pass project IDs and improved table validation logic to ensure more reliable test execution.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@i05nagai i05nagai changed the title Add biquery query parameters to support parametrize query Add biquery query parameter option to support parametrize query Jul 20, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for parameterized queries in the Go SDK's BigQuery IO connector, adding a new WithQueryParameters option, serializing parameters during pipeline execution, and updating integration tests. The reviewer feedback is highly constructive and identifies critical issues: JSON serialization will cause type loss for query parameters (e.g., converting integers to floats), which can be resolved by using gob encoding; decoding will fail on empty parameters without a guard check; tests should be expanded to cover numeric types; and encoding should be skipped when no parameters are provided to avoid overhead.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +18 to +41
import (
"encoding/json"
"fmt"

"cloud.google.com/go/bigquery"
)

func encodeQueryParameters(params []bigquery.QueryParameter) ([]byte, error) {
out, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("error encoding JSON: %w", err)
}

return out, nil
}

func decodeQueryParameters(bytes []byte) ([]bigquery.QueryParameter, error) {
var out []bigquery.QueryParameter
if err := json.Unmarshal(bytes, &out); err != nil {
return nil, fmt.Errorf("error decoding JSON: %w", err)
}

return out, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using json.Marshal and json.Unmarshal for bigquery.QueryParameter will cause type loss for the Value interface{} field. For example, any integer value (like int or int64) will be unmarshaled as a float64, which will cause BigQuery to fail with type mismatch errors (e.g., when comparing an INT64 column with a FLOAT64 parameter). Similarly, time.Time or civil.Date will be unmarshaled as string, which may also cause query failures.

Consider using gob encoding instead, and registering the common types (like time.Time, civil.Date, civil.DateTime, and civil.Time) using gob.Register so that type fidelity is preserved across the serialization boundary.

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"time"

	"cloud.google.com/go/bigquery"
	"cloud.google.com/go/civil"
)

func init() {
	gob.Register(time.Time{})
	gob.Register(civil.Date{})
	gob.Register(civil.DateTime{})
	gob.Register(civil.Time{})
}

func encodeQueryParameters(params []bigquery.QueryParameter) ([]byte, error) {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	if err := enc.Encode(params); err != nil {
		return nil, fmt.Errorf("error encoding gob: %w", err)
	}
	return buf.Bytes(), nil
}

func decodeQueryParameters(b []byte) ([]bigquery.QueryParameter, error) {
	var out []bigquery.QueryParameter
	dec := gob.NewDecoder(bytes.NewReader(b))
	if err := dec.Decode(&out); err != nil {
		return nil, fmt.Errorf("error decoding gob: %w", err)
	}
	return out, nil
}

Comment on lines +192 to +196
parameters, err := decodeQueryParameters(f.QueryParameters)
if err != nil {
return errors.Wrapf(err, "bigqueryio.queryFn: failed to decode query parameters")
}
q.Parameters = parameters

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If f.QueryParameters is empty or nil (which is the case when no parameters are set, or for backward compatibility with older serialized pipelines), calling decodeQueryParameters directly will fail with an error (e.g., unexpected end of JSON input or EOF with gob). We should guard this call and only decode if f.QueryParameters is not empty.

Suggested change
parameters, err := decodeQueryParameters(f.QueryParameters)
if err != nil {
return errors.Wrapf(err, "bigqueryio.queryFn: failed to decode query parameters")
}
q.Parameters = parameters
if len(f.QueryParameters) > 0 {
parameters, err := decodeQueryParameters(f.QueryParameters)
if err != nil {
return errors.Wrapf(err, "bigqueryio.queryFn: failed to decode query parameters")
}
q.Parameters = parameters
}

Comment on lines +26 to +44
tests := []struct {
name string
val bigquery.QueryParameter
}{
{
name: "Encode/decode QueryOptions with parameters",
val: bigquery.QueryParameter{
Name: "key",
Value: "value",
},
},
{
name: "Encode/decode QueryOptions with nil parameter",
val: bigquery.QueryParameter{
Name: "key",
Value: nil,
},
},
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current test cases only cover string and nil values, which hides the type loss issue of JSON serialization. Please add test cases for int and float64 values to ensure type preservation.

	tests := []struct {
		name string
		val  bigquery.QueryParameter
	}{
		{
			name: "Encode/decode QueryOptions with string parameter",
			val: bigquery.QueryParameter{
				Name:  "key",
				Value: "value",
				},
		},
		{
			name: "Encode/decode QueryOptions with int parameter",
			val: bigquery.QueryParameter{
				Name:  "key",
				Value: 42,
				},
		},
		{
			name: "Encode/decode QueryOptions with float parameter",
			val: bigquery.QueryParameter{
				Name:  "key",
				Value: 3.14,
				},
		},
		{
			name: "Encode/decode QueryOptions with nil parameter",
			val: bigquery.QueryParameter{
				Name:  "key",
				Value: nil,
				},
		},
	}

Comment on lines +156 to +159
queryParameters, err := encodeQueryParameters(queryOptions.parameters)
if err != nil {
panic(errors.Wrapf(err, "bigqueryio.Query: failed to encode query parameters"))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To avoid unnecessary serialization overhead when no query parameters are provided, we should only encode the parameters if the slice is not empty.

	var queryParameters []byte
	if len(queryOptions.parameters) > 0 {
		var err error
		queryParameters, err = encodeQueryParameters(queryOptions.parameters)
		if err != nil {
			panic(errors.Wrapf(err, "bigqueryio.Query: failed to encode query parameters"))
		}
	}

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @lostluck for label go.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant