Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

217 lignes
6.3 KiB

  1. // Copyright 2017 Google LLC
  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. // DO NOT EDIT doc.go. Modify internal/doc.template, then run make -C internal.
  15. /*
  16. Package firestore provides a client for reading and writing to a Cloud Firestore
  17. database.
  18. See https://cloud.google.com/firestore/docs for an introduction
  19. to Cloud Firestore and additional help on using the Firestore API.
  20. See https://godoc.org/cloud.google.com/go for authentication, timeouts,
  21. connection pooling and similar aspects of this package.
  22. Note: you can't use both Cloud Firestore and Cloud Datastore in the same
  23. project.
  24. Creating a Client
  25. To start working with this package, create a client with a project ID:
  26. ctx := context.Background()
  27. client, err := firestore.NewClient(ctx, "projectID")
  28. if err != nil {
  29. // TODO: Handle error.
  30. }
  31. CollectionRefs and DocumentRefs
  32. In Firestore, documents are sets of key-value pairs, and collections are groups of
  33. documents. A Firestore database consists of a hierarchy of alternating collections
  34. and documents, referred to by slash-separated paths like
  35. "States/California/Cities/SanFrancisco".
  36. This client is built around references to collections and documents. CollectionRefs
  37. and DocumentRefs are lightweight values that refer to the corresponding database
  38. entities. Creating a ref does not involve any network traffic.
  39. states := client.Collection("States")
  40. ny := states.Doc("NewYork")
  41. // Or, in a single call:
  42. ny = client.Doc("States/NewYork")
  43. Reading
  44. Use DocumentRef.Get to read a document. The result is a DocumentSnapshot.
  45. Call its Data method to obtain the entire document contents as a map.
  46. docsnap, err := ny.Get(ctx)
  47. if err != nil {
  48. // TODO: Handle error.
  49. }
  50. dataMap := docsnap.Data()
  51. fmt.Println(dataMap)
  52. You can also obtain a single field with DataAt, or extract the data into a struct
  53. with DataTo. With the type definition
  54. type State struct {
  55. Capital string `firestore:"capital"`
  56. Population float64 `firestore:"pop"` // in millions
  57. }
  58. we can extract the document's data into a value of type State:
  59. var nyData State
  60. if err := docsnap.DataTo(&nyData); err != nil {
  61. // TODO: Handle error.
  62. }
  63. Note that this client supports struct tags beginning with "firestore:" that work like
  64. the tags of the encoding/json package, letting you rename fields, ignore them, or
  65. omit their values when empty.
  66. To retrieve multiple documents from their references in a single call, use
  67. Client.GetAll.
  68. docsnaps, err := client.GetAll(ctx, []*firestore.DocumentRef{
  69. states.Doc("Wisconsin"), states.Doc("Ohio"),
  70. })
  71. if err != nil {
  72. // TODO: Handle error.
  73. }
  74. for _, ds := range docsnaps {
  75. _ = ds // TODO: Use ds.
  76. }
  77. Writing
  78. For writing individual documents, use the methods on DocumentReference.
  79. Create creates a new document.
  80. wr, err := ny.Create(ctx, State{
  81. Capital: "Albany",
  82. Population: 19.8,
  83. })
  84. if err != nil {
  85. // TODO: Handle error.
  86. }
  87. fmt.Println(wr)
  88. The first return value is a WriteResult, which contains the time
  89. at which the document was updated.
  90. Create fails if the document exists. Another method, Set, either replaces an existing
  91. document or creates a new one.
  92. ca := states.Doc("California")
  93. _, err = ca.Set(ctx, State{
  94. Capital: "Sacramento",
  95. Population: 39.14,
  96. })
  97. To update some fields of an existing document, use Update. It takes a list of
  98. paths to update and their corresponding values.
  99. _, err = ca.Update(ctx, []firestore.Update{{Path: "capital", Value: "Sacramento"}})
  100. Use DocumentRef.Delete to delete a document.
  101. _, err = ny.Delete(ctx)
  102. Preconditions
  103. You can condition Deletes or Updates on when a document was last changed. Specify
  104. these preconditions as an option to a Delete or Update method. The check and the
  105. write happen atomically with a single RPC.
  106. docsnap, err = ca.Get(ctx)
  107. if err != nil {
  108. // TODO: Handle error.
  109. }
  110. _, err = ca.Update(ctx,
  111. []firestore.Update{{Path: "capital", Value: "Sacramento"}},
  112. firestore.LastUpdateTime(docsnap.UpdateTime))
  113. Here we update a doc only if it hasn't changed since we read it.
  114. You could also do this with a transaction.
  115. To perform multiple writes at once, use a WriteBatch. Its methods chain
  116. for convenience.
  117. WriteBatch.Commit sends the collected writes to the server, where they happen
  118. atomically.
  119. writeResults, err := client.Batch().
  120. Create(ny, State{Capital: "Albany"}).
  121. Update(ca, []firestore.Update{{Path: "capital", Value: "Sacramento"}}).
  122. Delete(client.Doc("States/WestDakota")).
  123. Commit(ctx)
  124. Queries
  125. You can use SQL to select documents from a collection. Begin with the collection, and
  126. build up a query using Select, Where and other methods of Query.
  127. q := states.Where("pop", ">", 10).OrderBy("pop", firestore.Desc)
  128. Call the Query's Documents method to get an iterator, and use it like
  129. the other Google Cloud Client iterators.
  130. iter := q.Documents(ctx)
  131. defer iter.Stop()
  132. for {
  133. doc, err := iter.Next()
  134. if err == iterator.Done {
  135. break
  136. }
  137. if err != nil {
  138. // TODO: Handle error.
  139. }
  140. fmt.Println(doc.Data())
  141. }
  142. To get all the documents in a collection, you can use the collection itself
  143. as a query.
  144. iter = client.Collection("States").Documents(ctx)
  145. Transactions
  146. Use a transaction to execute reads and writes atomically. All reads must happen
  147. before any writes. Transaction creation, commit, rollback and retry are handled for
  148. you by the Client.RunTransaction method; just provide a function and use the
  149. read and write methods of the Transaction passed to it.
  150. ny := client.Doc("States/NewYork")
  151. err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
  152. doc, err := tx.Get(ny) // tx.Get, NOT ny.Get!
  153. if err != nil {
  154. return err
  155. }
  156. pop, err := doc.DataAt("pop")
  157. if err != nil {
  158. return err
  159. }
  160. return tx.Update(ny, []firestore.Update{{Path: "pop", Value: pop.(float64) + 0.2}})
  161. })
  162. if err != nil {
  163. // TODO: Handle error.
  164. }
  165. */
  166. package firestore