example_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  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. package datastore_test
  15. import (
  16. "io/ioutil"
  17. "log"
  18. "time"
  19. "golang.org/x/net/context"
  20. "golang.org/x/oauth2/google"
  21. "google.golang.org/cloud"
  22. "google.golang.org/cloud/datastore"
  23. )
  24. // TODO(djd): reevaluate this example given new Client config.
  25. func Example_auth() *datastore.Client {
  26. // Initialize an authorized context with Google Developers Console
  27. // JSON key. Read the google package examples to learn more about
  28. // different authorization flows you can use.
  29. // http://godoc.org/golang.org/x/oauth2/google
  30. jsonKey, err := ioutil.ReadFile("/path/to/json/keyfile.json")
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. conf, err := google.JWTConfigFromJSON(
  35. jsonKey,
  36. datastore.ScopeDatastore,
  37. datastore.ScopeUserEmail,
  38. )
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. ctx := context.Background()
  43. client, err := datastore.NewClient(ctx, "project-id", cloud.WithTokenSource(conf.TokenSource(ctx)))
  44. if err != nil {
  45. log.Fatal(err)
  46. }
  47. // Use the client (see other examples).
  48. return client
  49. }
  50. func ExampleGet() {
  51. ctx := context.Background()
  52. client, err := datastore.NewClient(ctx, "project-id")
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. type Article struct {
  57. Title string
  58. Description string
  59. Body string `datastore:",noindex"`
  60. Author *datastore.Key
  61. PublishedAt time.Time
  62. }
  63. key := datastore.NewKey(ctx, "Article", "articled1", 0, nil)
  64. article := &Article{}
  65. if err := client.Get(ctx, key, article); err != nil {
  66. log.Fatal(err)
  67. }
  68. }
  69. func ExamplePut() {
  70. ctx := context.Background()
  71. client, err := datastore.NewClient(ctx, "project-id")
  72. if err != nil {
  73. log.Fatal(err)
  74. }
  75. type Article struct {
  76. Title string
  77. Description string
  78. Body string `datastore:",noindex"`
  79. Author *datastore.Key
  80. PublishedAt time.Time
  81. }
  82. newKey := datastore.NewIncompleteKey(ctx, "Article", nil)
  83. _, err = client.Put(ctx, newKey, &Article{
  84. Title: "The title of the article",
  85. Description: "The description of the article...",
  86. Body: "...",
  87. Author: datastore.NewKey(ctx, "Author", "jbd", 0, nil),
  88. PublishedAt: time.Now(),
  89. })
  90. if err != nil {
  91. log.Fatal(err)
  92. }
  93. }
  94. func ExampleDelete() {
  95. ctx := context.Background()
  96. client, err := datastore.NewClient(ctx, "project-id")
  97. if err != nil {
  98. log.Fatal(err)
  99. }
  100. key := datastore.NewKey(ctx, "Article", "articled1", 0, nil)
  101. if err := client.Delete(ctx, key); err != nil {
  102. log.Fatal(err)
  103. }
  104. }
  105. type Post struct {
  106. Title string
  107. PublishedAt time.Time
  108. Comments int
  109. }
  110. func ExampleGetMulti() {
  111. ctx := context.Background()
  112. client, err := datastore.NewClient(ctx, "project-id")
  113. if err != nil {
  114. log.Fatal(err)
  115. }
  116. keys := []*datastore.Key{
  117. datastore.NewKey(ctx, "Post", "post1", 0, nil),
  118. datastore.NewKey(ctx, "Post", "post2", 0, nil),
  119. datastore.NewKey(ctx, "Post", "post3", 0, nil),
  120. }
  121. posts := make([]Post, 3)
  122. if err := client.GetMulti(ctx, keys, posts); err != nil {
  123. log.Println(err)
  124. }
  125. }
  126. func ExamplePutMulti_slice() {
  127. ctx := context.Background()
  128. client, err := datastore.NewClient(ctx, "project-id")
  129. if err != nil {
  130. log.Fatal(err)
  131. }
  132. keys := []*datastore.Key{
  133. datastore.NewKey(ctx, "Post", "post1", 0, nil),
  134. datastore.NewKey(ctx, "Post", "post2", 0, nil),
  135. }
  136. // PutMulti with a Post slice.
  137. posts := []*Post{
  138. {Title: "Post 1", PublishedAt: time.Now()},
  139. {Title: "Post 2", PublishedAt: time.Now()},
  140. }
  141. if _, err := client.PutMulti(ctx, keys, posts); err != nil {
  142. log.Fatal(err)
  143. }
  144. }
  145. func ExamplePutMulti_interfaceSlice() {
  146. ctx := context.Background()
  147. client, err := datastore.NewClient(ctx, "project-id")
  148. if err != nil {
  149. log.Fatal(err)
  150. }
  151. keys := []*datastore.Key{
  152. datastore.NewKey(ctx, "Post", "post1", 0, nil),
  153. datastore.NewKey(ctx, "Post", "post2", 0, nil),
  154. }
  155. // PutMulti with an empty interface slice.
  156. posts := []interface{}{
  157. &Post{Title: "Post 1", PublishedAt: time.Now()},
  158. &Post{Title: "Post 2", PublishedAt: time.Now()},
  159. }
  160. if _, err := client.PutMulti(ctx, keys, posts); err != nil {
  161. log.Fatal(err)
  162. }
  163. }
  164. func ExampleQuery() {
  165. ctx := context.Background()
  166. client, err := datastore.NewClient(ctx, "project-id")
  167. if err != nil {
  168. log.Fatal(err)
  169. }
  170. // Count the number of the post entities.
  171. q := datastore.NewQuery("Post")
  172. n, err := client.Count(ctx, q)
  173. if err != nil {
  174. log.Fatal(err)
  175. }
  176. log.Println("There are %d posts.", n)
  177. // List the posts published since yesterday.
  178. yesterday := time.Now().Add(-24 * time.Hour)
  179. q = datastore.NewQuery("Post").Filter("PublishedAt >", yesterday)
  180. it := client.Run(ctx, q)
  181. // Use the iterator.
  182. _ = it
  183. // Order the posts by the number of comments they have recieved.
  184. datastore.NewQuery("Post").Order("-Comments")
  185. // Start listing from an offset and limit the results.
  186. datastore.NewQuery("Post").Offset(20).Limit(10)
  187. }
  188. func ExampleTransaction() {
  189. ctx := context.Background()
  190. client, err := datastore.NewClient(ctx, "project-id")
  191. if err != nil {
  192. log.Fatal(err)
  193. }
  194. const retries = 3
  195. // Increment a counter.
  196. // See https://cloud.google.com/appengine/articles/sharding_counters for
  197. // a more scalable solution.
  198. type Counter struct {
  199. Count int
  200. }
  201. key := datastore.NewKey(ctx, "counter", "CounterA", 0, nil)
  202. for i := 0; i < retries; i++ {
  203. tx, err := client.NewTransaction(ctx)
  204. if err != nil {
  205. break
  206. }
  207. var c Counter
  208. if err := tx.Get(key, &c); err != nil && err != datastore.ErrNoSuchEntity {
  209. break
  210. }
  211. c.Count++
  212. if _, err := tx.Put(key, &c); err != nil {
  213. break
  214. }
  215. // Attempt to commit the transaction. If there's a conflict, try again.
  216. if _, err := tx.Commit(); err != datastore.ErrConcurrentTransaction {
  217. break
  218. }
  219. }
  220. }