- 1.70.0 (latest)
- 1.69.0
- 1.68.0
- 1.67.0
- 1.66.2
- 1.65.0
- 1.64.0
- 1.63.1
- 1.62.0
- 1.61.0
- 1.60.0
- 1.59.1
- 1.58.0
- 1.57.1
- 1.54.0
- 1.53.0
- 1.52.0
- 1.51.2
- 1.50.0
- 1.49.0
- 1.48.0
- 1.47.0
- 1.46.0
- 1.45.0
- 1.44.0
- 1.43.0
- 1.42.0
- 1.41.0
- 1.40.0
- 1.39.0
- 1.38.0
- 1.37.0
- 1.36.0
- 1.35.0
- 1.34.1
- 1.33.0
- 1.32.0
- 1.31.0
- 1.30.2
- 1.29.0
- 1.28.0
- 1.27.0
- 1.26.0
- 1.25.0
- 1.24.0
- 1.23.0
- 1.22.0
- 1.21.0
- 1.20.1
- 1.19.0
- 1.18.0
- 1.17.0
- 1.16.0
- 1.15.0
Package bigquery provides a client for the BigQuery service.
The following assumes a basic familiarity with BigQuery concepts. See https://cloud.google.com/bigquery/docs.
See https://godoc.org/cloud.google.com/go for authentication, timeouts, connection pooling and similar aspects of this package.
Creating a Client
To start working with this package, create a client with NewClient:
ctx := context.Background() client, err := bigquery.NewClient(ctx, projectID) if err != nil { // TODO: Handle error. }
Querying
To query existing tables, create a Client.Query and call its Query.Read method, which starts the query and waits for it to complete:
q := client.Query(` SELECT year, SUM(number) as num FROM bigquery-public-data.usa_names.usa_1910_2013 WHERE name = @name GROUP BY year ORDER BY year `) q.Parameters = []bigquery.QueryParameter{ {Name: "name", Value: "William"}, } it, err := q.Read(ctx) if err != nil { // TODO: Handle error. }
Then iterate through the resulting rows. You can store a row using anything that implements the ValueLoader interface, or with a slice or map of Value. A slice is simplest:
for { var values []bigquery.Value err := it.Next(&values) if err == iterator.Done { break } if err != nil { // TODO: Handle error. } fmt.Println(values) }
You can also use a struct whose exported fields match the query:
type Count struct { Year int Num int } for { var c Count err := it.Next(&c) if err == iterator.Done { break } if err != nil { // TODO: Handle error. } fmt.Println(c) }
You can also start the query running and get the results later. Create the query as above, but call Query.Run instead of Query.Read. This returns a Job, which represents an asynchronous operation.
job, err := q.Run(ctx) if err != nil { // TODO: Handle error. }
Get the job's ID, a printable string. You can save this string to retrieve the results at a later time, even in another process.
jobID := job.ID() fmt.Printf("The job ID is %s\n", jobID)
To retrieve the job's results from the ID, first look up the Job with the Client.JobFromID method:
job, err = client.JobFromID(ctx, jobID) if err != nil { // TODO: Handle error. }
Use the Job.Read method to obtain an iterator, and loop over the rows. Calling Query.Read is preferred for queries with a relatively small result set, as it will call BigQuery jobs.query API for a optimized query path. If the query doesn't meet that criteria, the method will just combine Query.Run and Job.Read.
it, err = job.Read(ctx) if err != nil { // TODO: Handle error. } // Proceed with iteration as above.
Datasets and Tables
You can refer to datasets in the client's project with the Client.Dataset method, and in other projects with the Client.DatasetInProject method:
myDataset := client.Dataset("my_dataset") yourDataset := client.DatasetInProject("your-project-id", "your_dataset")
These methods create references to datasets, not the datasets themselves. You can have a dataset reference even if the dataset doesn't exist yet. Use Dataset.Create to create a dataset from a reference:
if err := myDataset.Create(ctx, nil); err != nil { // TODO: Handle error. }
You can refer to tables with Dataset.Table. Like Dataset, Table is a reference to an object in BigQuery that may or may not exist.
table := myDataset.Table("my_table")
You can create, delete and update the metadata of tables with methods on Table. For instance, you could create a temporary table with:
err = myDataset.Table("temp").Create(ctx, &bigquery.TableMetadata{ ExpirationTime: time.Now().Add(1*time.Hour)}) if err != nil { // TODO: Handle error. }
We'll see how to create a table with a schema in the next section.
Schemas
There are two ways to construct schemas with this package. You can build a schema by hand with the Schema struct, like so:
schema1 := bigquery.Schema{ {Name: "Name", Required: true, Type: bigquery.StringFieldType}, {Name: "Grades", Repeated: true, Type: bigquery.IntegerFieldType}, {Name: "Optional", Required: false, Type: bigquery.IntegerFieldType}, }
Or you can infer the schema from a struct with the InferSchema method:
type student struct { Name string Grades []int Optional bigquery.NullInt64 } schema2, err := bigquery.InferSchema(student{}) if err != nil { // TODO: Handle error. } // schema1 and schema2 are identical.
Struct inference supports tags like those of the encoding/json package, so you can change names, ignore fields, or mark a field as nullable (non-required). Fields declared as one of the Null types (NullInt64, NullFloat64, NullString, NullBool, NullTimestamp, NullDate, NullTime, NullDateTime, NullGeography, and NullJSON) are automatically inferred as nullable, so the "nullable" tag is only needed for []byte, *big.Rat and pointer-to-struct fields.
type student2 struct { Name string `bigquery:"full_name"` Grades []int Secret string `bigquery:"-"` Optional []byte `bigquery:",nullable"` } schema3, err := bigquery.InferSchema(student2{}) if err != nil { // TODO: Handle error. } // schema3 has required fields "full_name" and "Grade", and nullable BYTES field "Optional".
Having constructed a schema, you can create a table with it using the Table.Create method like so:
if err := table.Create(ctx, &bigquery.TableMetadata{Schema: schema1}); err != nil { // TODO: Handle error. }
Copying
You can copy one or more tables to another table. Begin by constructing a Copier describing the copy using the Table.CopierFrom. Then set any desired copy options, and finally call Copier.Run to get a Job:
copier := myDataset.Table("dest").CopierFrom(myDataset.Table("src")) copier.WriteDisposition = bigquery.WriteTruncate job, err = copier.Run(ctx) if err != nil { // TODO: Handle error. }
You can chain the call to Copier.Run if you don't want to set options:
job, err = myDataset.Table("dest").CopierFrom(myDataset.Table("src")).Run(ctx) if err != nil { // TODO: Handle error. }
You can wait for your job to complete with the Job.Wait method:
status, err := job.Wait(ctx) if err != nil { // TODO: Handle error. }
Job.Wait polls with exponential backoff. You can also poll yourself, if you wish:
for { status, err := job.Status(ctx) if err != nil { // TODO: Handle error. } if status.Done() { if status.Err() != nil { log.Fatalf("Job failed with error %v", status.Err()) } break } time.Sleep(pollInterval) }
Loading and Uploading
There are two ways to populate a table with this package: load the data from a Google Cloud Storage object, or upload rows directly from your program.
For loading, first create a GCSReference with the NewGCSReference method, configuring it if desired. Then make a Loader from a table with the Table.LoaderFrom method with the reference, optionally configure it as well, and call its Loader.Run method.
gcsRef := bigquery.NewGCSReference("gs://my-bucket/my-object") gcsRef.AllowJaggedRows = true loader := myDataset.Table("dest").LoaderFrom(gcsRef) loader.CreateDisposition = bigquery.CreateNever job, err = loader.Run(ctx) // Poll the job for completion if desired, as above.
To upload, first define a type that implements the ValueSaver interface, which has a single method named Save. Then create an Inserter, and call its Inserter.Put method with a slice of values.
type Item struct { Name string Size float64 Count int } // Save implements the ValueSaver interface. func (i *Item) Save() (map[string]bigquery.Value, string, error) { return map[string]bigquery.Value{ "Name": i.Name, "Size": i.Size, "Count": i.Count, }, "", nil } u := table.Inserter() // Item implements the ValueSaver interface. items := []*Item{ {Name: "n1", Size: 32.6, Count: 7}, {Name: "n2", Size: 4, Count: 2}, {Name: "n3", Size: 101.5, Count: 1}, } if err := u.Put(ctx, items); err != nil { // TODO: Handle error. }
You can also upload a struct that doesn't implement ValueSaver. Use the StructSaver type to specify the schema and insert ID by hand:
type item struct { Name string Num int } // Assume schema holds the table's schema. savers := []*bigquery.StructSaver{ {Struct: score{Name: "n1", Num: 12}, Schema: schema, InsertID: "id1"}, {Struct: score{Name: "n2", Num: 31}, Schema: schema, InsertID: "id2"}, {Struct: score{Name: "n3", Num: 7}, Schema: schema, InsertID: "id3"}, } if err := u.Put(ctx, savers); err != nil { // TODO: Handle error. }
Lastly, but not least, you can just supply the struct or struct pointer directly and the schema will be inferred:
type Item2 struct { Name string Size float64 Count int } // Item2 doesn't implement ValueSaver interface, so schema will be inferred. items2 := []*Item2{ {Name: "n1", Size: 32.6, Count: 7}, {Name: "n2", Size: 4, Count: 2}, {Name: "n3", Size: 101.5, Count: 1}, } if err := u.Put(ctx, items2); err != nil { // TODO: Handle error. }
BigQuery allows for higher throughput when omitting insertion IDs. To enable this, specify the sentinel NoDedupeID value for the insertion ID when implementing a ValueSaver.
Extracting
If you've been following so far, extracting data from a BigQuery table into a Google Cloud Storage object will feel familiar. First create an Extractor, then optionally configure it, and lastly call its Extractor.Run method.
extractor := table.ExtractorTo(gcsRef) extractor.DisableHeader = true job, err = extractor.Run(ctx) // Poll the job for completion if desired, as above.
Errors
Errors returned by this client are often of the type googleapi.Error. These errors can be introspected for more information by using errors.As with the richer googleapi.Error type. For example:
var e *googleapi.Error if ok := errors.As(err, &e); ok { if e.Code == 409 { ... } }
In some cases, your client may received unstructured googleapi.Error error responses. In such cases, it is likely that you have exceeded BigQuery request limits, documented at: https://cloud.google.com/bigquery/quotas
Constants
LogicalStorageBillingModel, PhysicalStorageBillingModel
const (
// LogicalStorageBillingModel indicates billing for logical bytes.
LogicalStorageBillingModel = ""
// PhysicalStorageBillingModel indicates billing for physical bytes.
PhysicalStorageBillingModel = "PHYSICAL"
)
ScalarFunctionRoutine, ProcedureRoutine, TableValuedFunctionRoutine
const (
// ScalarFunctionRoutine scalar function routine type
ScalarFunctionRoutine = "SCALAR_FUNCTION"
// ProcedureRoutine procedure routine type
ProcedureRoutine = "PROCEDURE"
// TableValuedFunctionRoutine routine type for table valued functions
TableValuedFunctionRoutine = "TABLE_VALUED_FUNCTION"
)
NumericPrecisionDigits, NumericScaleDigits, BigNumericPrecisionDigits, BigNumericScaleDigits
const (
// NumericPrecisionDigits is the maximum number of digits in a NUMERIC value.
NumericPrecisionDigits = 38
// NumericScaleDigits is the maximum number of digits after the decimal point in a NUMERIC value.
NumericScaleDigits = 9
// BigNumericPrecisionDigits is the maximum number of full digits in a BIGNUMERIC value.
BigNumericPrecisionDigits = 76
// BigNumericScaleDigits is the maximum number of full digits in a BIGNUMERIC value.
BigNumericScaleDigits = 38
)
DetectProjectID
const DetectProjectID = "*detect-project-id*"
DetectProjectID is a sentinel value that instructs [NewClient] to detect the project ID. It is given in place of the projectID argument. [NewClient] will use the project ID from the given credentials or the default credentials (https://developers.google.com/accounts/docs/application-default-credentials) if no credentials were provided. When providing credentials, not all options will allow [NewClient] to extract the project ID. Specifically a JWT does not have the project ID encoded.
NoDedupeID
const NoDedupeID = "NoDedupeID"
NoDedupeID indicates a streaming insert row wants to opt out of best-effort deduplication. It is EXPERIMENTAL and subject to change or removal without notice.
Scope
const (
// Scope is the Oauth2 scope for the service.
// For relevant BigQuery scopes, see:
// https://developers.google.com/identity/protocols/googlescopes#bigqueryv2
Scope = "https://www.googleapis.com/auth/bigquery"
)
Variables
NeverExpire
NeverExpire is a sentinel value used to remove a table'e expiration time.
Functions
func BigNumericString
BigNumericString returns a string representing a *big.Rat in a format compatible with BigQuery SQL. It returns a floating point literal with 38 digits after the decimal point.
func CivilDateTimeString
CivilDateTimeString returns a string representing a civil.DateTime in a format compatible with BigQuery SQL. It separate the date and time with a space, and formats the time with CivilTimeString.
Use CivilDateTimeString when using civil.DateTime in DML, for example in INSERT statements.
func CivilTimeString
CivilTimeString returns a string representing a civil.Time in a format compatible with BigQuery SQL. It rounds the time to the nearest microsecond and returns a string with six digits of sub-second precision.
Use CivilTimeString when using civil.Time in DML, for example in INSERT statements.
func IntervalString
func IntervalString(iv *IntervalValue) string
IntervalString returns a string representing an *IntervalValue in a format compatible with BigQuery SQL. It returns an interval literal in canonical format.
func NewArrowIteratorReader
func NewArrowIteratorReader(it ArrowIterator) io.Reader
NewArrowIteratorReader allows to consume an ArrowIterator as an io.Reader. Experimental: this interface is experimental and may be modified or removed in future versions, regardless of any other documented package stability guarantees.
func NumericString
NumericString returns a string representing a *big.Rat in a format compatible with BigQuery SQL. It returns a floating-point literal with 9 digits after the decimal point.
func Seed
func Seed(s int64)
Seed seeds this package's random number generator, used for generating job and insert IDs. Use Seed to obtain repeatable, deterministic behavior from bigquery clients. Seed should be called before any clients are created.
func WithDefaultJobCreationMode
func WithDefaultJobCreationMode(mode JobCreationMode) option.ClientOption
WithDefaultJobCreationMode is a ClientOption that governs the job creation mode used when executing queries that can be accelerated via the jobs.Query API. Users may experience performance improvements by leveraging the JobCreationModeOptional mode.
AccessEntry
type AccessEntry struct {
Role AccessRole // The role of the entity
EntityType EntityType // The type of entity
Entity string // The entity (individual or group) granted access
View *Table // The view granted access (EntityType must be ViewEntity)
Routine *Routine // The routine granted access (only UDF currently supported)
Dataset *DatasetAccessEntry // The resources within a dataset granted access.
Condition *Expr // Condition for the access binding.
}
An AccessEntry describes the permissions that an entity has on a dataset.
AccessRole
type AccessRole string
AccessRole is the level of access to grant to a dataset.
OwnerRole, ReaderRole, WriterRole
const (
// OwnerRole is the OWNER AccessRole.
OwnerRole AccessRole = "OWNER"
// ReaderRole is the READER AccessRole.
ReaderRole AccessRole = "READER"
// WriterRole is the WRITER AccessRole.
WriterRole AccessRole = "WRITER"
)
ArrowIterator
type ArrowIterator interface {
Next() (*ArrowRecordBatch, error)
Schema() Schema
SerializedArrowSchema() []byte
}
ArrowIterator represents a way to iterate through a stream of arrow records. Experimental: this interface is experimental and may be modified or removed in future versions, regardless of any other documented package stability guarantees.
ArrowRecordBatch
type ArrowRecordBatch struct {
// Serialized Arrow Record Batch.
Data []byte
// Serialized Arrow Schema.
Schema []byte
// Source partition ID. In the Storage API world, it represents the ReadStream.
PartitionID string
// contains filtered or unexported fields
}
ArrowRecordBatch represents an Arrow RecordBatch with the source PartitionID
func (*ArrowRecordBatch) Read
func (r *ArrowRecordBatch) Read(p []byte) (int, error)
Read makes ArrowRecordBatch implements io.Reader
AvroOptions
type AvroOptions struct {
// UseAvroLogicalTypes indicates whether to interpret logical types as the
// corresponding BigQuery data type (for example, TIMESTAMP), instead of using
// the raw type (for example, INTEGER).
UseAvroLogicalTypes bool
}
AvroOptions are additional options for Avro external data data sources.
BIEngineReason
type BIEngineReason struct {
// High-Level BI engine reason for partial or disabled acceleration.
Code string
// Human-readable reason for partial or disabled acceleration.
Message string
}
BIEngineReason contains more detailed information about why a query wasn't fully accelerated.
BIEngineStatistics
type BIEngineStatistics struct {
// Specifies which mode of BI Engine acceleration was performed.
BIEngineMode string
// In case of DISABLED or PARTIAL BIEngineMode, these
// contain the explanatory reasons as to why BI Engine could not
// accelerate. In case the full query was accelerated, this field is not
// populated.
BIEngineReasons []*BIEngineReason
}
BIEngineStatistics contains query statistics specific to the use of BI Engine.
BigLakeConfiguration
type BigLakeConfiguration struct {
// Optional. The connection specifying the credentials to be used to read and
// write to external storage, such as Cloud Storage. The connection_id can
// have the form `{project}.{location}.{connection_id}` or
// `projects/{project}/locations/{location}/connections/{connection_id}".
ConnectionID string
// Optional. The fully qualified location prefix of the external folder where
// table data is stored. The '*' wildcard character is not allowed. The URI
// should be in the format `gs://bucket/path_to_table/`
StorageURI string
// Optional. The file format the table data is stored in.
FileFormat BigLakeFileFormat
// Optional. The table format the metadata only snapshots are stored in.
TableFormat BigLakeTableFormat
}
BigLakeConfiguration is used to configure aspects of BigQuery tables for Apache Iceberg (previously known as BigLake managed tables).
BigLakeFileFormat
type BigLakeFileFormat string
BigLakeFileFormat represents the file format for Managed Tables for Apache Iceberg.
UnspecifiedBigLakeFileFormat, ParquetBigLakeFileFormat
var (
// UnspecifiedBigLakeFileFormat represents the default value.
UnspecifiedBigLakeFileFormat BigLakeFileFormat = "FILE_FORMAT_UNSPECIFIED"
// ParquetBigLakeFileFormat represents Apache Parquet Format.
ParquetBigLakeFileFormat BigLakeFileFormat = "PARQUET"
)
BigLakeTableFormat
type BigLakeTableFormat string
BigLakeTableFormat represents the table metadata format for Managed Tables for Apache Iceberg.
UnspecifiedBigLakeTableFormat, IcebergBigLakeTableFormat
var (
// UnspecifiedBigLakeTableFormat represents the default value.
UnspecifiedBigLakeTableFormat BigLakeTableFormat = "TABLE_FORMAT_UNSPECIFIED"
// IcebergBigLakeTableFormat represent Apache Iceberg Format.
IcebergBigLakeTableFormat BigLakeTableFormat = "ICEBERG"
)
BigtableColumn
type BigtableColumn struct {
// Qualifier of the column. Columns in the parent column family that have this
// exact qualifier are exposed as . field. The column field name is the
// same as the column qualifier.
Qualifier string
// If the qualifier is not a valid BigQuery field identifier i.e. does not match
// [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as the column field
// name and is used as field name in queries.
FieldName string
// If true, only the latest version of values are exposed for this column.
// See BigtableColumnFamily.OnlyReadLatest.
OnlyReadLatest bool
// The encoding of the values when the type is not STRING.
// See BigtableColumnFamily.Encoding
Encoding string
// The type to convert the value in cells of this column.
// See BigtableColumnFamily.Type
Type string
}
BigtableColumn describes how BigQuery should access a Bigtable column.
BigtableColumnFamily
type BigtableColumnFamily struct {
// Identifier of the column family.
FamilyID string
// Lists of columns that should be exposed as individual fields as opposed to a
// list of (column name, value) pairs. All columns whose qualifier matches a
// qualifier in this list can be accessed as .. Other columns can be accessed as
// a list through .Column field.
Columns []*BigtableColumn
// The encoding of the values when the type is not STRING. Acceptable encoding values are:
// - TEXT - indicates values are alphanumeric text strings.
// - BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions.
// This can be overridden for a specific column by listing that column in 'columns' and
// specifying an encoding for it.
Encoding string
// If true, only the latest version of values are exposed for all columns in this
// column family. This can be overridden for a specific column by listing that
// column in 'columns' and specifying a different setting for that column.
OnlyReadLatest bool
// The type to convert the value in cells of this
// column family. The values are expected to be encoded using HBase
// Bytes.toBytes function when using the BINARY encoding value.
// Following BigQuery types are allowed (case-sensitive):
// BYTES STRING INTEGER FLOAT BOOLEAN.
// The default type is BYTES. This can be overridden for a specific column by
// listing that column in 'columns' and specifying a type for it.
Type string
}
BigtableColumnFamily describes how BigQuery should access a Bigtable column family.
BigtableOptions
type BigtableOptions struct {
// A list of column families to expose in the table schema along with their
// types. If omitted, all column families are present in the table schema and
// their values are read as BYTES.
ColumnFamilies []*BigtableColumnFamily
// If true, then the column families that are not specified in columnFamilies
// list are not exposed in the table schema. Otherwise, they are read with BYTES
// type values. The default is false.
IgnoreUnspecifiedColumnFamilies bool
// If true, then the rowkey column families will be read and converted to string.
// Otherwise they are read with BYTES type values and users need to manually cast
// them with CAST if necessary. The default is false.
ReadRowkeyAsString bool
}
BigtableOptions are additional options for Bigtable external data sources.
CSVOptions
type CSVOptions struct {
// AllowJaggedRows causes missing trailing optional columns to be tolerated
// when reading CSV data. Missing values are treated as nulls.
AllowJaggedRows bool
// AllowQuotedNewlines sets whether quoted data sections containing
// newlines are allowed when reading CSV data.
AllowQuotedNewlines bool
// Encoding is the character encoding of data to be read.
Encoding Encoding
// FieldDelimiter is the separator for fields in a CSV file, used when
// reading or exporting data. The default is ",".
FieldDelimiter string
// Quote is the value used to quote data sections in a CSV file. The
// default quotation character is the double quote ("), which is used if
// both Quote and ForceZeroQuote are unset.
// To specify that no character should be interpreted as a quotation
// character, set ForceZeroQuote to true.
// Only used when reading data.
Quote string
ForceZeroQuote bool
// The number of rows at the top of a CSV file that BigQuery will skip when
// reading data.
SkipLeadingRows int64
// An optional custom string that will represent a NULL
// value in CSV import data.
//
// NullMarker and NullMarkers are mutually exclusive and should not be set at the same time.
NullMarker string
// An optional list of custom strings that will represent
// a NULL value in CSV import data.
//
// NullMarker and NullMarkers are mutually exclusive and should not be set at the same time.
NullMarkers []string
// Preserves the embedded ASCII control characters (the first 32 characters in the ASCII-table,
// from '\\x00' to '\\x1F') when loading from CSV. Only applicable to CSV, ignored for other formats.
PreserveASCIIControlCharacters bool
// SourceColumnMatch controls the strategy used to match loaded columns to the schema.
// If not set, a sensible default is chosen based on how the schema is provided. If
// autodetect is used, then columns are matched by name. Otherwise, columns
// are matched by position. This is done to keep the behavior
// backward-compatible.
SourceColumnMatch SourceColumnMatch
}
CSVOptions are additional options for CSV external data sources.
Client
type Client struct {
// Location, if set, will be used as the default location for all subsequent
// dataset creation and job operations. A location specified directly in one of
// those operations will override this value.
Location string
// contains filtered or unexported fields
}
Client may be used to perform BigQuery operations.
func NewClient
NewClient constructs a new [Client] which can perform BigQuery operations. Operations performed via the client are billed to the specified GCP project.
If the project ID is set to [DetectProjectID], NewClient will attempt to detect the project ID from credentials.
Example
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
_ = client // TODO: Use client.
}
func (*Client) Close
Close closes any resources held by the client. Close should be called when the client is no longer needed. It need not be called at program exit.
func (*Client) Dataset
Dataset creates a handle to a BigQuery dataset in the client's project.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
ds := client.Dataset("my_dataset")
fmt.Println(ds)
}
func (*Client) DatasetInProject
DatasetInProject creates a handle to a BigQuery dataset in the specified project.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
ds := client.DatasetInProject("their-project-id", "their-dataset")
fmt.Println(ds)
}
func (*Client) Datasets
func (c *Client) Datasets(ctx context.Context) *DatasetIterator
Datasets returns an iterator over the datasets in a project. The Client's project is used by default, but that can be changed by setting ProjectID on the returned iterator before calling Next.
Example
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
it := client.Datasets(ctx)
_ = it // TODO: iterate using Next or iterator.Pager.
}
func (*Client) DatasetsInProject (deprecated)
func (c *Client) DatasetsInProject(ctx context.Context, projectID string) *DatasetIterator
DatasetsInProject returns an iterator over the datasets in the provided project.
Deprecated: call Client.Datasets, then set ProjectID on the returned iterator.
Example
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
it := client.DatasetsInProject(ctx, "their-project-id")
_ = it // TODO: iterate using Next or iterator.Pager.
}
func (*Client) EnableStorageReadClient
EnableStorageReadClient sets up Storage API connection to be used when fetching large datasets from tables, jobs or queries. Currently out of pagination methods like PageInfo().Token and RowIterator.StartIndex are not supported when the Storage API is enabled. Calling this method twice will return an error.
func (*Client) JobFromID
JobFromID creates a Job which refers to an existing BigQuery job. The job need not have been created by this package. For example, the job may have been created in the BigQuery console.
For jobs whose location is other than "US" or "EU", set Client.Location or use JobFromIDLocation.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/bigquery"
)
func getJobID() string { return "" }
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
jobID := getJobID() // Get a job ID using Job.ID, the console or elsewhere.
job, err := client.JobFromID(ctx, jobID)
if err != nil {
// TODO: Handle error.
}
fmt.Println(job.LastStatus()) // Display the job's status.
}
func (*Client) JobFromIDLocation
JobFromIDLocation creates a Job which refers to an existing BigQuery job. The job need not have been created by this package (for example, it may have been created in the BigQuery console), but it must exist in the specified location.
func (*Client) JobFromProject
func (c *Client) JobFromProject(ctx context.Context, projectID, jobID, location string) (j *Job, err error)
JobFromProject creates a Job which refers to an existing BigQuery job. The job need not have been created by this package, nor does it need to reside within the same project or location as the instantiated client.
func (*Client) Jobs
func (c *Client) Jobs(ctx context.Context) *JobIterator
Jobs lists jobs within a project.
Example
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
it := client.Jobs(ctx)
it.State = bigquery.Running // list only running jobs.
_ = it // TODO: iterate using Next or iterator.Pager.
}
func (*Client) Project
Project returns the project ID or number for this instance of the client, which may have either been explicitly specified or autodetected.
func (*Client) Query
Query creates a query with string q. The returned Query may optionally be further configured before its Run method is called.
Examples
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
q := client.Query("select name, num from t1")
q.DefaultProjectID = "project-id"
// TODO: set other options on the Query.
// TODO: Call Query.Run or Query.Read.
}
encryptionKey
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
q := client.Query("select name, num from t1")
// TODO: Replace this key with a key you have created in Cloud KMS.
keyName := "projects/P/locations/L/keyRings/R/cryptoKeys/K"
q.DestinationEncryptionConfig = &bigquery.EncryptionConfig{KMSKeyName: keyName}
// TODO: set other options on the Query.
// TODO: Call Query.Run or Query.Read.
}
parameters
package main
import (
"context"
"cloud.google.com/go/bigquery"
)
func main() {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
q := client.Query("select num from t1 where name = @user")
q.Parameters = []bigquery.QueryParameter{
{Name: "user", Value: "Elizabeth"},
}
// TODO: set other options on the Query.
// TODO: Call Query.Run or Query.Read.
}
CloneDefinition
type CloneDefinition struct {
// BaseTableReference describes the ID of the table that this clone
// came from.
BaseTableReference *Table
// CloneTime indicates when the base table was cloned.
CloneTime time.Time
}
CloneDefinition provides metadata related to the origin of a clone.
Clustering
type Clustering struct {
Fields []string
}
Clustering governs the organization of data within a managed table. For more information, see https://cloud.google.com/bigquery/docs/clustered-tables
ColumnNameCharacterMap
type ColumnNameCharacterMap string
ColumnNameCharacterMap is used to specific column naming behavior for load jobs.
UnspecifiedColumnNameCharacterMap, StrictColumnNameCharacterMap, V1ColumnNameCharacterMap, V2ColumnNameCharacterMap
var (
// UnspecifiedColumnNameCharacterMap is the unspecified default value.
UnspecifiedColumnNameCharacterMap ColumnNameCharacterMap = "COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED"
// StrictColumnNameCharacterMap indicates support for flexible column names.
// Invalid column names will be rejected.
StrictColumnNameCharacterMap ColumnNameCharacterMap = "STRICT"
// V1ColumnNameCharacterMap indicates support for alphanumeric + underscore characters and names must start with a letter or underscore.
// Invalid column names will be normalized.
V1ColumnNameCharacterMap ColumnNameCharacterMap = "V1"
// V2ColumnNameCharacterMap indicates support for flexible column names.
// Invalid column names will be normalized.
V2ColumnNameCharacterMap ColumnNameCharacterMap = "V2"
)
ColumnReference
type ColumnReference struct {
// ReferencingColumn is the column in the current table that composes the foreign key.
ReferencingColumn string
// ReferencedColumn is the column in the primary key of the foreign table that
// is referenced by the ReferencingColumn.
ReferencedColumn string
}
ColumnReference represents the pair of the foreign key column and primary key column.
Compression
type Compression string
Compression is the type of compression to apply when writing data to Google Cloud Storage.
None, Gzip, Deflate, Snappy
const (
// None specifies no compression.
None Compression = "NONE"
// Gzip specifies gzip compression.
Gzip Compression = "GZIP"
// Deflate specifies DEFLATE compression for Avro files.
Deflate Compression = "DEFLATE"
// Snappy specifies SNAPPY compression for Avro files.
Snappy