func ExampleClient_Put_flatten() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { log.Fatal(err) } type Animal struct { Name string Type string Breed string } type Human struct { Name string Height int Pet Animal `datastore:",flatten"` } newKey := datastore.IncompleteKey("Human", nil) _, err = client.Put(ctx, newKey, &Human{ Name: "Susan", Height: 67, Pet: Animal{ Name: "Fluffy", Type: "Cat", Breed: "Sphynx", }, }) if err != nil { log.Fatal(err) } }
// NewResultDataRepo - return new instance of the ResultDataRepo func NewResultDataRepo(limit int, autoResize bool, symbol string, r *http.Request) ResultDataRepo { var ctx context.Context if r != nil { ctx = appengine.NewContext(r) } else { ctx = context.Background() } client, err := datastore.NewClient(ctx, projectID) if err != nil { log.Fatal(err) } rr := new(resultDataRepo) rr.pipe = make(chan commandResultData) rr.symbol = symbol rr.limit = limit rr.autoResize = autoResize == true rr.client = client if err := rr.loadStartResultData(); err != nil { log.Fatal(err) } go rr.run() return rr }
// NewEfficiencyRepo return instance of the EfficiencyRepo func NewEfficiencyRepo(trainType, symbol string, rangesCount, limit, frame int32, r *http.Request) EfficiencyRepo { // todo: switch from http.Request to context.Context var ctx context.Context if r != nil { ctx = appengine.NewContext(r) } else { ctx = context.Background() } client, err := datastore.NewClient(ctx, projectID) if err != nil { log.Fatal(err) } rr := new(efficiencyRepo) rr.pipe = make(chan commandEfficiency) rr.symbol = symbol rr.trainType = trainType rr.limit = limit rr.frame = frame rr.rangesCount = rangesCount rr.client = client if err := rr.loadStartEfficiency(); err != nil { log.Fatal(err) } go rr.run() return rr }
func ExampleClient_Put() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } type Article struct { Title string Description string Body string `datastore:",noindex"` Author *datastore.Key PublishedAt time.Time } newKey := datastore.IncompleteKey("Article", nil) _, err = client.Put(ctx, newKey, &Article{ Title: "The title of the article", Description: "The description of the article...", Body: "...", Author: datastore.NameKey("Author", "jbd", nil), PublishedAt: time.Now(), }) if err != nil { // TODO: Handle error. } }
// New - return new instance of repo func New(limit int, autoResize bool, r *http.Request) RateRepo { _limit = limit _autoResize = autoResize == true var ctx context.Context if r != nil { ctx = appengine.NewContext(r) //_ctx = ctx } else { ctx = context.Background() } client, err := datastore.NewClient(ctx, projectID) if err != nil { log.Fatal(err) } _client = client if err := loadStartRates(); err != nil { log.Fatal(err) } rr := make(rateRepo) go rr.run() return rr }
func Example_serviceAccount() { // Warning: The better way to use service accounts is to set GOOGLE_APPLICATION_CREDENTIALS // and use the Application Default Credentials. ctx := context.Background() // Use a JSON key file associated with a Google service account to // authenticate and authorize. // Go to https://console.developers.google.com/permissions/serviceaccounts to create // and download a service account key for your project. // // Note: The example uses the datastore client, but the same steps apply to // the other client libraries underneath this package. key, err := ioutil.ReadFile("/path/to/service-account-key.json") if err != nil { // TODO: handle error. } cfg, err := google.JWTConfigFromJSON(key, datastore.ScopeDatastore) if err != nil { // TODO: handle error. } client, err := datastore.NewClient( ctx, "project-id", option.WithTokenSource(cfg.TokenSource(ctx))) if err != nil { // TODO: handle error. } // Use the client. _ = client }
func _getRatesKeys(r *http.Request, jsonKey []byte, unixtime int64) <-chan keyResult { out := make(chan keyResult) go func() { defer close(out) var ctx context.Context if r != nil { ctx = appengine.NewContext(r) } else { ctx = context.Background() } client, err := datastore.NewClient(ctx, "rp-optima") if err != nil { out <- keyResult{error: err} return } /*if keys, err := client.GetAll(ctx, datastore.NewQuery("ResultData").Filter("timestamp<", unixtime).KeysOnly(), nil); err != nil { out <- keyResult{error:err} return }else { out <- keyResult{keys:keys} }*/ if keys, err := client.GetAll(ctx, datastore.NewQuery("Rate").Filter("id<", unixtime).KeysOnly(), nil); err != nil { out <- keyResult{error: err} } else { out <- keyResult{keys: keys} } }() return out }
func ExampleCommit_Key() { ctx := context.Background() client, err := datastore.NewClient(ctx, "") if err != nil { // TODO: Handle error. } var pk1, pk2 *datastore.PendingKey // Create two posts in a single transaction. commit, err := client.RunInTransaction(ctx, func(tx *datastore.Transaction) error { var err error pk1, err = tx.Put(datastore.IncompleteKey("Post", nil), &Post{Title: "Post 1", PublishedAt: time.Now()}) if err != nil { return err } pk2, err = tx.Put(datastore.IncompleteKey("Post", nil), &Post{Title: "Post 2", PublishedAt: time.Now()}) if err != nil { return err } return nil }) if err != nil { // TODO: Handle error. } // Now pk1, pk2 are valid PendingKeys. Let's convert them into real keys // using the Commit object. k1 := commit.Key(pk1) k2 := commit.Key(pk2) fmt.Println(k1, k2) }
func ExampleIterator_Cursor() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") cursorStr := "" // [START cursor_paging] const pageSize = 5 query := datastore.NewQuery("Tasks").Limit(pageSize) if cursorStr != "" { cursor, err := datastore.DecodeCursor(cursorStr) if err != nil { log.Fatalf("Bad cursor %q: %v", cursorStr, err) } query = query.Start(cursor) } // Read the tasks. var tasks []Task var task Task it := client.Run(ctx, query) _, err := it.Next(&task) for err == nil { tasks = append(tasks, task) _, err = it.Next(&task) } if err != datastore.Done { log.Fatalf("Failed fetching results: %v", err) } // Get the cursor for the next page of results. nextCursor, err := it.Cursor() // [END cursor_paging] _ = err // Check the error. _ = nextCursor // Use nextCursor.String as the next page's token. }
func ExampleClient_PutMulti() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") // [START batch_upsert] tasks := []*Task{ { Category: "Personal", Done: false, Priority: 4, Description: "Learn Cloud Datastore", }, { Category: "Personal", Done: false, Priority: 5, Description: "Integrate Cloud Datastore", }, } keys := []*datastore.Key{ datastore.NewIncompleteKey(ctx, "Task", nil), datastore.NewIncompleteKey(ctx, "Task", nil), } keys, err := client.PutMulti(ctx, keys, tasks) // [END batch_upsert] _ = err // Make sure you check err. _ = keys // keys now has the complete keys for the newly stored tasks. }
func ExampleIterator_Cursor() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } it := client.Run(ctx, datastore.NewQuery("Post")) for { var p Post _, err := it.Next(&p) if err == iterator.Done { break } if err != nil { // TODO: Handle error. } fmt.Println(p) cursor, err := it.Cursor() if err != nil { // TODO: Handle error. } // When printed, a cursor will display as a string that can be passed // to datastore.NewCursor. fmt.Printf("to resume with this post, use cursor %s\n", cursor) } }
func Example_Transaction() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") var to, from *datastore.Key // [START transactional_update] type BankAccount struct { Balance int } const amount = 50 keys := []*datastore.Key{to, from} tx, err := client.NewTransaction(ctx) if err != nil { log.Fatalf("client.NewTransaction: %v", err) } accs := make([]BankAccount, 2) if err := tx.GetMulti(keys, accs); err != nil { tx.Rollback() log.Fatalf("tx.GetMulti: %v", err) } accs[0].Balance += amount accs[1].Balance -= amount if _, err := tx.PutMulti(keys, accs); err != nil { tx.Rollback() log.Fatalf("tx.PutMulti: %v", err) } if _, err = tx.Commit(); err != nil { log.Fatalf("tx.Commit: %v", err) } // [END transactional_update] }
func ExampleQuery() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { log.Fatal(err) } // Count the number of the post entities. q := datastore.NewQuery("Post") n, err := client.Count(ctx, q) if err != nil { log.Fatal(err) } log.Printf("There are %d posts.", n) // List the posts published since yesterday. yesterday := time.Now().Add(-24 * time.Hour) q = datastore.NewQuery("Post").Filter("PublishedAt >", yesterday) it := client.Run(ctx, q) // Use the iterator. _ = it // Order the posts by the number of comments they have recieved. datastore.NewQuery("Post").Order("-Comments") // Start listing from an offset and limit the results. datastore.NewQuery("Post").Offset(20).Limit(10) }
func ExampleClient_RunInTransaction() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } // Increment a counter. // See https://cloud.google.com/appengine/articles/sharding_counters for // a more scalable solution. type Counter struct { Count int } var count int key := datastore.NameKey("Counter", "singleton", nil) _, err = client.RunInTransaction(ctx, func(tx *datastore.Transaction) error { var x Counter if err := tx.Get(key, &x); err != nil && err != datastore.ErrNoSuchEntity { return err } x.Count++ if _, err := tx.Put(key, &x); err != nil { return err } count = x.Count return nil }) if err != nil { // TODO: Handle error. } // The value of count is only valid once the transaction is successful // (RunInTransaction has returned nil). fmt.Printf("Count=%d\n", count) }
func ExampleNewClient() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } _ = client // TODO: Use client. }
func ExampleClient_Delete() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") key := datastore.NewKey(ctx, "Task", "sampletask", 0, nil) // [START delete] err := client.Delete(ctx, key) // [END delete] _ = err // Make sure you check err. }
func ExampleClient_DeleteMulti() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") var taskKeys []*datastore.Key // Populated with incomplete keys. // [START batch_delete] err := client.DeleteMulti(ctx, taskKeys) // [END batch_delete] _ = err // Make sure you check err. }
func ExampleClient_Get() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") taskKey := datastore.NewKey(ctx, "Task", "sampleTask", 0, nil) // [START lookup] var task Task err := client.Get(ctx, taskKey, &task) // [END lookup] _ = err // Make sure you check err. }
func ExampleClient_Put_upsert() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") task := &Task{} // Populated with appropriate data. key := datastore.NewIncompleteKey(ctx, "Task", nil) // [START upsert] key, err := client.Put(ctx, key, task) // [END upsert] _ = err // Make sure you check err. _ = key // key is the complete key for the newly stored task }
func ExampleClient_Run() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } // List the posts published since yesterday. yesterday := time.Now().Add(-24 * time.Hour) q := datastore.NewQuery("Post").Filter("PublishedAt >", yesterday) it := client.Run(ctx, q) _ = it // TODO: iterate using Next. }
func ExampleClient_Delete() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } key := datastore.NameKey("Article", "articled1", nil) if err := client.Delete(ctx, key); err != nil { // TODO: Handle error. } }
func ExampleDelete() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { log.Fatal(err) } key := datastore.NewKey(ctx, "Article", "articled1", 0, nil) if err := client.Delete(ctx, key); err != nil { log.Fatal(err) } }
func TestMain(m *testing.M) { ctx := context.Background() if tc, ok := testutil.ContextMain(m); ok { var err error client, err = datastore.NewClient(ctx, tc.ProjectID) if err != nil { log.Fatalf("datastore.NewClient: %v", err) } defer client.Close() } os.Exit(m.Run()) }
func ExampleQuery_KeysOnly() { ctx := context.Background() client, _ := datastore.NewClient(ctx, "my-proj") // [START keys_only_query] query := datastore.NewQuery("Task").KeysOnly() // [END keys_only_query] // [START run_keys_only_query] keys, err := client.GetAll(ctx, query, nil) // [END run_keys_only_query] _ = err // Make sure you check err. _ = keys // Keys contains keys for all stored tasks. }
// TODO(jbd): Document other authorization methods and refer to them here. func Example_auth() *datastore.Client { ctx := context.Background() // Use Google Application Default Credentials to authorize and authenticate the client. // More information about Application Default Credentials and how to enable is at // https://developers.google.com/identity/protocols/application-default-credentials. client, err := datastore.NewClient(ctx, "project-id") if err != nil { log.Fatal(err) } // Use the client (see other examples). return client }
func ExampleClient_GetAll() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } var posts []*Post keys, err := client.GetAll(ctx, datastore.NewQuery("Post"), &posts) for i, key := range keys { fmt.Println(key) fmt.Println(posts[i]) } }
func ExampleClient_DeleteMulti() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } var keys []*datastore.Key for i := 1; i <= 10; i++ { keys = append(keys, datastore.IDKey("Article", int64(i), nil)) } if err := client.DeleteMulti(ctx, keys); err != nil { // TODO: Handle error. } }
func ExampleClient_Count() { ctx := context.Background() client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } // Count the number of the post entities. q := datastore.NewQuery("Post") n, err := client.Count(ctx, q) if err != nil { // TODO: Handle error. } fmt.Printf("There are %d posts.", n) }
// TODO(jbd): Document other authorization methods and refer to them here. func Example_auth() { ctx := context.Background() // Use Google Application Default Credentials to authorize and authenticate the client. // More information about Application Default Credentials and how to enable is at // https://developers.google.com/identity/protocols/application-default-credentials. client, err := datastore.NewClient(ctx, "project-id") if err != nil { // TODO: Handle error. } // Use the client (see other examples). // Close the client when finished. client.Close() }
func main() { ctx := context.Background() // Set this in app.yaml when running in production. projectID := os.Getenv("GCLOUD_DATASET_ID") var err error datastoreClient, err = datastore.NewClient(ctx, projectID) if err != nil { log.Fatal(err) } http.HandleFunc("/", handle) appengine.Main() }