...

Source file src/cloud.google.com/go/bigquery/examples_test.go

Documentation: cloud.google.com/go/bigquery

     1  // Copyright 2016 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bigquery_test
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"os"
    21  	"time"
    22  
    23  	"cloud.google.com/go/bigquery"
    24  	"google.golang.org/api/iterator"
    25  )
    26  
    27  func ExampleNewClient() {
    28  	ctx := context.Background()
    29  	client, err := bigquery.NewClient(ctx, "project-id")
    30  	if err != nil {
    31  		// TODO: Handle error.
    32  	}
    33  	_ = client // TODO: Use client.
    34  }
    35  
    36  func ExampleClient_Dataset() {
    37  	ctx := context.Background()
    38  	client, err := bigquery.NewClient(ctx, "project-id")
    39  	if err != nil {
    40  		// TODO: Handle error.
    41  	}
    42  	ds := client.Dataset("my_dataset")
    43  	fmt.Println(ds)
    44  }
    45  
    46  func ExampleClient_DatasetInProject() {
    47  	ctx := context.Background()
    48  	client, err := bigquery.NewClient(ctx, "project-id")
    49  	if err != nil {
    50  		// TODO: Handle error.
    51  	}
    52  	ds := client.DatasetInProject("their-project-id", "their-dataset")
    53  	fmt.Println(ds)
    54  }
    55  
    56  func ExampleClient_Datasets() {
    57  	ctx := context.Background()
    58  	client, err := bigquery.NewClient(ctx, "project-id")
    59  	if err != nil {
    60  		// TODO: Handle error.
    61  	}
    62  	it := client.Datasets(ctx)
    63  	_ = it // TODO: iterate using Next or iterator.Pager.
    64  }
    65  
    66  func ExampleClient_DatasetsInProject() {
    67  	ctx := context.Background()
    68  	client, err := bigquery.NewClient(ctx, "project-id")
    69  	if err != nil {
    70  		// TODO: Handle error.
    71  	}
    72  	it := client.DatasetsInProject(ctx, "their-project-id")
    73  	_ = it // TODO: iterate using Next or iterator.Pager.
    74  }
    75  
    76  func getJobID() string { return "" }
    77  
    78  func ExampleClient_JobFromID() {
    79  	ctx := context.Background()
    80  	client, err := bigquery.NewClient(ctx, "project-id")
    81  	if err != nil {
    82  		// TODO: Handle error.
    83  	}
    84  	jobID := getJobID() // Get a job ID using Job.ID, the console or elsewhere.
    85  	job, err := client.JobFromID(ctx, jobID)
    86  	if err != nil {
    87  		// TODO: Handle error.
    88  	}
    89  	fmt.Println(job.LastStatus()) // Display the job's status.
    90  }
    91  
    92  func ExampleClient_Jobs() {
    93  	ctx := context.Background()
    94  	client, err := bigquery.NewClient(ctx, "project-id")
    95  	if err != nil {
    96  		// TODO: Handle error.
    97  	}
    98  	it := client.Jobs(ctx)
    99  	it.State = bigquery.Running // list only running jobs.
   100  	_ = it                      // TODO: iterate using Next or iterator.Pager.
   101  }
   102  
   103  func ExampleNewGCSReference() {
   104  	gcsRef := bigquery.NewGCSReference("gs://my-bucket/my-object")
   105  	fmt.Println(gcsRef)
   106  }
   107  
   108  func ExampleClient_Query() {
   109  	ctx := context.Background()
   110  	client, err := bigquery.NewClient(ctx, "project-id")
   111  	if err != nil {
   112  		// TODO: Handle error.
   113  	}
   114  	q := client.Query("select name, num from t1")
   115  	q.DefaultProjectID = "project-id"
   116  	// TODO: set other options on the Query.
   117  	// TODO: Call Query.Run or Query.Read.
   118  }
   119  
   120  func ExampleClient_Query_parameters() {
   121  	ctx := context.Background()
   122  	client, err := bigquery.NewClient(ctx, "project-id")
   123  	if err != nil {
   124  		// TODO: Handle error.
   125  	}
   126  	q := client.Query("select num from t1 where name = @user")
   127  	q.Parameters = []bigquery.QueryParameter{
   128  		{Name: "user", Value: "Elizabeth"},
   129  	}
   130  	// TODO: set other options on the Query.
   131  	// TODO: Call Query.Run or Query.Read.
   132  }
   133  
   134  // This example demonstrates how to run a query job on a table
   135  // with a customer-managed encryption key. The same
   136  // applies to load and copy jobs as well.
   137  func ExampleClient_Query_encryptionKey() {
   138  	ctx := context.Background()
   139  	client, err := bigquery.NewClient(ctx, "project-id")
   140  	if err != nil {
   141  		// TODO: Handle error.
   142  	}
   143  	q := client.Query("select name, num from t1")
   144  	// TODO: Replace this key with a key you have created in Cloud KMS.
   145  	keyName := "projects/P/locations/L/keyRings/R/cryptoKeys/K"
   146  	q.DestinationEncryptionConfig = &bigquery.EncryptionConfig{KMSKeyName: keyName}
   147  	// TODO: set other options on the Query.
   148  	// TODO: Call Query.Run or Query.Read.
   149  }
   150  
   151  func ExampleQuery_Read() {
   152  	ctx := context.Background()
   153  	client, err := bigquery.NewClient(ctx, "project-id")
   154  	if err != nil {
   155  		// TODO: Handle error.
   156  	}
   157  	q := client.Query("select name, num from t1")
   158  	it, err := q.Read(ctx)
   159  	if err != nil {
   160  		// TODO: Handle error.
   161  	}
   162  	_ = it // TODO: iterate using Next or iterator.Pager.
   163  }
   164  
   165  func ExampleQuery_Read_accelerated() {
   166  	ctx := context.Background()
   167  	client, err := bigquery.NewClient(ctx, "project-id")
   168  	if err != nil {
   169  		// TODO: Handle error.
   170  	}
   171  
   172  	// Enable Storage API usage for fetching data
   173  	err = client.EnableStorageReadClient(ctx)
   174  	if err != nil {
   175  		// TODO: Handle error.
   176  	}
   177  
   178  	sql := fmt.Sprintf(`SELECT name, number, state FROM %s WHERE state = "CA"`, `bigquery-public-data.usa_names.usa_1910_current`)
   179  	q := client.Query(sql)
   180  	it, err := q.Read(ctx)
   181  	if err != nil {
   182  		// TODO: Handle error.
   183  	}
   184  
   185  	_ = it // TODO: iterate using Next or iterator.Pager.
   186  }
   187  
   188  func ExampleRowIterator_Next() {
   189  	ctx := context.Background()
   190  	client, err := bigquery.NewClient(ctx, "project-id")
   191  	if err != nil {
   192  		// TODO: Handle error.
   193  	}
   194  	q := client.Query("select name, num from t1")
   195  	it, err := q.Read(ctx)
   196  	if err != nil {
   197  		// TODO: Handle error.
   198  	}
   199  	for {
   200  		var row []bigquery.Value
   201  		err := it.Next(&row)
   202  		if err == iterator.Done {
   203  			break
   204  		}
   205  		if err != nil {
   206  			// TODO: Handle error.
   207  		}
   208  		fmt.Println(row)
   209  	}
   210  }
   211  
   212  func ExampleRowIterator_Next_struct() {
   213  	ctx := context.Background()
   214  	client, err := bigquery.NewClient(ctx, "project-id")
   215  	if err != nil {
   216  		// TODO: Handle error.
   217  	}
   218  
   219  	type score struct {
   220  		Name string
   221  		Num  int
   222  	}
   223  
   224  	q := client.Query("select name, num from t1")
   225  	it, err := q.Read(ctx)
   226  	if err != nil {
   227  		// TODO: Handle error.
   228  	}
   229  	for {
   230  		var s score
   231  		err := it.Next(&s)
   232  		if err == iterator.Done {
   233  			break
   234  		}
   235  		if err != nil {
   236  			// TODO: Handle error.
   237  		}
   238  		fmt.Println(s)
   239  	}
   240  }
   241  
   242  func ExampleJob_Read() {
   243  	ctx := context.Background()
   244  	client, err := bigquery.NewClient(ctx, "project-id")
   245  	if err != nil {
   246  		// TODO: Handle error.
   247  	}
   248  	q := client.Query("select name, num from t1")
   249  	// Call Query.Run to get a Job, then call Read on the job.
   250  	// Note: Query.Read is a shorthand for this.
   251  	job, err := q.Run(ctx)
   252  	if err != nil {
   253  		// TODO: Handle error.
   254  	}
   255  	it, err := job.Read(ctx)
   256  	if err != nil {
   257  		// TODO: Handle error.
   258  	}
   259  	_ = it // TODO: iterate using Next or iterator.Pager.
   260  }
   261  
   262  func ExampleJob_Wait() {
   263  	ctx := context.Background()
   264  	client, err := bigquery.NewClient(ctx, "project-id")
   265  	if err != nil {
   266  		// TODO: Handle error.
   267  	}
   268  	ds := client.Dataset("my_dataset")
   269  	job, err := ds.Table("t1").CopierFrom(ds.Table("t2")).Run(ctx)
   270  	if err != nil {
   271  		// TODO: Handle error.
   272  	}
   273  	status, err := job.Wait(ctx)
   274  	if err != nil {
   275  		// TODO: Handle error.
   276  	}
   277  	if status.Err() != nil {
   278  		// TODO: Handle error.
   279  	}
   280  }
   281  
   282  func ExampleJob_Config() {
   283  	ctx := context.Background()
   284  	client, err := bigquery.NewClient(ctx, "project-id")
   285  	if err != nil {
   286  		// TODO: Handle error.
   287  	}
   288  	ds := client.Dataset("my_dataset")
   289  	job, err := ds.Table("t1").CopierFrom(ds.Table("t2")).Run(ctx)
   290  	if err != nil {
   291  		// TODO: Handle error.
   292  	}
   293  	jc, err := job.Config()
   294  	if err != nil {
   295  		// TODO: Handle error.
   296  	}
   297  	copyConfig := jc.(*bigquery.CopyConfig)
   298  	fmt.Println(copyConfig.Dst, copyConfig.CreateDisposition)
   299  }
   300  
   301  func ExampleDataset_Create() {
   302  	ctx := context.Background()
   303  	client, err := bigquery.NewClient(ctx, "project-id")
   304  	if err != nil {
   305  		// TODO: Handle error.
   306  	}
   307  	ds := client.Dataset("my_dataset")
   308  	if err := ds.Create(ctx, &bigquery.DatasetMetadata{Location: "EU"}); err != nil {
   309  		// TODO: Handle error.
   310  	}
   311  }
   312  
   313  func ExampleDataset_Delete() {
   314  	ctx := context.Background()
   315  	client, err := bigquery.NewClient(ctx, "project-id")
   316  	if err != nil {
   317  		// TODO: Handle error.
   318  	}
   319  	if err := client.Dataset("my_dataset").Delete(ctx); err != nil {
   320  		// TODO: Handle error.
   321  	}
   322  }
   323  
   324  func ExampleDataset_Metadata() {
   325  	ctx := context.Background()
   326  	client, err := bigquery.NewClient(ctx, "project-id")
   327  	if err != nil {
   328  		// TODO: Handle error.
   329  	}
   330  	md, err := client.Dataset("my_dataset").Metadata(ctx)
   331  	if err != nil {
   332  		// TODO: Handle error.
   333  	}
   334  	fmt.Println(md)
   335  }
   336  
   337  // This example illustrates how to perform a read-modify-write sequence on dataset
   338  // metadata. Passing the metadata's ETag to the Update call ensures that the call
   339  // will fail if the metadata was changed since the read.
   340  func ExampleDataset_Update_readModifyWrite() {
   341  	ctx := context.Background()
   342  	client, err := bigquery.NewClient(ctx, "project-id")
   343  	if err != nil {
   344  		// TODO: Handle error.
   345  	}
   346  	ds := client.Dataset("my_dataset")
   347  	md, err := ds.Metadata(ctx)
   348  	if err != nil {
   349  		// TODO: Handle error.
   350  	}
   351  	md2, err := ds.Update(ctx,
   352  		bigquery.DatasetMetadataToUpdate{Name: "new " + md.Name},
   353  		md.ETag)
   354  	if err != nil {
   355  		// TODO: Handle error.
   356  	}
   357  	fmt.Println(md2)
   358  }
   359  
   360  // To perform a blind write, ignoring the existing state (and possibly overwriting
   361  // other updates), pass the empty string as the etag.
   362  func ExampleDataset_Update_blindWrite() {
   363  	ctx := context.Background()
   364  	client, err := bigquery.NewClient(ctx, "project-id")
   365  	if err != nil {
   366  		// TODO: Handle error.
   367  	}
   368  	md, err := client.Dataset("my_dataset").Update(ctx, bigquery.DatasetMetadataToUpdate{Name: "blind"}, "")
   369  	if err != nil {
   370  		// TODO: Handle error.
   371  	}
   372  	fmt.Println(md)
   373  }
   374  
   375  func ExampleDataset_Table() {
   376  	ctx := context.Background()
   377  	client, err := bigquery.NewClient(ctx, "project-id")
   378  	if err != nil {
   379  		// TODO: Handle error.
   380  	}
   381  	// Table creates a reference to the table. It does not create the actual
   382  	// table in BigQuery; to do so, use Table.Create.
   383  	t := client.Dataset("my_dataset").Table("my_table")
   384  	fmt.Println(t)
   385  }
   386  
   387  func ExampleDataset_Tables() {
   388  	ctx := context.Background()
   389  	client, err := bigquery.NewClient(ctx, "project-id")
   390  	if err != nil {
   391  		// TODO: Handle error.
   392  	}
   393  	it := client.Dataset("my_dataset").Tables(ctx)
   394  	_ = it // TODO: iterate using Next or iterator.Pager.
   395  }
   396  
   397  func ExampleDatasetIterator_Next() {
   398  	ctx := context.Background()
   399  	client, err := bigquery.NewClient(ctx, "project-id")
   400  	if err != nil {
   401  		// TODO: Handle error.
   402  	}
   403  	it := client.Datasets(ctx)
   404  	for {
   405  		ds, err := it.Next()
   406  		if err == iterator.Done {
   407  			break
   408  		}
   409  		if err != nil {
   410  			// TODO: Handle error.
   411  		}
   412  		fmt.Println(ds)
   413  	}
   414  }
   415  
   416  func ExampleInferSchema() {
   417  	type Item struct {
   418  		Name  string
   419  		Size  float64
   420  		Count int
   421  	}
   422  	schema, err := bigquery.InferSchema(Item{})
   423  	if err != nil {
   424  		fmt.Println(err)
   425  		// TODO: Handle error.
   426  	}
   427  	for _, fs := range schema {
   428  		fmt.Println(fs.Name, fs.Type)
   429  	}
   430  	// Output:
   431  	// Name STRING
   432  	// Size FLOAT
   433  	// Count INTEGER
   434  }
   435  
   436  func ExampleInferSchema_tags() {
   437  	type Item struct {
   438  		Name     string
   439  		Size     float64
   440  		Count    int    `bigquery:"number"`
   441  		Secret   []byte `bigquery:"-"`
   442  		Optional bigquery.NullBool
   443  		OptBytes []byte `bigquery:",nullable"`
   444  	}
   445  	schema, err := bigquery.InferSchema(Item{})
   446  	if err != nil {
   447  		fmt.Println(err)
   448  		// TODO: Handle error.
   449  	}
   450  	for _, fs := range schema {
   451  		fmt.Println(fs.Name, fs.Type, fs.Required)
   452  	}
   453  	// Output:
   454  	// Name STRING true
   455  	// Size FLOAT true
   456  	// number INTEGER true
   457  	// Optional BOOLEAN false
   458  	// OptBytes BYTES false
   459  }
   460  
   461  func ExampleTable_Create() {
   462  	ctx := context.Background()
   463  	client, err := bigquery.NewClient(ctx, "project-id")
   464  	if err != nil {
   465  		// TODO: Handle error.
   466  	}
   467  	t := client.Dataset("my_dataset").Table("new-table")
   468  	if err := t.Create(ctx, nil); err != nil {
   469  		// TODO: Handle error.
   470  	}
   471  }
   472  
   473  // Initialize a new table by passing TableMetadata to Table.Create.
   474  func ExampleTable_Create_initialize() {
   475  	ctx := context.Background()
   476  	// Infer table schema from a Go type.
   477  	schema, err := bigquery.InferSchema(Item{})
   478  	if err != nil {
   479  		// TODO: Handle error.
   480  	}
   481  	client, err := bigquery.NewClient(ctx, "project-id")
   482  	if err != nil {
   483  		// TODO: Handle error.
   484  	}
   485  	t := client.Dataset("my_dataset").Table("new-table")
   486  	if err := t.Create(ctx,
   487  		&bigquery.TableMetadata{
   488  			Name:           "My New Table",
   489  			Schema:         schema,
   490  			ExpirationTime: time.Now().Add(24 * time.Hour),
   491  		}); err != nil {
   492  		// TODO: Handle error.
   493  	}
   494  }
   495  
   496  // This example demonstrates how to create a table with
   497  // a customer-managed encryption key.
   498  func ExampleTable_Create_encryptionKey() {
   499  	ctx := context.Background()
   500  	// Infer table schema from a Go type.
   501  	schema, err := bigquery.InferSchema(Item{})
   502  	if err != nil {
   503  		// TODO: Handle error.
   504  	}
   505  	client, err := bigquery.NewClient(ctx, "project-id")
   506  	if err != nil {
   507  		// TODO: Handle error.
   508  	}
   509  	t := client.Dataset("my_dataset").Table("new-table")
   510  
   511  	// TODO: Replace this key with a key you have created in Cloud KMS.
   512  	keyName := "projects/P/locations/L/keyRings/R/cryptoKeys/K"
   513  	if err := t.Create(ctx,
   514  		&bigquery.TableMetadata{
   515  			Name:             "My New Table",
   516  			Schema:           schema,
   517  			EncryptionConfig: &bigquery.EncryptionConfig{KMSKeyName: keyName},
   518  		}); err != nil {
   519  		// TODO: Handle error.
   520  	}
   521  }
   522  
   523  func ExampleTable_Delete() {
   524  	ctx := context.Background()
   525  	client, err := bigquery.NewClient(ctx, "project-id")
   526  	if err != nil {
   527  		// TODO: Handle error.
   528  	}
   529  	if err := client.Dataset("my_dataset").Table("my_table").Delete(ctx); err != nil {
   530  		// TODO: Handle error.
   531  	}
   532  }
   533  
   534  func ExampleTable_Metadata() {
   535  	ctx := context.Background()
   536  	client, err := bigquery.NewClient(ctx, "project-id")
   537  	if err != nil {
   538  		// TODO: Handle error.
   539  	}
   540  	md, err := client.Dataset("my_dataset").Table("my_table").Metadata(ctx)
   541  	if err != nil {
   542  		// TODO: Handle error.
   543  	}
   544  	fmt.Println(md)
   545  }
   546  
   547  func ExampleTable_Inserter() {
   548  	ctx := context.Background()
   549  	client, err := bigquery.NewClient(ctx, "project-id")
   550  	if err != nil {
   551  		// TODO: Handle error.
   552  	}
   553  	ins := client.Dataset("my_dataset").Table("my_table").Inserter()
   554  	_ = ins // TODO: Use ins.
   555  }
   556  
   557  func ExampleTable_Inserter_options() {
   558  	ctx := context.Background()
   559  	client, err := bigquery.NewClient(ctx, "project-id")
   560  	if err != nil {
   561  		// TODO: Handle error.
   562  	}
   563  	ins := client.Dataset("my_dataset").Table("my_table").Inserter()
   564  	ins.SkipInvalidRows = true
   565  	ins.IgnoreUnknownValues = true
   566  	_ = ins // TODO: Use ins.
   567  }
   568  
   569  func ExampleTable_CopierFrom() {
   570  	ctx := context.Background()
   571  	client, err := bigquery.NewClient(ctx, "project-id")
   572  	if err != nil {
   573  		// TODO: Handle error.
   574  	}
   575  	ds := client.Dataset("my_dataset")
   576  	c := ds.Table("combined").CopierFrom(ds.Table("t1"), ds.Table("t2"))
   577  	c.WriteDisposition = bigquery.WriteTruncate
   578  	// TODO: set other options on the Copier.
   579  	job, err := c.Run(ctx)
   580  	if err != nil {
   581  		// TODO: Handle error.
   582  	}
   583  	status, err := job.Wait(ctx)
   584  	if err != nil {
   585  		// TODO: Handle error.
   586  	}
   587  	if status.Err() != nil {
   588  		// TODO: Handle error.
   589  	}
   590  }
   591  
   592  func ExampleTable_ExtractorTo() {
   593  	ctx := context.Background()
   594  	client, err := bigquery.NewClient(ctx, "project-id")
   595  	if err != nil {
   596  		// TODO: Handle error.
   597  	}
   598  	gcsRef := bigquery.NewGCSReference("gs://my-bucket/my-object")
   599  	gcsRef.FieldDelimiter = ":"
   600  	// TODO: set other options on the GCSReference.
   601  	ds := client.Dataset("my_dataset")
   602  	extractor := ds.Table("my_table").ExtractorTo(gcsRef)
   603  	extractor.DisableHeader = true
   604  	// TODO: set other options on the Extractor.
   605  	job, err := extractor.Run(ctx)
   606  	if err != nil {
   607  		// TODO: Handle error.
   608  	}
   609  	status, err := job.Wait(ctx)
   610  	if err != nil {
   611  		// TODO: Handle error.
   612  	}
   613  	if status.Err() != nil {
   614  		// TODO: Handle error.
   615  	}
   616  }
   617  
   618  func ExampleTable_LoaderFrom() {
   619  	ctx := context.Background()
   620  	client, err := bigquery.NewClient(ctx, "project-id")
   621  	if err != nil {
   622  		// TODO: Handle error.
   623  	}
   624  	gcsRef := bigquery.NewGCSReference("gs://my-bucket/my-object")
   625  	gcsRef.AllowJaggedRows = true
   626  	gcsRef.MaxBadRecords = 5
   627  	gcsRef.Schema = schema
   628  	// TODO: set other options on the GCSReference.
   629  	ds := client.Dataset("my_dataset")
   630  	loader := ds.Table("my_table").LoaderFrom(gcsRef)
   631  	loader.CreateDisposition = bigquery.CreateNever
   632  	// TODO: set other options on the Loader.
   633  	job, err := loader.Run(ctx)
   634  	if err != nil {
   635  		// TODO: Handle error.
   636  	}
   637  	status, err := job.Wait(ctx)
   638  	if err != nil {
   639  		// TODO: Handle error.
   640  	}
   641  	if status.Err() != nil {
   642  		// TODO: Handle error.
   643  	}
   644  }
   645  
   646  func ExampleTable_LoaderFrom_reader() {
   647  	ctx := context.Background()
   648  	client, err := bigquery.NewClient(ctx, "project-id")
   649  	if err != nil {
   650  		// TODO: Handle error.
   651  	}
   652  	f, err := os.Open("data.csv")
   653  	if err != nil {
   654  		// TODO: Handle error.
   655  	}
   656  	rs := bigquery.NewReaderSource(f)
   657  	rs.AllowJaggedRows = true
   658  	rs.MaxBadRecords = 5
   659  	rs.Schema = schema
   660  	// TODO: set other options on the GCSReference.
   661  	ds := client.Dataset("my_dataset")
   662  	loader := ds.Table("my_table").LoaderFrom(rs)
   663  	loader.CreateDisposition = bigquery.CreateNever
   664  	// TODO: set other options on the Loader.
   665  	job, err := loader.Run(ctx)
   666  	if err != nil {
   667  		// TODO: Handle error.
   668  	}
   669  	status, err := job.Wait(ctx)
   670  	if err != nil {
   671  		// TODO: Handle error.
   672  	}
   673  	if status.Err() != nil {
   674  		// TODO: Handle error.
   675  	}
   676  }
   677  
   678  func ExampleTable_Read() {
   679  	ctx := context.Background()
   680  	client, err := bigquery.NewClient(ctx, "project-id")
   681  	if err != nil {
   682  		// TODO: Handle error.
   683  	}
   684  	it := client.Dataset("my_dataset").Table("my_table").Read(ctx)
   685  	_ = it // TODO: iterate using Next or iterator.Pager.
   686  }
   687  
   688  // This example illustrates how to perform a read-modify-write sequence on table
   689  // metadata. Passing the metadata's ETag to the Update call ensures that the call
   690  // will fail if the metadata was changed since the read.
   691  func ExampleTable_Update_readModifyWrite() {
   692  	ctx := context.Background()
   693  	client, err := bigquery.NewClient(ctx, "project-id")
   694  	if err != nil {
   695  		// TODO: Handle error.
   696  	}
   697  	t := client.Dataset("my_dataset").Table("my_table")
   698  	md, err := t.Metadata(ctx)
   699  	if err != nil {
   700  		// TODO: Handle error.
   701  	}
   702  	md2, err := t.Update(ctx,
   703  		bigquery.TableMetadataToUpdate{Name: "new " + md.Name},
   704  		md.ETag)
   705  	if err != nil {
   706  		// TODO: Handle error.
   707  	}
   708  	fmt.Println(md2)
   709  }
   710  
   711  // To perform a blind write, ignoring the existing state (and possibly overwriting
   712  // other updates), pass the empty string as the etag.
   713  func ExampleTable_Update_blindWrite() {
   714  	ctx := context.Background()
   715  	client, err := bigquery.NewClient(ctx, "project-id")
   716  	if err != nil {
   717  		// TODO: Handle error.
   718  	}
   719  	t := client.Dataset("my_dataset").Table("my_table")
   720  	tm, err := t.Update(ctx, bigquery.TableMetadataToUpdate{
   721  		Description: "my favorite table",
   722  	}, "")
   723  	if err != nil {
   724  		// TODO: Handle error.
   725  	}
   726  	fmt.Println(tm)
   727  }
   728  
   729  func ExampleTableIterator_Next() {
   730  	ctx := context.Background()
   731  	client, err := bigquery.NewClient(ctx, "project-id")
   732  	if err != nil {
   733  		// TODO: Handle error.
   734  	}
   735  	it := client.Dataset("my_dataset").Tables(ctx)
   736  	for {
   737  		t, err := it.Next()
   738  		if err == iterator.Done {
   739  			break
   740  		}
   741  		if err != nil {
   742  			// TODO: Handle error.
   743  		}
   744  		fmt.Println(t)
   745  	}
   746  }
   747  
   748  type Item struct {
   749  	Name  string
   750  	Size  float64
   751  	Count int
   752  }
   753  
   754  // Save implements the ValueSaver interface.
   755  func (i *Item) Save() (map[string]bigquery.Value, string, error) {
   756  	return map[string]bigquery.Value{
   757  		"Name":  i.Name,
   758  		"Size":  i.Size,
   759  		"Count": i.Count,
   760  	}, "", nil
   761  }
   762  
   763  func ExampleInserter_Put() {
   764  	ctx := context.Background()
   765  	client, err := bigquery.NewClient(ctx, "project-id")
   766  	if err != nil {
   767  		// TODO: Handle error.
   768  	}
   769  	ins := client.Dataset("my_dataset").Table("my_table").Inserter()
   770  	// Item implements the ValueSaver interface.
   771  	items := []*Item{
   772  		{Name: "n1", Size: 32.6, Count: 7},
   773  		{Name: "n2", Size: 4, Count: 2},
   774  		{Name: "n3", Size: 101.5, Count: 1},
   775  	}
   776  	if err := ins.Put(ctx, items); err != nil {
   777  		// TODO: Handle error.
   778  	}
   779  }
   780  
   781  var schema bigquery.Schema
   782  
   783  func ExampleInserter_Put_structSaver() {
   784  	ctx := context.Background()
   785  	client, err := bigquery.NewClient(ctx, "project-id")
   786  	if err != nil {
   787  		// TODO: Handle error.
   788  	}
   789  	ins := client.Dataset("my_dataset").Table("my_table").Inserter()
   790  
   791  	type score struct {
   792  		Name string
   793  		Num  int
   794  	}
   795  
   796  	// Assume schema holds the table's schema.
   797  	savers := []*bigquery.StructSaver{
   798  		{Struct: score{Name: "n1", Num: 12}, Schema: schema, InsertID: "id1"},
   799  		{Struct: score{Name: "n2", Num: 31}, Schema: schema, InsertID: "id2"},
   800  		{Struct: score{Name: "n3", Num: 7}, Schema: schema, InsertID: "id3"},
   801  	}
   802  	if err := ins.Put(ctx, savers); err != nil {
   803  		// TODO: Handle error.
   804  	}
   805  }
   806  
   807  func ExampleInserter_Put_struct() {
   808  	ctx := context.Background()
   809  	client, err := bigquery.NewClient(ctx, "project-id")
   810  	if err != nil {
   811  		// TODO: Handle error.
   812  	}
   813  	ins := client.Dataset("my_dataset").Table("my_table").Inserter()
   814  
   815  	type score struct {
   816  		Name string
   817  		Num  int
   818  	}
   819  	scores := []score{
   820  		{Name: "n1", Num: 12},
   821  		{Name: "n2", Num: 31},
   822  		{Name: "n3", Num: 7},
   823  	}
   824  	// Schema is inferred from the score type.
   825  	if err := ins.Put(ctx, scores); err != nil {
   826  		// TODO: Handle error.
   827  	}
   828  }
   829  
   830  func ExampleInserter_Put_valuesSaver() {
   831  	ctx := context.Background()
   832  	client, err := bigquery.NewClient(ctx, "project-id")
   833  	if err != nil {
   834  		// TODO: Handle error.
   835  	}
   836  
   837  	ins := client.Dataset("my_dataset").Table("my_table").Inserter()
   838  
   839  	var vss []*bigquery.ValuesSaver
   840  	for i, name := range []string{"n1", "n2", "n3"} {
   841  		// Assume schema holds the table's schema.
   842  		vss = append(vss, &bigquery.ValuesSaver{
   843  			Schema:   schema,
   844  			InsertID: name,
   845  			Row:      []bigquery.Value{name, int64(i)},
   846  		})
   847  	}
   848  
   849  	if err := ins.Put(ctx, vss); err != nil {
   850  		// TODO: Handle error.
   851  	}
   852  }
   853  

View as plain text