Skip to content

Instantly share code, notes, and snippets.

@u110
Created June 24, 2020 04:28
Show Gist options
  • Save u110/8519277b790fb2be662aeef036f1075e to your computer and use it in GitHub Desktop.
Save u110/8519277b790fb2be662aeef036f1075e to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"cloud.google.com/go/bigquery"
)
// Item represents a row item.
type Item struct {
Name string
Age int
Inserted string
}
// Save implements the ValueSaver interface.
func (i *Item) Save() (map[string]bigquery.Value, string, error) {
return map[string]bigquery.Value{
"name": i.Name,
"age": i.Age,
"inserted": i.Inserted,
}, "", nil
}
// insertRows demonstrates inserting data into a table using the streaming insert mechanism.
func insertRows(projectID, datasetID, tableID string) error {
// projectID := "my-project-id"
// datasetID := "mydataset"
// tableID := "mytable"
ctx := context.Background()
client, err := bigquery.NewClient(ctx, projectID)
if err != nil {
return fmt.Errorf("bigquery.NewClient: %v", err)
}
defer client.Close()
inserter := client.Dataset(datasetID).Table(tableID).Inserter()
items := []*Item{
// Item implements the ValueSaver interface.
{Name: "Phred Phlyntstone", Age: 32, Inserted: "AUTO"},
{Name: "Wylma Phlyntstone", Age: 29, Inserted: "AUTO"},
}
if err := inserter.Put(ctx, items); err != nil {
return err
}
return nil
}
func main() {
if err := insertRows("my-gcp-project", "test_u110", "stream_insert_tbl"); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment