bigquery gae

workers/bigquery.go

package workers

import (
    "cloud.google.com/go/bigquery"
    "golang.org/x/net/context"
)

// BigQuery ...
type BigQuery struct {
    ctx       context.Context
    projectID string
    client    *bigquery.Client
}

// CreateNewBigquery ...
func CreateNewBigquery(ctx context.Context, projectID string) (*BigQuery, error) {
    b := BigQuery{ctx: ctx, projectID: projectID}
    client, err := bigquery.NewClient(b.ctx, b.projectID)
    if err != nil {
        return nil, err
    }
    b.client = client
    return &b, nil
}

// CreateDataset ...
func (b *BigQuery) CreateDataset(datasetName string) error {
    dataset := b.client.Dataset(datasetName)
    if err := dataset.Create(b.ctx); err != nil {
        return err
    }
    return nil
}

// User ...
type User struct {
    Name string
}

// PutUser ...
func (b *BigQuery) PutUser(user *User, datasetName, tableName string) error {
    var users []*User
    users = append(users, user)
    u := b.client.Dataset(datasetName).Table(tableName).Uploader()
    if err := u.Put(b.ctx, users); err != nil {
        return err
    }
    return nil
}

handlers/bigquery.go

package handlers

import (
    "camera-raspi/app/workers"
    "net/http"

    "google.golang.org/appengine"
)

// BigQuery ...
type BigQuery struct{}

// CreateDataset ...
func (BigQuery) CreateDataset(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)
    b, err := workers.CreateNewBigquery(ctx, "camera-raspi")
    if err != nil {
        panic(err)
    }
    b.CreateDataset("my_new_dataset")
}

// PutUser ...
func (BigQuery) PutUser(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)
    b, err := workers.CreateNewBigquery(ctx, "camera-raspi")
    if err != nil {
        panic(err)
    }
    type user struct{ Name string }
    u := workers.User{Name: "yohei"}
    b.PutUser(&u, "my_new_dataset", "users")
}

参考

https://cloud.google.com/bigquery/docs/reference/libraries?hl=ja
https://cloud.google.com/bigquery/streaming-data-into-bigquery?hl=ja#bigquery-stream-data-go