Ejemplo n.º 1
0
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)
	}
}
Ejemplo n.º 2
0
// 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
}
Ejemplo n.º 3
0
// 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
}
Ejemplo n.º 4
0
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.
	}
}
Ejemplo n.º 5
0
// 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
}
Ejemplo n.º 6
0
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
}
Ejemplo n.º 7
0
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
}
Ejemplo n.º 8
0
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)
}
Ejemplo n.º 9
0
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.
}
Ejemplo n.º 10
0
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.
}
Ejemplo n.º 11
0
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)
	}
}
Ejemplo n.º 12
0
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]
}
Ejemplo n.º 13
0
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)
}
Ejemplo n.º 14
0
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)
}
Ejemplo n.º 15
0
func ExampleNewClient() {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	_ = client // TODO: Use client.
}
Ejemplo n.º 16
0
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.
}
Ejemplo n.º 17
0
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.
}
Ejemplo n.º 18
0
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.
}
Ejemplo n.º 19
0
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
}
Ejemplo n.º 20
0
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.
}
Ejemplo n.º 21
0
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.
	}
}
Ejemplo n.º 22
0
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())
}
Ejemplo n.º 24
0
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.
}
Ejemplo n.º 25
0
// 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
}
Ejemplo n.º 26
0
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])
	}
}
Ejemplo n.º 27
0
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.
	}
}
Ejemplo n.º 28
0
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)
}
Ejemplo n.º 29
0
// 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()
}
Ejemplo n.º 30
0
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()
}